diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index f180f84969..4967919f7a 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -895,6 +895,65 @@ jobs: run: | pnpm --filter '@bytecodealliance/${{ matrix.workspace }}' --fail-if-no-match run test + test-jco-std-wintertc: + runs-on: ubuntu-latest + needs: + - build + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 + with: + version: 11 + + # The WinterTC components are built for wasm32-wasip3 with the toolchain pinned in + # packages/jco-std/crates/rust-toolchain.toml. + - name: Install the WinterTC components' Rust toolchain + working-directory: packages/jco-std/crates + run: rustup toolchain install --no-self-update + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + workspaces: packages/jco-std/crates + + - uses: taiki-e/cache-cargo-install-action@9ee83daaa7b96a6fab930949ecf1122bba04a389 # v3.0.8 + with: + tool: wasm-tools + - uses: taiki-e/cache-cargo-install-action@9ee83daaa7b96a6fab930949ecf1122bba04a389 # v3.0.8 + with: + tool: wac-cli + - uses: bytecodealliance/actions/wasmtime/setup@9152e710e9f7182e4c29ad218e4f335a7b203613 # v1.1.3 + with: + version: v51.0.0 + + - name: Install node modules + run: pnpm install --frozen-lockfile + + # The tests build components with the workspace CLI (`jco componentize --backend quickjs`). + - name: Restore workspace CLI and transpiler + uses: $/.github/actions/restore-jco + + - name: Build the WinterTC components + run: pnpm --filter '@bytecodealliance/jco-std' --fail-if-no-match run build:wintertc:components + + - name: Fetch the pinned WPT subset + run: pnpm --filter '@bytecodealliance/jco-std' --fail-if-no-match run fetch:wpt + + - name: Type-check the WinterTC polyfills + run: pnpm --filter '@bytecodealliance/jco-std' --fail-if-no-match run check:wintertc + + - name: Run the WinterTC tests in components + env: + WINTERTC_REQUIRE_TOOLS: "1" + run: pnpm --filter '@bytecodealliance/jco-std' --fail-if-no-match run test:wintertc + examples: needs: - build diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5d0a1d2186..51c489e98f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -479,6 +479,13 @@ jobs: run: | pnpm install + # jco-std's prepack builds its WinterTC components with the Rust toolchain pinned in + # packages/jco-std/crates/rust-toolchain.toml. + - name: Install the jco-std components' Rust toolchain + if: ${{ needs.meta.outputs.project == 'jco-std' }} + working-directory: packages/jco-std/crates + run: rustup toolchain install --no-self-update + - name: Create release package working-directory: ${{ needs.meta.outputs.project-dir }} env: diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md index 7c2cdd2c10..1d834b95fa 100644 --- a/docs/src/SUMMARY.md +++ b/docs/src/SUMMARY.md @@ -14,6 +14,7 @@ - [CLI helpers](./wasi/preview2-shim/helpers/cli.md) - [Filesystem helpers](./wasi/preview2-shim/helpers/filesystem.md) - [Preview 3 shim](./wasi/preview3-shim.md) + - [WinterTC APIs](./wasi/wintertc.md) - [JavaScript ecosystem interoperability](./interop/index.md) - [`jco-std`](./interop/jco-std.md) - [Node.js built-in compatibility](./interop/nodejs-builtins.md) diff --git a/docs/src/wasi/wintertc.md b/docs/src/wasi/wintertc.md new file mode 100644 index 0000000000..3c8c637cfd --- /dev/null +++ b/docs/src/wasi/wintertc.md @@ -0,0 +1,179 @@ +# WinterTC APIs for WASI 0.3 components + +`@bytecodealliance/jco-std` provides polyfills for the [WinterTC Minimum Common API][ecma-429] +(ECMA-429), for JavaScript engines in WASI 0.3 components that don't have these APIs built in, such +as QuickJS in `jco componentize --backend quickjs`. ECMAScript itself, and anything only an engine +can provide, is the engine's job. + +The polyfills are ES module exports for now (they don't install globals). They call WASI directly, +so they work with any toolchain that follows the types `jco guest-types` generates. + +> [!NOTE] +> The WinterTC implementation is under active development. Module paths, the `jco:wintertc` +> interfaces and the component sizes below may still change. + +## Using it + +Import what you need: + +```ts +import { console, flushOutput, URL } from '@bytecodealliance/jco-std/wintertc'; + +export const run = { + async run(): Promise { + console.log(new URL('../b', 'https://example.com/a/').href); + await flushOutput(); + }, +}; +``` + +Declare a world that has the WASI interfaces and the `jco:wintertc` interfaces your code uses (the +[table below](#whats-available) lists them). The `jco:wintertc` WIT ships with the package, in +`node_modules/@bytecodealliance/jco-std/wit/wintertc-0.1.0/`; copy it into your `wit/deps/`: + +```wit +package example:app; + +world app { + include wasi:cli/imports@0.3.0; + import jco:wintertc/url@0.1.0; + export wasi:cli/run@0.3.0; +} +``` + +Build, compose and run: + +```sh +jco componentize app.js --backend quickjs --wit wit --world-name app -o app.wasm +WASM=node_modules/@bytecodealliance/jco-std/wasm +wac plug app.wasm --plug $WASM/wintertc-url.wasm -o app.composed.wasm +wasmtime run -S p3=y -W component-model-async=y app.composed.wasm +``` + +Most APIs are compiled into your component. A few (`URL`, `URLPattern`, compression, non-UTF-8 +text decoding and Web Crypto) call a separate component through a `jco:wintertc` interface, which +you compose with yours. The components are in the package's `wasm/` directory. They import only +WASI 0.3 interfaces (`wasi:cli`, `wasi:clocks` and `wasi:random`) that hosts provide, so composing +them adds no new requirements. Any host can also provide the `jco:wintertc` interfaces itself. + +If you forget one, instantiation fails with an unsatisfied import: + +```text +Error: failed to run main module `app.wasm` + +Caused by: + 0: component imports instance `jco:wintertc/url@0.1.0`, but a matching implementation was not found in the linker +``` + +## What's available + +"Yes" means jco-std provides it. Where a row needs more than `wasi:cli/imports@0.3.0` (clocks, +random, stdout and stderr), the notes say what to import and compose. + +| Interface or member | Available | Notes | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `AbortController`, `AbortSignal` | Yes | | +| `Event`, `EventTarget`, `CustomEvent`, `ErrorEvent` | Yes | | +| `PromiseRejectionEvent` | Yes | Never fired: detecting unhandled rejections needs the engine | +| `DOMException` | Yes | | +| `MessageChannel`, `MessagePort`, `MessageEvent` | Yes | `postMessage()` needs the engine's `structuredClone`; without it, it throws `DataCloneError` | +| `structuredClone()` | No | A faithful polyfill needs engine internals: copying every built-in type's internal state, and detecting values that can't be cloned. It has to come from the engine | +| `Headers` | Yes | | +| `Request`, `Response` | Yes | Compose with `wintertc-url.wasm` and `wintertc-encoding.wasm` | +| `fetch()` | Yes | Import `wasi:http/client@0.3.0`; compose with `wintertc-url.wasm` and `wintertc-encoding.wasm` | +| `FormData`, `Blob`, `File` | Yes | Compose with `wintertc-encoding.wasm` | +| `TextEncoder`, `TextDecoder`, `TextEncoderStream`, `TextDecoderStream` | Yes | Compose with `wintertc-encoding.wasm` (only non-UTF-8 decoding calls it) | +| `CompressionStream`, `DecompressionStream` | Yes | Compose with `wintertc-compression.wasm` | +| `ReadableStream`, `WritableStream`, `TransformStream`, their readers, writers and controllers, `ByteLengthQueuingStrategy`, `CountQueuingStrategy` | Yes | | +| `URL` | Yes | Compose with `wintertc-url.wasm` | +| `URLSearchParams` | Yes | | +| `URLPattern` | Yes | Compose with `wintertc-urlpattern.wasm` | +| `crypto`, `Crypto`, `SubtleCrypto`, `CryptoKey` | Yes | Compose with `wintertc-crypto.wasm`, even for `crypto.randomUUID()` alone | +| `performance`, `Performance` | Yes | | +| `console` | Yes | Commands await `flushOutput()` before returning; see [below](#differences-from-the-standards) | +| `setTimeout()`, `setInterval()`, `clearTimeout()`, `clearInterval()` | Yes | String handlers aren't supported | +| `queueMicrotask()`, `reportError()` | Yes | Errors are reported to `errorTarget()` and stderr, as there is no global object | +| `atob()`, `btoa()` | Yes | | +| `navigator.userAgent` | Yes | | +| `globalThis` | No | Part of ECMAScript, so the engine's job | +| `self`, `onerror`, `onunhandledrejection`, `onrejectionhandled` | No | The polyfills are module exports and install nothing on the global object yet. `onunhandledrejection` and `onrejectionhandled` also need the engine to report unhandled rejections | +| `WebAssembly` (`Module`, `Instance`, `Memory`, `Table`, `Global`, `Tag`, `Exception`, the error classes, `compile()`, `instantiate()`, `validate()`, `JSTag`, `compileStreaming()`, `instantiateStreaming()`) | No | Polyfilling it would mean shipping a WebAssembly engine inside the component. It has to come from the engine | + +## Differences from the standards + +- **`flushOutput()` (non-standard):** exported next to `console`, it resolves once all `console` + output written so far has reached the host. It exists because WASI 0.3 stdout and stderr are + asynchronous streams, so the synchronous `console` methods can only queue output, and a host may + stop a command as soon as its `wasi:cli/run` export returns (`wasmtime run` does), dropping + output it hasn't read yet. Await it before `run` returns. HTTP handlers under `wasmtime serve` + don't need it: the host keeps running pending work after the handler returns. +- **`errorTarget()` (non-standard):** HTML fires an `error` event at the global object for each + reported exception, and the polyfills install nothing there. `errorTarget()` returns the + `EventTarget` that receives those events instead (from `reportError()`, event listeners, + microtasks, timers and message handlers); `preventDefault()` suppresses the console output. +- **`disposeCryptoKey()` (non-standard):** a key's material lives in the composed crypto component + and is otherwise freed only when the key is garbage collected, which may be late or never. + `disposeCryptoKey(key)` frees it right away, for components that create many short-lived keys. +- **`URLPattern`:** regular expression groups such as `/:id(\\d+)` don't use ECMAScript's regular + expressions. Lookahead, lookbehind and backreferences are rejected as invalid patterns, and some + escapes and character classes differ. Patterns without regular expression groups behave as + specified. The tentative `URLPattern.compareComponent()` and `generate()` are not available. +- **`URL`:** parsing lags the standard in a few places: an opaque path's trailing spaces + (`data:text ?q`) are stripped rather than the last one percent-encoded, some `file:` URL edge + cases differ, and some invalid Punycode (`xn--`) labels are accepted. +- **`CompressionStream`, `DecompressionStream`:** the `brotli` format is not supported. Data after + the end of a compressed stream (including a second GZIP member) is an error. +- **Fetch:** there is no CORS, cache, cookie store or credentials handling, and only `http:` and + `https:` URLs are fetched, as in other server-side runtimes. +- **State held by composed components:** compression streams, and a `TextDecoder` in the middle of + a `{ stream: true }` sequence, keep state in their component until the stream ends, errors or is + canceled. If one is dropped while still open, its state is freed when it is garbage collected, on + engines that have `FinalizationRegistry`; otherwise it stays for the life of the component + instance. + +Each module's source documents its remaining deviations. + +## Implementation notes + +The separately composed parts are pure algorithms that need large, well-tested implementations: +URL parsing with IDNA, URL patterns, deflate, every WHATWG text encoding, and cryptography. They +are currently written in Rust, using established crates, built for the `wasm32-wasip3` target, and +live in their own Cargo workspace in `packages/jco-std/crates`. The `jco:wintertc` interfaces are plain records and numbers, so the +implementation behind them can change without changing the JavaScript side. + +### Sizes and licences + +Composition copies these components into your binary, so their licences travel with it. Measured +from a release build for `wasm32-wasip3`, not further optimized: + +| Component | Size | Gzipped | Crates linked in (licences) | +| --------------------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `wintertc-url.wasm` | 281 KiB | 103 KiB | `url`, `idna`, `idna_adapter`, `form_urlencoded`, `percent-encoding`, `smallvec`, `utf8_iter` and others (MIT OR Apache-2.0); ICU4X `icu_normalizer`, `icu_properties` and their data and support crates (Unicode-3.0) | +| `wintertc-urlpattern.wasm` | 1.28 MiB | 423 KiB | `urlpattern` (MIT); `regex`, `regex-automata`, `regex-syntax`, `serde` (MIT OR Apache-2.0); `aho-corasick`, `memchr` (Unlicense OR MIT); the `url` crates and ICU4X data as above | +| `wintertc-compression.wasm` | 106 KiB | 43 KiB | `miniz_oxide` (MIT OR Zlib OR Apache-2.0), `adler2` (0BSD OR MIT OR Apache-2.0) | +| `wintertc-encoding.wasm` | 230 KiB | 150 KiB | `encoding_rs` ((Apache-2.0 OR MIT) AND BSD-3-Clause), `cfg-if`, `scopeguard` (MIT OR Apache-2.0) | +| `wintertc-crypto.wasm` | 356 KiB | 116 KiB | RustCrypto `sha1`, `sha2`, `hmac`, `hkdf`, `pbkdf2`, `aes`, `ctr`, `ghash`, `p256`, `p384`, `rand_chacha` and their support crates (MIT OR Apache-2.0); `ed25519-dalek`, `x25519-dalek`, `curve25519-dalek`, `subtle` (BSD-3-Clause); `zerocopy` (BSD-2-Clause OR Apache-2.0 OR MIT) | + +Every component also links Rust's standard library (MIT OR Apache-2.0) and `wit-bindgen`'s runtime +(Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT). The components' own code is under jco's +licence, Apache-2.0 WITH LLVM-exception. + +### Building and testing + +Building the components needs [rustup][rustup], which installs the Rust toolchain and the +`wasm32-wasip3` target that `crates/rust-toolchain.toml` names. With [`wasm-tools`][wasm-tools] on +the `PATH`, the build also checks that each component imports only WASI 0.3. The package's +`prepack` builds them, so the published package includes them. From `packages/jco-std`: + +```sh +node scripts/build-wintertc-components.mjs # all components, into wasm/ +node scripts/build-wintertc-components.mjs url # one component +pnpm run test:wintertc # unit tests, WPT and end-to-end tests +``` + +The tests run inside real componentize-qjs components under wasmtime, composed with these +components. + +[ecma-429]: https://ecma-international.org/publications-and-standards/standards/ecma-429/ +[wasm-tools]: https://github.com/bytecodealliance/wasm-tools +[rustup]: https://rustup.rs diff --git a/packages/jco-std/.gitignore b/packages/jco-std/.gitignore index 41cba5996a..1471a81d50 100644 --- a/packages/jco-std/.gitignore +++ b/packages/jco-std/.gitignore @@ -1,2 +1,13 @@ dist -*.tgz \ No newline at end of file +*.tgz + +# WinterTC: generated type declarations (scripts/generate-wintertc-types.mjs) +src/wintertc/generated +src/wintertc/imports +# WinterTC components: cargo output and built components +crates/target +/wasm +# componentize-qjs end-to-end fixtures: bundles, WIT and components +test/wintertc/e2e-qjs/.build +test/wintertc/wpt/.cache/ +test/wintertc/wpt/.cache.partial/ diff --git a/packages/jco-std/.oxfmtrc.json b/packages/jco-std/.oxfmtrc.json index ce1cc68b38..ad1f07d28e 100644 --- a/packages/jco-std/.oxfmtrc.json +++ b/packages/jco-std/.oxfmtrc.json @@ -1,3 +1,9 @@ { - "ignorePatterns": ["src/wasi/**/generated/**/*"] + "ignorePatterns": [ + "src/wasi/**/generated/**/*", + "src/wintertc/generated/**/*", + "src/wintertc/imports/**/*", + "test/wintertc/wpt/.cache/**/*", + "test/wintertc/wpt/.cache.partial/**/*" + ] } diff --git a/packages/jco-std/.oxlintrc.json b/packages/jco-std/.oxlintrc.json index 4bdaaa2fa4..f920df212b 100644 --- a/packages/jco-std/.oxlintrc.json +++ b/packages/jco-std/.oxlintrc.json @@ -13,7 +13,9 @@ "src/wasi/0.2.x/generated/types/**/*.d.ts", "src/wasi/0.2.3/generated/types/**/*.d.ts", "src/wasi/0.2.6/generated/types/**/*.d.ts", - "src/wasi/0.2.12/generated/types/**/*.d.ts" + "src/wasi/0.2.12/generated/types/**/*.d.ts", + "src/wintertc/generated/types/**/*.d.ts", + "src/wintertc/imports/**/*.d.ts" ], "rules": { "no-unused-vars": "error", diff --git a/packages/jco-std/README.md b/packages/jco-std/README.md index 1e5a161f7f..bef4df3028 100644 --- a/packages/jco-std/README.md +++ b/packages/jco-std/README.md @@ -28,6 +28,13 @@ Below is a list of adapters provided by `@bytecodealliance/jco-std`: | -------------------- | ---------------------------------------------------- | | `http/adapters/hono` | Enables easier building of [Hono][hono] HTTP servers | +## WinterTC APIs (in development) + +The WinterTC Minimum Common API for WASI 0.3 components lives in `src/wintertc/`. A few APIs +(`URL`, `URLPattern`, compression streams, non-UTF-8 `TextDecoder`, `crypto.subtle`) are backed by +Rust components in `wasm/` that you compose with your component; see +[WinterTC APIs](https://bytecodealliance.github.io/jco/wasi/wintertc.html) in the jco book. + ## NodeJS API (experimental) `jco-std` also makes available an experimental NodeJS API that is used by tools like `jco` to diff --git a/packages/jco-std/crates/Cargo.lock b/packages/jco-std/crates/Cargo.lock new file mode 100644 index 0000000000..50eae688e3 --- /dev/null +++ b/packages/jco-std/crates/Cargo.lock @@ -0,0 +1,1325 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aes" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" +dependencies = [ + "cipher", + "cpubits", + "cpufeatures", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anyhow" +version = "1.0.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base16ct" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "block-buffer", + "crypto-common", + "inout", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-bigint" +version = "0.7.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "914c195c4d7fbc5ed7f88d14cbf85914d5c664967658d43404b263913a477e82" +dependencies = [ + "cpubits", + "ctutils", + "hybrid-array", + "num-traits", + "rand_core", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", + "rand_core", +] + +[[package]] +name = "ctr" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21" +dependencies = [ + "cipher", +] + +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", + "subtle", +] + +[[package]] +name = "curve25519-dalek" +version = "5.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94c1aa5a9b7626ed65ac0cf5ea9d4f1547af89017fbac20bd4de40022fff516f" +dependencies = [ + "cfg-if", + "cpufeatures", + "curve25519-dalek-derive", + "digest", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "der" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" +dependencies = [ + "const-oid", + "zeroize", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "ctutils", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "ecdsa" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0" +dependencies = [ + "der", + "digest", + "elliptic-curve", + "rfc6979", + "signature", + "zeroize", +] + +[[package]] +name = "ed25519" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a" +dependencies = [ + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de" +dependencies = [ + "curve25519-dalek", + "ed25519", + "sha2", + "subtle", + "zeroize", +] + +[[package]] +name = "elliptic-curve" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900f37e7e18d74a2347389af6cd69e3a30d5cc9e697f40004865679aa75e9c7c" +dependencies = [ + "base16ct", + "crypto-bigint", + "crypto-common", + "digest", + "ff", + "group", + "hybrid-array", + "rand_core", + "sec1", + "subtle", + "zeroize", +] + +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "ff" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1f686ab92a9fb0eaf188f6c6c87b89490baa6fdb0db4544ba4dc47f7942489f" +dependencies = [ + "rand_core", + "subtle", +] + +[[package]] +name = "fiat-crypto" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "ghash" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2eecf2d5dc9b66b732b97707a0210906b1d30523eb773193ab777c0c84b3e8d5" +dependencies = [ + "polyval", +] + +[[package]] +name = "group" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4" +dependencies = [ + "ff", + "rand_core", + "subtle", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hkdf" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest", +] + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "subtle", + "typenum", + "zeroize", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "inout" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "p256" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primefield", + "primeorder", + "sha2", +] + +[[package]] +name = "p384" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d17b851e6b3e378ab4ecb07fa2ed23f4d15f075735f8fec9fa1e7bdce5f8301f" +dependencies = [ + "ecdsa", + "elliptic-curve", + "fiat-crypto", + "primefield", + "primeorder", + "sha2", +] + +[[package]] +name = "pbkdf2" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629" +dependencies = [ + "digest", + "hmac", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "polyval" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0fa31d631f2b2cb2a544d0aa321ce847a94764d701ca2becc411138b93d49cd" +dependencies = [ + "cpubits", + "cpufeatures", + "universal-hash", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn 3.0.10", +] + +[[package]] +name = "primefield" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4" +dependencies = [ + "crypto-bigint", + "crypto-common", + "ff", + "rand_core", + "subtle", + "zeroize", +] + +[[package]] +name = "primeorder" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06" +dependencies = [ + "elliptic-curve", + "primefield", + "wnaf", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand_chacha" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e6af7f3e25ded52c41df4e0b1af2d047e45896c2f3281792ed68a1c243daedb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "regex" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "rfc6979" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b" +dependencies = [ + "crypto-bigint", + "hmac", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sec1" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" +dependencies = [ + "base16ct", + "ctutils", + "der", + "hybrid-array", + "subtle", + "zeroize", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sha2" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "signature" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" +dependencies = [ + "digest", + "rand_core", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "universal-hash" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96" +dependencies = [ + "crypto-common", + "ctutils", +] + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "urlpattern" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df16f50ef4cc145211879a3867ba757076b25dfee812040dcb0658bd9ae7904b" +dependencies = [ + "icu_properties", + "regex", + "serde", + "url", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "wasm-encoder" +version = "0.264.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "574848c680febb315739f766586b322da8ef271572c495ff5504c780d5de40ad" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.264.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7835b37c16a0fb026135e368a75fd555c75329e38650fc2fb8f39bd34e2941f3" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.264.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fef67d509e777f18cd3854c71b8ed194dec928860e306f620077d9b7c9b32224" +dependencies = [ + "bitflags", + "hashbrown", + "indexmap", + "semver", +] + +[[package]] +name = "wintertc-compression" +version = "0.1.0" +dependencies = [ + "miniz_oxide", + "wit-bindgen", +] + +[[package]] +name = "wintertc-crypto" +version = "0.1.0" +dependencies = [ + "aes", + "base64ct", + "ctr", + "ed25519-dalek", + "ghash", + "hkdf", + "hmac", + "p256", + "p384", + "pbkdf2", + "rand_chacha", + "rand_core", + "sha1", + "sha2", + "subtle", + "wit-bindgen", + "x25519-dalek", + "zeroize", +] + +[[package]] +name = "wintertc-encoding" +version = "0.1.0" +dependencies = [ + "encoding_rs", + "wit-bindgen", +] + +[[package]] +name = "wintertc-url" +version = "0.1.0" +dependencies = [ + "url", + "wit-bindgen", +] + +[[package]] +name = "wintertc-urlpattern" +version = "0.1.0" +dependencies = [ + "regex", + "urlpattern", + "wit-bindgen", +] + +[[package]] +name = "wit-bindgen" +version = "0.64.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d21697886cf446ab875ae73f86177a988995a70b3b64f630564bcfb5a332f8e1" +dependencies = [ + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.64.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c6867b6847414aa0a615dde361dacb9b575ea1feff3934e90a9c55b363a36d1" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.64.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94333f13cee499930e21d577ba3c7b8b223358481c33f287ff28733c30ce8037" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 3.0.10", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.64.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0abcc527a511256e40d3f998e3cebd0bf545f155851eb8a8e0ba63d8659573eb" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 3.0.10", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.264.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "098639bb161401c9ad8b97ba20203cbb016a4b11af5fdaa10c30c6801baf16e7" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.264.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c62a5e118a3aa2d08948efed16b3ee18dfe5290bffdd8a6239f004e655c9e334" +dependencies = [ + "anyhow", + "hashbrown", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser", +] + +[[package]] +name = "wnaf" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa" +dependencies = [ + "ff", + "group", + "hybrid-array", + "primefield", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "x25519-dalek" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e8131a03190127fb2263afc72b322ecadae46b6ff8c6f399ff5d02f5559af6" +dependencies = [ + "curve25519-dalek", + "rand_core", + "zeroize", +] + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/packages/jco-std/crates/Cargo.toml b/packages/jco-std/crates/Cargo.toml new file mode 100644 index 0000000000..50f76873c7 --- /dev/null +++ b/packages/jco-std/crates/Cargo.toml @@ -0,0 +1,29 @@ +# Rust components behind jco-std's WinterTC implementation (`jco:wintertc` WIT package). +# Built for wasm32-wasip3 (see rust-toolchain.toml), which produces components directly; besides +# their jco:wintertc export they import only WASI 0.3. See scripts/build-wintertc-components.mjs. +[workspace] +resolver = "3" +members = [ + "wintertc-compression", + "wintertc-crypto", + "wintertc-encoding", + "wintertc-url", + "wintertc-urlpattern", +] + +[workspace.package] +version = "0.1.0" +edition = "2024" +license = "Apache-2.0 WITH LLVM-exception" +publish = false + +[workspace.dependencies] +wit-bindgen = { version = "0.64.0", default-features = false, features = ["macros", "realloc"] } + +[profile.release] +opt-level = "s" +lto = true +codegen-units = 1 +panic = "abort" +strip = true +debug = false diff --git a/packages/jco-std/crates/rust-toolchain.toml b/packages/jco-std/crates/rust-toolchain.toml new file mode 100644 index 0000000000..5d6af872cb --- /dev/null +++ b/packages/jco-std/crates/rust-toolchain.toml @@ -0,0 +1,4 @@ +# The components are built for wasm32-wasip3, which is stable from Rust 1.100.0. +[toolchain] +channel = "1.100.0" +targets = ["wasm32-wasip3"] diff --git a/packages/jco-std/crates/wintertc-compression/Cargo.toml b/packages/jco-std/crates/wintertc-compression/Cargo.toml new file mode 100644 index 0000000000..908a8ca47d --- /dev/null +++ b/packages/jco-std/crates/wintertc-compression/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "wintertc-compression" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true + +[lib] +crate-type = ["cdylib"] + +[dependencies] +miniz_oxide = "0.9" +wit-bindgen.workspace = true diff --git a/packages/jco-std/crates/wintertc-compression/src/lib.rs b/packages/jco-std/crates/wintertc-compression/src/lib.rs new file mode 100644 index 0000000000..5beb4a85d9 --- /dev/null +++ b/packages/jco-std/crates/wintertc-compression/src/lib.rs @@ -0,0 +1,540 @@ +//! The `jco:wintertc/compression` component: streaming DEFLATE, ZLIB and GZIP compression and +//! decompression with `miniz_oxide`, for `CompressionStream` and `DecompressionStream`. +//! +//! `miniz_oxide` handles raw DEFLATE and the ZLIB wrapper; the GZIP header and trailer +//! (RFC 1952) are written and checked here. + +use std::collections::HashMap; +use std::sync::{LazyLock, Mutex, PoisonError}; + +use miniz_oxide::deflate::core::{CompressorOxide, create_comp_flags_from_zip_params}; +use miniz_oxide::inflate::stream::{InflateState, inflate}; +use miniz_oxide::{DataFormat, MZError, MZFlush, MZStatus}; + +wit_bindgen::generate!({ + path: "../../wit/wintertc-0.1.0", + world: "wintertc-compression", +}); + +use exports::jco::wintertc::compression::{Guest, Outcome}; + +struct Component; + +export!(Component); + +/// A compression format of the Compression Streams standard. +#[derive(Clone, Copy, PartialEq)] +enum Format { + /// ZLIB (RFC 1950), called `deflate`. + Deflate, + /// Raw DEFLATE (RFC 1951). + DeflateRaw, + /// GZIP (RFC 1952). + Gzip, +} + +impl Format { + /// Parse a format name. + fn from_name(name: &str) -> Option { + match name { + "deflate" => Some(Format::Deflate), + "deflate-raw" => Some(Format::DeflateRaw), + "gzip" => Some(Format::Gzip), + _ => None, + } + } +} + +/// Size of the scratch buffer each (de)compression step writes into. +const CHUNK: usize = 32 * 1024; + +/// The zlib compression level browsers use by default. +const LEVEL: i32 = 6; + +/// A GZIP header with no optional fields, no modification time and an unknown OS. +const GZIP_HEADER: [u8; 10] = [0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 0xff]; + +// --------------------------------------------------------------------------------------------- +// CRC-32 (the GZIP checksum) +// --------------------------------------------------------------------------------------------- + +/// The CRC-32 lookup table for the reflected polynomial 0xEDB88320, built at compile time. +const CRC_TABLE: [u32; 256] = { + let mut table = [0u32; 256]; + let mut index = 0; + while index < 256 { + let mut crc = index as u32; + let mut bit = 0; + while bit < 8 { + crc = if crc & 1 != 0 { + 0xEDB8_8320 ^ (crc >> 1) + } else { + crc >> 1 + }; + bit += 1; + } + table[index] = crc; + index += 1; + } + table +}; + +/// A running CRC-32 and byte count, as the GZIP trailer records them. +#[derive(Default)] +struct Checksum { + crc: u32, + size: u32, +} + +impl Checksum { + /// Add `bytes` to the checksum. + fn update(&mut self, bytes: &[u8]) { + let mut crc = !self.crc; + for &byte in bytes { + crc = CRC_TABLE[((crc ^ u32::from(byte)) & 0xff) as usize] ^ (crc >> 8); + } + self.crc = !crc; + self.size = self.size.wrapping_add(bytes.len() as u32); + } + + /// The 8-byte GZIP trailer: CRC-32 then size modulo 2^32, both little-endian. + fn trailer(&self) -> [u8; 8] { + let mut trailer = [0u8; 8]; + trailer[..4].copy_from_slice(&self.crc.to_le_bytes()); + trailer[4..].copy_from_slice(&self.size.to_le_bytes()); + trailer + } +} + +// --------------------------------------------------------------------------------------------- +// Compression +// --------------------------------------------------------------------------------------------- + +struct CompressState { + deflater: Box, + /// `Some` for GZIP: the checksum of the uncompressed input so far. + gzip: Option, + /// Whether anything has been output yet (the GZIP header goes first). + started: bool, + finished: bool, +} + +impl CompressState { + /// Run the deflater over `input`, collecting all output it produces with `flush`. + fn deflate(&mut self, mut input: &[u8], flush: MZFlush) -> Vec { + let mut output = Vec::new(); + if !self.started { + self.started = true; + if self.gzip.is_some() { + output.extend_from_slice(&GZIP_HEADER); + } + } + if let Some(checksum) = self.gzip.as_mut() { + checksum.update(input); + } + + let mut buffer = vec![0u8; CHUNK]; + loop { + let result = miniz_oxide::deflate::stream::deflate( + &mut self.deflater, + input, + &mut buffer, + flush, + ); + output.extend_from_slice(&buffer[..result.bytes_written]); + input = &input[result.bytes_consumed..]; + let progressed = result.bytes_written > 0 || result.bytes_consumed > 0; + match result.status { + Ok(MZStatus::StreamEnd) => break, + Ok(_) if progressed => {} + // No progress: everything is consumed and buffered internally until more input or + // `finish` arrives. + _ => break, + } + } + output + } +} + +impl CompressState { + /// Start compressing into `format`. + fn new(format: Format) -> Self { + let window_bits = match format { + Format::Deflate => DataFormat::Zlib.to_window_bits(), + Format::DeflateRaw | Format::Gzip => DataFormat::Raw.to_window_bits(), + }; + let flags = create_comp_flags_from_zip_params(LEVEL, window_bits, 0); + CompressState { + deflater: Box::new(CompressorOxide::new(flags)), + gzip: (format == Format::Gzip).then(Checksum::default), + started: false, + finished: false, + } + } + + /// Compress a chunk. + fn push(&mut self, input: &[u8]) -> Vec { + if self.finished || input.is_empty() { + return Vec::new(); + } + self.deflate(input, MZFlush::None) + } + + /// End the stream, returning the rest of the output (including the GZIP trailer). + fn finish(&mut self) -> Vec { + if self.finished { + return Vec::new(); + } + self.finished = true; + let mut output = self.deflate(&[], MZFlush::Finish); + if let Some(checksum) = self.gzip.as_ref() { + output.extend_from_slice(&checksum.trailer()); + } + output + } +} + +// --------------------------------------------------------------------------------------------- +// Decompression +// --------------------------------------------------------------------------------------------- + +/// Where a GZIP decompressor is in the member. +enum GzipStage { + /// Collecting the header, which has variable length. + Header(Vec), + /// Inflating the body. + Body, + /// Collecting the 8-byte trailer. + Trailer(Vec), + /// The member is complete. + Done, +} + +struct DecompressState { + inflater: Box, + /// `Some` for GZIP: the stage and the checksum of the output so far. + gzip: Option<(GzipStage, Checksum)>, + /// Whether the DEFLATE stream has ended. + ended: bool, + /// Set once an error has been reported; the stream is unusable after that. + failed: bool, +} + +/// Why decompression failed. +const CORRUPT: &str = "the compressed data is corrupt"; +const TRAILING: &str = "there is data after the end of the compressed stream"; +const TRUNCATED: &str = "the compressed data ended unexpectedly"; + +/// Parse a GZIP header at the start of `bytes`. +/// +/// Returns the header's length once it is complete, `Ok(None)` if more bytes are needed. +fn parse_gzip_header(bytes: &[u8]) -> Result, &'static str> { + const FHCRC: u8 = 1 << 1; + const FEXTRA: u8 = 1 << 2; + const FNAME: u8 = 1 << 3; + const FCOMMENT: u8 = 1 << 4; + const RESERVED: u8 = 0b1110_0000; + + // Check the fixed part as far as it has arrived, so garbage fails early. + for (index, expected) in [0x1f, 0x8b, 8].into_iter().enumerate() { + match bytes.get(index) { + Some(&byte) if byte != expected => return Err(CORRUPT), + None => return Ok(None), + _ => {} + } + } + let Some(&flags) = bytes.get(3) else { + return Ok(None); + }; + if flags & RESERVED != 0 { + return Err(CORRUPT); + } + let mut length = 10; + if bytes.len() < length { + return Ok(None); + } + + if flags & FEXTRA != 0 { + let Some(extra) = bytes.get(length..length + 2) else { + return Ok(None); + }; + length += 2 + usize::from(u16::from_le_bytes([extra[0], extra[1]])); + if bytes.len() < length { + return Ok(None); + } + } + for flag in [FNAME, FCOMMENT] { + if flags & flag != 0 { + match bytes[length..].iter().position(|&byte| byte == 0) { + Some(end) => length += end + 1, + None => return Ok(None), + } + } + } + if flags & FHCRC != 0 { + let Some(stored) = bytes.get(length..length + 2) else { + return Ok(None); + }; + let mut checksum = Checksum::default(); + checksum.update(&bytes[..length]); + if u16::from_le_bytes([stored[0], stored[1]]) != (checksum.crc & 0xffff) as u16 { + return Err(CORRUPT); + } + length += 2; + } + Ok(Some(length)) +} + +impl DecompressState { + /// Inflate `input`, appending output to `output`, until the input is used up or the DEFLATE + /// stream ends. Returns the input left over after the end of the stream. + fn inflate<'a>( + &mut self, + mut input: &'a [u8], + output: &mut Vec, + ) -> Result<&'a [u8], &'static str> { + let mut buffer = vec![0u8; CHUNK]; + while !self.ended { + let result = inflate(&mut self.inflater, input, &mut buffer, MZFlush::None); + let written = &buffer[..result.bytes_written]; + if let Some((_, checksum)) = self.gzip.as_mut() { + checksum.update(written); + } + output.extend_from_slice(written); + input = &input[result.bytes_consumed..]; + let progressed = result.bytes_written > 0 || result.bytes_consumed > 0; + match result.status { + Ok(MZStatus::StreamEnd) => self.ended = true, + Ok(_) if progressed => {} + // No progress: waiting for more input. + Ok(_) | Err(MZError::Buf) => break, + Err(_) => return Err(CORRUPT), + } + } + Ok(input) + } + + /// Decompress `input`, appending the output to `output`. + fn push(&mut self, input: &[u8], output: &mut Vec) -> Result<(), &'static str> { + if self.gzip.is_none() { + let rest = self.inflate(input, output)?; + return if rest.is_empty() { + Ok(()) + } else { + Err(TRAILING) + }; + } + + // GZIP: walk the input through header, body and trailer. + let mut input = input; + let mut pending: Vec; + loop { + let Some((stage, checksum)) = self.gzip.as_mut() else { + unreachable!() + }; + match stage { + GzipStage::Header(header) => { + header.extend_from_slice(input); + match parse_gzip_header(header)? { + None => return Ok(()), + Some(length) => { + pending = header.split_off(length); + input = &pending; + *stage = GzipStage::Body; + } + } + } + GzipStage::Body => { + let rest = self.inflate(input, output)?; + if !self.ended { + return Ok(()); + } + pending = rest.to_vec(); + input = &pending; + if let Some((stage, _)) = self.gzip.as_mut() { + *stage = GzipStage::Trailer(Vec::with_capacity(8)); + } + } + GzipStage::Trailer(trailer) => { + let take = input.len().min(8 - trailer.len()); + trailer.extend_from_slice(&input[..take]); + input = &input[take..]; + if trailer.len() < 8 { + return Ok(()); + } + if trailer[..] != checksum.trailer() { + return Err(CORRUPT); + } + *stage = GzipStage::Done; + } + GzipStage::Done => { + return if input.is_empty() { + Ok(()) + } else { + Err(TRAILING) + }; + } + } + } + } + + /// Check that the stream is complete. + fn finish(&mut self) -> Result<(), &'static str> { + let complete = match &self.gzip { + Some((stage, _)) => matches!(stage, GzipStage::Done), + None => self.ended, + }; + if complete { Ok(()) } else { Err(TRUNCATED) } + } +} + +impl DecompressState { + /// Start decompressing `format`. + fn new(format: Format) -> Self { + let data_format = match format { + Format::Deflate => DataFormat::Zlib, + Format::DeflateRaw | Format::Gzip => DataFormat::Raw, + }; + DecompressState { + inflater: InflateState::new_boxed(data_format), + gzip: (format == Format::Gzip) + .then(|| (GzipStage::Header(Vec::new()), Checksum::default())), + ended: false, + failed: false, + } + } + + /// Run `step` unless the stream has already failed, remembering a failure. + /// + /// Output decoded before data found after the end of the stream is still returned with the + /// failure, since the standard enqueues it before erroring; other failures return no output. + fn guarded( + &mut self, + step: impl FnOnce(&mut DecompressState, &mut Vec) -> Result<(), &'static str>, + ) -> Outcome { + if self.failed { + return failure("the decompressor has already failed"); + } + let mut bytes = Vec::new(); + match step(self, &mut bytes) { + Ok(()) => Outcome { + ok: true, + bytes, + error: String::new(), + }, + Err(message) => { + self.failed = true; + if message != TRAILING { + bytes.clear(); + } + Outcome { + ok: false, + bytes, + error: message.to_owned(), + } + } + } + } +} + +// --------------------------------------------------------------------------------------------- +// Handles +// --------------------------------------------------------------------------------------------- + +/// A live stream. +enum Stream { + Compress(CompressState), + Decompress(DecompressState), +} + +/// The live streams by handle, and the next handle to try. +#[derive(Default)] +struct Table { + streams: HashMap, + next: u32, +} + +impl Table { + /// Store `stream` under a fresh, nonzero handle. + fn insert(&mut self, stream: Stream) -> u32 { + loop { + self.next = self.next.wrapping_add(1); + if self.next != 0 && !self.streams.contains_key(&self.next) { + self.streams.insert(self.next, stream); + return self.next; + } + } + } +} + +/// The instance's state. Not `thread_local!`: on wasm32-wasip3 thread-local storage belongs to the +/// current task, so it would be lost between export calls. +static TABLE: LazyLock> = LazyLock::new(Mutex::default); + +/// Run `f` on the instance's state. +fn with_table(action: impl FnOnce(&mut Table) -> Output) -> Output { + action(&mut TABLE.lock().unwrap_or_else(PoisonError::into_inner)) +} + +/// A failed outcome. +fn failure(message: &str) -> Outcome { + Outcome { + ok: false, + bytes: Vec::new(), + error: message.to_owned(), + } +} + +/// Run `step` on the stream behind `handle`. +fn with_stream(handle: u32, step: impl FnOnce(&mut Stream) -> Outcome) -> Outcome { + with_table(|table| match table.streams.get_mut(&handle) { + Some(stream) => step(stream), + None => failure("unknown compression handle"), + }) +} + +impl Guest for Component { + fn compressor_create(format: String) -> u32 { + match Format::from_name(&format) { + Some(format) => { + with_table(|table| table.insert(Stream::Compress(CompressState::new(format)))) + } + None => 0, + } + } + + fn decompressor_create(format: String) -> u32 { + match Format::from_name(&format) { + Some(format) => { + with_table(|table| table.insert(Stream::Decompress(DecompressState::new(format)))) + } + None => 0, + } + } + + fn push(handle: u32, input: Vec) -> Outcome { + with_stream(handle, |stream| match stream { + Stream::Compress(state) => Outcome { + ok: true, + bytes: state.push(&input), + error: String::new(), + }, + Stream::Decompress(state) => state.guarded(|state, output| state.push(&input, output)), + }) + } + + fn finish(handle: u32) -> Outcome { + with_stream(handle, |stream| match stream { + Stream::Compress(state) => Outcome { + ok: true, + bytes: state.finish(), + error: String::new(), + }, + Stream::Decompress(state) => state.guarded(|state, _output| state.finish()), + }) + } + + fn free(handle: u32) { + with_table(|table| table.streams.remove(&handle)); + } +} diff --git a/packages/jco-std/crates/wintertc-crypto/Cargo.toml b/packages/jco-std/crates/wintertc-crypto/Cargo.toml new file mode 100644 index 0000000000..73f378c1dd --- /dev/null +++ b/packages/jco-std/crates/wintertc-crypto/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "wintertc-crypto" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +aes = "0.9" +base64ct = { version = "1.8", features = ["alloc"] } +ctr = "0.10" +ed25519-dalek = { version = "3", default-features = false, features = ["zeroize"] } +ghash = "0.6" +hkdf = "0.13" +hmac = "0.13" +p256 = { version = "0.14", default-features = false, features = ["ecdsa", "arithmetic"] } +p384 = { version = "0.14", default-features = false, features = ["ecdsa", "arithmetic"] } +pbkdf2 = { version = "0.13", default-features = false, features = ["hmac"] } +rand_chacha = { version = "0.10", default-features = false } +rand_core = "0.10" +sha1 = { version = "0.11", default-features = false } +sha2 = { version = "0.11", default-features = false } +subtle = { version = "2.6", default-features = false } +wit-bindgen.workspace = true +x25519-dalek = { version = "3", default-features = false, features = ["static_secrets", "zeroize"] } +zeroize = "1.8" diff --git a/packages/jco-std/crates/wintertc-crypto/src/gcm.rs b/packages/jco-std/crates/wintertc-crypto/src/gcm.rs new file mode 100644 index 0000000000..6d159177db --- /dev/null +++ b/packages/jco-std/crates/wintertc-crypto/src/gcm.rs @@ -0,0 +1,246 @@ +//! AES-GCM (NIST SP 800-38D) over the `aes`, `ctr` and `ghash` crates. +//! +//! Web Crypto allows any nonzero IV length and tags of 32 to 128 bits, which the `aes-gcm` crate +//! fixes at compile time. Building GCM from its parts handles every combination with one code path: +//! a tag of `t` bits is the first `t` bits of the full tag (SP 800-38D, section 7.1), so decryption +//! recomputes the full tag and compares the prefix in constant time. + +use aes::cipher::{ + Block, BlockCipherEncrypt, BlockSizeUser, InnerIvInit, KeyInit, StreamCipher, consts::U16, +}; +use aes::{Aes128, Aes192, Aes256}; +use ghash::GHash; +use ghash::universal_hash::UniversalHash; +use subtle::ConstantTimeEq; + +/// Why a GCM operation failed. +pub enum GcmError { + /// The key is not 16, 24 or 32 bytes. + KeyLength, + /// The IV is empty. + IvLength, + /// The ciphertext is shorter than the tag, or the tag does not match. + Authentication, +} + +/// Encrypt `plaintext`, returning the ciphertext followed by a `tag_len`-byte tag. +pub fn encrypt( + key: &[u8], + iv: &[u8], + aad: &[u8], + tag_len: usize, + plaintext: &[u8], +) -> Result, GcmError> { + match key.len() { + 16 => seal::(key, iv, aad, tag_len, plaintext), + 24 => seal::(key, iv, aad, tag_len, plaintext), + 32 => seal::(key, iv, aad, tag_len, plaintext), + _ => Err(GcmError::KeyLength), + } +} + +/// Decrypt `ciphertext` (with its `tag_len`-byte tag at the end), checking the tag. +pub fn decrypt( + key: &[u8], + iv: &[u8], + aad: &[u8], + tag_len: usize, + ciphertext: &[u8], +) -> Result, GcmError> { + match key.len() { + 16 => open::(key, iv, aad, tag_len, ciphertext), + 24 => open::(key, iv, aad, tag_len, ciphertext), + 32 => open::(key, iv, aad, tag_len, ciphertext), + _ => Err(GcmError::KeyLength), + } +} + +/// The block cipher, hash subkey and pre-counter block (`J0`) for one message. +struct Setup { + cipher: Cipher, + hash_key: Block, + j0: Block, +} + +/// Derive the hash subkey `H = E(K, 0)` and `J0` from the key and IV. +fn setup(key: &[u8], iv: &[u8]) -> Result, GcmError> +where + Cipher: BlockCipherEncrypt + BlockSizeUser + KeyInit, +{ + if iv.is_empty() { + return Err(GcmError::IvLength); + } + let cipher = Cipher::new_from_slice(key).map_err(|_| GcmError::KeyLength)?; + let mut hash_key = Block::::default(); + cipher.encrypt_block(&mut hash_key); + + // A 96-bit IV is used directly with a counter of 1; any other length is hashed together with + // its bit length. + let mut j0 = Block::::default(); + if iv.len() == 12 { + j0[..12].copy_from_slice(iv); + j0[15] = 1; + } else { + let mut ghash = GHash::new(&hash_key); + ghash.update_padded(iv); + let mut lengths = ghash::Block::default(); + lengths[8..].copy_from_slice(&((iv.len() as u64) * 8).to_be_bytes()); + ghash.update(&[lengths]); + j0.copy_from_slice(&ghash.finalize()); + } + Ok(Setup { + cipher, + hash_key, + j0, + }) +} + +/// Apply the keystream starting at `inc32(J0)` to `data` in place. +fn keystream(setup: &Setup, data: &mut [u8]) +where + Cipher: BlockCipherEncrypt + BlockSizeUser + KeyInit + Clone, +{ + let mut counter = setup.j0; + let low = + u32::from_be_bytes([counter[12], counter[13], counter[14], counter[15]]).wrapping_add(1); + counter[12..].copy_from_slice(&low.to_be_bytes()); + let core = ctr::CtrCore::::inner_iv_init( + setup.cipher.clone(), + &counter, + ); + let mut ctr = ctr::Ctr32BE::::from_core(core); + ctr.apply_keystream(data); +} + +/// The full 16-byte tag over `aad` and `ciphertext`. +fn full_tag(setup: &Setup, aad: &[u8], ciphertext: &[u8]) -> [u8; 16] +where + Cipher: BlockCipherEncrypt + BlockSizeUser + KeyInit, +{ + let mut ghash = GHash::new(&setup.hash_key); + ghash.update_padded(aad); + ghash.update_padded(ciphertext); + let mut lengths = ghash::Block::default(); + lengths[..8].copy_from_slice(&((aad.len() as u64) * 8).to_be_bytes()); + lengths[8..].copy_from_slice(&((ciphertext.len() as u64) * 8).to_be_bytes()); + ghash.update(&[lengths]); + let hash = ghash.finalize(); + + let mut mask = setup.j0; + setup.cipher.encrypt_block(&mut mask); + let mut tag = [0u8; 16]; + for (index, byte) in tag.iter_mut().enumerate() { + *byte = hash[index] ^ mask[index]; + } + tag +} + +fn seal( + key: &[u8], + iv: &[u8], + aad: &[u8], + tag_len: usize, + plaintext: &[u8], +) -> Result, GcmError> +where + Cipher: BlockCipherEncrypt + BlockSizeUser + KeyInit + Clone, +{ + let setup = setup::(key, iv)?; + let mut out = plaintext.to_vec(); + keystream(&setup, &mut out); + let tag = full_tag(&setup, aad, &out); + out.extend_from_slice(&tag[..tag_len]); + Ok(out) +} + +fn open( + key: &[u8], + iv: &[u8], + aad: &[u8], + tag_len: usize, + input: &[u8], +) -> Result, GcmError> +where + Cipher: BlockCipherEncrypt + BlockSizeUser + KeyInit + Clone, +{ + let setup = setup::(key, iv)?; + if input.len() < tag_len { + return Err(GcmError::Authentication); + } + let (ciphertext, tag) = input.split_at(input.len() - tag_len); + let expected = full_tag(&setup, aad, ciphertext); + if !bool::from(expected[..tag_len].ct_eq(tag)) { + return Err(GcmError::Authentication); + } + let mut out = ciphertext.to_vec(); + keystream(&setup, &mut out); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hex(text: &str) -> Vec { + (0..text.len()) + .step_by(2) + .map(|index| u8::from_str_radix(&text[index..index + 2], 16).unwrap()) + .collect() + } + + // Test cases 4 and 6 from the GCM specification (McGrew and Viega), AES-128. + const KEY: &str = "feffe9928665731c6d6a8f9467308308"; + const PLAINTEXT: &str = "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39"; + const AAD: &str = "feedfacedeadbeeffeedfacedeadbeefabaddad2"; + + #[test] + fn test_case_4_96_bit_iv() { + let out = encrypt( + &hex(KEY), + &hex("cafebabefacedbaddecaf888"), + &hex(AAD), + 16, + &hex(PLAINTEXT), + ) + .ok() + .unwrap(); + let expected = "42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e0915bc94fbc3221a5db94fae95ae7121a47"; + assert_eq!(out, hex(expected)); + let back = decrypt( + &hex(KEY), + &hex("cafebabefacedbaddecaf888"), + &hex(AAD), + 16, + &out, + ) + .ok() + .unwrap(); + assert_eq!(back, hex(PLAINTEXT)); + } + + #[test] + fn test_case_6_long_iv() { + let iv = "9313225df88406e555909c5aff5269aa6a7a9538534f7da1e4c303d2a318a728c3c0c95156809539fcf0e2429a6b525416aedbf5a0de6a57a637b39b"; + let out = encrypt(&hex(KEY), &hex(iv), &hex(AAD), 16, &hex(PLAINTEXT)) + .ok() + .unwrap(); + let expected = "8ce24998625615b603a033aca13fb894be9112a5c3a211a8ba262a3cca7e2ca701e4a9a4fba43c90ccdcb281d48c7c6fd62875d2aca417034c34aee5619cc5aefffe0bfa462af43c1699d050"; + assert_eq!(out, hex(expected)); + let back = decrypt(&hex(KEY), &hex(iv), &hex(AAD), 16, &out) + .ok() + .unwrap(); + assert_eq!(back, hex(PLAINTEXT)); + } + + #[test] + fn truncated_tag_and_tamper() { + let iv = hex("cafebabefacedbaddecaf888"); + let out = encrypt(&hex(KEY), &iv, &hex(AAD), 4, &hex(PLAINTEXT)) + .ok() + .unwrap(); + assert_eq!(&out[out.len() - 4..], &hex("5bc94fbc")[..]); + let mut bad = out.clone(); + bad[0] ^= 1; + assert!(decrypt(&hex(KEY), &iv, &hex(AAD), 4, &bad).is_err()); + } +} diff --git a/packages/jco-std/crates/wintertc-crypto/src/lib.rs b/packages/jco-std/crates/wintertc-crypto/src/lib.rs new file mode 100644 index 0000000000..c980fb7b9a --- /dev/null +++ b/packages/jco-std/crates/wintertc-crypto/src/lib.rs @@ -0,0 +1,410 @@ +//! The `jco:wintertc/crypto` component: Web Crypto primitives over RustCrypto crates. +//! +//! Key material stays in a table inside the component, addressed by `u32` handles. The component +//! has no randomness source of its own; key generation takes a random seed from the caller and +//! expands it with ChaCha20. + +mod gcm; +mod material; + +wit_bindgen::generate!({ + path: "../../wit/wintertc-0.1.0", + world: "wintertc-crypto", +}); + +use std::collections::BTreeMap; +use std::sync::{Mutex, PoisonError}; + +use exports::jco::wintertc::crypto::{ + BytesOutcome, Guest, JwkMaterial as WitJwk, JwkOutcome, KeyInfo, KeyOutcome, VerifyOutcome, +}; +use material::{Curve, Error, Hash, JwkMaterial, KeyType, Material}; + +struct Component; + +export!(Component); + +/// A key in the table. +struct Entry { + material: Material, + extractable: bool, +} + +impl Entry { + /// Whether the material may leave the component. + fn may_export(&self) -> bool { + self.extractable || self.material.key_type() == KeyType::Public + } +} + +/// The live keys, by handle. +struct Table { + keys: BTreeMap, + next: u32, +} + +/// The instance's state. Not `thread_local!`: on wasm32-wasip3 thread-local storage belongs to the +/// current task, so it would be lost between export calls. +static TABLE: Mutex = Mutex::new(Table { + keys: BTreeMap::new(), + next: 1, +}); + +/// Run `f` on the instance's state. +fn with_table(action: impl FnOnce(&mut Table) -> Output) -> Output { + action(&mut TABLE.lock().unwrap_or_else(PoisonError::into_inner)) +} + +/// Store a key and return its handle. +fn insert(material: Material, extractable: bool) -> u32 { + with_table(|table| { + // Handles are never 0 and never reused while live. + let mut handle = table.next; + while handle == 0 || table.keys.contains_key(&handle) { + handle = handle.wrapping_add(1); + } + table.next = handle.wrapping_add(1); + table.keys.insert( + handle, + Entry { + material, + extractable, + }, + ); + handle + }) +} + +/// Run `f` on the key behind `handle`. +fn with_key( + handle: u32, + action: impl FnOnce(&Entry) -> Result, +) -> Result { + with_table(|table| match table.keys.get(&handle) { + Some(entry) => action(entry), + None => Err(Error { + name: "InvalidAccessError", + message: "unknown key handle".to_owned(), + }), + }) +} + +/// Run `f` on the materials behind two handles. +fn with_keys( + first: u32, + second: u32, + action: impl FnOnce(&Material, &Material) -> Result, +) -> Result { + with_table( + |table| match (table.keys.get(&first), table.keys.get(&second)) { + (Some(first_entry), Some(second_entry)) => { + action(&first_entry.material, &second_entry.material) + } + _ => Err(Error { + name: "InvalidAccessError", + message: "unknown key handle".to_owned(), + }), + }, + ) +} + +fn bytes(result: Result, Error>) -> BytesOutcome { + match result { + Ok(value) => BytesOutcome { + ok: true, + value, + error_name: String::new(), + message: String::new(), + }, + Err(err) => BytesOutcome { + ok: false, + value: Vec::new(), + error_name: err.name.to_owned(), + message: err.message, + }, + } +} + +fn verified(result: Result) -> VerifyOutcome { + match result { + Ok(valid) => VerifyOutcome { + ok: true, + valid, + error_name: String::new(), + message: String::new(), + }, + Err(err) => VerifyOutcome { + ok: false, + valid: false, + error_name: err.name.to_owned(), + message: err.message, + }, + } +} + +/// Store a new key, or report why it couldn't be created. +fn key(result: Result, extractable: bool) -> KeyOutcome { + match result { + Ok(material) => KeyOutcome { + ok: true, + handle: insert(material, extractable), + error_name: String::new(), + message: String::new(), + }, + Err(err) => KeyOutcome { + ok: false, + handle: 0, + error_name: err.name.to_owned(), + message: err.message, + }, + } +} + +/// A non-empty string as a present JWK member. +fn member(text: String) -> Option { + if text.is_empty() { None } else { Some(text) } +} + +impl Guest for Component { + fn digest(hash: String, data: Vec) -> BytesOutcome { + bytes(Hash::parse(&hash).map(|hash| material::digest(hash, &data))) + } + + fn import_secret(material: Vec, extractable: bool) -> KeyOutcome { + key(Ok(Material::secret(material)), extractable) + } + + fn generate_secret(length_bits: u32, seed: Vec, extractable: bool) -> KeyOutcome { + key(Material::generate_secret(length_bits, &seed), extractable) + } + + fn generate_private(curve: String, seed: Vec, extractable: bool) -> KeyOutcome { + key( + Curve::parse(&curve).and_then(|curve| Material::generate_private(curve, &seed)), + extractable, + ) + } + + fn import_public_raw(curve: String, material: Vec) -> KeyOutcome { + key( + Curve::parse(&curve).and_then(|curve| Material::import_public_raw(curve, &material)), + true, + ) + } + + fn import_jwk(curve: String, material: WitJwk, private: bool, extractable: bool) -> KeyOutcome { + let curve = if curve.is_empty() { + Ok(None) + } else { + Curve::parse(&curve).map(Some) + }; + // Absent members arrive as empty strings; `d` is present exactly when `private` is set. + let jwk = JwkMaterial { + k: Some(material.k), + x: member(material.x), + y: member(material.y), + d: if private { Some(material.d) } else { None }, + }; + let is_secret = matches!(curve, Ok(None)); + let extractable = extractable || !(private || is_secret); + key( + curve.and_then(|curve| Material::import_jwk(curve, &jwk)), + extractable, + ) + } + + fn public_key(handle: u32) -> KeyOutcome { + let public = with_key(handle, |entry| { + entry.material.public_key().ok_or(Error { + name: "InvalidAccessError", + message: "key is not a private key".to_owned(), + }) + }); + key(public, true) + } + + fn describe_key(handle: u32) -> KeyInfo { + let info = with_key(handle, |entry| { + Ok(KeyInfo { + key_type: entry.material.key_type().name().to_owned(), + curve: entry + .material + .curve() + .map(Curve::name) + .unwrap_or_default() + .to_owned(), + length_bits: entry.material.length_bits(), + extractable: entry.extractable, + }) + }); + info.unwrap_or(KeyInfo { + key_type: String::new(), + curve: String::new(), + length_bits: 0, + extractable: false, + }) + } + + fn free_key(handle: u32) { + with_table(|table| table.keys.remove(&handle)); + } + + fn export_raw(handle: u32) -> BytesOutcome { + bytes(with_key(handle, |entry| { + if !entry.may_export() { + return Err(Error { + name: "InvalidAccessError", + message: "key is not extractable".to_owned(), + }); + } + entry.material.export_raw().ok_or(Error { + name: "InvalidAccessError", + message: "key cannot be exported as raw".to_owned(), + }) + })) + } + + fn export_jwk(handle: u32) -> JwkOutcome { + let result = with_key(handle, |entry| { + if !entry.may_export() { + return Err(Error { + name: "InvalidAccessError", + message: "key is not extractable".to_owned(), + }); + } + Ok(entry.material.export_jwk()) + }); + match result { + Ok(jwk) => JwkOutcome { + ok: true, + material: WitJwk { + k: jwk.k.unwrap_or_default(), + x: jwk.x.unwrap_or_default(), + y: jwk.y.unwrap_or_default(), + d: jwk.d.unwrap_or_default(), + }, + error_name: String::new(), + message: String::new(), + }, + Err(err) => JwkOutcome { + ok: false, + material: WitJwk { + k: String::new(), + x: String::new(), + y: String::new(), + d: String::new(), + }, + error_name: err.name.to_owned(), + message: err.message, + }, + } + } + + fn hmac_sign(handle: u32, hash: String, data: Vec) -> BytesOutcome { + bytes(with_key(handle, |entry| { + entry.material.hmac(Hash::parse(&hash)?, &data) + })) + } + + fn hmac_verify(handle: u32, hash: String, data: Vec, signature: Vec) -> VerifyOutcome { + verified(with_key(handle, |entry| { + entry + .material + .hmac_verify(Hash::parse(&hash)?, &data, &signature) + })) + } + + fn hkdf_derive( + handle: u32, + hash: String, + salt: Vec, + info: Vec, + length_bits: u32, + ) -> BytesOutcome { + bytes(with_key(handle, |entry| { + entry + .material + .hkdf(Hash::parse(&hash)?, &salt, &info, length_bits) + })) + } + + fn pbkdf2_derive( + handle: u32, + hash: String, + salt: Vec, + iterations: u32, + length_bits: u32, + ) -> BytesOutcome { + bytes(with_key(handle, |entry| { + entry + .material + .pbkdf2(Hash::parse(&hash)?, &salt, iterations, length_bits) + })) + } + + fn aes_gcm_encrypt( + handle: u32, + iv: Vec, + additional_data: Vec, + tag_length_bits: u32, + plaintext: Vec, + ) -> BytesOutcome { + bytes(with_key(handle, |entry| { + entry + .material + .aes_gcm(true, &iv, &additional_data, tag_length_bits, &plaintext) + })) + } + + fn aes_gcm_decrypt( + handle: u32, + iv: Vec, + additional_data: Vec, + tag_length_bits: u32, + ciphertext: Vec, + ) -> BytesOutcome { + bytes(with_key(handle, |entry| { + entry + .material + .aes_gcm(false, &iv, &additional_data, tag_length_bits, &ciphertext) + })) + } + + fn ecdsa_sign(handle: u32, hash: String, data: Vec) -> BytesOutcome { + bytes(with_key(handle, |entry| { + entry.material.ecdsa_sign(Hash::parse(&hash)?, &data) + })) + } + + fn ecdsa_verify(handle: u32, hash: String, data: Vec, signature: Vec) -> VerifyOutcome { + verified(with_key(handle, |entry| { + entry + .material + .ecdsa_verify(Hash::parse(&hash)?, &data, &signature) + })) + } + + fn ed25519_sign(handle: u32, data: Vec) -> BytesOutcome { + bytes(with_key(handle, |entry| entry.material.ed25519_sign(&data))) + } + + fn ed25519_verify(handle: u32, data: Vec, signature: Vec) -> VerifyOutcome { + verified(with_key(handle, |entry| { + entry.material.ed25519_verify(&data, &signature) + })) + } + + fn x25519_derive( + private_handle: u32, + public_handle: u32, + truncate: bool, + length_bits: u32, + ) -> BytesOutcome { + let length = if truncate { Some(length_bits) } else { None }; + bytes(with_keys( + private_handle, + public_handle, + |private, public| private.x25519(public, length), + )) + } +} diff --git a/packages/jco-std/crates/wintertc-crypto/src/material.rs b/packages/jco-std/crates/wintertc-crypto/src/material.rs new file mode 100644 index 0000000000..86e90a9057 --- /dev/null +++ b/packages/jco-std/crates/wintertc-crypto/src/material.rs @@ -0,0 +1,652 @@ +//! Key material and the operations on it. + +use base64ct::{Base64UrlUnpadded, Encoding}; +use hmac::{Hmac, KeyInit, Mac}; +use rand_chacha::ChaCha20Rng; +use rand_chacha::rand_core::{Rng, SeedableRng}; +use sha1::Sha1; +use sha2::{Digest, Sha256, Sha384, Sha512}; +use subtle::ConstantTimeEq; +use zeroize::Zeroizing; + +use crate::gcm; + +/// A failed operation: the `DOMException` name and a message. +#[derive(Debug)] +pub struct Error { + pub name: &'static str, + pub message: String, +} + +/// Build an error named `name`. +fn error(name: &'static str, message: &str) -> Error { + Error { + name, + message: message.to_owned(), + } +} + +/// A hash function. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Hash { + Sha1, + Sha256, + Sha384, + Sha512, +} + +impl Hash { + /// Parse a Web Crypto hash name. + pub fn parse(name: &str) -> Result { + match name { + "SHA-1" => Ok(Hash::Sha1), + "SHA-256" => Ok(Hash::Sha256), + "SHA-384" => Ok(Hash::Sha384), + "SHA-512" => Ok(Hash::Sha512), + _ => Err(error( + "NotSupportedError", + &format!("unsupported hash \"{name}\""), + )), + } + } +} + +/// The curve of an asymmetric key. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Curve { + P256, + P384, + Ed25519, + X25519, +} + +impl Curve { + /// Parse a curve name. + pub fn parse(name: &str) -> Result { + match name { + "P-256" => Ok(Curve::P256), + "P-384" => Ok(Curve::P384), + "Ed25519" => Ok(Curve::Ed25519), + "X25519" => Ok(Curve::X25519), + _ => Err(error( + "NotSupportedError", + &format!("unsupported curve \"{name}\""), + )), + } + } + + /// The curve's name. + pub fn name(self) -> &'static str { + match self { + Curve::P256 => "P-256", + Curve::P384 => "P-384", + Curve::Ed25519 => "Ed25519", + Curve::X25519 => "X25519", + } + } +} + +/// What a key holds. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum KeyType { + Secret, + Private, + Public, +} + +impl KeyType { + /// The Web Crypto name of the key type. + pub fn name(self) -> &'static str { + match self { + KeyType::Secret => "secret", + KeyType::Private => "private", + KeyType::Public => "public", + } + } +} + +/// The key-material members of a JSON Web Key; `None` for absent members. +#[derive(Default)] +pub struct JwkMaterial { + pub k: Option, + pub x: Option, + pub y: Option, + pub d: Option, +} + +/// What a `key` resource holds. +pub enum Material { + Secret(Zeroizing>), + P256Private(p256::SecretKey), + P256Public(p256::PublicKey), + P384Private(p384::SecretKey), + P384Public(p384::PublicKey), + Ed25519Private(ed25519_dalek::SigningKey), + /// Ed25519 public keys are checked when used, as the Web Cryptography API specifies, so any + /// 32 bytes can be imported. + Ed25519Public([u8; 32]), + X25519Private(x25519_dalek::StaticSecret), + X25519Public(x25519_dalek::PublicKey), +} + +/// The digest of `data` with `hash`. +pub fn digest(hash: Hash, data: &[u8]) -> Vec { + match hash { + Hash::Sha1 => Sha1::digest(data).to_vec(), + Hash::Sha256 => Sha256::digest(data).to_vec(), + Hash::Sha384 => Sha384::digest(data).to_vec(), + Hash::Sha512 => Sha512::digest(data).to_vec(), + } +} + +/// A `DataError`. +fn data_error(message: &str) -> Error { + error("DataError", message) +} + +/// An `OperationError`. +fn operation_error(message: &str) -> Error { + error("OperationError", message) +} + +/// An `InvalidAccessError` for a key used with the wrong algorithm. +fn wrong_key() -> Error { + error("InvalidAccessError", "key does not support this operation") +} + +/// Decode a base64url JWK member. +fn decode(member: &Option, name: &str) -> Result>, Error> { + let Some(text) = member else { + return Err(data_error(&format!("JWK member \"{name}\" is missing"))); + }; + Base64UrlUnpadded::decode_vec(text) + .map(Zeroizing::new) + .map_err(|_| data_error(&format!("JWK member \"{name}\" is not valid base64url"))) +} + +/// Decode a base64url JWK member of exactly `length` bytes. +fn decode_exact( + member: &Option, + name: &str, + length: usize, +) -> Result>, Error> { + let bytes = decode(member, name)?; + if bytes.len() != length { + return Err(data_error(&format!( + "JWK member \"{name}\" must be {length} bytes" + ))); + } + Ok(bytes) +} + +/// Encode bytes as a base64url JWK member. +fn encode(bytes: &[u8]) -> Option { + Some(Base64UrlUnpadded::encode_string(bytes)) +} + +/// A ChaCha20 generator seeded from the caller's random bytes. +fn generator(seed: &[u8]) -> Result { + let Some(seed) = seed.get(..32) else { + return Err(operation_error("seed must be at least 32 bytes")); + }; + let mut array = Zeroizing::new([0u8; 32]); + array.copy_from_slice(seed); + Ok(ChaCha20Rng::from_seed(*array)) +} + +/// Draw 32 random bytes. +fn random_32(rng: &mut ChaCha20Rng) -> Zeroizing<[u8; 32]> { + let mut bytes = Zeroizing::new([0u8; 32]); + rng.fill_bytes(bytes.as_mut_slice()); + bytes +} + +/// Convert a digest to the integer ECDSA signs: shorter digests are left-padded with zeros so the +/// `ecdsa` crate accepts them (the integer value is unchanged); longer ones are truncated by it. +fn ecdsa_prehash(hash: Hash, data: &[u8], field_size: usize) -> Vec { + let digest = digest(hash, data); + if digest.len() >= field_size { + return digest; + } + let mut padded = vec![0u8; field_size - digest.len()]; + padded.extend_from_slice(&digest); + padded +} + +/// Implement the per-curve EC operations for one NIST curve module. +macro_rules! nist_curve { + ($module:ident, $krate:ident, $size:expr) => { + mod $module { + use super::*; + use ::$krate::ecdsa::signature::hazmat::{PrehashSigner, PrehashVerifier}; + use ::$krate::ecdsa::{Signature, SigningKey, VerifyingKey}; + use ::$krate::elliptic_curve::sec1::ToSec1Point; + use ::$krate::{PublicKey, SecretKey}; + + pub const SIZE: usize = $size; + + /// A random private key. + pub fn generate(rng: &mut ChaCha20Rng) -> SecretKey { + loop { + let mut bytes = Zeroizing::new([0u8; $size]); + rng.fill_bytes(bytes.as_mut_slice()); + if let Ok(secret) = SecretKey::from_slice(bytes.as_slice()) { + return secret; + } + } + } + + /// The uncompressed SEC1 point of a public key. + pub fn uncompressed(public: &PublicKey) -> Vec { + public.to_sec1_point(false).as_bytes().to_vec() + } + + /// A public key from SEC1 bytes, compressed or not. + pub fn public_from_sec1(bytes: &[u8]) -> Result { + PublicKey::from_sec1_bytes(bytes).map_err(|_| data_error("invalid EC public key")) + } + + /// The JWK members `x`, `y` and, for a private key, `d`. + pub fn jwk(public: &PublicKey, private: Option<&SecretKey>) -> JwkMaterial { + let point = uncompressed(public); + JwkMaterial { + k: None, + x: encode(&point[1..1 + SIZE]), + y: encode(&point[1 + SIZE..]), + d: private.and_then(|secret| encode(secret.to_bytes().as_slice())), + } + } + + /// Keys from the JWK members. + pub fn from_jwk( + material: &JwkMaterial, + ) -> Result<(PublicKey, Option), Error> { + let x = decode_exact(&material.x, "x", SIZE)?; + let y = decode_exact(&material.y, "y", SIZE)?; + let mut point = Vec::with_capacity(1 + 2 * SIZE); + point.push(4); + point.extend_from_slice(&x); + point.extend_from_slice(&y); + let public = public_from_sec1(&point)?; + if material.d.is_none() { + return Ok((public, None)); + } + let d = decode_exact(&material.d, "d", SIZE)?; + let secret = + SecretKey::from_slice(&d).map_err(|_| data_error("invalid EC private key"))?; + if secret.public_key() != public { + return Err(data_error("JWK members \"x\" and \"y\" do not match \"d\"")); + } + Ok((public, Some(secret))) + } + + /// Sign the `hash` digest of `data`, returning `r || s`. + pub fn sign(secret: &SecretKey, hash: Hash, data: &[u8]) -> Result, Error> { + let signing = SigningKey::from(secret.clone()); + let signature: Signature = signing + .sign_prehash(&ecdsa_prehash(hash, data, SIZE)) + .map_err(|_| operation_error("ECDSA signing failed"))?; + Ok(signature.to_bytes().to_vec()) + } + + /// Verify an `r || s` signature; a malformed signature is simply invalid. + pub fn verify(public: &PublicKey, hash: Hash, data: &[u8], signature: &[u8]) -> bool { + let Ok(signature) = Signature::from_slice(signature) else { + return false; + }; + VerifyingKey::from(public) + .verify_prehash(&ecdsa_prehash(hash, data, SIZE), &signature) + .is_ok() + } + } + }; +} + +nist_curve!(nist_p256, p256, 32); +nist_curve!(nist_p384, p384, 48); + +/// HMAC of `data` under `key`. +fn hmac_bytes(hash: Hash, key: &[u8], data: &[u8]) -> Vec { + fn run(key: &[u8], data: &[u8]) -> Vec { + let mut mac = ::new_from_slice(key) + .expect("HMAC accepts keys of any length"); + mac.update(data); + mac.finalize().into_bytes().to_vec() + } + match hash { + Hash::Sha1 => run::>(key, data), + Hash::Sha256 => run::>(key, data), + Hash::Sha384 => run::>(key, data), + Hash::Sha512 => run::>(key, data), + } +} + +/// Check a derivation length in bits and convert it to bytes. +fn derive_length(length_bits: u32) -> Result { + if !length_bits.is_multiple_of(8) { + return Err(operation_error("length must be a multiple of 8")); + } + Ok((length_bits / 8) as usize) +} + +impl Material { + /// A secret key holding `bytes`. + pub fn secret(bytes: Vec) -> Material { + Material::Secret(Zeroizing::new(bytes)) + } + + /// A random secret key of `length_bits` bits. + pub fn generate_secret(length_bits: u32, seed: &[u8]) -> Result { + if length_bits == 0 || !length_bits.is_multiple_of(8) { + return Err(operation_error( + "key length must be a positive multiple of 8", + )); + } + let mut rng = generator(seed)?; + let mut bytes = Zeroizing::new(vec![0u8; (length_bits / 8) as usize]); + rng.fill_bytes(bytes.as_mut_slice()); + Ok(Material::Secret(bytes)) + } + + /// A random private key on `curve`. + pub fn generate_private(curve: Curve, seed: &[u8]) -> Result { + let mut rng = generator(seed)?; + Ok(match curve { + Curve::P256 => Material::P256Private(nist_p256::generate(&mut rng)), + Curve::P384 => Material::P384Private(nist_p384::generate(&mut rng)), + Curve::Ed25519 => Material::Ed25519Private(ed25519_dalek::SigningKey::from_bytes( + &random_32(&mut rng), + )), + Curve::X25519 => { + Material::X25519Private(x25519_dalek::StaticSecret::from(*random_32(&mut rng))) + } + }) + } + + /// A public key from its raw form. + pub fn import_public_raw(curve: Curve, bytes: &[u8]) -> Result { + match curve { + Curve::P256 => nist_p256::public_from_sec1(bytes).map(Material::P256Public), + Curve::P384 => nist_p384::public_from_sec1(bytes).map(Material::P384Public), + Curve::Ed25519 | Curve::X25519 => { + let array: [u8; 32] = bytes + .try_into() + .map_err(|_| data_error("public key must be 32 bytes"))?; + Ok(match curve { + Curve::Ed25519 => Material::Ed25519Public(array), + _ => Material::X25519Public(x25519_dalek::PublicKey::from(array)), + }) + } + } + } + + /// A key from JWK members. + pub fn import_jwk(curve: Option, material: &JwkMaterial) -> Result { + let Some(curve) = curve else { + let k = decode(&material.k, "k")?; + return Ok(Material::Secret(k)); + }; + match curve { + Curve::P256 => nist_p256::from_jwk(material).map(|(public, private)| match private { + Some(secret) => Material::P256Private(secret), + None => Material::P256Public(public), + }), + Curve::P384 => nist_p384::from_jwk(material).map(|(public, private)| match private { + Some(secret) => Material::P384Private(secret), + None => Material::P384Public(public), + }), + Curve::Ed25519 | Curve::X25519 => { + let x = decode_exact(&material.x, "x", 32)?; + let mut public = [0u8; 32]; + public.copy_from_slice(&x); + if material.d.is_none() { + return Material::import_public_raw(curve, &public); + } + let d = decode_exact(&material.d, "d", 32)?; + let mut seed = Zeroizing::new([0u8; 32]); + seed.copy_from_slice(&d); + let private = match curve { + Curve::Ed25519 => { + Material::Ed25519Private(ed25519_dalek::SigningKey::from_bytes(&seed)) + } + _ => Material::X25519Private(x25519_dalek::StaticSecret::from(*seed)), + }; + let derived = private.public_key().and_then(|key| key.export_raw()); + if derived.as_deref() != Some(&public[..]) { + return Err(data_error("JWK member \"x\" does not match \"d\"")); + } + Ok(private) + } + } + } + + pub fn key_type(&self) -> KeyType { + match self { + Material::Secret(_) => KeyType::Secret, + Material::P256Private(_) + | Material::P384Private(_) + | Material::Ed25519Private(_) + | Material::X25519Private(_) => KeyType::Private, + _ => KeyType::Public, + } + } + + pub fn curve(&self) -> Option { + match self { + Material::Secret(_) => None, + Material::P256Private(_) | Material::P256Public(_) => Some(Curve::P256), + Material::P384Private(_) | Material::P384Public(_) => Some(Curve::P384), + Material::Ed25519Private(_) | Material::Ed25519Public(_) => Some(Curve::Ed25519), + Material::X25519Private(_) | Material::X25519Public(_) => Some(Curve::X25519), + } + } + + pub fn length_bits(&self) -> u32 { + match self { + Material::Secret(bytes) => (bytes.len() as u32) * 8, + _ => 0, + } + } + + /// The public key of a private key. + pub fn public_key(&self) -> Option { + Some(match self { + Material::P256Private(secret) => Material::P256Public(secret.public_key()), + Material::P384Private(secret) => Material::P384Public(secret.public_key()), + Material::Ed25519Private(signing) => { + Material::Ed25519Public(signing.verifying_key().to_bytes()) + } + Material::X25519Private(secret) => { + Material::X25519Public(x25519_dalek::PublicKey::from(secret)) + } + _ => return None, + }) + } + + /// The raw export of a secret or public key. + pub fn export_raw(&self) -> Option> { + Some(match self { + Material::Secret(bytes) => bytes.to_vec(), + Material::P256Public(public) => nist_p256::uncompressed(public), + Material::P384Public(public) => nist_p384::uncompressed(public), + Material::Ed25519Public(bytes) => bytes.to_vec(), + Material::X25519Public(public) => public.as_bytes().to_vec(), + _ => return None, + }) + } + + /// The JWK key-material members. + pub fn export_jwk(&self) -> JwkMaterial { + let okp = |x: &[u8], d: Option<&[u8]>| JwkMaterial { + k: None, + x: encode(x), + y: None, + d: d.and_then(encode), + }; + match self { + Material::Secret(bytes) => JwkMaterial { + k: encode(bytes), + x: None, + y: None, + d: None, + }, + Material::P256Private(secret) => nist_p256::jwk(&secret.public_key(), Some(secret)), + Material::P256Public(public) => nist_p256::jwk(public, None), + Material::P384Private(secret) => nist_p384::jwk(&secret.public_key(), Some(secret)), + Material::P384Public(public) => nist_p384::jwk(public, None), + Material::Ed25519Private(signing) => { + okp(signing.verifying_key().as_bytes(), Some(signing.as_bytes())) + } + Material::Ed25519Public(bytes) => okp(bytes, None), + Material::X25519Private(secret) => okp( + x25519_dalek::PublicKey::from(secret).as_bytes(), + Some(secret.as_bytes()), + ), + Material::X25519Public(public) => okp(public.as_bytes(), None), + } + } + + /// The bytes of a secret key. + fn secret_bytes(&self) -> Result<&[u8], Error> { + match self { + Material::Secret(bytes) => Ok(bytes), + _ => Err(wrong_key()), + } + } + + pub fn hmac(&self, hash: Hash, data: &[u8]) -> Result, Error> { + Ok(hmac_bytes(hash, self.secret_bytes()?, data)) + } + + pub fn hmac_verify(&self, hash: Hash, data: &[u8], signature: &[u8]) -> Result { + let expected = hmac_bytes(hash, self.secret_bytes()?, data); + Ok(expected.len() == signature.len() && bool::from(expected.ct_eq(signature))) + } + + pub fn hkdf( + &self, + hash: Hash, + salt: &[u8], + info: &[u8], + length_bits: u32, + ) -> Result, Error> { + let ikm = self.secret_bytes()?; + let mut out = vec![0u8; derive_length(length_bits)?]; + let expanded = match hash { + Hash::Sha1 => hkdf::Hkdf::::new(Some(salt), ikm).expand(info, &mut out), + Hash::Sha256 => hkdf::Hkdf::::new(Some(salt), ikm).expand(info, &mut out), + Hash::Sha384 => hkdf::Hkdf::::new(Some(salt), ikm).expand(info, &mut out), + Hash::Sha512 => hkdf::Hkdf::::new(Some(salt), ikm).expand(info, &mut out), + }; + expanded.map_err(|_| operation_error("HKDF output is too long"))?; + Ok(out) + } + + pub fn pbkdf2( + &self, + hash: Hash, + salt: &[u8], + iterations: u32, + length_bits: u32, + ) -> Result, Error> { + let password = self.secret_bytes()?; + if iterations == 0 { + return Err(operation_error("iterations must not be zero")); + } + let mut out = vec![0u8; derive_length(length_bits)?]; + match hash { + Hash::Sha1 => pbkdf2::pbkdf2_hmac::(password, salt, iterations, &mut out), + Hash::Sha256 => pbkdf2::pbkdf2_hmac::(password, salt, iterations, &mut out), + Hash::Sha384 => pbkdf2::pbkdf2_hmac::(password, salt, iterations, &mut out), + Hash::Sha512 => pbkdf2::pbkdf2_hmac::(password, salt, iterations, &mut out), + } + Ok(out) + } + + pub fn aes_gcm( + &self, + encrypt: bool, + iv: &[u8], + aad: &[u8], + tag_length_bits: u32, + input: &[u8], + ) -> Result, Error> { + let key = self.secret_bytes()?; + if !matches!(tag_length_bits, 32 | 64 | 96 | 104 | 112 | 120 | 128) { + return Err(operation_error("invalid AES-GCM tag length")); + } + let tag_len = (tag_length_bits / 8) as usize; + let result = if encrypt { + gcm::encrypt(key, iv, aad, tag_len, input) + } else { + gcm::decrypt(key, iv, aad, tag_len, input) + }; + result.map_err(|failure| match failure { + gcm::GcmError::KeyLength => operation_error("AES key must be 128, 192 or 256 bits"), + gcm::GcmError::IvLength => operation_error("AES-GCM iv must not be empty"), + gcm::GcmError::Authentication => operation_error("AES-GCM decryption failed"), + }) + } + + pub fn ecdsa_sign(&self, hash: Hash, data: &[u8]) -> Result, Error> { + match self { + Material::P256Private(secret) => nist_p256::sign(secret, hash, data), + Material::P384Private(secret) => nist_p384::sign(secret, hash, data), + _ => Err(wrong_key()), + } + } + + pub fn ecdsa_verify(&self, hash: Hash, data: &[u8], signature: &[u8]) -> Result { + match self { + Material::P256Public(public) => Ok(nist_p256::verify(public, hash, data, signature)), + Material::P384Public(public) => Ok(nist_p384::verify(public, hash, data, signature)), + _ => Err(wrong_key()), + } + } + + pub fn ed25519_sign(&self, data: &[u8]) -> Result, Error> { + use ed25519_dalek::Signer; + match self { + Material::Ed25519Private(signing) => Ok(signing.sign(data).to_bytes().to_vec()), + _ => Err(wrong_key()), + } + } + + /// Verify with the strict rules the Web Cryptography API requires: small-order public keys and + /// `R` values are rejected, and the equation is cofactorless. + pub fn ed25519_verify(&self, data: &[u8], signature: &[u8]) -> Result { + let Material::Ed25519Public(public) = self else { + return Err(wrong_key()); + }; + let Ok(signature) = ed25519_dalek::Signature::from_slice(signature) else { + return Ok(false); + }; + let Ok(verifying) = ed25519_dalek::VerifyingKey::from_bytes(public) else { + return Ok(false); + }; + Ok(verifying.verify_strict(data, &signature).is_ok()) + } + + pub fn x25519(&self, public: &Material, length_bits: Option) -> Result, Error> { + let (Material::X25519Private(secret), Material::X25519Public(public)) = (self, public) + else { + return Err(wrong_key()); + }; + let shared = secret.diffie_hellman(public); + if shared.as_bytes().iter().all(|byte| *byte == 0) { + return Err(operation_error("X25519 shared secret is all zeros")); + } + let Some(length_bits) = length_bits else { + return Ok(shared.as_bytes().to_vec()); + }; + if length_bits > 256 { + return Err(operation_error("length is longer than the shared secret")); + } + let mut out = shared.as_bytes()[..length_bits.div_ceil(8) as usize].to_vec(); + let spare = (8 - length_bits % 8) % 8; + if let Some(last) = out.last_mut() { + *last &= 0xffu8 << spare; + } + Ok(out) + } +} diff --git a/packages/jco-std/crates/wintertc-encoding/Cargo.toml b/packages/jco-std/crates/wintertc-encoding/Cargo.toml new file mode 100644 index 0000000000..05b28f5634 --- /dev/null +++ b/packages/jco-std/crates/wintertc-encoding/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "wintertc-encoding" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true + +[lib] +crate-type = ["cdylib"] + +[dependencies] +encoding_rs = "0.8" +wit-bindgen.workspace = true diff --git a/packages/jco-std/crates/wintertc-encoding/src/lib.rs b/packages/jco-std/crates/wintertc-encoding/src/lib.rs new file mode 100644 index 0000000000..13e09b60f4 --- /dev/null +++ b/packages/jco-std/crates/wintertc-encoding/src/lib.rs @@ -0,0 +1,145 @@ +//! The `jco:wintertc/encoding` component: decoders for every WHATWG encoding, using Firefox's +//! `encoding_rs`, for `TextDecoder` with encodings other than UTF-8. +//! +//! A decoder's state is kept here only between the chunks of a streaming decode, under a handle; +//! a one-shot decode allocates nothing that outlives the call. + +use std::collections::HashMap; +use std::sync::{LazyLock, Mutex, PoisonError}; + +use encoding_rs::{DecoderResult, Encoding, REPLACEMENT}; + +wit_bindgen::generate!({ + path: "../../wit/wintertc-0.1.0", + world: "wintertc-encoding", +}); + +use exports::jco::wintertc::encoding::{Decoded, Guest}; + +struct Component; + +export!(Component); + +/// Resolve `label` to an encoding a `TextDecoder` may use: `None` for unknown labels and for the +/// `replacement` encoding. +fn lookup(label: &str) -> Option<&'static Encoding> { + Encoding::for_label(label.as_bytes()).filter(|encoding| *encoding != REPLACEMENT) +} + +/// A decoder in the middle of a stream. +struct Stream { + decoder: encoding_rs::Decoder, + fatal: bool, +} + +/// Streams by handle, and the next handle to try. +#[derive(Default)] +struct Table { + streams: HashMap, + next: u32, +} + +impl Table { + /// Store `stream` under a fresh, nonzero handle. + fn insert(&mut self, stream: Stream) -> u32 { + loop { + self.next = self.next.wrapping_add(1); + if self.next != 0 && !self.streams.contains_key(&self.next) { + self.streams.insert(self.next, stream); + return self.next; + } + } + } +} + +/// The instance's state. Not `thread_local!`: on wasm32-wasip3 thread-local storage belongs to the +/// current task, so it would be lost between export calls. +static TABLE: LazyLock> = LazyLock::new(Mutex::default); + +/// Run `f` on the instance's state. +fn with_table(action: impl FnOnce(&mut Table) -> Output) -> Output { + action(&mut TABLE.lock().unwrap_or_else(PoisonError::into_inner)) +} + +/// A failed decode, which also ends the stream. +fn failure() -> Decoded { + Decoded { + ok: false, + text: String::new(), + handle: 0, + } +} + +/// Decode `input` with `stream`'s decoder. Returns `None` on malformed input when fatal. +fn decode_chunk(stream: &mut Stream, input: &[u8], last: bool) -> Option { + let decoder = &mut stream.decoder; + if stream.fatal { + // Size the output for the worst case, so one call decodes the whole chunk. + let capacity = decoder.max_utf8_buffer_length_without_replacement(input.len())?; + let mut output = String::with_capacity(capacity); + let (result, _read) = + decoder.decode_to_string_without_replacement(input, &mut output, last); + match result { + DecoderResult::InputEmpty => Some(output), + DecoderResult::Malformed(_, _) | DecoderResult::OutputFull => None, + } + } else { + let capacity = decoder.max_utf8_buffer_length(input.len())?; + let mut output = String::with_capacity(capacity); + let (_result, _read, _replaced) = decoder.decode_to_string(input, &mut output, last); + Some(output) + } +} + +impl Guest for Component { + fn lookup(label: String) -> String { + lookup(&label) + .map(|encoding| encoding.name().to_ascii_lowercase()) + .unwrap_or_default() + } + + fn decode( + encoding: String, + fatal: bool, + ignore_bom: bool, + handle: u32, + input: Vec, + more: bool, + ) -> Decoded { + // Continue the stream behind `handle`, or start a new one. + let mut stream = if handle == 0 { + let Some(encoding) = lookup(&encoding) else { + return failure(); + }; + let decoder = if ignore_bom { + encoding.new_decoder_without_bom_handling() + } else { + encoding.new_decoder_with_bom_removal() + }; + Stream { decoder, fatal } + } else { + match with_table(|table| table.streams.remove(&handle)) { + Some(stream) => stream, + None => return failure(), + } + }; + + let Some(text) = decode_chunk(&mut stream, &input, !more) else { + return failure(); + }; + let handle = if more { + with_table(|table| table.insert(stream)) + } else { + 0 + }; + Decoded { + ok: true, + text, + handle, + } + } + + fn free(handle: u32) { + with_table(|table| table.streams.remove(&handle)); + } +} diff --git a/packages/jco-std/crates/wintertc-url/Cargo.toml b/packages/jco-std/crates/wintertc-url/Cargo.toml new file mode 100644 index 0000000000..89942b0223 --- /dev/null +++ b/packages/jco-std/crates/wintertc-url/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "wintertc-url" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true + +[lib] +crate-type = ["cdylib"] + +[dependencies] +url = "2.5.9" +wit-bindgen.workspace = true diff --git a/packages/jco-std/crates/wintertc-url/src/lib.rs b/packages/jco-std/crates/wintertc-url/src/lib.rs new file mode 100644 index 0000000000..88bfc72f88 --- /dev/null +++ b/packages/jco-std/crates/wintertc-url/src/lib.rs @@ -0,0 +1,104 @@ +//! The `jco:wintertc/url` component: WHATWG URL parsing, setters and serialization, using +//! Servo's `url` crate (and its `idna` dependency for domain names). + +use url::{Url, quirks}; + +wit_bindgen::generate!({ + path: "../../wit/wintertc-0.1.0", + world: "wintertc-url", +}); + +use exports::jco::wintertc::url::{Guest, UrlRecord}; + +struct Component; + +export!(Component); + +/// Read every attribute of `url` the way the `URL` getters return them. +fn record(url: &Url) -> UrlRecord { + UrlRecord { + ok: true, + href: quirks::href(url).to_owned(), + origin: quirks::origin(url), + protocol: quirks::protocol(url).to_owned(), + username: quirks::username(url).to_owned(), + password: quirks::password(url).to_owned(), + host: quirks::host(url).to_owned(), + hostname: quirks::hostname(url).to_owned(), + port: quirks::port(url).to_owned(), + pathname: quirks::pathname(url).to_owned(), + search: quirks::search(url).to_owned(), + hash: quirks::hash(url).to_owned(), + } +} + +/// The record of a failed parse or setter. +fn failure() -> UrlRecord { + UrlRecord { + ok: false, + href: String::new(), + origin: String::new(), + protocol: String::new(), + username: String::new(), + password: String::new(), + host: String::new(), + hostname: String::new(), + port: String::new(), + pathname: String::new(), + search: String::new(), + hash: String::new(), + } +} + +/// Run the basic URL parser on `input` against an optional `base`. +fn parse(input: &str, base: Option<&str>) -> Option { + let base = match base { + Some(base) => Some(Url::parse(base).ok()?), + None => None, + }; + Url::options().base_url(base.as_ref()).parse(input).ok() +} + +/// Run the setter for `attribute`. Returns `None` if `attribute` is unknown, or it is `href` and +/// `value` is not a valid URL. +fn set(url: &mut Url, attribute: &str, value: &str) -> Option<()> { + // Only the href setter reports failure; the others leave the URL unchanged when the new value + // is invalid, so their `Err(())` results are deliberately ignored. + match attribute { + "href" => quirks::set_href(url, value).ok()?, + "protocol" => quirks::set_protocol(url, value).unwrap_or(()), + "username" => quirks::set_username(url, value).unwrap_or(()), + "password" => quirks::set_password(url, value).unwrap_or(()), + "host" => quirks::set_host(url, value).unwrap_or(()), + "hostname" => quirks::set_hostname(url, value).unwrap_or(()), + "port" => quirks::set_port(url, value).unwrap_or(()), + "pathname" => quirks::set_pathname(url, value), + "search" => quirks::set_search(url, value), + "hash" => quirks::set_hash(url, value), + _ => return None, + } + Some(()) +} + +impl Guest for Component { + fn parse(input: String, has_base: bool, base: String) -> UrlRecord { + match parse(&input, has_base.then_some(base.as_str())) { + Some(url) => record(&url), + None => failure(), + } + } + + fn can_parse(input: String, has_base: bool, base: String) -> bool { + parse(&input, has_base.then_some(base.as_str())).is_some() + } + + fn set(href: String, attribute: String, value: String) -> UrlRecord { + let Ok(mut url) = Url::parse(&href) else { + return failure(); + }; + match set(&mut url, &attribute, &value) { + Some(()) => record(&url), + None => failure(), + } + } +} diff --git a/packages/jco-std/crates/wintertc-urlpattern/Cargo.toml b/packages/jco-std/crates/wintertc-urlpattern/Cargo.toml new file mode 100644 index 0000000000..bf7db9f5c0 --- /dev/null +++ b/packages/jco-std/crates/wintertc-urlpattern/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "wintertc-urlpattern" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true + +[lib] +crate-type = ["cdylib"] + +[dependencies] +regex = "1" +urlpattern = "0.6" +wit-bindgen.workspace = true diff --git a/packages/jco-std/crates/wintertc-urlpattern/src/lib.rs b/packages/jco-std/crates/wintertc-urlpattern/src/lib.rs new file mode 100644 index 0000000000..123c2ce632 --- /dev/null +++ b/packages/jco-std/crates/wintertc-urlpattern/src/lib.rs @@ -0,0 +1,266 @@ +//! The `jco:wintertc/urlpattern` component: the URLPattern standard, using Deno's `urlpattern` +//! crate. +//! +//! Regular expression groups compile with the Rust `regex` crate, so they follow its syntax and +//! semantics rather than ECMAScript's (no lookaround, no backreferences). + +use std::borrow::Cow; +use std::sync::{Arc, Mutex, PoisonError}; + +use urlpattern::quirks::{self, StringOrInit}; +use urlpattern::regexp::RegExp; +use urlpattern::{RegexSyntax, UrlPattern, UrlPatternComponentResult, UrlPatternOptions}; + +wit_bindgen::generate!({ + path: "../../wit/wintertc-0.1.0", + world: "wintertc-urlpattern", +}); + +use exports::jco::wintertc::urlpattern::{Compiled, ComponentResult, Group, Guest, Input, Matched}; + +struct Component; + +export!(Component); + +/// A Rust `regex` that honours the `i` flag, which `urlpattern`'s own `regex::Regex` support +/// ignores (it would make `ignoreCase` patterns match case-sensitively). +#[derive(Debug)] +struct Regex(regex::Regex); + +impl RegExp for Regex { + fn syntax() -> RegexSyntax { + RegexSyntax::Rust + } + + fn parse(pattern: &str, flags: &str, _force_eval: bool) -> Result { + regex::RegexBuilder::new(pattern) + .case_insensitive(flags.contains('i')) + .build() + .map(Regex) + .map_err(|_| ()) + } + + fn matches<'a>(&self, text: &'a str) -> Option>> { + let captures = self.0.captures(text)?; + Some( + captures + .iter() + .skip(1) + .map(|group| group.map(|matched| matched.as_str())) + .collect(), + ) + } + + fn pattern_string(&self) -> &str { + self.0.as_str() + } +} + +/// Convert a WIT `input` to the crate's string-or-dictionary input and base URL. +fn input(input: &Input) -> (StringOrInit<'static>, Option) { + let base = input.has_base.then(|| input.base.clone()); + if !input.is_init { + return (StringOrInit::String(Cow::Owned(input.text.clone())), base); + } + let mut init = quirks::UrlPatternInit::default(); + for member in &input.members { + let value = Some(member.value.clone()); + match member.name.as_str() { + "protocol" => init.protocol = value, + "username" => init.username = value, + "password" => init.password = value, + "hostname" => init.hostname = value, + "port" => init.port = value, + "pathname" => init.pathname = value, + "search" => init.search = value, + "hash" => init.hash = value, + "base-url" => init.base_url = value, + _ => {} + } + } + (StringOrInit::Init(init), base) +} + +/// A cache key identifying a pattern's constructor arguments. +fn cache_key(pattern: &Input, ignore_case: bool) -> String { + // Length-prefixed fields, so different arguments never produce the same key. + let mut key = String::new(); + let mut field = |text: &str| { + key.push_str(&text.len().to_string()); + key.push(':'); + key.push_str(text); + }; + field(if ignore_case { "i" } else { "" }); + field(if pattern.is_init { "init" } else { "text" }); + field(&pattern.text); + for member in &pattern.members { + field(&member.name); + field(&member.value); + } + field(if pattern.has_base { "base" } else { "" }); + field(&pattern.base); + key +} + +/// How many compiled patterns to keep. +const CACHE_SIZE: usize = 64; + +/// Recently compiled patterns, most recently used last. Not `thread_local!`: on wasm32-wasip3 +/// thread-local storage belongs to the current task, so the cache would be empty on every call. +static CACHE: Mutex>)>> = Mutex::new(Vec::new()); + +/// Run `f` on the pattern cache. +fn with_cache( + action: impl FnOnce(&mut Vec<(String, Arc>)>) -> Output, +) -> Output { + action(&mut CACHE.lock().unwrap_or_else(PoisonError::into_inner)) +} + +/// Compile `pattern`, or take it from the cache. +fn compile(pattern: &Input, ignore_case: bool) -> Result>, String> { + let key = cache_key(pattern, ignore_case); + let cached = with_cache(|cache| { + let index = cache.iter().position(|(cached, _)| *cached == key)?; + let entry = cache.remove(index); + let compiled = entry.1.clone(); + cache.push(entry); + Some(compiled) + }); + if let Some(compiled) = cached { + return Ok(compiled); + } + + let (pattern, base) = input(pattern); + let compiled = quirks::process_construct_pattern_input(pattern, base.as_deref()) + .and_then(|init| { + UrlPattern::::parse( + init, + UrlPatternOptions { + regex_syntax: RegexSyntax::Rust, + ignore_case, + }, + ) + }) + .map_err(|error| error.to_string())?; + let compiled = Arc::new(compiled); + with_cache(|cache| { + if cache.len() >= CACHE_SIZE { + cache.remove(0); + } + cache.push((key, compiled.clone())); + }); + Ok(compiled) +} + +/// Convert one component's match, listing groups in the pattern's order. +fn component_result( + component: &urlpattern::component::Component, + mut result: UrlPatternComponentResult, +) -> ComponentResult { + let groups = component + .group_name_list + .iter() + .map(|name| { + let value = result.groups.remove(name).flatten(); + Group { + name: name.clone(), + matched: value.is_some(), + value: value.unwrap_or_default(), + } + }) + .collect(); + ComponentResult { + input: result.input, + groups, + } +} + +/// An empty component result, for failures and non-matches. +fn empty() -> ComponentResult { + ComponentResult { + input: String::new(), + groups: Vec::new(), + } +} + +/// A `matched` record with no match. +fn no_match(ok: bool, error: String) -> Matched { + Matched { + ok, + error, + found: false, + protocol: empty(), + username: empty(), + password: empty(), + hostname: empty(), + port: empty(), + pathname: empty(), + search: empty(), + hash: empty(), + } +} + +impl Guest for Component { + fn compile(pattern: Input, ignore_case: bool) -> Compiled { + match compile(&pattern, ignore_case) { + Ok(pattern) => Compiled { + ok: true, + error: String::new(), + protocol: pattern.protocol().to_owned(), + username: pattern.username().to_owned(), + password: pattern.password().to_owned(), + hostname: pattern.hostname().to_owned(), + port: pattern.port().to_owned(), + pathname: pattern.pathname().to_owned(), + search: pattern.search().to_owned(), + hash: pattern.hash().to_owned(), + has_regexp_groups: pattern.has_regexp_groups(), + }, + Err(error) => Compiled { + ok: false, + error, + protocol: String::new(), + username: String::new(), + password: String::new(), + hostname: String::new(), + port: String::new(), + pathname: String::new(), + search: String::new(), + hash: String::new(), + has_regexp_groups: false, + }, + } + } + + fn exec(pattern: Input, ignore_case: bool, target: Input) -> Matched { + let pattern = match compile(&pattern, ignore_case) { + Ok(pattern) => pattern, + Err(error) => return no_match(false, error), + }; + let (target, base) = input(&target); + let matched = match quirks::process_match_input(target, base.as_deref()) { + Ok(Some((target, _inputs))) => pattern.exec(target), + Ok(None) => return no_match(true, String::new()), + Err(error) => return no_match(false, error.to_string()), + }; + let result = match matched { + Ok(Some(result)) => result, + Ok(None) => return no_match(true, String::new()), + Err(error) => return no_match(false, error.to_string()), + }; + + Matched { + ok: true, + error: String::new(), + found: true, + protocol: component_result(&pattern.protocol, result.protocol), + username: component_result(&pattern.username, result.username), + password: component_result(&pattern.password, result.password), + hostname: component_result(&pattern.hostname, result.hostname), + port: component_result(&pattern.port, result.port), + pathname: component_result(&pattern.pathname, result.pathname), + search: component_result(&pattern.search, result.search), + hash: component_result(&pattern.hash, result.hash), + } + } +} diff --git a/packages/jco-std/package.json b/packages/jco-std/package.json index c966508e49..c8e7c468b2 100644 --- a/packages/jco-std/package.json +++ b/packages/jco-std/package.json @@ -25,7 +25,9 @@ "files": [ "dist", "wit/node-0.1.0", - "wit/tls-0.2.0-draft" + "wit/tls-0.2.0-draft", + "wit/wintertc-0.1.0", + "wasm" ], "type": "module", "exports": { @@ -717,6 +719,118 @@ "types": "./dist/wasi/0.2.x/node/24.x.x/fs-host-node.d.ts", "node": "./dist/wasi/0.2.x/node/24.x.x/fs-host-node.js" }, + "./wintertc": { + "types": "./dist/wintertc/index.d.ts", + "default": "./dist/wintertc/index.js" + }, + "./wintertc/abort": { + "types": "./dist/wintertc/abort.d.ts", + "default": "./dist/wintertc/abort.js" + }, + "./wintertc/base64": { + "types": "./dist/wintertc/base64.d.ts", + "default": "./dist/wintertc/base64.js" + }, + "./wintertc/blob": { + "types": "./dist/wintertc/blob.d.ts", + "default": "./dist/wintertc/blob.js" + }, + "./wintertc/body": { + "types": "./dist/wintertc/body.d.ts", + "default": "./dist/wintertc/body.js" + }, + "./wintertc/compression": { + "types": "./dist/wintertc/compression.d.ts", + "default": "./dist/wintertc/compression.js" + }, + "./wintertc/console": { + "types": "./dist/wintertc/console.d.ts", + "default": "./dist/wintertc/console.js" + }, + "./wintertc/crypto": { + "types": "./dist/wintertc/crypto.d.ts", + "default": "./dist/wintertc/crypto.js" + }, + "./wintertc/dom-exception": { + "types": "./dist/wintertc/dom-exception.d.ts", + "default": "./dist/wintertc/dom-exception.js" + }, + "./wintertc/encoding-streams": { + "types": "./dist/wintertc/encoding-streams.d.ts", + "default": "./dist/wintertc/encoding-streams.js" + }, + "./wintertc/encoding": { + "types": "./dist/wintertc/encoding.d.ts", + "default": "./dist/wintertc/encoding.js" + }, + "./wintertc/events": { + "types": "./dist/wintertc/events.d.ts", + "default": "./dist/wintertc/events.js" + }, + "./wintertc/fetch": { + "types": "./dist/wintertc/fetch.d.ts", + "default": "./dist/wintertc/fetch.js" + }, + "./wintertc/form-data": { + "types": "./dist/wintertc/form-data.d.ts", + "default": "./dist/wintertc/form-data.js" + }, + "./wintertc/headers": { + "types": "./dist/wintertc/headers.d.ts", + "default": "./dist/wintertc/headers.js" + }, + "./wintertc/messaging": { + "types": "./dist/wintertc/messaging.d.ts", + "default": "./dist/wintertc/messaging.js" + }, + "./wintertc/microtask": { + "types": "./dist/wintertc/microtask.d.ts", + "default": "./dist/wintertc/microtask.js" + }, + "./wintertc/navigator": { + "types": "./dist/wintertc/navigator.d.ts", + "default": "./dist/wintertc/navigator.js" + }, + "./wintertc/performance": { + "types": "./dist/wintertc/performance.d.ts", + "default": "./dist/wintertc/performance.js" + }, + "./wintertc/report-error": { + "types": "./dist/wintertc/report-error.d.ts", + "default": "./dist/wintertc/report-error.js" + }, + "./wintertc/request": { + "types": "./dist/wintertc/request.d.ts", + "default": "./dist/wintertc/request.js" + }, + "./wintertc/response": { + "types": "./dist/wintertc/response.d.ts", + "default": "./dist/wintertc/response.js" + }, + "./wintertc/subtle-crypto": { + "types": "./dist/wintertc/subtle-crypto.d.ts", + "default": "./dist/wintertc/subtle-crypto.js" + }, + "./wintertc/timers": { + "types": "./dist/wintertc/timers.d.ts", + "default": "./dist/wintertc/timers.js" + }, + "./wintertc/url-pattern": { + "types": "./dist/wintertc/url-pattern.d.ts", + "default": "./dist/wintertc/url-pattern.js" + }, + "./wintertc/url-search-params": { + "types": "./dist/wintertc/url-search-params.d.ts", + "default": "./dist/wintertc/url-search-params.js" + }, + "./wintertc/url": { + "types": "./dist/wintertc/url.d.ts", + "default": "./dist/wintertc/url.js" + }, + "./wintertc/streams": { + "types": "./dist/wintertc/streams/index.d.ts", + "default": "./dist/wintertc/streams/index.js" + }, "./wasi/0.3.x/node/24.x.x/web-globals": { "types": "./dist/wasi/0.2.x/node/24.x.x/web-globals.d.ts", "default": "./dist/wasi/0.2.x/node/24.x.x/web-globals.js" @@ -1311,12 +1425,17 @@ "build:bindings:wasi:http:0.2.6": "WIT_PATH=wit/http-v0m2p6 OUTPUT_DIR_PATH=src/wasi/0.2.6/generated/types node scripts/generate-wasi-bindings.mjs", "build:bindings:wasi:http:0.2.12": "WIT_PATH=wit/http-v0m2p12 OUTPUT_DIR_PATH=src/wasi/0.2.12/generated/types node scripts/generate-wasi-bindings.mjs", "build:bindings:wasi:http:0.2.3": "WIT_PATH=wit/http-v0m2p3 OUTPUT_DIR_PATH=src/wasi/0.2.3/generated/types node scripts/generate-wasi-bindings.mjs", - "build:bindings": "pnpm run build:bindings:wasi:http:0.2.3 && pnpm run build:bindings:wasi:http:0.2.6 && pnpm run build:bindings:wasi:http:0.2.12 && pnpm run build:bindings:wasi:tls", - "build:ts": "node scripts/sync-p3-node-exports.mjs --check && tsc", + "build:bindings:wintertc": "node scripts/generate-wintertc-types.mjs", + "build:bindings": "pnpm run build:bindings:wasi:http:0.2.3 && pnpm run build:bindings:wasi:http:0.2.6 && pnpm run build:bindings:wasi:http:0.2.12 && pnpm run build:bindings:wasi:tls && pnpm run build:bindings:wintertc", + "build:ts": "node scripts/sync-p3-node-exports.mjs --check && node scripts/generate-wintertc-types.mjs && tsc", "build": "pnpm run setup:jco-transpile:build && pnpm run build:bindings && pnpm run build:ts", "test": "vitest run -c test/vitest.ts", - "prepack": "pnpm run build", - "build:bindings:wasi:tls": "node scripts/generate-tls-bindings.mjs" + "prepack": "pnpm run build && pnpm run build:wintertc:components", + "build:bindings:wasi:tls": "node scripts/generate-tls-bindings.mjs", + "check:wintertc": "node scripts/generate-wintertc-types.mjs && tsc -p src/wintertc", + "test:wintertc": "vitest run -c test/wintertc/vitest.ts", + "fetch:wpt": "node scripts/fetch-wpt.mjs", + "build:wintertc:components": "node scripts/build-wintertc-components.mjs" }, "dependencies": { "@noble/hashes": "1.8.0", diff --git a/packages/jco-std/scripts/build-wintertc-components.mjs b/packages/jco-std/scripts/build-wintertc-components.mjs new file mode 100644 index 0000000000..241455e2b0 --- /dev/null +++ b/packages/jco-std/scripts/build-wintertc-components.mjs @@ -0,0 +1,109 @@ +#!/usr/bin/env node +/** + * Build the WinterTC components (`crates/wintertc-*`), each implementing one `jco:wintertc` + * interface, into `wasm/wintertc-.wasm`, the files users compose with. + * + * The crates are built with `cargo build --release --target wasm32-wasip3`, which produces + * components directly. Besides their `jco:wintertc` export they may only import WASI 0.3 + * interfaces (Rust's standard library imports some), which the host provides. + * + * Usage: `node scripts/build-wintertc-components.mjs [name...]` (names such as `url`; default: + * every `crates/wintertc-*` directory). Needs `cargo` on the `PATH`; `crates/rust-toolchain.toml` + * selects the Rust toolchain and target. `prepack` runs it, so the published package includes the + * components. With `wasm-tools` on the `PATH` it also checks each component's imports (CI does); + * without it, the check is skipped with a warning. + */ + +import { execFileSync } from "node:child_process"; +import { copyFile, mkdir, readdir, stat } from "node:fs/promises"; +import { join } from "node:path"; +import { argv } from "node:process"; +import { fileURLToPath } from "node:url"; + +const PACKAGE_DIR = fileURLToPath(new URL("..", import.meta.url)); +const CRATES_DIR = join(PACKAGE_DIR, "crates"); +const WASM_DIR = join(PACKAGE_DIR, "wasm"); +const TARGET = "wasm32-wasip3"; + +/** + * Run a command, inheriting stdio, and fail loudly if it fails. + * + * @param {string} command - Program to run. + * @param {string[]} args - Its arguments. + * @param {string} cwd - Working directory. + */ +function run(command, args, cwd) { + console.error(`$ ${command} ${args.join(" ")}`); + execFileSync(command, args, { cwd, stdio: "inherit" }); +} + +/** + * List the component names (`url`, `compression`, …) with a crate in `crates/`. + * + * @returns {Promise} Names, sorted. + */ +async function availableComponents() { + const entries = await readdir(CRATES_DIR, { withFileTypes: true }); + return entries + .filter((entry) => entry.isDirectory() && entry.name.startsWith("wintertc-")) + .map((entry) => entry.name.slice("wintertc-".length)) + .sort(); +} + +/** + * Check that a component imports only WASI 0.3 interfaces, so composing it needs nothing but the + * host's WASI. + * + * @param {string} name - The component name. + * @param {string} path - The component file. + */ +function checkImports(name, path) { + let wit; + try { + wit = execFileSync("wasm-tools", ["component", "wit", path], { encoding: "utf8" }); + } catch (error) { + if (error.code === "ENOENT") { + console.error(`wasm-tools not found; not checking the imports of wintertc-${name}.wasm`); + return; + } + throw error; + } + const world = wit.slice(wit.indexOf("world "), wit.indexOf("}", wit.indexOf("world "))); + const unexpected = world + .split("\n") + .map((line) => line.trim()) + .filter( + (line) => line.startsWith("import ") && !/^import wasi:[a-z-]+\/[a-z-]+@0\.3\./.test(line), + ); + if (unexpected.length > 0) { + throw new Error(`wintertc-${name}.wasm has non-WASI 0.3 imports:\n${unexpected.join("\n")}`); + } +} + +/** + * Compile the crates and copy each component into `wasm/`. + * + * @param {string[]} names - Components to build. + */ +async function buildComponents(names) { + const packages = names.flatMap((name) => ["-p", `wintertc-${name}`]); + run("cargo", ["build", "--release", "--target", TARGET, ...packages], CRATES_DIR); + + await mkdir(WASM_DIR, { recursive: true }); + for (const name of names) { + const built = join( + CRATES_DIR, + "target", + TARGET, + "release", + `wintertc_${name.replaceAll("-", "_")}.wasm`, + ); + const component = join(WASM_DIR, `wintertc-${name}.wasm`); + await copyFile(built, component); + checkImports(name, component); + console.error(`wintertc-${name}.wasm: ${(await stat(component)).size} bytes`); + } +} + +const requested = argv.slice(2).filter((arg) => !arg.startsWith("--")); +await buildComponents(requested.length > 0 ? requested : await availableComponents()); diff --git a/packages/jco-std/scripts/fetch-wpt.mjs b/packages/jco-std/scripts/fetch-wpt.mjs new file mode 100644 index 0000000000..dcfd6eb1d0 --- /dev/null +++ b/packages/jco-std/scripts/fetch-wpt.mjs @@ -0,0 +1,312 @@ +#!/usr/bin/env node +/** + * Download the web-platform-tests directories the WinterTC WPT runner needs, at a pinned commit. + * + * The GitHub codeload tarball is streamed through gunzip and a small tar reader; only entries under + * `WPT_PATHS` are written. No git checkout is involved. The result lands in + * `test/wintertc/wpt/.cache/`, with a `.wpt-sha` marker so a second run with the same pin is a + * no-op. + * + * Usage: `node scripts/fetch-wpt.mjs [--force]` + */ + +import { Readable } from "node:stream"; +import { existsSync, statSync } from "node:fs"; +import { copyFile, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import { dirname, isAbsolute, join, normalize, sep } from "node:path"; +import { fileURLToPath } from "node:url"; + +/** The pinned web-platform-tests commit (web-platform-tests/wpt, master, 2026-12-03). */ +export const WPT_SHA = "2f147eb52a5d1f098d3bcd2b3504cb3498da9e96"; + +/** WPT directories (relative to the repository root) to extract. */ +export const WPT_PATHS = [ + "resources", + "common", + "interfaces", + "console", + "dom/events", + "dom/abort", + "encoding", + "url", + "urlpattern", + "streams", + "FileAPI", + "fetch/api", + "xhr/formdata", + "compression", + "html/webappapis/atob", + "html/webappapis/microtask-queuing", + "html/webappapis/timers", + "webmessaging", + "hr-time", + "WebCryptoAPI", +]; + +const PACKAGE_ROOT = join(dirname(fileURLToPath(import.meta.url)), ".."); +const CACHE_DIR = join(PACKAGE_ROOT, "test", "wintertc", "wpt", ".cache"); +const MARKER = ".wpt-sha"; + +/** + * Decide whether a path inside the WPT repository is one we want. + * + * @param {string} path - Path relative to the WPT repository root, `/`-separated. + * @returns {boolean} True if the path is under one of `WPT_PATHS`. + */ +function wanted(path) { + return WPT_PATHS.some((prefix) => path === prefix || path.startsWith(prefix + "/")); +} + +/** + * Parse the records of a pax extended header block. + * + * @param {Buffer} data - The header block contents. + * @returns {Record} The key/value records. + */ +function parsePax(data) { + const records = {}; + let offset = 0; + while (offset < data.length) { + const space = data.indexOf(0x20, offset); + if (space < 0) { + break; + } + const length = Number(data.subarray(offset, space).toString("utf8")); + if (!Number.isFinite(length) || length <= 0) { + break; + } + const record = data.subarray(space + 1, offset + length - 1).toString("utf8"); + const equals = record.indexOf("="); + if (equals > 0) { + records[record.slice(0, equals)] = record.slice(equals + 1); + } + offset += length; + } + return records; +} + +/** + * Read a NUL-terminated string field from a tar header. + * + * @param {Buffer} header - The 512-byte header. + * @param {number} start - Field offset. + * @param {number} length - Field length. + * @returns {string} The field value. + */ +function field(header, start, length) { + const raw = header.subarray(start, start + length); + const end = raw.indexOf(0); + return raw.subarray(0, end < 0 ? raw.length : end).toString("utf8"); +} + +/** + * Stream a tar archive and call `onFile` for each regular file whose path passes `filter`, and + * `onLink` for each such symbolic link. + * + * Supports ustar, pax (`x`/`g`) and GNU long-name (`L`) headers, which is what codeload emits. + * Bodies of unwanted entries are skipped without buffering. + * + * @param {AsyncIterable} source - The decompressed tar stream. + * @param {(path: string) => boolean} filter - Selects which archive paths to keep. + * @param {(path: string, data: Buffer) => Promise} onFile - Receives kept files. + * @param {(path: string, target: string) => void} onLink - Receives kept symbolic links. + * @returns {Promise} Resolves once the archive ends. + */ +async function extractTar(source, filter, onFile, onLink) { + let buffer = Buffer.alloc(0); + // The entry whose body (plus padding to a 512-byte boundary) is being consumed. + let entry = null; + // A path (and link target) supplied by a preceding pax or GNU long-name header. + let nextPath = null; + let nextLink = null; + + for await (const chunk of source) { + buffer = buffer.length === 0 ? chunk : Buffer.concat([buffer, chunk]); + for (;;) { + if (entry) { + // Consume body and padding; keep only the body bytes of wanted entries. + const take = Math.min(entry.remaining, buffer.length); + const bodyLeft = Math.max(0, entry.size - entry.consumed); + if (entry.keep && bodyLeft > 0) { + entry.chunks.push(buffer.subarray(0, Math.min(take, bodyLeft))); + } + entry.consumed += take; + entry.remaining -= take; + buffer = buffer.subarray(take); + if (entry.remaining > 0) { + break; + } + + const done = entry; + entry = null; + const data = done.keep ? Buffer.concat(done.chunks) : null; + if (done.kind === "x") { + const pax = parsePax(data); + if (pax.path) { + nextPath = pax.path; + } + if (pax.linkpath) { + nextLink = pax.linkpath; + } + } else if (done.kind === "L") { + nextPath = data.toString("utf8").replace(/\0+$/, ""); + } else if (done.kind === "file" && done.keep) { + await onFile(done.path, data); + } + continue; + } + + if (buffer.length < 512) { + break; + } + const header = buffer.subarray(0, 512); + buffer = buffer.subarray(512); + if (header.every((byte) => byte === 0)) { + continue; + } + + const size = parseInt(field(header, 124, 12).trim() || "0", 8); + const type = String.fromCharCode(header[156] || 0x30); + const prefix = field(header, 345, 155); + const name = field(header, 0, 100); + const path = nextPath ?? (prefix ? `${prefix}/${name}` : name); + const padded = size + ((512 - (size % 512)) % 512); + if (type === "x" || type === "L" || type === "g") { + entry = { + path, + size, + consumed: 0, + remaining: padded, + keep: type !== "g", + chunks: [], + kind: type, + }; + } else { + const linkTarget = nextLink ?? field(header, 157, 100); + nextPath = null; + nextLink = null; + if (type === "2" && filter(path)) { + onLink(path, linkTarget); + } + const isFile = type === "0" || type === "\0" || type === "7"; + entry = { + path, + size, + consumed: 0, + remaining: padded, + keep: isFile && filter(path), + chunks: [], + kind: isFile ? "file" : "other", + }; + } + } + } +} + +const ATTEMPTS = 4; + +/** + * Stream the pinned tarball and write the wanted entries under `staging`. + * + * @param {string} staging - Directory to extract into. + * @returns {Promise} Number of files written. + */ +async function downloadInto(staging) { + const url = `https://codeload.github.com/web-platform-tests/wpt/tar.gz/${WPT_SHA}`; + console.log(`Downloading ${url}`); + const response = await fetch(url); + if (!response.ok || !response.body) { + throw new Error(`WPT download failed: ${response.status} ${response.statusText}`); + } + + // A single web-stream chain, so network and decompression errors reach the iterator. + const tar = Readable.fromWeb(response.body.pipeThrough(new DecompressionStream("gzip"))); + const root = `wpt-${WPT_SHA}/`; + let count = 0; + const links = []; + await extractTar( + tar, + (path) => path.startsWith(root) && wanted(path.slice(root.length)), + async (path, data) => { + const relative = normalize(path.slice(root.length)); + if (relative.startsWith("..") || relative.split(sep).includes("..")) { + throw new Error(`Refusing to extract ${path}`); + } + const target = join(staging, relative); + await mkdir(dirname(target), { recursive: true }); + await writeFile(target, data); + count++; + }, + (path, target) => { + // Links are written into the staging directory too, so check their paths like files'. + const relative = normalize(path.slice(root.length)); + if (relative.startsWith("..") || relative.split(sep).includes("..")) { + throw new Error(`Refusing to extract ${path}`); + } + links.push([relative, target]); + }, + ); + + // Materialize symbolic links (e.g. resources/WebIDLParser.js) as copies of their targets. + // Links to links resolve over successive passes. + for (let pass = 0; pass < 4 && links.length > 0; pass++) { + for (const [index, [path, target]] of [...links.entries()].reverse()) { + const resolved = normalize(join(dirname(path), target)); + if (resolved.startsWith("..") || isAbsolute(resolved)) { + links.splice(index, 1); + continue; + } + const source = join(staging, resolved); + if (existsSync(source) && statSync(source).isFile()) { + await mkdir(dirname(join(staging, path)), { recursive: true }); + await copyFile(source, join(staging, path)); + links.splice(index, 1); + count++; + } + } + } + return count; +} + +/** + * Download and extract the pinned WPT subset into the cache directory. + * + * @param {{ force?: boolean }} options - `force` re-downloads even if the marker matches. + * @returns {Promise} Resolves once the cache is ready. + */ +export async function fetchWpt({ force = false } = {}) { + if (!force) { + const current = await readFile(join(CACHE_DIR, MARKER), "utf8").catch(() => ""); + if (current.trim() === WPT_SHA) { + console.log(`WPT ${WPT_SHA} already present in ${CACHE_DIR}`); + return; + } + } + + // Extract into a sibling staging directory, then swap it in so an interrupted run never leaves + // a half-populated cache behind a valid marker. + const staging = `${CACHE_DIR}.partial`; + let count = 0; + for (let attempt = 1; ; attempt++) { + await rm(staging, { recursive: true, force: true }); + await mkdir(staging, { recursive: true }); + try { + count = await downloadInto(staging); + break; + } catch (error) { + if (attempt >= ATTEMPTS) { + throw error; + } + console.warn(`Attempt ${attempt} failed (${error.cause?.code ?? error.message}); retrying`); + } + } + + await writeFile(join(staging, MARKER), `${WPT_SHA}\n`); + await rm(CACHE_DIR, { recursive: true, force: true }); + await rename(staging, CACHE_DIR); + console.log(`Extracted ${count} files into ${CACHE_DIR}`); +} + +if (process.argv[1] && fileURLToPath(import.meta.url) === normalize(process.argv[1])) { + await fetchWpt({ force: process.argv.includes("--force") }); +} diff --git a/packages/jco-std/scripts/generate-wintertc-types.mjs b/packages/jco-std/scripts/generate-wintertc-types.mjs new file mode 100644 index 0000000000..b84fca72c1 --- /dev/null +++ b/packages/jco-std/scripts/generate-wintertc-types.mjs @@ -0,0 +1,128 @@ +#!/usr/bin/env node +/** + * Generate the TypeScript declarations the WinterTC modules are type-checked against, with jco's + * guest type generator. Both outputs are gitignored and regenerated by `build:ts` and + * `check:wintertc`: + * + * - `src/wintertc/generated/types/`: the WASI 0.3 imports and exports, from + * `wit/wintertc-v0m3p0/` (ambient `declare module 'wasi:…'` files, mapped by the tsconfig + * `paths`). + * - `src/wintertc/imports/`: the `jco:wintertc/*` imports of the Rust components, from + * `wit/wintertc-0.1.0/`, one plain module per interface. + * + * Uses the workspace's `packages/jco-transpile` when it has been built + * (`pnpm run setup:jco-transpile:build`), else the `@bytecodealliance/jco-transpile` dependency. + * + * Usage: `node scripts/generate-wintertc-types.mjs` + */ + +import { existsSync } from "node:fs"; +import { mkdir, readdir, rm, writeFile } from "node:fs/promises"; +import { dirname, join, relative } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const PACKAGE_DIR = fileURLToPath(new URL("..", import.meta.url)); + +// Prefer the workspace's jco-transpile, which follows this repository's bindgen. +const WORKSPACE_TRANSPILE = join(PACKAGE_DIR, "..", "jco-transpile", "dist", "index.js"); +const { generateGuestTypes } = await import( + existsSync(WORKSPACE_TRANSPILE) + ? pathToFileURL(WORKSPACE_TRANSPILE).href + : "@bytecodealliance/jco-transpile" +); + +/** WIT of the WASI interfaces the WinterTC modules use. */ +const WASI_WIT_DIR = join(PACKAGE_DIR, "wit", "wintertc-v0m3p0"); + +/** Where the WASI declarations go. */ +const WASI_TYPES_DIR = join(PACKAGE_DIR, "src", "wintertc", "generated", "types"); + +/** WIT of the Rust components. */ +const COMPONENTS_WIT_DIR = join(PACKAGE_DIR, "wit", "wintertc-0.1.0"); + +/** Where the `jco:wintertc/*` declarations go. */ +const IMPORT_TYPES_DIR = join(PACKAGE_DIR, "src", "wintertc", "imports"); + +/** The Rust components' WIT package and version. */ +const WIT_PACKAGE = "jco:wintertc"; +const WIT_VERSION = "0.1.0"; + +/** + * Write generated files, replacing the directory's previous contents. + * + * @param {string} dir - The output directory. + * @param {Record} files - Contents by path (paths start with `dir`). + */ +async function replaceDirectory(dir, files) { + await rm(dir, { recursive: true, force: true }); + for (const [path, contents] of Object.entries(files)) { + await mkdir(dirname(path), { recursive: true }); + await writeFile(path, contents); + } +} + +/** Generate the WASI 0.3 declarations. */ +async function generateWasiTypes() { + const files = await generateGuestTypes(WASI_WIT_DIR, { outDir: WASI_TYPES_DIR }); + await replaceDirectory(WASI_TYPES_DIR, files); + console.error(`types: ${relative(PACKAGE_DIR, WASI_TYPES_DIR)}/`); +} + +/** + * The Rust components, by name (`url` for `crates/wintertc-url`). + * + * @returns {Promise} The names. + */ +async function componentNames() { + const entries = await readdir(join(PACKAGE_DIR, "crates"), { withFileTypes: true }); + return entries + .filter((entry) => entry.isDirectory() && entry.name.startsWith("wintertc-")) + .map((entry) => entry.name.slice("wintertc-".length)) + .sort(); +} + +/** + * Generate one plain module per `jco:wintertc/*` interface. The generator emits ambient + * `declare module '…' { … }` files; the wrapper is dropped so each file can be mapped by `paths` + * as an ordinary module. + */ +async function generateImportTypes() { + const files = await generateGuestTypes(COMPONENTS_WIT_DIR, { + worldName: "wintertc-imports", + outDir: "types", + }); + const decoder = new TextDecoder(); + const output = {}; + for (const name of await componentNames()) { + const file = Object.keys(files).find((path) => + path.endsWith(`/interfaces/jco-wintertc-${name}.d.ts`), + ); + if (!file) { + throw new Error( + `no guest types generated for ${name}; is it imported by world wintertc-imports?`, + ); + } + + const lines = decoder + .decode(files[file]) + .replace(/[ \t]+$/gm, "") + .trimEnd() + .split("\n"); + if (!lines[0]?.startsWith("declare module") || lines.at(-1) !== "}") { + throw new Error(`unexpected guest types layout for ${name}`); + } + const body = lines.slice(1, -1).map((line) => line.replace(/^ {2}/, "")); + const header = [ + `// Generated by scripts/generate-wintertc-types.mjs (jco guest types) from wit/wintertc-0.1.0.`, + `// Declares the ${WIT_PACKAGE}/${name}@${WIT_VERSION} import; do not edit by hand.`, + ]; + output[join(IMPORT_TYPES_DIR, `jco-wintertc-${name}.d.ts`)] = new TextEncoder().encode( + `${[...header, ...body].join("\n").trimEnd()}\n`, + ); + } + await replaceDirectory(IMPORT_TYPES_DIR, output); + console.error(`types: ${relative(PACKAGE_DIR, IMPORT_TYPES_DIR)}/`); +} + +await generateWasiTypes(); +await generateImportTypes(); diff --git a/packages/jco-std/src/wintertc/README.md b/packages/jco-std/src/wintertc/README.md new file mode 100644 index 0000000000..e9f7398df6 --- /dev/null +++ b/packages/jco-std/src/wintertc/README.md @@ -0,0 +1,77 @@ +# WinterTC polyfills + +Polyfills for the WinterTC Minimum Common API (ECMA-429), for JavaScript engines in WASI 0.3 +components that don't have these APIs built in (such as QuickJS in componentize-qjs). They are ES +module exports for now. ECMAScript, and APIs only an engine can provide (`structuredClone`, +`WebAssembly`), are the engine's job. User documentation: `docs/src/wasi/wintertc.md` at the +repository root. + +The modules call WASI 0.3 directly (`wasi:clocks`, `wasi:random`, `wasi:cli/stdout`, +`wasi:cli/stderr`, `wasi:http`), typed by the declarations `jco guest-types` generates, so any +toolchain that follows those types can build a component from them. There are no adapters to +install: import the APIs and use them. + +## Layout + +| Path | Contents | Constraints | +| ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | +| `*.ts`, `streams/`, `internal/` | The APIs, one module per spec area (`events.ts`, `abort.ts`, `streams/…`), with shared helpers in `internal/`. `index.ts` re-exports them all. | Must pass `pnpm run check:wintertc` (ES2024 library, plus `esnext.disposable` for the generated types; no DOM or Node types) | +| `internal/` WASI modules | One module per WASI interface the APIs use: `monotonic-clock.ts`, `wall-clock.ts`, `random.ts`, `output.ts` (stdout/stderr), `http.ts` + `http-client.ts` (`wasi:http`) | Same as the APIs | +| `internal/wit.ts` | Helpers for where componentize-qjs differs from the generated types (futures, `stream`, cancelling an import call) | Same as the APIs | +| `generated/types/` | WASI 0.3 types generated by `jco guest-types` from `wit/wintertc-v0m3p0/`, mapped by the tsconfig `paths` | Gitignored; generated by `scripts/generate-wintertc-types.mjs` (run by `check:wintertc` and `build:ts`) | +| `imports/` | TypeScript declarations of the `jco:wintertc/*` imports, mapped by the tsconfig `paths` | Gitignored; generated by `scripts/generate-wintertc-types.mjs` from `wit/wintertc-0.1.0` (run by `check:wintertc` and `build:ts`) | +| `../../crates/` | Rust components implementing the `jco:wintertc` interfaces | Own Cargo workspace, built for `wasm32-wasip3` (`rust-toolchain.toml`) | +| `../../wit/wintertc-0.1.0/` | The `jco:wintertc` WIT: the interfaces of the composed components. Published with the package, for users' worlds | Changing an interface means bumping its version | + +## Rules for the APIs + +- **Follow the spec.** Exported names, types and behaviour match the WinterTC specs, with WebIDL + types written as TypeScript's `lib.dom.d.ts` writes them (`unknown` where WebIDL says `any`). + Where the platform makes the spec impossible, record the deviation in the spec-deviation list of + the module's doc comment. Anything extra is a separate, clearly named helper. +- **Promises that settle later** come from `Deferred` in `internal/deferred.ts`. +- **Host capabilities come from WASI imports**, never from globals and never through an injected + port. Each WASI interface is imported by one internal module (`internal/monotonic-clock.ts` and so + on), and an API imports only the modules it needs, so a bundler drops the rest: a component that + only uses `URL` doesn't import `wasi:http`. The one global read is the engine's + `structuredClone`, in `internal/structured-clone.ts`. +- **WASI imports are typed by the generated types.** Where componentize-qjs passes something else + (futures that aren't thenable, `stream` as `Uint8Array` chunks, cancellable import calls), + go through the helpers in `internal/wit.ts`; elsewhere they do what the types say. +- **No WASI calls at module top level.** componentize-qjs runs module top-level code at build time + and snapshots the result, so a clock reading or random bytes taken then would be the same in + every instance (and output can't be written yet). Read them inside functions. +- **No top-level side effects:** module scope may only import, export and declare. Lazily create + shared state inside functions. A stateless singleton (such as `navigator`) may be created at + module scope as `/* @__PURE__ */ new X()`, with a comment saying why it is harmless. +- **No `static` blocks** or other code that runs when a class is defined: bundlers then keep the + class, and its component imports, even when it is unused. In particular `Symbol.toStringTag` is a + prototype getter rather than WebIDL's data property (a known deviation for every class). +- Every exported function and method has explicit types and a JSDoc comment. + +## Lifetime + +Under `wasmtime serve`, work still pending when an export returns (timers, bodies, console +output) runs to completion. A `wasi:cli/run` export ends the process when it returns, so a command +awaits its own timers and then `flushOutput()` (from `console.ts`) before returning. + +`flushOutput()`, `disposeCryptoKey()` and `errorTarget()` are the only non-standard exports; each +module's doc comment lists them under "Non-standard additions", with the reason in their JSDoc. +`flushOutput()` exists because WASI 0.3 stdout and stderr are asynchronous +streams, while `console` methods are synchronous and can only queue output, and a host may stop a +command as soon as `run` returns (`wasmtime run` does). Its documentation in `console.ts` has the +details. + +The package provides no export glue: components write their own `wasi:cli/run` or +`wasi:http/handler` exports, typed by the generated WASI types. The end-to-end fixtures have +examples (`test/wintertc/e2e-qjs/command.ts` and `serve.ts`). + +## Commands + +```sh +pnpm run check:wintertc # type-check the APIs against ES2024 +pnpm run test:wintertc # unit tests, WPT and end-to-end tests, all in componentize-qjs components + # (skipped when tools are missing; WINTERTC_REQUIRE_TOOLS=1 makes that fail) +node scripts/build-wintertc-components.mjs # build the Rust components (needed by the tests) +pnpm run build:bindings:wintertc # regenerate the generated type declarations (check:wintertc and build:ts do this too) +``` diff --git a/packages/jco-std/src/wintertc/abort.ts b/packages/jco-std/src/wintertc/abort.ts new file mode 100644 index 0000000000..209dca0be7 --- /dev/null +++ b/packages/jco-std/src/wintertc/abort.ts @@ -0,0 +1,428 @@ +/** + * `AbortController` and `AbortSignal` (DOM § 3.1, § 3.2). + * + * `AbortSignal.any()` links a dependent signal to its sources weakly in both directions, as the + * spec's weak sets do. A source keeps a dependent alive only while the dependent is not aborted + * and something observes it (an `abort` listener, an `onabort` handler or an abort algorithm), so + * an unobserved dependent can be collected while its sources live on. Dead links are pruned when a + * source gains new dependents. + * + * Spec deviations: + * - `AbortSignal.timeout()` waits on `wasi:clocks/monotonic-clock`, and a pending wait keeps the + * current task alive until it ends, even when nothing observes the signal. + * - `Symbol.toStringTag` is an accessor on each prototype rather than a data property. + */ +import { DOMException } from "./dom-exception.js"; +import { Event, EventTarget, checkArgumentCount } from "./events.js"; +import type { + AddEventListenerOptions, + EventHandler, + EventListenerOptions, + EventListenerOrEventListenerObject, +} from "./events.js"; +import { sleep } from "./internal/monotonic-clock.js"; + +/** An abort algorithm: internal steps run, before the `abort` event, when the signal aborts. */ +export type AbortAlgorithm = () => void; + +/** The events an `AbortSignal` fires, keyed by type. */ +export interface AbortSignalEventMap { + abort: Event; +} + +/** The link between a source signal and one of its dependents, shared by both. */ +class DependentLink { + readonly source: WeakRef; + readonly dependent: WeakRef; + /** The dependent, held strongly while it is observed; `null` otherwise. */ + retained: AbortSignal | null = null; + + constructor(source: AbortSignal, dependent: AbortSignal) { + this.source = new WeakRef(source); + this.dependent = new WeakRef(dependent); + } +} + +/** The number of dependent links a source holds before it first prunes dead ones. */ +const MIN_PRUNE_THRESHOLD = 16; + +/** Set while `createSignal()` runs, so the constructor can refuse direct construction. */ +let constructing = false; + +/** + * Create a signal, bypassing the illegal-constructor check. + * + * @returns A new, not aborted signal. + */ +function createSignal(): AbortSignal { + constructing = true; + try { + return new AbortSignal(); + } finally { + constructing = false; + } +} + +/** The signal's `addEventListener` and `removeEventListener`, typed by `AbortSignalEventMap`. */ +// Only method signatures are merged, and `EventTarget` implements them, as in lib.dom.d.ts. +// oxlint-disable-next-line typescript/no-unsafe-declaration-merging +export interface AbortSignal { + addEventListener( + type: K, + listener: (this: AbortSignal, event: AbortSignalEventMap[K]) => unknown, + options?: boolean | AddEventListenerOptions, + ): void; + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject | null, + options?: boolean | AddEventListenerOptions, + ): void; + removeEventListener( + type: K, + listener: (this: AbortSignal, event: AbortSignalEventMap[K]) => unknown, + options?: boolean | EventListenerOptions, + ): void; + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject | null, + options?: boolean | EventListenerOptions, + ): void; +} + +/** A signal that reports whether, and why, an operation was aborted. */ +export class AbortSignal extends EventTarget { + private reasonValue: unknown = undefined; + private isAborted: boolean = false; + private algorithms: AbortAlgorithm[] = []; + private dependent: boolean = false; + /** Links to this signal's sources, when it is dependent. */ + private sourceLinks: DependentLink[] = []; + /** Links to the dependents of this signal, in the order they were created. */ + private dependentLinks: DependentLink[] = []; + private pruneThreshold: number = MIN_PRUNE_THRESHOLD; + + /** + * Signals are created by `AbortController` and the static factories. + * + * @throws `TypeError` when called directly. + */ + constructor() { + if (!constructing) { + throw new TypeError("Illegal constructor"); + } + super(); + } + + /** + * A signal that is already aborted. + * + * @param reason - The abort reason, any value; defaults to an `AbortError` `DOMException`. + * @returns The aborted signal. + */ + static abort(reason?: unknown): AbortSignal { + const signal = createSignal(); + signal.reasonValue = reason === undefined ? defaultReason() : reason; + signal.isAborted = true; + return signal; + } + + /** + * A signal that aborts with a `TimeoutError` `DOMException` after `milliseconds`. + * + * @param milliseconds - The delay (WebIDL `unsigned long long`, enforced range). + * @returns The signal. + * @throws `TypeError` if `milliseconds` is missing or out of range. + */ + static timeout(milliseconds: number): AbortSignal { + checkArgumentCount(arguments.length, 1, "Failed to execute 'timeout' on 'AbortSignal'"); + const ms = Number(milliseconds); + if (!Number.isFinite(ms) || ms < 0 || ms > Number.MAX_SAFE_INTEGER) { + throw new TypeError( + "Failed to execute 'timeout': value is outside the 'unsigned long long' value range", + ); + } + const signal = createSignal(); + sleep(Math.trunc(ms)).then(() => + signal._signalAbort(new DOMException("The operation timed out.", "TimeoutError")), + ); + return signal; + } + + /** + * A signal that aborts when any of `signals` aborts, with that signal's reason. + * + * @param signals - The source signals: any iterable of `AbortSignal`s. + * @returns The dependent signal. + * @throws `TypeError` if `signals` is missing, not iterable, or holds something other than an + * `AbortSignal`. + */ + static any(signals: Iterable): AbortSignal { + checkArgumentCount(arguments.length, 1, "Failed to execute 'any' on 'AbortSignal'"); + const list: AbortSignal[] = []; + for (const signal of signals) { + if (!(signal instanceof AbortSignal)) { + throw new TypeError( + "Failed to execute 'any' on 'AbortSignal': element is not of type 'AbortSignal'", + ); + } + list.push(signal); + } + + const result = createSignal(); + for (const signal of list) { + if (signal.isAborted) { + result.reasonValue = signal.reasonValue; + result.isAborted = true; + return result; + } + } + + result.dependent = true; + const linked: AbortSignal[] = []; + for (const signal of list) { + // A dependent signal's sources are never themselves dependent, so `any()` of `any()` links + // straight to the original sources. + const sources = signal.dependent ? signal.liveSources() : [signal]; + for (const source of sources) { + if (linked.indexOf(source) >= 0) { + continue; + } + linked.push(source); + const link = new DependentLink(source, result); + result.sourceLinks.push(link); + source.addDependentLink(link); + } + } + return result; + } + + /** Whether the signal has aborted. */ + get aborted(): boolean { + return this.isAborted; + } + + /** The abort reason, or `undefined` while not aborted. Any value, not necessarily an `Error`. */ + get reason(): unknown { + return this.reasonValue; + } + + /** + * Throw the abort reason if the signal has aborted. + * + * @throws The abort reason. + */ + throwIfAborted(): void { + if (this.isAborted) { + throw this.reasonValue; + } + } + + /** Handler for the `abort` event. */ + get onabort(): EventHandler { + return this.getEventHandler("abort"); + } + + set onabort(handler: EventHandler) { + this.setEventHandler("abort", handler); + } + + /** `"AbortSignal"`. */ + override get [Symbol.toStringTag](): string { + return "AbortSignal"; + } + + /** + * @internal Run `algorithm` when the signal aborts (DOM "add" an abort algorithm). Does nothing + * if already aborted. + * + * @param algorithm - The steps to run. + */ + _addAlgorithm(algorithm: AbortAlgorithm): void { + if (this.isAborted) { + return; + } + this.algorithms.push(algorithm); + this.updateRetention(); + } + + /** + * @internal Stop running `algorithm` on abort (DOM "remove" an abort algorithm). + * + * @param algorithm - Steps previously added. + */ + _removeAlgorithm(algorithm: AbortAlgorithm): void { + const index = this.algorithms.indexOf(algorithm); + if (index < 0) { + return; + } + this.algorithms.splice(index, 1); + this.updateRetention(); + } + + /** + * @internal The DOM "signal abort" algorithm. + * + * @param reason - The abort reason, any value; `undefined` means an `AbortError` `DOMException`. + */ + _signalAbort(reason: unknown): void { + if (this.isAborted) { + return; + } + this.reasonValue = reason === undefined ? defaultReason() : reason; + this.isAborted = true; + + // Mark every dependent aborted first, so their state is consistent while any listener runs. + const toAbort: AbortSignal[] = []; + for (const link of this.dependentLinks) { + const dependent = link.dependent.deref(); + if (dependent === undefined || dependent.isAborted) { + continue; + } + dependent.reasonValue = this.reasonValue; + dependent.isAborted = true; + toAbort.push(dependent); + } + + this.runAbortSteps(); + for (const dependent of toAbort) { + dependent.runAbortSteps(); + } + } + + /** + * Track `abort` listeners, which decide whether this signal's sources keep it alive. + * + * @param type - The event type whose listeners changed. + */ + protected override listenersChanged(type: string): void { + if (type === "abort") { + this.updateRetention(); + } + } + + /** The DOM "run the abort steps": algorithms, then the trusted `abort` event. */ + private runAbortSteps(): void { + const algorithms = this.algorithms; + this.algorithms = []; + for (const algorithm of algorithms) { + algorithm(); + } + + this.detachFromSources(); + this.dependentLinks = []; + + const event = new Event("abort"); + event._isTrusted = true; + this._dispatch(event); + } + + /** + * The sources of a dependent signal that have not been collected. + * + * @returns The live source signals. + */ + private liveSources(): AbortSignal[] { + const sources: AbortSignal[] = []; + for (const link of this.sourceLinks) { + const source = link.source.deref(); + if (source !== undefined) { + sources.push(source); + } + } + return sources; + } + + /** + * Add a link to a new dependent, first dropping links to dependents that were collected once the + * list has grown past the prune threshold. + * + * @param link - The link. + */ + private addDependentLink(link: DependentLink): void { + if (this.dependentLinks.length >= this.pruneThreshold) { + this.dependentLinks = this.dependentLinks.filter( + (existing) => existing.dependent.deref() !== undefined, + ); + this.pruneThreshold = Math.max(MIN_PRUNE_THRESHOLD, this.dependentLinks.length * 2); + } + this.dependentLinks.push(link); + } + + /** + * Have this dependent's sources hold it strongly while it is not aborted and observed, and only + * weakly otherwise (the DOM rule for when an `AbortSignal` may be garbage collected). + */ + private updateRetention(): void { + if (this.sourceLinks.length === 0) { + return; + } + const observed = !this.isAborted && (this.algorithms.length > 0 || this.hasListeners("abort")); + for (const link of this.sourceLinks) { + link.retained = observed ? this : null; + } + } + + /** Remove this signal from its sources' dependent lists. */ + private detachFromSources(): void { + for (const link of this.sourceLinks) { + link.retained = null; + const source = link.source.deref(); + if (source === undefined) { + continue; + } + const index = source.dependentLinks.indexOf(link); + if (index >= 0) { + source.dependentLinks.splice(index, 1); + } + } + this.sourceLinks = []; + } +} + +/** Controls an `AbortSignal`. */ +export class AbortController { + private readonly signalValue: AbortSignal; + + /** Create a controller with a fresh signal. */ + constructor() { + this.signalValue = createSignal(); + } + + /** The controlled signal. */ + get signal(): AbortSignal { + return this.signalValue; + } + + /** + * Abort the signal. + * + * @param reason - The abort reason, any value; defaults to an `AbortError` `DOMException`. + */ + abort(reason?: unknown): void { + this.signalValue._signalAbort(reason); + } + + /** `"AbortController"`. */ + get [Symbol.toStringTag](): string { + return "AbortController"; + } +} + +/** + * Abort `signal` (DOM "signal abort"), for other modules such as `fetch`. + * + * @param signal - The signal. + * @param reason - The abort reason, any value; defaults to an `AbortError` `DOMException`. + */ +export function signalAbort(signal: AbortSignal, reason?: unknown): void { + signal._signalAbort(reason); +} + +/** + * The default abort reason. + * + * @returns A new `AbortError` `DOMException`. + */ +function defaultReason(): DOMException { + return new DOMException("signal is aborted without reason", "AbortError"); +} diff --git a/packages/jco-std/src/wintertc/base64.ts b/packages/jco-std/src/wintertc/base64.ts new file mode 100644 index 0000000000..727c4213b3 --- /dev/null +++ b/packages/jco-std/src/wintertc/base64.ts @@ -0,0 +1,168 @@ +/** + * `atob()` and `btoa()` (HTML § 8.3), on top of forgiving-base64 (Infra § 4.6). + * + * Both work on "binary strings", whose code units are all at most 0xFF. Characters are built with + * `String.fromCodePoint`, which gives the same result as `String.fromCharCode` for that range. + * + * Arguments are converted as WebIDL `DOMString` conversion does, so values from untyped callers + * become strings and symbols throw a `TypeError`. + * + * Spec deviations: none. + */ +import { DOMException } from "./dom-exception.js"; +import { toDOMString } from "./internal/utf8.js"; + +/** The base64 alphabet, indexed by 6-bit value. */ +const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +/** + * The 6-bit value of a base64 alphabet code unit. + * + * @param unit - A UTF-16 code unit. + * @returns 0-63, or -1 if `unit` is not in the alphabet. + */ +function sextet(unit: number): number { + if (unit >= 0x41 && unit <= 0x5a) { + return unit - 0x41; + } + if (unit >= 0x61 && unit <= 0x7a) { + return unit - 0x61 + 26; + } + if (unit >= 0x30 && unit <= 0x39) { + return unit - 0x30 + 52; + } + if (unit === 0x2b) { + return 62; + } + if (unit === 0x2f) { + return 63; + } + return -1; +} + +/** + * Decode base64 to a binary string, using forgiving-base64 decode: ASCII whitespace is ignored and + * padding is optional. + * + * @param data - The base64 text. + * @returns One code unit (0-255) per decoded byte. + * @throws `InvalidCharacterError` `DOMException` if `data` is not valid base64. + */ +export function atob(data: string): string { + const input = toDOMString(data); + + // Remove ASCII whitespace. + const units: number[] = []; + for (let i = 0; i < input.length; i++) { + const unit = input.charCodeAt(i); + if (unit === 0x09 || unit === 0x0a || unit === 0x0c || unit === 0x0d || unit === 0x20) { + continue; + } + units.push(unit); + } + + // Up to two trailing `=` are allowed when the length is a multiple of 4. + let length = units.length; + if (length % 4 === 0 && length > 0 && units[length - 1] === 0x3d) { + length--; + if (units[length - 1] === 0x3d) { + length--; + } + } + if (length % 4 === 1) { + throw invalid(); + } + + const points: number[] = []; + let buffer = 0; + let bits = 0; + for (let i = 0; i < length; i++) { + const value = sextet(units[i] ?? 0); + if (value < 0) { + throw invalid(); + } + buffer = (buffer << 6) | value; + bits += 6; + if (bits >= 24) { + points.push((buffer >> 16) & 0xff, (buffer >> 8) & 0xff, buffer & 0xff); + buffer = 0; + bits = 0; + } + } + // Leftover bits: 12 give one byte, 18 give two; the remaining low bits are discarded. + if (bits === 12) { + points.push((buffer >> 4) & 0xff); + } else if (bits === 18) { + points.push((buffer >> 10) & 0xff, (buffer >> 2) & 0xff); + } + return fromCodePoints(points); +} + +/** + * Encode a binary string as base64. + * + * @param data - A string whose code units are all at most 0xFF. + * @returns The base64 text, with padding. + * @throws `InvalidCharacterError` `DOMException` if a code unit is above 0xFF. + */ +export function btoa(data: string): string { + const input = toDOMString(data); + let out = ""; + let i = 0; + while (i < input.length) { + const b0 = byteAt(input, i); + const b1 = i + 1 < input.length ? byteAt(input, i + 1) : -1; + const b2 = i + 2 < input.length ? byteAt(input, i + 2) : -1; + const triple = (b0 << 16) | ((b1 < 0 ? 0 : b1) << 8) | (b2 < 0 ? 0 : b2); + out += ALPHABET.charAt((triple >> 18) & 0x3f) + ALPHABET.charAt((triple >> 12) & 0x3f); + out += b1 < 0 ? "=" : ALPHABET.charAt((triple >> 6) & 0x3f); + out += b2 < 0 ? "=" : ALPHABET.charAt(triple & 0x3f); + i += 3; + } + return out; +} + +/** + * The byte value of a binary string's code unit. + * + * @param input - The string. + * @param index - The code unit index. + * @returns The value, 0-255. + * @throws `InvalidCharacterError` `DOMException` above 0xFF. + */ +function byteAt(input: string, index: number): number { + const unit = input.charCodeAt(index); + if (unit > 0xff) { + throw new DOMException( + "The string to be encoded contains characters outside of the Latin1 range.", + "InvalidCharacterError", + ); + } + return unit; +} + +/** + * The error for malformed base64. + * + * @returns An `InvalidCharacterError` `DOMException`. + */ +function invalid(): DOMException { + return new DOMException( + "The string to be decoded is not correctly encoded.", + "InvalidCharacterError", + ); +} + +/** + * Build a string from code points in bounded chunks. + * + * @param points - Code points. + * @returns The string. + */ +function fromCodePoints(points: number[]): string { + let out = ""; + for (let start = 0; start < points.length; start += 4096) { + out += String.fromCodePoint(...points.slice(start, start + 4096)); + } + return out; +} diff --git a/packages/jco-std/src/wintertc/blob.ts b/packages/jco-std/src/wintertc/blob.ts new file mode 100644 index 0000000000..0be022aa48 --- /dev/null +++ b/packages/jco-std/src/wintertc/blob.ts @@ -0,0 +1,466 @@ +/** + * `Blob` and `File` (File API § 3, § 4). + * + * Spec deviations: + * - The bytes are held in memory, copied once when the blob is built; slices share them. + * - `endings: "native"` converts line endings to `"\n"` (WASI hosts have no native convention). + * - `File` without `lastModified` reads `wasi:clocks/system-clock`, so the component imports it. + * - `stream()` returns a readable byte stream, read in chunks of up to 64 KiB. + * - `Symbol.toStringTag` is an accessor on the prototype rather than a data property. + */ +import { wallClockNow } from "./internal/wall-clock.js"; +import { TextDecoder, TextEncoder } from "./encoding.js"; +import { TextDecoderStream } from "./encoding-streams.js"; +import { toDOMString, toUSVString } from "./internal/utf8.js"; +import { collectIterable, isObject, iteratorMethod } from "./internal/webidl.js"; +import { ReadableByteStreamController, ReadableStream } from "./streams/readable.js"; +import type { UnderlyingByteSource } from "./streams/readable.js"; + +/** One part of a blob's contents: the WebIDL union `(BufferSource or Blob or USVString)`. */ +export type BlobPart = ArrayBufferView | ArrayBuffer | Blob | string; + +/** How string parts' line endings are treated. */ +export type EndingType = "transparent" | "native"; + +/** Options for `new Blob()`. */ +export interface BlobPropertyBag { + type?: string; + endings?: EndingType; +} + +/** Options for `new File()`. */ +export interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} + +/** The chunk size `stream()` reads with. */ +const STREAM_CHUNK_SIZE = 65536; + +/** + * Normalise a `type` option: empty unless every character is printable ASCII, then lowercased. + * + * @param type - The type as given. + * @returns The normalised type. + */ +function normalizeType(type: string): string { + for (let i = 0; i < type.length; i++) { + const code = type.charCodeAt(i); + if (code < 0x20 || code > 0x7e) { + return ""; + } + } + return type.toLowerCase(); +} + +/** + * Convert line endings to `"\n"` (the spec's "convert line endings to native"). + * + * @param text - The string. + * @returns The converted string. + */ +function convertLineEndingsToNative(text: string): string { + let result = ""; + let start = 0; + for (let i = 0; i < text.length; i++) { + const code = text.charCodeAt(i); + if (code === 0x0d) { + result += text.slice(start, i) + "\n"; + if (i + 1 < text.length && text.charCodeAt(i + 1) === 0x0a) { + i++; + } + start = i + 1; + } + } + return result + text.slice(start); +} + +/** + * Convert the `endings` option as WebIDL would. + * + * @param endings - The option. + * @returns Whether to convert to native line endings. + */ +function nativeEndings(endings: EndingType | undefined): boolean { + if (endings === undefined) { + return false; + } + const value = toDOMString(endings); + if (value === "native") { + return true; + } + if (value === "transparent") { + return false; + } + throw new TypeError(`'${value}' is not a valid value for endings`); +} + +/** One blob part after argument conversion: a string, or bytes (copied or a blob's own). */ +class ConvertedPart { + readonly text: string | null; + readonly bytes: Uint8Array | null; + + constructor(text: string | null, bytes: Uint8Array | null) { + this.text = text; + this.bytes = bytes; + } +} + +/** + * Convert one item of `blobParts` to the `BlobPart` union as WebIDL would: blobs keep their bytes, + * buffers and views are copied (detached ones are empty), and anything else is converted to a + * scalar value string. + * + * @param part - The item. + * @returns The converted part. + * @throws TypeError for a symbol. + */ +function convertBlobPart(part: unknown): ConvertedPart { + if (typeof part === "string") { + return new ConvertedPart(toUSVString(part), null); + } + if (part instanceof Blob) { + return new ConvertedPart(null, part._bytes); + } + if (part instanceof ArrayBuffer) { + return new ConvertedPart( + null, + part.byteLength === 0 ? new Uint8Array(0) : new Uint8Array(part.slice(0)), + ); + } + if (ArrayBuffer.isView(part)) { + const view = + part.byteLength === 0 + ? new Uint8Array(0) + : new Uint8Array(part.buffer, part.byteOffset, part.byteLength).slice(); + return new ConvertedPart(null, view); + } + return new ConvertedPart(toUSVString(part), null); +} + +/** + * Convert the `blobParts` argument as WebIDL's `sequence` (before the options are read): + * any object with an `@@iterator` method is iterated, and each item is converted as soon as it is + * produced, so getters and conversions run in order until one throws. + * + * @param parts - The argument. + * @returns The converted parts. + * @throws TypeError if `parts` is not an iterable object, the iterator misbehaves, or an item + * can't be converted. + */ +function convertBlobParts(parts: unknown): ConvertedPart[] { + const method = isObject(parts) ? iteratorMethod(parts) : undefined; + if (method === undefined) { + throw new TypeError("blobParts must be an iterable object"); + } + return collectIterable(method, convertBlobPart); +} + +/** + * The spec's "process blob parts": concatenate every part's bytes. + * + * @param parts - The converted parts. + * @param native - Whether string parts get native line endings. + * @returns The bytes. + */ +function processBlobParts(parts: ConvertedPart[], native: boolean): Uint8Array { + const chunks: Uint8Array[] = []; + let total = 0; + let encoder: TextEncoder | null = null; + for (const part of parts) { + let bytes: Uint8Array; + if (part.text !== null) { + if (encoder === null) { + encoder = new TextEncoder(); + } + bytes = encoder.encode(native ? convertLineEndingsToNative(part.text) : part.text); + } else { + bytes = part.bytes as Uint8Array; + } + chunks.push(bytes); + total += bytes.byteLength; + } + + const result = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + result.set(chunk, offset); + offset += chunk.byteLength; + } + return result; +} + +/** + * WebIDL `[Clamp] long long` conversion: NaN becomes 0, and values round half to even. + * + * @param value - The value. + * @returns The integer. + */ +function clampLongLong(value: number): number { + const number = Number(value); + if (Number.isNaN(number)) { + return 0; + } + const clamped = Math.min(Math.max(number, -Number.MAX_SAFE_INTEGER), Number.MAX_SAFE_INTEGER); + const floor = Math.floor(clamped); + const fraction = clamped - floor; + let rounded = floor; + if (fraction > 0.5 || (fraction === 0.5 && floor % 2 !== 0)) { + rounded = floor + 1; + } + return rounded === 0 ? 0 : rounded; +} + +/** + * Convert a `slice()` position: negative values count from the end; the result is clamped. + * + * @param value - The position as given. + * @param size - The blob's size. + * @param fallback - The position when `value` is undefined. + * @returns The absolute position. + */ +function relativePosition(value: number | undefined, size: number, fallback: number): number { + if (value === undefined) { + return fallback; + } + const position = clampLongLong(value); + if (position < 0) { + return Math.max(size + position, 0); + } + return Math.min(position, size); +} + +/** A `BlobPropertyBag` after WebIDL conversion. */ +class ConvertedBlobPropertyBag { + readonly native: boolean; + readonly type: string; + + constructor(native: boolean, type: string) { + this.native = native; + this.type = type; + } +} + +/** + * Read a `BlobPropertyBag` as WebIDL would: reject non-objects, then read `endings`, then `type`. + * + * @param options - The options, if any. + * @returns The converted options. + */ +function convertBlobPropertyBag(options: BlobPropertyBag | undefined): ConvertedBlobPropertyBag { + if (options === undefined || options === null) { + return new ConvertedBlobPropertyBag(false, ""); + } + if (typeof options !== "object" && typeof options !== "function") { + throw new TypeError("options must be an object"); + } + const native = nativeEndings(options.endings); + const type: unknown = options.type; + return new ConvertedBlobPropertyBag(native, type === undefined ? "" : toDOMString(type)); +} + +/** Immutable raw data. */ +export class Blob { + /** @internal The blob's bytes. Never modified. */ + _bytes: Uint8Array; + /** Written once, by the constructor or by `File`'s constructor right after it. */ + private typeValue: string; + + /** + * Create a blob. + * + * @param blobParts - The contents, concatenated: any iterable of strings, buffers, views and + * blobs. + * @param options - `type` and `endings`. + * @throws TypeError if `blobParts` is not iterable, or `options` is invalid. + */ + // Default values keep `Blob.length` at 0, as WebIDL gives for optional arguments. + constructor( + blobParts: Iterable | undefined = undefined, + options: BlobPropertyBag | undefined = undefined, + ) { + const parts = blobParts === undefined ? [] : convertBlobParts(blobParts); + const bag = convertBlobPropertyBag(options); + this._bytes = processBlobParts(parts, bag.native); + this.typeValue = normalizeType(bag.type); + } + + /** The size in bytes. */ + get size(): number { + return this._bytes.byteLength; + } + + /** The MIME type, lowercased, or `""`. */ + get type(): string { + return this.typeValue; + } + + /** `"Blob"`, for `Object.prototype.toString`. */ + get [Symbol.toStringTag](): string { + return "Blob"; + } + + /** + * A new blob holding a range of this one's bytes. + * + * @param start - Start position; negative counts from the end. + * @param end - End position (exclusive); negative counts from the end. + * @param contentType - The new blob's type. + * @returns The slice. + */ + slice(start?: number, end?: number, contentType?: string): Blob { + const size = this.size; + const relativeStart = relativePosition(start, size, 0); + const relativeEnd = relativePosition(end, size, size); + const span = Math.max(relativeEnd - relativeStart, 0); + const result = new Blob([], { type: contentType === undefined ? "" : String(contentType) }); + result._bytes = this._bytes.subarray(relativeStart, relativeStart + span); + return result; + } + + /** + * A readable byte stream of the contents. + * + * @returns The stream. + */ + stream(): ReadableStream { + return new ReadableStream(new BlobByteSource(this._bytes)); + } + + /** + * A stream of the contents decoded as UTF-8 (whatever the blob's `type` says). + * + * @returns The text stream. + */ + textStream(): ReadableStream { + const decoder = new TextDecoderStream(); + return this.stream().pipeThrough(decoder); + } + + /** + * The contents decoded as UTF-8. + * + * @returns The text. + */ + text(): Promise { + return Promise.resolve(new TextDecoder().decode(this._bytes)); + } + + /** + * A copy of the contents. + * + * @returns The bytes, in a new `ArrayBuffer`. + */ + arrayBuffer(): Promise { + return Promise.resolve(this._bytes.slice().buffer); + } + + /** + * A copy of the contents. + * + * @returns The bytes, in a new `Uint8Array`. + */ + bytes(): Promise { + return Promise.resolve(this._bytes.slice()); + } +} + +/** Feeds a blob's bytes into a readable byte stream, one chunk per pull. */ +class BlobByteSource implements UnderlyingByteSource { + readonly type = "bytes" as const; + private readonly bytes: Uint8Array; + private offset: number = 0; + + constructor(bytes: Uint8Array) { + this.bytes = bytes; + } + + /** + * Enqueue the next chunk, or close at the end. + * + * @param controller - The stream's controller. + */ + pull(controller: ReadableByteStreamController): void { + if (this.offset >= this.bytes.byteLength) { + controller.close(); + const request = controller.byobRequest; + if (request !== null) { + request.respond(0); + } + return; + } + const end = Math.min(this.offset + STREAM_CHUNK_SIZE, this.bytes.byteLength); + // Copy, since enqueueing may transfer the chunk's buffer. + controller.enqueue(this.bytes.slice(this.offset, end)); + this.offset = end; + } +} + +/** + * WebIDL `long long` conversion, simplified to truncation (NaN becomes 0). + * + * @param value - The value. + * @returns The integer. + */ +function toLongLong(value: number): number { + const number = Math.trunc(Number(value)); + if (!Number.isFinite(number)) { + return 0; + } + return number === 0 ? 0 : number; +} + +/** A named blob with a modification time. */ +export class File extends Blob { + private readonly nameValue: string; + private readonly lastModifiedValue: number; + + /** + * Create a file. The arguments are converted in order (`fileBits`, `fileName`, then the options' + * `endings`, `type` and `lastModified`) before anything else happens. + * + * @param fileBits - The contents, concatenated: any iterable of strings, buffers, views and + * blobs. + * @param fileName - The file name. + * @param options - `type`, `endings` and `lastModified` (default: now, from the wall clock). + * @throws TypeError if `fileBits` or `fileName` is missing, `fileBits` is not iterable, or + * `options` is invalid. + */ + // The default value keeps `File.length` at 2, as WebIDL gives for an optional argument. + constructor( + fileBits: Iterable, + fileName: string, + options: FilePropertyBag | undefined = undefined, + ) { + if (fileBits === undefined || fileName === undefined) { + throw new TypeError("File requires fileBits and fileName"); + } + const parts = convertBlobParts(fileBits); + const name = toUSVString(fileName); + const bag = convertBlobPropertyBag(options); + const lastModified = + options === undefined || options === null ? undefined : options.lastModified; + const modified = + lastModified === undefined ? Math.trunc(wallClockNow()) : toLongLong(lastModified); + + super(); + this._bytes = processBlobParts(parts, bag.native); + this["typeValue"] = normalizeType(bag.type); + this.nameValue = name; + this.lastModifiedValue = modified; + } + + /** `"File"`, for `Object.prototype.toString`. */ + override get [Symbol.toStringTag](): string { + return "File"; + } + + /** The file name. */ + get name(): string { + return this.nameValue; + } + + /** Last modification time, in milliseconds since the Unix epoch. */ + get lastModified(): number { + return this.lastModifiedValue; + } +} diff --git a/packages/jco-std/src/wintertc/body.ts b/packages/jco-std/src/wintertc/body.ts new file mode 100644 index 0000000000..4b38327a14 --- /dev/null +++ b/packages/jco-std/src/wintertc/body.ts @@ -0,0 +1,686 @@ +/** + * The Fetch standard's body handling, shared by `Request` and `Response`: extracting a body from + * an init value, the `Body` mixin's reading methods, `bodyUsed`, and cloning with `tee()`. + * + * This module holds the logic; `Request` and `Response` each declare the mixin's members and + * delegate here, so neither class gains a non-spec base class. + * + * Spec deviations: + * - `json()` resolves to `unknown` where WebIDL says `any` (lib.dom's `Promise`): the parsed + * value is whatever `JSON.parse` returns, so callers narrow it before use. + * - `formData()` rejects for a `multipart/form-data` content type when there is no body at all, + * but parses an empty body as an empty form (the spec leaves multipart parsing to RFC 7578; this + * matches WPT). + * - `Content-Length` isn't derived here; a body's known length is passed to the host port instead. + * + * Body streams are readable byte streams created through the Streams module's internal + * `createReadableByteStream` (see {@link BodyStreamSource}), and reading uses read requests rather + * than promises of read results, so neither is affected by changes to `Object.prototype`. + */ +import { Blob } from "./blob.js"; +import { + FormData, + FormDataEntry, + appendFormDataEntry, + formDataEntries, + generateBoundary, + parseMultipart, + serializeMultipart, +} from "./form-data.js"; +import type { MultipartBody } from "./form-data.js"; +import { Deferred } from "./internal/deferred.js"; +import { extractMimeType, serializeMimeType } from "./internal/mime.js"; +import { concatBytes, toUSVString, utf8Decode, utf8Encode } from "./internal/utf8.js"; +import { + ReadableByteStreamController, + CallbackReadRequest, + ReadableStream, + ReadableStreamDefaultReader, + acquireReadableStreamDefaultReader, + createReadableByteStream, + readableStreamDefaultReaderRead, + isReadableStreamLocked, +} from "./streams/readable.js"; +import { + URLSearchParams, + parseFormUrlencodedBytes, + searchParamsList, + serializeFormUrlencoded, +} from "./url-search-params.js"; + +/** + * What `Request` and `Response` accept as a body: the WebIDL union + * `(ReadableStream or Blob or BufferSource or FormData or URLSearchParams or USVString)`. + */ +export type BodyInit = + | ReadableStream + | Blob + | ArrayBufferView + | ArrayBuffer + | FormData + | URLSearchParams + | string; + +/** Recreates a body's stream from its source, for redirects and retries. */ +export type BodySourceFactory = () => ReadableStream; + +/** A body: its stream, a way to recreate it from its source (if it has one), and its length. */ +export class InnerBody { + stream: ReadableStream; + /** `null` when the body came from a stream and can't be read twice. */ + source: BodySourceFactory | null; + /** Length in bytes, if known. */ + length: number | null; + + constructor( + stream: ReadableStream, + source: BodySourceFactory | null, + length: number | null, + ) { + this.stream = stream; + this.source = source; + this.length = length; + } +} + +/** The result of extracting a body: the body and the `Content-Type` it implies, if any. */ +export class ExtractedBody { + body: InnerBody; + type: string | null; + + constructor(body: InnerBody, type: string | null) { + this.body = body; + this.type = type; + } +} + +// --------------------------------------------------------------------------- +// Streams over known contents +// --------------------------------------------------------------------------- + +/** + * Where a body stream's bytes come from. Body streams are created with the Streams standard's + * internal algorithms ("set up with byte reading support"), not through a user-visible + * `UnderlyingSource` and queuing strategy, so changes to `Object.prototype` can't affect them. + */ +export abstract class BodyStreamSource { + /** + * Called once, right after the stream is created. + * + * @param _controller - The stream's controller. + */ + start(_controller: ReadableByteStreamController): void {} + + /** + * Called when the stream wants more bytes. + * + * @param _controller - The stream's controller. + * @returns A promise that settles when the pull is done. + */ + pull(_controller: ReadableByteStreamController): Promise { + return Promise.resolve(); + } + + /** + * Called when the consumer cancels the stream. + * + * @param _reason - The cancellation reason (any value). + * @returns A promise that settles when cleanup is done. + */ + cancel(_reason: unknown): Promise { + return Promise.resolve(); + } +} + +/** + * Create a readable byte stream over a body source. + * + * @param source - The source. + * @returns The stream. + */ +export function createBodyStream(source: BodyStreamSource): ReadableStream { + let controller: ReadableByteStreamController | null = null; + const stream = createReadableByteStream( + (): Promise => Promise.resolve(), + (): Promise => (controller === null ? Promise.resolve() : source.pull(controller)), + (reason: unknown): Promise => source.cancel(reason), + ); + const created = stream._controller; + if (!(created instanceof ReadableByteStreamController)) { + throw new TypeError("A byte stream must have a byte stream controller"); + } + controller = created; + source.start(created); + return stream; +} + +/** A byte source that enqueues one array and closes. */ +class BytesSource extends BodyStreamSource { + private readonly bytes: Uint8Array; + + constructor(bytes: Uint8Array) { + super(); + this.bytes = bytes; + } + + /** + * Enqueue the bytes (a copy, as enqueueing may detach the buffer) and close. + * + * @param controller - The stream's controller. + */ + override start(controller: ReadableByteStreamController): void { + if (this.bytes.length > 0) { + controller.enqueue(this.bytes.slice()); + } + controller.close(); + } +} + +/** + * A byte stream over fixed bytes. + * + * @param bytes - The contents; they're copied when read, so the caller may keep them. + * @returns The stream. + */ +export function bytesToStream(bytes: Uint8Array): ReadableStream { + return createBodyStream(new BytesSource(bytes)); +} + +/** A byte source that reads a multipart body's segments in order, reading files as it goes. */ +class MultipartSource extends BodyStreamSource { + private readonly body: MultipartBody; + private index: number = 0; + + constructor(body: MultipartBody) { + super(); + this.body = body; + } + + /** + * Enqueue the next non-empty segment, or close after the last one. Empty segments (such as an + * empty file) are skipped here: a pull that neither enqueues nor closes would leave the pending + * read waiting forever, since the stream only pulls again when asked to during a pull. + * + * @param controller - The stream's controller. + */ + override async pull(controller: ReadableByteStreamController): Promise { + while (this.index < this.body.segments.length) { + const segment = this.body.segments[this.index]; + this.index++; + if (segment === undefined) { + continue; + } + + let bytes = segment.bytes; + if (bytes === null) { + const file = segment.file; + bytes = file === null ? new Uint8Array(0) : new Uint8Array(await file.arrayBuffer()); + } + if (bytes.length > 0) { + controller.enqueue(bytes.slice()); + if (this.index >= this.body.segments.length) { + controller.close(); + } + return; + } + } + controller.close(); + } +} + +/** A byte source that forwards another stream's chunks through a reader. */ +class ProxySource extends BodyStreamSource { + private readonly reader: ReadableStreamDefaultReader; + + constructor(reader: ReadableStreamDefaultReader) { + super(); + this.reader = reader; + } + + /** + * Forward the next non-empty chunk, or close. Empty chunks are skipped, since a pull that + * neither enqueues nor closes would leave the pending read waiting forever. Each chunk is + * copied: enqueueing into a byte stream transfers the chunk's buffer, and the buffer belongs to + * whoever produced the source stream (and may not be transferable at all). + * + * @param controller - The stream's controller. + */ + override async pull(controller: ReadableByteStreamController): Promise { + for (;;) { + const result = await this.reader.read(); + if (result.done || result.value === undefined) { + controller.close(); + return; + } + + const chunk: unknown = result.value; + if (!(chunk instanceof Uint8Array)) { + // Not a `Uint8Array` (as reading a body requires): error this stream and cancel the + // source, as a pipe does when its destination errors. + const error = new TypeError("Body stream chunks must be Uint8Array"); + this.reader.cancel(error).catch(ignore); + throw error; + } + if (chunk.byteLength > 0) { + controller.enqueue(chunk.slice()); + return; + } + } + } + + /** + * Cancel the source stream. + * + * @param reason - The cancellation reason. + */ + override async cancel(reason: unknown): Promise { + await this.reader.cancel(reason); + } +} + +/** + * Move a body into a new stream that reads from the old one (the spec's "proxy" through an + * identity transform). The old stream is locked and marked disturbed, so its owner's `bodyUsed` + * becomes `true`. + * + * @param body - The body to take over. + * @returns A body over the new stream, with the same source and length. + */ +export function proxyBody(body: InnerBody): InnerBody { + const reader = acquireReadableStreamDefaultReader(body.stream); + body.stream._disturbed = true; + return new InnerBody(createBodyStream(new ProxySource(reader)), body.source, body.length); +} + +// --------------------------------------------------------------------------- +// Extraction +// --------------------------------------------------------------------------- + +/** + * A body over fixed bytes. + * + * @param bytes - The contents. + * @param type - The implied `Content-Type`, or `null`. + * @returns The extracted body. + */ +function fixedBody(bytes: Uint8Array, type: string | null): ExtractedBody { + const source = (): ReadableStream => bytesToStream(bytes); + return new ExtractedBody(new InnerBody(source(), source, bytes.length), type); +} + +/** + * Extract a body from a string (`text/plain;charset=UTF-8`). + * + * @param text - The string; it's UTF-8 encoded. + * @returns The extracted body. + */ +export function extractStringBody(text: string): ExtractedBody { + return fixedBody(utf8Encode(text), "text/plain;charset=UTF-8"); +} + +/** + * Extract a body from bytes (no content type). + * + * @param bytes - The bytes; they're copied. + * @returns The extracted body. + */ +export function extractBytesBody(bytes: Uint8Array): ExtractedBody { + return fixedBody(bytes.slice(), null); +} + +/** + * Extract a body from a `Blob` (its `type`, if not empty). + * + * @param blob - The blob. + * @returns The extracted body. + */ +export function extractBlobBody(blob: Blob): ExtractedBody { + const source = (): ReadableStream => blob.stream(); + return new ExtractedBody( + new InnerBody(source(), source, blob.size), + blob.type === "" ? null : blob.type, + ); +} + +/** + * Extract a body from `URLSearchParams` (`application/x-www-form-urlencoded;charset=UTF-8`). + * + * @param params - The parameters. + * @returns The extracted body. + */ +export function extractSearchParamsBody(params: URLSearchParams): ExtractedBody { + return fixedBody( + utf8Encode(serializeFormUrlencoded(searchParamsList(params))), + "application/x-www-form-urlencoded;charset=UTF-8", + ); +} + +/** + * Extract a body from `FormData` (`multipart/form-data` with a fresh boundary). + * + * @param form - The form. + * @returns The extracted body. + */ +export function extractFormDataBody(form: FormData): ExtractedBody { + const multipart = serializeMultipart(formDataEntries(form), generateBoundary()); + const source = (): ReadableStream => createBodyStream(new MultipartSource(multipart)); + return new ExtractedBody( + new InnerBody(source(), source, multipart.length), + "multipart/form-data; boundary=" + multipart.boundary, + ); +} + +/** + * Extract a body from a stream (no content type, unknown length). + * + * @param stream - The stream. + * @returns The extracted body. + * @throws TypeError if the stream is locked or already read from. + */ +export function extractStreamBody(stream: ReadableStream): ExtractedBody { + if (stream._disturbed || isReadableStreamLocked(stream)) { + throw new TypeError("The body stream is locked or has been read"); + } + return new ExtractedBody(new InnerBody(stream, null, null), null); +} + +/** + * The Fetch "extract a body" algorithm for a `BodyInit`. A value that is none of the union's + * object types converts to a string, as WebIDL's `USVString` member does. + * + * @param object - The body init. + * @returns The extracted body. + * @throws TypeError for a locked or disturbed stream, or a symbol. + */ +export function extractBody(object: BodyInit): ExtractedBody { + const value: unknown = object; + if (typeof value === "string") { + return extractStringBody(value); + } + if (value instanceof ReadableStream) { + return extractStreamBody(value); + } + if (value instanceof Blob) { + return extractBlobBody(value); + } + if (value instanceof FormData) { + return extractFormDataBody(value); + } + if (value instanceof URLSearchParams) { + return extractSearchParamsBody(value); + } + if (value instanceof Uint8Array) { + return extractBytesBody(value); + } + if (value instanceof ArrayBuffer) { + return extractBytesBody(new Uint8Array(value)); + } + if (ArrayBuffer.isView(value)) { + return extractBytesBody(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)); + } + return extractStringBody(toUSVString(value)); +} + +// --------------------------------------------------------------------------- +// The Body mixin +// --------------------------------------------------------------------------- + +/** + * Whether a body has been read from or canceled (the mixin's `bodyUsed`). + * + * @param body - The body, or `null`. + * @returns `true` if the stream is disturbed. + */ +export function isBodyUsed(body: InnerBody | null): boolean { + return body !== null && body.stream._disturbed; +} + +/** + * Whether a body can't be read: it has been read from, or its stream is locked. + * + * @param body - The body, or `null`. + * @returns `true` if unusable. + */ +export function isBodyUnusable(body: InnerBody | null): boolean { + return body !== null && (body.stream._disturbed || isReadableStreamLocked(body.stream)); +} + +/** Swallow a rejection that nobody can observe. */ +function ignore(): void {} + +/** + * Read a stream to the end through read requests (the Streams "read all bytes" steps), then + * convert the bytes. Reading doesn't go through promises of read results, so a patched + * `Object.prototype.then` can't intercept chunks. + * + * @param stream - The stream; it's locked to a new reader. + * @param convert - Turns the bytes into the result; an exception it throws rejects the promise. + * @returns The converted result. + * @throws (rejects) TypeError if a chunk isn't a `Uint8Array`; the stream's error if it errors. + */ +function readAllAndConvert( + stream: ReadableStream, + convert: (bytes: Uint8Array) => T, +): Promise { + const result = new Deferred(); + const reader = acquireReadableStreamDefaultReader(stream); + const chunks: Uint8Array[] = []; + let pumping = false; + let again = false; + let request: CallbackReadRequest | null = null; + + // Chunks may be delivered synchronously from inside a read, so reads loop here instead of + // recursing from the chunk steps. + const pump = (): void => { + if (pumping) { + again = true; + return; + } + pumping = true; + do { + again = false; + if (request !== null) { + readableStreamDefaultReaderRead(reader, request); + } + } while (again); + pumping = false; + }; + + request = new CallbackReadRequest( + (chunk: Uint8Array): void => { + if (!(chunk instanceof Uint8Array)) { + const error = new TypeError("Body stream chunks must be Uint8Array"); + reader.cancel(error).catch(ignore); + result.reject(error); + return; + } + chunks.push(chunk); + pump(); + }, + (): void => { + let value: T; + try { + value = convert(concatBytes(chunks)); + } catch (e) { + result.reject(e); + return; + } + result.resolve(value); + }, + (e: unknown): void => result.reject(e), + ); + pump(); + return result.promise; +} + +/** + * Read a stream to the end. + * + * @param stream - The stream. + * @returns All of its bytes. + * @throws (rejects) TypeError if a chunk isn't a `Uint8Array`; the stream's error if it errors. + */ +export function readAllBytes(stream: ReadableStream): Promise { + return readAllAndConvert(stream, (bytes: Uint8Array): Uint8Array => bytes); +} + +/** + * "Consume body": read everything and convert it, or reject if the body is unusable. + * + * @param body - The body, or `null` for an empty one. + * @param convert - Turns the bytes into the result. + * @returns The converted body. + * @throws (rejects) TypeError if the body was already read or is locked. + */ +export function consumeBody( + body: InnerBody | null, + convert: (bytes: Uint8Array) => T, +): Promise { + if (body === null) { + try { + return Promise.resolve(convert(new Uint8Array(0))); + } catch (e) { + return Promise.reject(e); + } + } + if (isBodyUnusable(body)) { + return Promise.reject(new TypeError("Body has already been read or is locked")); + } + return readAllAndConvert(body.stream, convert); +} + +/** + * The mixin's `text()`. + * + * @param body - The body. + * @returns The body decoded as UTF-8 (BOM removed). + */ +export function bodyText(body: InnerBody | null): Promise { + return consumeBody(body, (bytes: Uint8Array): string => utf8Decode(bytes, true)); +} + +/** + * The mixin's `json()`. + * + * @param body - The body. + * @returns The parsed JSON value. + * @throws (rejects) SyntaxError if the body isn't JSON. + */ +export function bodyJson(body: InnerBody | null): Promise { + return consumeBody(body, (bytes: Uint8Array): unknown => JSON.parse(utf8Decode(bytes, true))); +} + +/** + * The mixin's `arrayBuffer()`. + * + * @param body - The body. + * @returns The bytes in a new `ArrayBuffer`. + */ +export function bodyArrayBuffer(body: InnerBody | null): Promise { + return consumeBody(body, (bytes: Uint8Array): ArrayBuffer => { + const copy = new Uint8Array(bytes.length); + copy.set(bytes); + return copy.buffer; + }); +} + +/** + * The mixin's `bytes()`. + * + * @param body - The body. + * @returns The bytes. + */ +export function bodyBytes(body: InnerBody | null): Promise { + return consumeBody(body, (bytes: Uint8Array): Uint8Array => bytes); +} + +/** + * The mixin's `blob()`. + * + * @param body - The body. + * @param contentType - The owner's combined `Content-Type` value, or `null`. + * @returns A `Blob` of the bytes, typed with the extracted MIME type (or `""`). + */ +export function bodyBlob(body: InnerBody | null, contentType: string | null): Promise { + const mime = extractMimeType(contentType); + return consumeBody( + body, + (bytes: Uint8Array): Blob => + new Blob([bytes], { type: mime === null ? "" : serializeMimeType(mime) }), + ); +} + +/** + * The mixin's `formData()`, for `multipart/form-data` and `application/x-www-form-urlencoded`. + * + * @param body - The body. + * @param contentType - The owner's combined `Content-Type` value, or `null`. + * @returns The parsed form. + * @throws (rejects) TypeError for another content type or a malformed body. + */ +export function bodyFormData( + body: InnerBody | null, + contentType: string | null, +): Promise { + // A missing body isn't a multipart body, while an empty one is an empty form (what a form with + // no entries serializes to); WPT expects both. + const nullBody = body === null; + return consumeBody( + body, + (bytes: Uint8Array): FormData => parseFormBody(bytes, contentType, nullBody), + ); +} + +/** + * Parse a body as a form, by its content type. + * + * @param bytes - The body. + * @param contentType - The combined `Content-Type` value, or `null`. + * @param nullBody - Whether there was no body at all, which isn't a valid multipart body. + * @returns The form. + * @throws TypeError for another content type or a malformed body. + */ +function parseFormBody(bytes: Uint8Array, contentType: string | null, nullBody: boolean): FormData { + const mime = extractMimeType(contentType); + const form = new FormData(); + + if (mime !== null && mime.essence === "multipart/form-data") { + const boundary = mime.parameter("boundary"); + if (boundary === null || boundary === "") { + throw new TypeError("multipart/form-data body without a boundary"); + } + if (nullBody) { + throw new TypeError("Missing multipart/form-data body"); + } + for (const entry of parseMultipart(bytes, boundary)) { + appendFormDataEntry(form, entry); + } + return form; + } + if (mime !== null && mime.essence === "application/x-www-form-urlencoded") { + for (const pair of parseFormUrlencodedBytes(bytes)) { + appendFormDataEntry(form, new FormDataEntry(pair.name, pair.value, null)); + } + return form; + } + throw new TypeError( + "Body's Content-Type is not multipart/form-data or application/x-www-form-urlencoded", + ); +} + +/** + * "Clone a body": tee its stream, keep one branch and return a body over the other. + * + * @param body - The body; its stream is replaced by the first branch. + * @returns A new body over the second branch. + */ +export function cloneBody(body: InnerBody): InnerBody { + const branches = body.stream.tee(); + const first = branches[0]; + const second = branches[1]; + if (first === undefined || second === undefined) { + throw new TypeError("tee() did not return two branches"); + } + body.stream = first; + return new InnerBody(second, body.source, body.length); +} diff --git a/packages/jco-std/src/wintertc/compression.ts b/packages/jco-std/src/wintertc/compression.ts new file mode 100644 index 0000000000..1ce52cd57d --- /dev/null +++ b/packages/jco-std/src/wintertc/compression.ts @@ -0,0 +1,233 @@ +/** + * `CompressionStream` and `DecompressionStream` (Compression Streams standard), over the + * `jco:wintertc/compression` component. + * + * Each stream is a `TransformStream` whose transformer feeds chunks to a compressor or + * decompressor in Rust (`miniz_oxide`) and enqueues the output. Using this module makes the + * component import `jco:wintertc/compression@0.1.0`; compose it with `wintertc-compression.wasm` + * (see the jco book page "WinterTC APIs"). + * + * The component keeps each stream's state under a handle, released when the stream finishes, + * errors or is canceled. A stream that is dropped while still open keeps its handle (and its + * window, about 300 KiB for compression) until it is garbage collected, when a + * `FinalizationRegistry` releases it (on engines that have one). + * + * Spec deviations: + * - The `brotli` format is not supported (constructing with it throws a `TypeError`): the + * component has no Brotli codec. + * - `Symbol.toStringTag` is an accessor on the prototype, not a data property. + */ +import { + compressorCreate, + decompressorCreate, + finish, + free, + push, +} from "jco:wintertc/compression@0.1.0"; +import type { Outcome } from "jco:wintertc/compression@0.1.0"; + +import { toDOMString } from "./internal/utf8.js"; +import type { ReadableStream, Transformer, WritableStream } from "./streams/index.js"; +import { TransformStream } from "./streams/index.js"; +import type { TransformStreamDefaultController } from "./streams/index.js"; +import type { BufferSource } from "./subtle-crypto.js"; + +/** A format of the Compression Streams standard. */ +export type CompressionFormat = "deflate" | "deflate-raw" | "gzip"; + +/** + * View a `BufferSource` chunk as bytes. + * + * @param chunk - The chunk written to the stream. + * @returns Its bytes. + * @throws TypeError if the chunk is not an `ArrayBufferView` or `ArrayBuffer`, or is backed by + * shared memory. + */ +function chunkBytes(chunk: BufferSource): Uint8Array { + const value: unknown = chunk; + // A BufferSource excludes views on shared memory. + const shared = typeof SharedArrayBuffer === "function"; + if (value !== null && value !== undefined) { + if (ArrayBuffer.isView(value) && !(shared && value.buffer instanceof SharedArrayBuffer)) { + return new Uint8Array(value.buffer, value.byteOffset, value.byteLength); + } + if (value instanceof ArrayBuffer) { + return new Uint8Array(value); + } + } + throw new TypeError("The chunk is not a BufferSource"); +} + +/** Releases the component streams of transformers garbage collected while open. */ +let openStreams: FinalizationRegistry | null = null; + +/** + * The registry that releases the component streams of transformers garbage collected while open. + * + * @returns The registry, or `null` if the engine has no `FinalizationRegistry`. + */ +function streamRegistry(): FinalizationRegistry | null { + if (openStreams === null && typeof FinalizationRegistry === "function") { + openStreams = new FinalizationRegistry((handle) => free(handle)); + } + return openStreams; +} + +/** Feeds chunks to a component stream and enqueues its output. */ +class ComponentTransformer implements Transformer { + private handle: number; + + constructor(handle: number) { + this.handle = handle; + streamRegistry()?.register(this, handle, this); + } + + /** Release the component stream, once. */ + private release(): void { + if (this.handle !== 0) { + streamRegistry()?.unregister(this); + free(this.handle); + } + this.handle = 0; + } + + /** + * Enqueue a step's output, or release the stream and throw if it failed. + * + * @param outcome - The step's outcome. + * @param controller - The stream's controller. + */ + private deliver( + outcome: Outcome, + controller: TransformStreamDefaultController, + ): void { + // Output decoded before data after the end of the stream is delivered before the error. + if (outcome.bytes.length > 0) { + controller.enqueue(outcome.bytes); + } + if (!outcome.ok) { + this.release(); + throw new TypeError(`Decompression failed: ${outcome.error}`); + } + } + + /** + * Compress or decompress one chunk. + * + * @param chunk - The input bytes. + * @param controller - The stream's controller. + */ + transform(chunk: BufferSource, controller: TransformStreamDefaultController): void { + // A rejected chunk errors the stream without calling `cancel`, so release the handle here. + let bytes: Uint8Array; + try { + bytes = chunkBytes(chunk); + } catch (e) { + this.release(); + throw e; + } + if (bytes.length === 0) { + return; + } + this.deliver(push(this.handle, bytes), controller); + } + + /** + * End the stream, enqueueing the remaining output. + * + * @param controller - The stream's controller. + */ + flush(controller: TransformStreamDefaultController): void { + const outcome = finish(this.handle); + this.deliver(outcome, controller); + this.release(); + } + + /** The stream was canceled or aborted: release the component stream. */ + cancel(): void { + this.release(); + } +} + +/** + * Check a format argument. + * + * @param format - The format. + * @param create - The component's create function. + * @returns A handle for a new component stream. + * @throws TypeError for an unsupported format. + */ +function open(format: string, create: (format: string) => number): number { + // WebIDL enum conversion: convert to a string first, then check the value. + const name = toDOMString(format); + const handle = name === "deflate" || name === "deflate-raw" || name === "gzip" ? create(name) : 0; + if (handle === 0) { + throw new TypeError(`Unsupported compression format: '${name}'`); + } + return handle; +} + +/** Compresses a stream of bytes. */ +export class CompressionStream { + private readonly transform: TransformStream; + + /** + * Create a compressing transform stream. + * + * @param format - `"deflate"` (ZLIB), `"deflate-raw"` or `"gzip"`. + * @throws TypeError for an unsupported format. + */ + constructor(format: CompressionFormat) { + this.transform = new TransformStream( + new ComponentTransformer(open(format, compressorCreate)), + ); + } + + /** The compressed output. */ + get readable(): ReadableStream { + return this.transform.readable; + } + + /** Where to write the bytes to compress. */ + get writable(): WritableStream { + return this.transform.writable; + } + + /** The interface name, for `Object.prototype.toString`. */ + get [Symbol.toStringTag](): string { + return "CompressionStream"; + } +} + +/** Decompresses a stream of bytes. */ +export class DecompressionStream { + private readonly transform: TransformStream; + + /** + * Create a decompressing transform stream. The stream errors with a `TypeError` if the input is + * corrupt, ends early, or continues after the end of the compressed data. + * + * @param format - `"deflate"` (ZLIB), `"deflate-raw"` or `"gzip"`. + * @throws TypeError for an unsupported format. + */ + constructor(format: CompressionFormat) { + this.transform = new TransformStream( + new ComponentTransformer(open(format, decompressorCreate)), + ); + } + + /** The decompressed output. */ + get readable(): ReadableStream { + return this.transform.readable; + } + + /** Where to write the compressed bytes. */ + get writable(): WritableStream { + return this.transform.writable; + } + + /** The interface name, for `Object.prototype.toString`. */ + get [Symbol.toStringTag](): string { + return "DecompressionStream"; + } +} diff --git a/packages/jco-std/src/wintertc/console.ts b/packages/jco-std/src/wintertc/console.ts new file mode 100644 index 0000000000..c8fa26ada5 --- /dev/null +++ b/packages/jco-std/src/wintertc/console.ts @@ -0,0 +1,724 @@ +/** + * The `console` namespace (Console standard), writing UTF-8 lines to `wasi:cli/stdout@0.3.0` and + * `wasi:cli/stderr@0.3.0`. + * + * `log`, `info` and `debug` (and `count`, `group`, `time*`, `table`, `dir`, `dirxml`) write to + * stdout; `warn`, `error`, `trace` and `assert` write to stderr. Nested groups indent by two spaces. + * Output is queued and sent asynchronously, in order per stream (see `flushOutput()`). + * + * As a WebIDL namespace object, `console` has a [[Prototype]] that is an empty object inheriting + * from `Object.prototype`, its members are writable, enumerable and configurable data properties, + * and its own `Symbol.toStringTag` is `"console"`. + * + * Object formatting (`%o`, `%O`, values after the format string, `dir`, `table` cells) is + * implementation-defined in the standard. It shows constructor names, own enumerable properties + * (accessors as `[Getter]` without calling them), array, typed array, `Map` and `Set` contents (at + * most 100 items each) and two levels of nesting, and marks cycles as `[Circular]`. + * + * Spec deviations: + * - Without engine internals, a `Promise`'s state, a `WeakMap`'s or `WeakSet`'s entries and a + * proxy's target can't be shown; inspecting a proxy runs its traps. + * - `trace` prints the engine's `Error().stack`, which some engines leave empty. + * + * Non-standard additions: + * - `flushOutput()`, exported next to `console`; see its documentation for why it exists. + */ +import { monotonicNow } from "./internal/monotonic-clock.js"; +import { flushOutput as flushOutputStreams } from "./internal/output.js"; +import type { OutputTarget } from "./internal/output.js"; +import { + DEFAULT_INSPECT_DEPTH, + describeError, + getGroupDepth, + inspect, + setGroupDepth, + writeLine, +} from "./internal/console-output.js"; + +/** The `console` namespace. */ +export interface Console { + /** + * Log at "log" level. + * + * @param data - Values to print; a leading string may contain `%s`, `%d`, `%i`, `%f`, `%o`, `%O` + * and `%c` format specifiers. + */ + log(...data: unknown[]): void; + + /** + * Log at "info" level. + * + * @param data - Values to print. + */ + info(...data: unknown[]): void; + + /** + * Log at "debug" level. + * + * @param data - Values to print. + */ + debug(...data: unknown[]): void; + + /** + * Log at "warn" level (stderr). + * + * @param data - Values to print. + */ + warn(...data: unknown[]): void; + + /** + * Log at "error" level (stderr). + * + * @param data - Values to print. + */ + error(...data: unknown[]): void; + + /** + * Log "Assertion failed" and `data` at "error" level if `condition` is false. + * + * @param condition - The asserted condition. + * @param data - Values to print on failure. + */ + assert(condition?: boolean, ...data: unknown[]): void; + + /** + * Log `data` followed by the current stack trace (stderr). + * + * @param data - Values to print. + */ + trace(...data: unknown[]): void; + + /** + * Log `tabularData` as a table with a row per property (or element) and a column per property + * of the rows; values that aren't objects are logged as they are. + * + * @param tabularData - The data. + * @param properties - The columns to show; all of them when absent. + */ + table(tabularData?: unknown, properties?: Iterable): void; + + /** + * Log one value with its properties. + * + * @param item - The value. + * @param options - `{ depth }`: how many levels of nested objects to expand (`null` for all). + */ + dir(item?: unknown, options?: object | null): void; + + /** + * Log values, as `log` does. + * + * @param data - Values to print. + */ + dirxml(...data: unknown[]): void; + + /** Reset the group indentation. Output already written can't be cleared. */ + clear(): void; + + /** + * Increment and log the counter for `label`. + * + * @param label - The counter name; defaults to `"default"`. + */ + count(label?: string): void; + + /** + * Reset the counter for `label` to zero. + * + * @param label - The counter name; defaults to `"default"`. + */ + countReset(label?: string): void; + + /** + * Log `data`, if any, and indent subsequent output. + * + * @param data - The group label. + */ + group(...data: unknown[]): void; + + /** + * Same as `group`. + * + * @param data - The group label. + */ + groupCollapsed(...data: unknown[]): void; + + /** End the innermost group. */ + groupEnd(): void; + + /** + * Start the timer `label`. + * + * @param label - The timer name; defaults to `"default"`. + */ + time(label?: string): void; + + /** + * Log the elapsed time of timer `label`, followed by `data`. + * + * @param label - The timer name; defaults to `"default"`. + * @param data - Extra values to print. + */ + timeLog(label?: string, ...data: unknown[]): void; + + /** + * Log the elapsed time of timer `label` and stop it. + * + * @param label - The timer name; defaults to `"default"`. + */ + timeEnd(label?: string): void; +} + +/** Per-label state for `count` and `time`, created on first use. */ +class ConsoleState { + readonly counts: Map = new Map(); + readonly timers: Map = new Map(); + + constructor() {} +} + +let state: ConsoleState | null = null; + +/** + * The console's label state. + * + * @returns The state, created on first use. + */ +function consoleState(): ConsoleState { + if (state === null) { + state = new ConsoleState(); + } + return state; +} + +/** + * Convert a value for `%s`: `String(value)`, except that bigints keep their `n` suffix, `-0` its + * sign and errors print with their stack. An object whose conversion throws is inspected instead. + * + * @param value - The value. + * @returns Its text. + */ +function display(value: unknown): string { + if (typeof value === "string") { + return value; + } + if (typeof value === "bigint") { + return String(value) + "n"; + } + if (typeof value === "number") { + return Object.is(value, -0) ? "-0" : String(value); + } + if (value instanceof Error) { + return describeError(value); + } + try { + return String(value); + } catch { + return inspect(value, DEFAULT_INSPECT_DEPTH, true); + } +} + +/** + * Convert a value for `%d` and `%i`: `parseInt(value, 10)`, `NaN` for symbols. + * + * @param value - The value. + * @returns Its integer text, or `NaN`. + */ +function integer(value: unknown): string { + if (typeof value === "bigint") { + return String(value) + "n"; + } + if (typeof value === "number") { + return String(Math.trunc(value)); + } + if (typeof value === "symbol") { + return "NaN"; + } + try { + return String(Number.parseInt(String(value), 10)); + } catch { + return "NaN"; + } +} + +/** + * Convert a value for `%f`: `parseFloat(value)`, `NaN` for symbols. + * + * @param value - The value. + * @returns Its floating-point text, or `NaN`. + */ +function float(value: unknown): string { + if (typeof value === "number") { + return String(value); + } + if (typeof value === "bigint") { + return String(Number(value)); + } + if (typeof value === "symbol") { + return "NaN"; + } + try { + return String(Number.parseFloat(String(value))); + } catch { + return "NaN"; + } +} + +/** + * Format a value as the Printer does with the values left after format specifiers: strings as + * they are, everything else inspected. + * + * @param value - The value. + * @returns Its text. + */ +function printed(value: unknown): string { + return inspect(value, DEFAULT_INSPECT_DEPTH, true); +} + +/** + * The Console standard's Formatter followed by the Printer's joining: substitute format specifiers + * in a leading string, then join the remaining values with spaces. + * + * @param data - The logged values. + * @returns The line to print. + */ +function format(data: unknown[]): string { + if (data.length === 0) { + return ""; + } + const first = data[0]; + let rest = 1; + let head: string; + + if (typeof first === "string" && data.length > 1) { + head = ""; + let i = 0; + while (i < first.length) { + const unit = first.charAt(i); + const next = first.charAt(i + 1); + if (unit !== "%" || i + 1 >= first.length) { + head += unit; + i++; + continue; + } + if (next === "%") { + head += "%"; + i += 2; + continue; + } + const isSpecifier = + next === "s" || + next === "d" || + next === "i" || + next === "f" || + next === "o" || + next === "O" || + next === "c"; + if (!isSpecifier || rest >= data.length) { + head += unit; + i++; + continue; + } + const value = data[rest]; + rest++; + if (next === "s") { + head += display(value); + } else if (next === "d" || next === "i") { + head += integer(value); + } else if (next === "f") { + head += float(value); + } else if (next === "o" || next === "O") { + head += inspect(value, DEFAULT_INSPECT_DEPTH, false); + } + i += 2; + } + } else { + head = printed(first); + } + + let line = head; + for (let i = rest; i < data.length; i++) { + line += " " + printed(data[i]); + } + return line; +} + +/** + * The Console standard's Logger: print `data` unless it is empty. + * + * @param target - Where to write. + * @param data - The logged values. + */ +function logger(target: OutputTarget, data: unknown[]): void { + if (data.length === 0) { + return; + } + writeLine(target, format(data)); +} + +/** + * Convert a label argument as WebIDL `DOMString` does for untyped callers. + * + * @param label - The label. + * @returns The label text. + * @throws `TypeError` for a symbol. + */ +function labelOf(label: unknown): string { + if (typeof label === "symbol") { + throw new TypeError("Cannot convert a Symbol value to a string"); + } + return String(label); +} + +/** + * Format a duration for `timeLog` and `timeEnd`. + * + * @param label - The timer name. + * @param start - The start time on the monotonic clock. + * @returns `"