diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 9736c7c4d..eb3b81b38 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -314,6 +314,47 @@ updates: update-types: - version-update:semver-major + # ── Cargo (recipher-js, the Rust half of @cipherstash/recipher) ── + # The recipher-js workspace and the value bridge's test addon, a workspace + # of its own that depends on the bridge by path. Grouped by dependency + # name, so one PR moves a crate in both lockfiles: + # scripts/__tests__/recipher-js-lock-parity.test.mjs fails when they + # resolve different napi or vitaminc crates. + - package-ecosystem: cargo + directories: + - /languages/typescript/packages/recipher-js + - /languages/typescript/packages/recipher-js/value-napi/tests/addon + # Lockfile only, like the other cargo entries: the addon shares a crate + # with the workspace by path. + versioning-strategy: lockfile-only + schedule: + interval: monthly + cooldown: + default-days: 7 + open-pull-requests-limit: 3 + labels: + - dependencies + - supply-chain + commit-message: + prefix: "chore" + include: scope + groups: + recipher-js-cargo: + group-by: dependency-name + patterns: + - "*" + update-types: + - minor + - patch + ignore: + # The bridge reads values into the plaintext model the engine uses, so + # vitaminc moves with the engine, by hand. + - dependency-name: "vitaminc*" + # Major bumps are reviewed and applied manually, not by Dependabot. + - dependency-name: "*" + update-types: + - version-update:semver-major + # ── Go (languages/golang) ────────────────────────────────────── # One entry for the three modules, grouped by dependency name, so one PR # moves a dependency in all of them. The nested modules replace the SDK diff --git a/.github/workflows/tests-recipher-js.yml b/.github/workflows/tests-recipher-js.yml new file mode 100644 index 000000000..5ecf01545 --- /dev/null +++ b/.github/workflows/tests-recipher-js.yml @@ -0,0 +1,94 @@ +name: Tests (recipher-js) + +# The Rust half of `@cipherstash/recipher`, the TypeScript SDK on the Stack +# Encrypt engine: its detached Cargo workspace. For now the workspace has one +# crate, `recipher-value-napi` (`value-napi/`), the value bridge that reads +# JavaScript values into vitaminc's plaintext model and builds them back. +# +# `cargo test` runs the bridge's unit tests and `tests/node.rs`, which builds +# the bridge's test addon (`value-napi/tests/addon`, a workspace of its own) +# and runs the Node suites against it. Every test here is offline, so the job +# takes no credentials. + +on: + pull_request: + paths: + - languages/typescript/packages/recipher-js/** + - mise.toml + - .github/workflows/tests-recipher-js.yml + push: + branches: [main] + paths: + - languages/typescript/packages/recipher-js/** + - mise.toml + - .github/workflows/tests-recipher-js.yml + workflow_dispatch: {} + +permissions: + contents: read + +defaults: + run: + shell: bash + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + RUST_BACKTRACE: full + CARGO_TERM_COLOR: always + CARGO_NET_GIT_FETCH_WITH_CLI: true + +jobs: + recipher-js: + name: cargo checks (Linux) + runs-on: blacksmith-16vcpu-ubuntu-2204 + # The slowest run so far took under three minutes. A run that is still + # going at ten is stuck, not slow: stop it rather than pay for 45. + timeout-minutes: 10 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + with: + persist-credentials: false + + # At the repository root: the root mise.toml pins rust 1.94.1. + - uses: jdx/mise-action@1648a7812b9aeae629881980618f079932869151 # v4 + with: + version: 2026.4.0 + install: true + working_directory: . + install_args: rust + cache: true + # Must name runs-on's image; see scripts/__tests__/workflow-mise-cache-image.test.mjs + cache_key_prefix: mise-v1-ubuntu-2204 + + # As in tests-crates.yml: a cached toolchain can lack the components + # mise.toml declares. A no-op when they are there. + - name: Add rustfmt and clippy to the pinned toolchain + run: rustup component add rustfmt clippy + + - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2 + with: + workspaces: languages/typescript/packages/recipher-js -> target + + # `tests/node.rs` runs the bridge's Node suites with `node`. + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + with: + node-version: 22 + + # `cargo test --locked`, `cargo fmt --check` and clippy, with every + # feature. The test addon is a workspace of its own, which `--all` + # does not reach, so it is checked by its manifest. Its clippy shares + # the directory `tests/node.rs` builds it in. It has no tests, and + # without them `--all-targets` would report its module entry point + # unused. + - name: cargo checks + working-directory: languages/typescript/packages/recipher-js + run: | + cargo test --locked --all-features + cargo fmt --all --check + cargo clippy --locked --all-targets --all-features -- -D warnings + cargo fmt --manifest-path value-napi/tests/addon/Cargo.toml --check + cargo clippy --locked --manifest-path value-napi/tests/addon/Cargo.toml \ + --target-dir target/napi-test-addon -- -D warnings diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index f0003ed28..31b4354e9 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -109,6 +109,15 @@ jobs: - '!packages/stack-kms/**' - '!packages/stack-guest-abi/**' - '!packages/stack-auth/fuzz/**' + # The TypeScript SDK on Stack Encrypt. Nothing these jobs build + # depends on it, and tests-recipher-js.yml runs its tests. + - '!languages/typescript/packages/recipher-js/**' + # Dependabot's config and the repo tooling's own tests. Their + # readers (`test:scripts`, the supply-chain test) run in + # `repo-checks`, which is not gated. `biome.json` stays in: the + # auth and profile packages run Biome in their `test` script. + - '!.github/dependabot.yml' + - '!scripts/__tests__/**' # EQL's SQL sources, test suites, codegen and tasks. What the # jobs do read from here is selected by `direct` below. - '!packages/eql/**' diff --git a/AGENTS.md b/AGENTS.md index f4cdc35ee..c05a25f86 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -92,6 +92,7 @@ Every npm package except EQL lives under `languages/typescript/`: packages in `l links are provenance only. - `packages/stack-auth`, `packages/stack-profile`, `packages/stack-kms`, `packages/stack-encrypt`, `packages/stack-encrypt-derive`, `packages/stack-encrypt-jsonpath`, `packages/stack-guest-abi`: The Rust crates imported from `cipherstash/cipherstash-suite` with their history, and one added here — `stack-auth` and `stack-profile` (published to crates.io, one version group), `stack-kms` (published to crates.io from 0.1.0, its own version group, re-exported by `stack-encrypt` as `stack_encrypt::kms`), `stack-encrypt` and `stack-encrypt-derive` (published to crates.io from 0.1.0, one version group; `eql-bindings`' `stack-encrypt` feature depends on them from the registry), `stack-encrypt-jsonpath` (the JSONPath grammar of the JSON index and the SQL/JSON path predicate grammar its `match` operator reads, moved out of `stack-encrypt` so the derive can check a field's declared paths, and `predicate!` a predicate's text, at compile time; in the `stack-encrypt` version group, re-exported at `stack_encrypt::json`; its first version is published by hand, as the others' were, before Trusted Publishing can take it), and `stack-guest-abi` (`publish = false`). They are the members of the **root Cargo workspace**, with the three node binding crates below. See "Working on the Rust crates". - `languages/typescript/packages/auth`, `languages/typescript/packages/profile`, `languages/typescript/packages/stack-auth-wasm`: The node bindings of those crates. `@cipherstash/auth` (napi-rs v2) and its six `platforms/*` packages are published to npm from this repository by `release.yml` (`auth-artifacts`, `publish-auth`); a change to what it ships, the `stack-auth` crate included, needs an `@cipherstash/auth` changeset (`require-auth-npm-changeset.yml`). `@cipherstash/profile` and its platforms are private and never published; `@cipherstash/stack-auth-wasm` is private and builds the wasm that `@cipherstash/auth` ships. Their `build` and `test` scripts never invoke cargo; `build:native`, `build:debug` and `test:cargo` do. `@cipherstash/auth` also ships two pure-JS framework adapters over the wasm `OidcFederationStrategy`: `./next` (Next.js App Router, hands the token to the render on a request header) and `./start` (TanStack Start: `csFederateCurrent` is called inside a function middleware the app declares itself, which hands the token to the server function through `next({ context })`; `@tanstack/react-start` is an optional peer loaded only by that entry). +- `languages/typescript/packages/recipher-js`: The Rust half of `@cipherstash/recipher`, the TypeScript SDK on the Stack Encrypt engine (design: `docs/plans/2026-11-22-recipher-typescript-sdk.md`). For now it holds the value bridge alone: `value-napi/` (crate `recipher-value-napi`, napi-rs 3), which reads JavaScript values into vitaminc's plaintext model and builds JavaScript values from it. It is a copy of vitaminc's `vitaminc-aead-napi` 0.10.0, unpublished (`publish = false`), the one member of a **detached Cargo workspace** with its own `Cargo.lock`. The root workspace names its members, so it needs no `exclude` entry there; leave the root `Cargo.toml` alone, because a change to it starts every stack-* crate workflow. It has a detached test addon workspace of its own at `value-napi/tests/addon`, which its `tests/node.rs` builds before it runs the Node suites against it, and vitaminc's value conformance corpus at `value-napi/tests/testdata`; Biome does not check that directory. `.github/workflows/tests-recipher-js.yml` is the only workflow a change under the directory runs, apart from `tests.yml`'s ungated lint and repo checks: it runs `cargo test --locked`, `cargo fmt --check` and clippy over the workspace, and fmt and clippy over the test addon by its manifest. One Dependabot cargo entry covers both lockfiles, and `scripts/__tests__/recipher-js-lock-parity.test.mjs` fails when they resolve different napi or vitaminc crates. - `languages/golang`: The Go module — the SDK `encrypt` with its generated-code support `encrypt/gensupport`, its test package `encrypt/encrypttest` (context assertions, and `NewClient`: an offline client over the deterministic test builds, for an application's tests; a **nested Go module** of its own, so only a program that imports it downloads those builds, requiring the SDK at the zero pseudo-version with `replace ../..` in the tree, and `NewClient` fails when the two are at different versions) and the policy packages `encrypt/policy` and `encrypt/policy/protosource`; the credential package `auth`; the generator `stashgen` and its command `cmd/stashgen`; and `internal` (the shared guest plumbing and the `record` wire model). A wazero host with no cgo. Its two WASI guests (`encrypt/guest`, `auth/guest`) are detached Cargo workspaces built by `mise run wasm:guest:build` and `mise run wasm:auth-guest:build`; `mise run wasm:guest:build:deterministic` and `wasm:guest:build:eql:deterministic` build the seeded TEST builds into `encrypt/encrypttest/wasm`, which `encrypttest` embeds and the hermetic Go tests read; the `.wasm` files are gitignored. The stack-encrypt guest has a second build with the EQL types (`mise run wasm:guest:build:eql`, cargo feature `eql`, linking `eql-bindings` by path; `wasm:guest:build:eql:deterministic` is its test build), embedded by `encrypt/eql` and registered on import, so a program whose generated code names an EQL type runs it (ADR-0007, amended). `encrypt/eql`'s types and `Types` table are generated from the EQL catalog by `eql-codegen` (`eql_gen.go`, written by `mise run types:generate` in `packages/eql` and drift-gated by `types:check` and `cargo test -p eql-codegen`). Generated `*_stash.go` files are committed and CI fails when `go generate ./...` changes one. Releases are cut by hand with `.github/workflows/release-golang.yml` (`gh workflow run release-golang.yml -f version=X.Y.Z[-pre] --ref `): because the guests are gitignored on main and Go fetches a version as the files committed at its tag, the workflow builds them, commits them on a release-only commit no branch points at, with `encrypt/encrypttest/go.mod` pinned to the SDK version by `scripts/go-release-pin-encrypttest.sh` (run in `build` and in `publish`), tags it `languages/golang/vX.Y.Z` and `languages/golang/encrypt/encrypttest/vX.Y.Z` (the workflow's `MODULES`) and pushes the tags alone, then attaches the EQL v4 SQL bundle to the GitHub release. The ref must carry the EQL v4 bundle, or the build stops at "Build the EQL SQL bundles". `scripts/go-release-version.mjs` refuses, before anything is built, every version Go would refuse (non-canonical semver, `+build` metadata, a v2+ major on a module path with no `/vN` suffix, a version shaped like a pseudo-version), a final version dispatched from anywhere but `main`, and a final version while `languages/golang/go.mod` pins a `github.com/cipherstash/vitaminc/…` module at a pseudo-version (vitaminc's Go bindings have no tags, and a TEMPORARY pin on an unreleased commit must be gone before the module is tagged); a pre-release may come from a branch and may carry such a pin. The build job also refuses a version the Go proxy already lists in `@v/list`, which catches a tag deleted after the proxy fetched it; it never asks the proxy for the version itself before the tag exists, because the proxy would cache "not found" for up to 30 minutes and `verify` would fail after the push. The build checks the `Cargo.lock` of the EQL workspace and both guest workspaces with `--locked` first, since none of those builds passes it. It runs in a job with no write token and hands the guests to a `publish` job that holds `contents: write` and runs only git and gh. `publish` fetches the commit with plain unauthenticated git rather than `actions/checkout`, whose `token` input defaults to the job's writable token, and refuses a release commit whose tree is not the one the build tested. `publish` takes the paths it commits from the workflow's fixed `GUESTS` list, never from the artifact, and refuses a `guests.sha256` that is not exactly one SHA-256 line for each of those five guests (the three production guests and the two test builds `encrypttest` embeds): the build job runs third-party code after writing that manifest, so a path read from it could put any file on the tag (`scripts/__tests__/go-release-artifact.test.mjs`). The release page's notes are the version's `## [X.Y.Z]` section of `languages/golang/CHANGELOG.md`, taken by `scripts/go-release-notes.mjs` in a `notes` job that runs no third-party code and that `build` waits for: a version with no section, or an empty one, is refused before anything is built, so write the section before dispatching. A version is immutable once the Go proxy has fetched it, so a tag is never moved or deleted: if `publish` or `verify` fails after the tag is pushed, use "Re-run failed jobs" on the same run, which keeps a tag that run pushed and creates or completes the release; a new dispatch of the same version is refused. Never tag a main commit by hand: `go get` would fetch a module with no guests. `encrypt/example` is a third nested module, never tagged: it requires both modules as an application does. `./...` stops at a nested module, so `scripts/go-binding-test.sh`, `go:lint` and the generated-code check find each `go.mod` and run in its directory. - `e2e/*`: Cross-package end-to-end tests (package managers, supply chain, Prisma example README) - `e2e/migration-guide`: Unpublished, separately installed npm examples for the Protect/EQL v2 to Stack/EQL v3 guide. See its README before running; Postgres requires a disposable database and DynamoDB persistence is in memory. @@ -748,6 +749,11 @@ exact pin would stop the suite sharing one `cts-common` with it. - **Three Cargo workspaces, not one.** The root workspace (the seven stack-* crates and the three node binding crates), protect-ffi's and EQL's. The root `Cargo.toml` excludes the other two, and they pin their own vitaminc. The + TypeScript SDK's crates (`languages/typescript/packages/recipher-js`, napi-rs 3: + for now the value bridge `value-napi` alone) are a detached workspace too, + with its own `Cargo.lock`. The value bridge's test addon + (`value-napi/tests/addon`) is one more, built by that crate's own + `tests/node.rs`. The three fuzz crates, the two Go guests and the EQL v4 block ORE timing harness's ciphertext generator (`packages/eql/tests/timing/ore_block_v2/ctgen`) are detached workspaces diff --git a/biome.json b/biome.json index 8c5b4f4d5..842d6bb13 100644 --- a/biome.json +++ b/biome.json @@ -51,6 +51,7 @@ "!languages/typescript/packages/auth/LICENSE", "!languages/typescript/packages/profile/index.d.ts", "!languages/typescript/packages/profile/native.d.ts", + "!languages/typescript/packages/recipher-js/value-napi", "!languages/golang", "!**/*.grit", "!**/*.yml", diff --git a/languages/typescript/packages/recipher-js/.gitignore b/languages/typescript/packages/recipher-js/.gitignore new file mode 100644 index 000000000..2f7896d1d --- /dev/null +++ b/languages/typescript/packages/recipher-js/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/languages/typescript/packages/recipher-js/Cargo.lock b/languages/typescript/packages/recipher-js/Cargo.lock new file mode 100644 index 000000000..533da20c0 --- /dev/null +++ b/languages/typescript/packages/recipher-js/Cargo.lock @@ -0,0 +1,1069 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bitvec" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + +[[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 = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" +dependencies = [ + "serde", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core 0.10.1", + "zeroize", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctor" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea691ed9f36489d087419b8b2ba3ef27d89621380b4178c73e2445a379e4e0f4" +dependencies = [ + "link-section", +] + +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "crypto-common", + "ctutils", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "jiff" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5e77cbfb9fff4798e283c2d69dff39fc2c45e7da017e5ce95b654e46ea41236" +dependencies = [ + "jiff-core", + "jiff-static", + "portable-atomic", + "portable-atomic-util", +] + +[[package]] +name = "jiff-core" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6b46a105a9874634dd96231021526bf24ca04955a5998c59a9c7666e634b7b8" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9067a0b23e5be3147d56b2dcf652b18e6b1364caca93fb157653b6fbcab23a9" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libloading" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1832accd5a4ca2795ace4d05d15c4039be15b62d3b950eff99746a990e3cc10" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "link-section" +version = "0.19.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d9aae57673c1a235149777a74d152f3210ebd3e3b13346d2cdb6809e566bd3c" + +[[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 = "miette" +version = "7.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7" +dependencies = [ + "cfg-if", + "miette-derive", + "unicode-width", +] + +[[package]] +name = "miette-derive" +version = "7.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "mutants" +version = "0.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "add0ac067452ff1aca8c5002111bd6b1c895baee6e45fcbc44e0193aea17be56" + +[[package]] +name = "napi" +version = "3.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "567c62b9c2d0fae123713f766686ad66a2c75b45ba3ee01ed8b06a7e99bc435b" +dependencies = [ + "bitflags", + "ctor", + "futures", + "libc", + "napi-build", + "napi-sys", + "nohash-hasher", + "rustc-hash", +] + +[[package]] +name = "napi-build" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b899b545d3aa6dca985939059f258c5488d34e4ecf39c274e20009748f4b846d" + +[[package]] +name = "napi-sys" +version = "3.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d153beb7d5c973f4b9395be8a83054a28968b61188f1dd1a2cc2321af22daea2" +dependencies = [ + "libloading", +] + +[[package]] +name = "nohash-hasher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[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 = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "recipher-value-napi" +version = "0.0.0" +dependencies = [ + "jiff", + "miette", + "mutants", + "napi", + "rust_decimal", + "thiserror", + "vitaminc-aead", + "vitaminc-protected", + "zeroize", +] + +[[package]] +name = "rust_decimal" +version = "1.43.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7653272e75dcac41dc199fbea6f5797633994fafd339943c06c9af16bf29cd3a" +dependencies = [ + "arrayvec", + "borsh", + "bytes", + "num-traits", + "rand 0.8.8", + "rand 0.9.5", + "serde", + "serde_json", + "wasm-bindgen", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[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_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + +[[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 = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[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 = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.20+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e76360e201d6dbd6583e17795ba71a88f47365a9139c8450a7979c32303b8e73" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.6+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31" +dependencies = [ + "winnow", +] + +[[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 = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "vitaminc-aead" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fcccedca9d80812af295cba43dc2ac388f4fbb0415faa3ebec783d072d014d8" +dependencies = [ + "bytes", + "futures-util", + "jiff", + "rust_decimal", + "serde", + "thiserror", + "vitaminc-aead-derive", + "vitaminc-context", + "vitaminc-protected", + "vitaminc-random", + "zeroize", +] + +[[package]] +name = "vitaminc-aead-derive" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3de85a0ff50572db91a5528b72775f63d57a2b24b8263fb8e728baf6a7731502" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "vitaminc-context" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "431a7fb023688dba855e52b9c4e44c942418dde8ea08a2b115cf6a7f762fa5b9" +dependencies = [ + "mutants", + "vitaminc-protected", +] + +[[package]] +name = "vitaminc-protected" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2153981f290343dffa8f618277c46a13b5a1e8131b4120760e9a1795ae1cb55b" +dependencies = [ + "bitvec", + "digest", + "libc", + "serde", + "serde_bytes", + "subtle", + "thiserror", + "vitaminc-protected-derive", + "zeroize", +] + +[[package]] +name = "vitaminc-protected-derive" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32eb239bc9aae16ef0320076934f3f592606960d42d0b5fdadafc0298f635221" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "vitaminc-random" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fae7eccb46ddc6f199cf5c934469fd5b199514f42e11579c46882b784ed992c8" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand 0.10.4", + "thiserror", + "vitaminc-protected", + "vitaminc-random-derives", + "zeroize", +] + +[[package]] +name = "vitaminc-random-derives" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e48c940c93c9ddb04a66d81ca42ca574826ddbbeece6a7c87c5d1ab31893e692" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wyz" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" +dependencies = [ + "tap", +] + +[[package]] +name = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/languages/typescript/packages/recipher-js/Cargo.toml b/languages/typescript/packages/recipher-js/Cargo.toml new file mode 100644 index 000000000..0ea2d1e2b --- /dev/null +++ b/languages/typescript/packages/recipher-js/Cargo.toml @@ -0,0 +1,18 @@ +# The Rust half of `@cipherstash/recipher`: its own Cargo workspace, with its +# own Cargo.lock. The root workspace names its members, so this one needs no +# `exclude` entry there: napi-rs 3 and this lock never enter a stack-* build, +# and a change here leaves the root `Cargo.toml`, and the stack-* crates' +# workflows that watch it, alone. +# +# It has one crate. `value-napi` (crate `recipher-value-napi`) is the value +# bridge: it reads JavaScript values into vitaminc's plaintext model, and +# builds JavaScript values from it. +[workspace] +resolver = "2" +# Listed by name, not by glob: scripts/__tests__/dependabot-cargo-cross-workspace.test.mjs +# reads this list and expands no globs. +members = ["value-napi"] + +[workspace.package] +edition = "2021" +repository = "https://github.com/cipherstash/stack" diff --git a/languages/typescript/packages/recipher-js/value-napi/Cargo.toml b/languages/typescript/packages/recipher-js/value-napi/Cargo.toml new file mode 100644 index 000000000..8250bffe2 --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/Cargo.toml @@ -0,0 +1,36 @@ +[package] +name = "recipher-value-napi" +description = "The JavaScript value bridge of @cipherstash/recipher: reads a Node-API value as vitaminc's plaintext model, and builds one from it" +version = "0.0.0" +edition.workspace = true +# Literal, not inherited: scripts/__tests__/cargo-publish-opt-out.test.mjs +# greps each member for this exact line. +publish = false +repository.workspace = true + +[dependencies] +rust_decimal = { version = "1.41", default-features = false, features = ["std"] } +thiserror = "2.0.18" +# A refusal is a diagnostic: a stable code, a message and help. +miette = "7.5.0" +jiff = { version = "1.0.0", default-features = false } +# The plaintext model this crate reads JavaScript values into, and the +# protected buffer a frame is held in. The versions the engine resolves. +vitaminc-aead = { version = "0.10.0", features = ["jiff", "rust_decimal"] } +vitaminc-protected = "0.10.0" + +# napi5 (Node ≥ 12) is needed for Date detection; napi6 (implies napi5) for +# BigInt and for `napi_get_all_property_names` — the only own-property +# enumeration Node-API offers. Every supported Node release is far beyond +# both levels. +napi = { version = "3", default-features = false, features = ["napi6"] } +zeroize = { version = "1", features = ["derive"] } +# Only for `#[cfg_attr(test, mutants::skip)]`; consumers never see it. +mutants = "0.0.4" + +[dev-dependencies] +# `noop` disables automatic addon registration in unit tests. The live +# Node suites, including the cipher round trips, run against the test addon +# in `tests/addon`, which is its own workspace so this feature cannot stub +# the real Node-API symbols there. +napi = { version = "3", default-features = false, features = ["noop"] } diff --git a/languages/typescript/packages/recipher-js/value-napi/README.md b/languages/typescript/packages/recipher-js/value-napi/README.md new file mode 100644 index 000000000..4db1a82d3 --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/README.md @@ -0,0 +1,234 @@ +# recipher-value-napi + +The JavaScript value bridge of `@cipherstash/recipher`: it reads a Node-API +value as vitaminc's plaintext model, and builds a JavaScript value from it. +The `recipher-js` addon reads and builds every value through it. + +This crate is a copy of `vitaminc-aead-napi` 0.10.0, from +[`cipherstash/vitaminc`](https://github.com/cipherstash/vitaminc) at commit +`b3f69b12c1fde38faff2becec04f9e633dbd4f1c`, renamed. It is not published. +`tests/testdata/value-conformance.json` is vitaminc's `testdata/value-conformance.json` +at the same commit: the vectors the Rust, Node and Go bindings all check. + +An incoming JavaScript value implements [`Encrypt`]; a [`Sink`] builds +the outgoing value. This crate supplies both sides of that conversion: + +- **`JsRef<'e>`** — a live JavaScript value as an `Encrypt`. The walk runs + on the JavaScript thread, reading each value as it goes, so no value tree + is built and a scalar leaves the engine only to go straight to the sink. + `encrypt(JsRef::new(value), &cipher, aad)` seals a value in place. To + encrypt off the JavaScript thread, `JsRef::to_frame` snapshots the value + as a frame there, and a worker seals the frame with no JavaScript access. +- **`JsBuilder<'e>`** — a `Sink` that builds JavaScript values, for + `decrypt_into(&cipher, ct, aad, JsBuilder::new(&env))`, or + `JsBuilder::build(&env, frame)` for a frame. +- **`JsCipherText`** — projects the generic `CipherText` container + onto plain JS values (`{ t, v }` nodes with `Buffer` leaves) and back, as + an in-memory/application-side representation. Durable cross-language + database storage is the EQL layer's job, not this projection's. The + passthrough payload `P` converts through `NapiPassthrough`, implemented + for `PassthroughFrame` (the sink-based tree's payload) and `()`, which + applies the tree's nesting limit to the payload too. +- **`Wrappers`** — the wrapper classes `VcDate`, `VcTimestamp`, + `VcDecimal` and `VcUuid`, defined once per environment and exported by an + addon with `Wrappers::exports`. The crate keeps them in its own registry, + keyed by the environment and released by an environment cleanup hook; the + addon's instance data is untouched. + +## Run a Node example + +This crate supplies Rust building blocks for a Node addon. The +[test addon](tests/addon/src/lib.rs) +exports `encryptValue` and `decryptValue` using `JsRef`, `JsCipherText`, and +`JsBuilder` with AES-256-GCM. It uses a fixed, public test key; use it only +with sample data. + +From `languages/typescript/packages/recipher-js`, with Rust and Node.js +installed, run: + +```sh +cargo test -p recipher-value-napi --test node +``` + +This builds the addon and runs the following example, along with the binding +tests. To run the example separately, save it as `example.cjs` in that +directory and run `node example.cjs target/napi-test-addon/addon.node`. + +```javascript +const assert = require('node:assert/strict'); +const path = require('node:path'); +const addon = require(path.resolve(process.argv[2])); + +const value = { name: 'Ada', count: 42n, tags: ['example'] }; +const aad = 'tenant:example'; +const ciphertext = addon.encryptValue(value, aad); +const recovered = addon.decryptValue(ciphertext, aad); + +assert.deepEqual(recovered, value); +assert.throws(() => addon.decryptValue(ciphertext, 'tenant:other')); +``` + +The associated data (`aad`) must match on encryption and decryption. It can +bind ciphertext to a tenant or another application context. Use `bigint` +for integer values, as shown by `42n`; JavaScript `number` values are floats. + +## The mapping + +| JavaScript | Scalar | +| ----------------------------------- | ---------------------------------------- | +| `null` | null | +| `undefined` | null, logical type `Undefined` | +| `boolean` | bool | +| `number` | float (`F64`) | +| `bigint` | int, at the narrowest fitting width | +| `string` | text | +| `Buffer`, `Uint8Array` | bytes (any other view is refused) | +| `Date` | `Timestamp(Millis)` over the `i64` count | +| `VcDate("YYYY-MM-DD")` | `Date` over the day count | +| `VcTimestamp("RFC 3339, ns")` | `Timestamp(Nanos)` over the count | +| `VcDecimal("1.50")` | `Decimal { scale }` over the mantissa | +| `VcUuid("hyphenated hex")` | `Uuid` over sixteen bytes | +| `Array` | sequence | +| plain object | map, over own enumerable string keys | + +And back: every int width is a `BigInt`; both float widths are a `number` +(`f32` widens exactly); a timestamp in any unit is a `Date` when it is +whole milliseconds and a `VcTimestamp` otherwise, so no precision is +discarded; a calendar date, a decimal and a UUID are their wrapper. A +`Date` is stored as its millisecond count and read back as the same +count, never converted through seconds and nanoseconds. A logical type +this build does not know has no JavaScript value and is refused rather +than shown with its type dropped. + +Equality terms share one domain across integer widths, so a `BigInt` +written as `int8` matches the same number written as `int64` from Go; +both float widths likewise share one domain. Integers and floats stay +distinct, so a JS `number` 5 does not match an `int64` 5: use `BigInt` for +integer data. + +### The wrapper classes + +JavaScript has no type of its own for a calendar date, a timestamp finer +than a millisecond, a decimal or a UUID, so each is an instance of a small +class holding its text: `new VcDecimal("1.50")`. The constructor takes a +string and nothing else; the text is checked, and the scalar built from +it, when the value is encrypted, so one rule applies however the instance +was made. `value` is an own, read-only, enumerable property, so +`JSON.stringify` (which gives the bare text through `toJSON`), +`structuredClone` and a deep equality all see it. A clone, or a wrapper +posted to a Worker, is a plain `{ value }` object and encrypts as a map; +rebuild it with the constructor on the other side. The classes, their +prototypes and every instance are frozen, and construction uses what the +class captured when it was defined, so a polluted `Object.prototype` or a +later edit of a class cannot make `value` writable, break a decrypt, or +turn a plain `{ value }` object back into a wrapper. + +An instance is not a plain object, so it is never confused with data +another language wrote as an ordinary one-key object: Go's +`{"date": "2024-01-01"}` decrypts in JS as that object and encrypts again +unchanged. Decimal text is exact fixed-point, not a JS number or an +arbitrary decimal-library instance; a negative zero reads back as zero +with its scale kept. A leap second has no count since the epoch +and is refused. Dates and timestamps cover jiff's range, years -9999 to +9999, as in every binding, and a negative year is a sign and six digits +(`-000005-03-01T12:00:00.000000001Z`), as JavaScript writes it. + +Scalar failures throw a `TypeError` with a stable code: `ERR_INTEGER_RANGE`, +`ERR_INVALID_DATE`, `ERR_INVALID_TIMESTAMP`, `ERR_INVALID_DECIMAL`, +`ERR_NON_FINITE_DECIMAL` and `ERR_INVALID_UUID`. + +## Errors + +A getter that throws, a string with an unpaired surrogate, a `BigInt` out +of range or a `Date` outside the wire's range (jiff's, about years -9999 +to 9999) +stops the walk through the +sink's `Error::source`, as a [`JsFault`] carrying the napi status and +reason. At the boundary, `JsFault::from_source` turns it back into the +napi error, and a pending JavaScript exception surfaces unchanged: the +application sees the error its getter threw. + +When the fault is this crate's refusal of a value, `JsFault::refusal()` says +which rule the value broke, as a `Refusal`: a diagnostic with a stable code +(`recipher::sparse_array`, `ERR_INTEGER_RANGE`), a message and, where there +is something to do, help. A caller reports the refusal from that, and never +reads the reason's text. It is `None` for a failure of Node-API's own and +for an exception the application threw. `JsRef::to_frame` and +`JsBuilder::build` return the `JsFault` itself. + +This crate is a library consumed by the Node addon (cdylib/npm package); +it is not itself loadable from Node. + +## Safety notes + +- The original copies of encrypted values in the V8 heap are owned by the + JS engine and cannot be wiped from Rust. On the way in, every copy Rust + makes of a string is wiped on drop: the UTF-16 code units and the UTF-8 + text of each value, key and wrapper class's text. The UTF-8 text is built + in a buffer of its final size, so no smaller buffer is left behind, and + the wrapper text is parsed in place without further copies. An error + message names no property of the value, except one of the three refused + names below, and holds no other part of it. A frame snapshot is `Protected` and + wiped on drop. +- On the way out, the build hands decrypted text and bytes to JavaScript, + where the engine owns them. The Rust copies made along the way are not + wiped: the text of each wrapper class (formatted by the binding or + `rust_decimal`), each map key, and the bytes copied into a + `Buffer`. +- Property names that would touch the prototype chain (`__proto__`, + `constructor`, `prototype`) are rejected in both directions. Nesting is + limited to 128 levels in both directions too, counted as the frame counts + it, including inside a ciphertext's passthrough payload. The walk and the + build each check the depth before recursing, so a tree far too deep for + the stack fails cleanly instead of aborting Node, and a document at the + limit walks in a debug build. +- Only **plain objects** (prototype `Object.prototype` or `null`) and the + wrapper classes are accepted for encryption. `Map`, `Set`, `RegExp`, + `DataView`, class instances and other exotic objects keep their state in + internal slots and would silently encrypt as `{}` — they are rejected with + an error instead. The prototype is asked through `Object.getPrototypeOf`, + which runs a `Proxy`'s trap, so a proxied `Map` or `Date` reports its + target's prototype and is refused; a proxy over a plain object walks + through its traps. Typed arrays other than `Uint8Array` (and `Buffer`), + and `DataView`, are refused rather than sealed as their raw bytes. +- Object enumeration reads **own, enumerable, string-keyed** properties + only, so a polluted `Object.prototype` (or inherited enumerable getters) + can never leak keys into — or run code during — encryption. An own + property explicitly set to `undefined` round-trips. +- Sparse arrays (`[, , "x"]`, `new Array(n)`) are rejected; `[undefined]` + is not sparse and round-trips. A hole is detected per index via + `Object.hasOwn` semantics, so a polluted `Array.prototype` cannot fill + holes with inherited elements. +- JS-reported array lengths are never trusted for up-front allocation + (a `new Array(2**32 - 1)` costs the attacker one line and materialises + nothing), in the walk, the build and the ciphertext rebuilder. +- Strings and object keys containing unpaired UTF-16 surrogates are + **rejected** rather than silently normalized: the UTF-8 fetch would + replace a lone surrogate with U+FFFD, sealing a plaintext that no longer + equals what the caller passed, or a key that no longer names its + property. Each property is read back through its original JS key. +- Everything this crate builds in JS is written with **own-property + defines** (`napi_define_properties`, one call per object), not `[[Set]]` + assignment: decrypted object properties and array elements, and every + ciphertext node's `t`, `v`, sequence elements and map entries. A polluted + setter on `Object.prototype` or `Array.prototype` can never observe + decrypted plaintext or ciphertext, or swallow a property. +- A ciphertext node handed back for decryption must be an object. N-API + reads properties of a primitive through its wrapper, so a bare string + would otherwise take `t` and `v` from `String.prototype`. +- Errors carry no cryptographic detail (`Unspecified` at the trait layer). + + +## Cargo features + +This crate defines no Cargo feature flags. + +## Compatibility + +Requires the Rust standard library (`std`). This crate targets native +Node.js addons; it is not a WebAssembly binding. + + +[`Encrypt`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/trait.Encrypt.html +[`Sink`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/trait.Sink.html +[`JsFault`]: src/error.rs diff --git a/languages/typescript/packages/recipher-js/value-napi/src/ciphertext.rs b/languages/typescript/packages/recipher-js/value-napi/src/ciphertext.rs new file mode 100644 index 000000000..4c4f88f25 --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/src/ciphertext.rs @@ -0,0 +1,497 @@ +//! Projection of the generic [`CipherText`] container onto JS structures. +//! +//! The container has **no canonical byte representation** — only the sealed +//! `Leaf` type does (see the container docs). Crossing the FFI boundary, the +//! tree is projected onto plain JS values that the application can hold, +//! store (e.g. as JSONB with its own Buffer encoding policy), and pass back +//! for decryption: +//! +//! ```text +//! Single(leaf) ↦ { t: "ct", v: Buffer } +//! Sequence(...) ↦ { t: "seq", v: [node, ...] } +//! EmptySequence(leaf) ↦ { t: "eseq", v: Buffer } +//! Map(entries) ↦ { t: "map", v: { key: node, ... } } +//! EmptyMap(leaf) ↦ { t: "emap", v: Buffer } +//! Passthrough(p) ↦ { t: "pt", v: } +//! ``` +//! +//! The passthrough payload of the sink-based tree ([`Node`]) is a +//! [`PassthroughFrame`], which projects onto the plain JavaScript value the +//! frame describes, and reads back by walking the JavaScript value into a +//! frame. +//! +//! The `t`/`v` node shape is an **in-memory/application-side convenience**: +//! it is what a JS application holds between `encrypt` and `decrypt` calls, +//! and what an application that manages its own storage may choose to +//! persist. Database interop across languages is *not* this projection's +//! job — that is the role of the EQL layer, which owns the durable +//! database format and treats the sealed leaves opaquely. Within that +//! scope the node shape should still change only deliberately (apps may +//! have persisted it), but it is not a cross-language wire commitment; +//! only the leaf byte format (the leaf codec in `vitaminc-aead`) is frozen. +//! +//! [`Node`]: vitaminc_aead::Node + +use napi::bindgen_prelude::{ + Array, Buffer, BufferSlice, FromNapiValue, JsObjectValue, JsValue, Object, ToNapiValue, + TypeName, Unknown, +}; +use napi::{sys, Env, Error, Result, Status, ValueType}; +use vitaminc_aead::{CipherText, Frame, PassthroughFrame}; +use vitaminc_protected::Controlled; + +use crate::js::{ + define_own_properties, depth_error, eager_capacity, forbidden_key, get_own, + get_property_unknown, new_array, own_enumerable_keys, own_property, MAX_DEPTH, +}; +use crate::js_builder::JsBuilder; +use crate::js_ref::{frame_error, JsRef}; +use crate::wrappers::Wrappers; + +const T_CIPHERTEXT: &str = "ct"; +const T_SEQ: &str = "seq"; +const T_EMPTY_SEQ: &str = "eseq"; +const T_MAP: &str = "map"; +const T_EMPTY_MAP: &str = "emap"; +const T_PASSTHROUGH: &str = "pt"; + +/// Newtype carrying a [`CipherText`] across the NAPI boundary using the +/// node projection documented at the module level. +/// +/// `Leaf` needs only byte-level accessors (`AsRef<[u8]>` out, +/// `From>` in); the passthrough payload `P` converts through +/// [`NapiPassthrough`], implemented for [`PassthroughFrame`] (the +/// sink-based tree's payload) and `()`. A cipher whose passthrough +/// payload type is something else needs its own `NapiPassthrough` impl. +pub struct JsCipherText(pub CipherText); + +/// A ciphertext passthrough payload's conversion to and from JS. +/// +/// A payload shares the tree's 128-level nesting limit, as it does in the +/// transport encoding, rather than starting a fresh count: it sits one level +/// below its passthrough node. +pub trait NapiPassthrough: Sized { + /// Build the payload's JS value. [`JsCipherText`] calls this only once + /// [`exceeds_depth`](Self::exceeds_depth) has passed for the payload's + /// position, which bounds any recursion here. + fn to_js(self, env: &Env) -> Result>; + /// Read the payload from its JS value at `depth`, refusing anything that + /// nests past the limit. + fn from_js(value: Unknown<'_>, depth: usize) -> Result; + /// Whether the payload, placed at `depth`, nests past the limit. + fn exceeds_depth(&self, depth: usize) -> bool; + /// Drop the payload without recursing once per nesting level, for a tree + /// refused as too deep. + fn drop_flat(self); +} + +/// No payload: projects to `undefined`, which is all it accepts back. It is +/// a single node, so it is too deep only past the limit itself. +impl NapiPassthrough for () { + fn to_js(self, env: &Env) -> Result> { + ().into_unknown(env) + } + + fn from_js(value: Unknown<'_>, depth: usize) -> Result { + if depth > MAX_DEPTH { + return Err(depth_error().into()); + } + // napi-rs's own `()` conversion accepts any value; check instead. + if value.get_type()? == ValueType::Undefined { + Ok(()) + } else { + Err(shape_error()) + } + } + + fn exceeds_depth(&self, depth: usize) -> bool { + depth > MAX_DEPTH + } + + fn drop_flat(self) {} +} + +/// A frame payload projects onto the JavaScript value it describes, and +/// reads back as the frame of the JavaScript value, walked at the +/// payload's depth so the tree's limit counts the whole structure. +impl NapiPassthrough for PassthroughFrame { + fn to_js(self, env: &Env) -> Result> { + // `exceeds_depth` has passed for this payload, which validated it. + let frame = Frame::parse(&self.0).map_err(|_| shape_error())?; + Ok(JsBuilder::build(env, frame)?) + } + + fn from_js(value: Unknown<'_>, depth: usize) -> Result { + let frame = vitaminc_aead::to_frame(JsRef::at_depth(value, depth)).map_err(frame_error)?; + Ok(PassthroughFrame(frame.risky_ref().to_vec())) + } + + /// A frame parsed `depth` levels down is bounded there; a payload that + /// is not a well-formed frame cannot be built either, so it counts as + /// exceeding too. + fn exceeds_depth(&self, depth: usize) -> bool { + Frame::parse_nested(&self.0, depth).is_err() + } + + /// A frame is one flat buffer. + fn drop_flat(self) {} +} + +/// Whether a ciphertext tree nests past [`MAX_DEPTH`], payloads included. +/// Iterative, so a tree of any depth is measured without recursion. +fn exceeds_depth(node: &CipherText) -> bool { + let mut stack = vec![(node, 0)]; + while let Some((node, depth)) = stack.pop() { + if depth > MAX_DEPTH { + return true; + } + match node { + CipherText::Sequence(items) => stack.extend(items.iter().map(|item| (item, depth + 1))), + CipherText::Map(entries) => { + stack.extend(entries.iter().map(|(_, value)| (value, depth + 1))) + } + CipherText::Passthrough(p) if p.exceeds_depth(depth + 1) => return true, + _ => {} + } + } + false +} + +/// Drop a ciphertext tree without recursing once per level (see +/// [`NapiPassthrough::drop_flat`]). +fn drop_flat(node: CipherText) { + let mut stack = vec![node]; + while let Some(node) = stack.pop() { + match node { + CipherText::Sequence(items) => stack.extend(items), + CipherText::Map(entries) => stack.extend(entries.into_iter().map(|(_, value)| value)), + CipherText::Passthrough(p) => p.drop_flat(), + _ => {} + } + } +} + +fn ciphertext_depth_error() -> Error { + Error::new(Status::InvalidArg, "ciphertext is nested too deeply") +} + +fn shape_error() -> Error { + Error::new(Status::InvalidArg, "malformed ciphertext value") +} + +/// Build `node` in JS. Callers check [`exceeds_depth`] first, which bounds +/// this recursion. +fn node_to_js(env: &Env, node: CipherText) -> Result> +where + Leaf: AsRef<[u8]>, + P: NapiPassthrough, +{ + let leaf = |tag: &'static str, leaf: Leaf| -> Result<(&'static str, Unknown<'_>)> { + Ok((tag, Buffer::from(leaf.as_ref().to_vec()).into_unknown(env)?)) + }; + let (tag, value) = match node { + CipherText::Single(l) => leaf(T_CIPHERTEXT, l)?, + CipherText::EmptySequence(l) => leaf(T_EMPTY_SEQ, l)?, + CipherText::EmptyMap(l) => leaf(T_EMPTY_MAP, l)?, + CipherText::Sequence(items) => { + let mut arr = new_array(env, items.len())?; + let mut elements = Vec::with_capacity(items.len()); + for (i, item) in items.into_iter().enumerate() { + let node = node_to_js(env, item)?; + elements.push(own_property(env, &i.to_string(), &node)?); + } + define_own_properties(&mut arr, &elements)?; + (T_SEQ, arr.into_unknown(env)?) + } + CipherText::Map(entries) => { + let mut map = Object::new(env)?; + let mut properties = Vec::with_capacity(entries.len()); + for (key, value) in entries { + // Map keys travel in the clear inside the stored ciphertext + // and are therefore attacker-writable; never assign + // prototype-polluting names onto a JS object. + if forbidden_key(&key) { + return Err(Error::new( + Status::InvalidArg, + format!("ciphertext map key is not allowed: {key}"), + )); + } + let node = node_to_js(env, value)?; + properties.push(own_property(env, &key, &node)?); + } + define_own_properties(&mut map, &properties)?; + (T_MAP, map.into_unknown(env)?) + } + CipherText::Passthrough(p) => (T_PASSTHROUGH, p.to_js(env)?), + }; + // Own properties throughout, so a polluted inherited `t`, `v` or index + // setter never sees the ciphertext (see `define_own_properties`). + let mut obj = Object::new(env)?; + let tag = tag.into_unknown(env)?; + define_own_properties( + &mut obj, + &[ + own_property(env, T_KEY, &tag)?, + own_property(env, V_KEY, &value)?, + ], + )?; + Ok(obj) +} + +const T_KEY: &str = "t"; +const V_KEY: &str = "v"; + +/// A node is a JavaScript object, for the places napi-rs asks what a value +/// is, such as the result of an async task. +impl TypeName for JsCipherText { + fn type_name() -> &'static str { + "CipherText" + } + + fn value_type() -> ValueType { + ValueType::Object + } +} + +impl ToNapiValue for JsCipherText +where + Leaf: AsRef<[u8]>, + P: NapiPassthrough, +{ + unsafe fn to_napi_value(env: sys::napi_env, val: Self) -> Result { + if exceeds_depth(&val.0) { + drop_flat(val.0); + return Err(ciphertext_depth_error()); + } + Ok(node_to_js(&Env::from_raw(env), val.0)?.raw()) + } +} + +/// A node must be a JS object. napi-rs's `Object` conversion does not check +/// the type, and N-API reads properties of a primitive through its wrapper +/// object, so a bare string would otherwise read `t` and `v` from a +/// (possibly polluted) `String.prototype`. +fn node_object(value: Unknown<'_>) -> Result> { + if value.get_type()? != ValueType::Object { + return Err(shape_error()); + } + Object::from_unknown(value) +} + +/// A node's own `t` or `v`. A node missing either would otherwise take it +/// from a (possibly polluted) prototype. Ownership is checked immediately +/// before the read, where no JS can run in between, so a getter on the +/// other field cannot delete this one after the check. +fn own_field<'e>(obj: &Object<'e>, key: &str) -> Result> { + if !obj.has_own_property(key)? { + return Err(shape_error()); + } + get_property_unknown(obj, key) +} + +/// A map node's own `v`, the object holding its entries. The entries are +/// own properties, so it must be a plain object: a `Map`, or any object +/// that is not plain, has none to read and would give an empty map. +/// +/// A helper of its own, so its frame is gone before the map recurses and a +/// tree at the depth limit reads in a debug build too. +#[inline(never)] +fn map_entries<'e>(obj: &Object<'e>) -> Result> { + let map = node_object(own_field(obj, V_KEY)?)?; + let env = Env::from_raw(map.value().env); + if !Wrappers::get(&env)?.is_plain(map.to_unknown())? { + return Err(shape_error()); + } + Ok(map) +} + +fn node_from_js(obj: &Object<'_>, depth: usize) -> Result> +where + Leaf: From>, + P: NapiPassthrough, +{ + if depth > MAX_DEPTH { + return Err(ciphertext_depth_error()); + } + let t = String::from_unknown(own_field(obj, T_KEY)?)?; + match t.as_str() { + T_CIPHERTEXT | T_EMPTY_SEQ | T_EMPTY_MAP => { + // Borrowed as a slice, which holds no reference: napi-rs's + // `Buffer` takes one before it checks the value and never + // releases it when the check fails. + let buf = BufferSlice::from_unknown(own_field(obj, V_KEY)?)?; + let leaf = Leaf::from(buf.to_vec()); + Ok(match t.as_str() { + T_CIPHERTEXT => CipherText::Single(leaf), + T_EMPTY_SEQ => CipherText::EmptySequence(leaf), + _ => CipherText::EmptyMap(leaf), + }) + } + T_SEQ => { + let arr = Array::from_unknown(own_field(obj, V_KEY)?)?; + // The same array seen as an object, for per-index own checks. + let elements = Object::from_unknown(arr.to_unknown())?; + let len = arr.len(); + // Capacity is granted lazily: the reported length is + // attacker-cheap (`{t:"seq", v:new Array(2**32-1)}` materialises + // nothing), so reserving it up front would abort the process on + // allocation failure before any element is validated. + let mut items = Vec::with_capacity(eager_capacity(len)); + for i in 0..len { + // Own elements only: a hole would otherwise read an element + // from a (possibly polluted) `Array.prototype`, and as + // `undefined` it is not a node anyway. + if !elements.has_own_property(&i.to_string())? { + return Err(shape_error()); + } + let element = arr.get::(i)?.ok_or_else(shape_error)?; + items.push(node_from_js(&node_object(element)?, depth + 1)?); + } + Ok(CipherText::Sequence(items)) + } + T_MAP => { + let map = map_entries(obj)?; + // Own keys only — `Object::keys` walks the prototype chain, so + // a hostile node object with enumerable prototype members would + // otherwise have its inherited keys become ciphertext map + // entries (see `own_enumerable_keys`). + let keys = own_enumerable_keys(&map)?; + let mut entries = Vec::with_capacity(keys.len()); + for key in keys { + if forbidden_key(&key.name) { + return Err(Error::new( + Status::InvalidArg, + format!("ciphertext map key is not allowed: {}", *key.name), + )); + } + let value = node_object(get_own(&map, &key)?)?; + entries.push((key.name.to_string(), node_from_js(&value, depth + 1)?)); + } + Ok(CipherText::Map(entries)) + } + T_PASSTHROUGH => { + // `undefined` is a *faithful* projection here (`P = ()` and + // `NapiValue::Undefined` both project to it), and + // `JSON.stringify` drops a `v: undefined` key outright, so a + // missing `v` reads as `undefined` rather than as malformed — + // never from the prototype. Whether `undefined` converts is + // `P`'s decision. + let env = Env::from_raw(obj.value().env); + let value = if obj.has_own_property(V_KEY)? { + own_field(obj, V_KEY)? + } else { + ().into_unknown(&env)? + }; + Ok(CipherText::Passthrough(P::from_js(value, depth + 1)?)) + } + _ => Err(shape_error()), + } +} + +impl FromNapiValue for JsCipherText +where + Leaf: From>, + P: NapiPassthrough, +{ + unsafe fn from_napi_value(env: sys::napi_env, napi_val: sys::napi_value) -> Result { + // SAFETY: napi-rs calls this with the `env` and `napi_val` of the + // current call, which is all `Unknown::from_napi_value` needs: an + // `Unknown` may hold any value type, and `node_object` checks it is + // an object before anything reads it as one. The handle does not + // outlive this call. + let value = unsafe { Unknown::from_napi_value(env, napi_val) }?; + let obj = node_object(value)?; + Ok(JsCipherText(node_from_js(&obj, 0)?)) + } +} + +#[cfg(test)] +mod tests { + use super::{drop_flat, exceeds_depth, CipherText, NapiPassthrough, MAX_DEPTH}; + use vitaminc_aead::{to_frame, PassthroughFrame}; + use vitaminc_protected::Controlled; + + type Node

= CipherText, P>; + + #[test] + fn a_node_is_a_javascript_object_named_ciphertext() { + use napi::bindgen_prelude::{TypeName, ValueType}; + type Js = super::JsCipherText, PassthroughFrame>; + assert_eq!(Js::type_name(), "CipherText"); + assert_eq!(Js::value_type(), ValueType::Object); + } + + fn nested

(levels: usize, wrap: fn(Node

) -> Node

, leaf: Node

) -> Node

{ + (0..levels).fold(leaf, |node, _| wrap(node)) + } + + fn seq

(node: Node

) -> Node

{ + CipherText::Sequence(vec![CipherText::Single(vec![1]), node]) + } + + fn map

(node: Node

) -> Node

{ + CipherText::Map(vec![ + ("a".into(), CipherText::EmptySequence(vec![1])), + ("k".into(), node), + ]) + } + + /// `levels` arrays around `true`, as a frame payload. + fn payload(levels: usize) -> Node { + struct Arrays(usize); + impl vitaminc_aead::Encrypt for Arrays { + fn visit(self, sink: S) -> Result { + use vitaminc_aead::SeqSink; + if self.0 == 0 { + return sink.scalar(None, vitaminc_aead::Physical::Bool(true)); + } + let mut seq = sink.seq(Some(1))?; + Arrays(self.0 - 1).visit(seq.element()?)?; + seq.end() + } + } + let frame = to_frame(Arrays(levels)).expect("within the frame's own bound"); + CipherText::Passthrough(PassthroughFrame(frame.risky_ref().to_vec())) + } + + #[test] + fn depth_is_measured_to_the_limit_for_every_container() { + for wrap in [seq::<()>, map::<()>] { + let leaf = || CipherText::EmptySequence(vec![1]); + assert!(!exceeds_depth(&nested(MAX_DEPTH, wrap, leaf()))); + assert!(exceeds_depth(&nested(MAX_DEPTH + 1, wrap, leaf()))); + } + } + + #[test] + fn a_payload_continues_the_count() { + // A `()` payload sits one level below its passthrough node. + assert!(!exceeds_depth(&nested( + MAX_DEPTH - 1, + seq, + CipherText::Passthrough(()) + ))); + assert!(exceeds_depth(&nested( + MAX_DEPTH, + seq, + CipherText::Passthrough(()) + ))); + assert!(!().exceeds_depth(MAX_DEPTH)); + assert!(().exceeds_depth(MAX_DEPTH + 1)); + // So does every level inside a frame payload. + assert!(!exceeds_depth(&nested(60, seq, payload(67)))); + assert!(exceeds_depth(&nested(60, seq, payload(68)))); + // A frame that is not well formed cannot be built, so it exceeds. + assert!(PassthroughFrame(vec![0xF0, 1, 0, 0, 0]).exceeds_depth(0)); + } + + #[test] + fn trees_too_deep_for_the_stack_are_measured_and_dropped_flat() { + for wrap in [seq::, map::] { + let deep = nested(1_000_000, wrap, CipherText::Single(vec![1])); + assert!(exceeds_depth(&deep)); + drop_flat(deep); + } + drop_flat(nested(1_000_000, seq, CipherText::Passthrough(()))); + } +} diff --git a/languages/typescript/packages/recipher-js/value-napi/src/error.rs b/languages/typescript/packages/recipher-js/value-napi/src/error.rs new file mode 100644 index 000000000..1eada4185 --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/src/error.rs @@ -0,0 +1,303 @@ +//! The error a walk or a build carries through the sink traits, and how it +//! comes back to JavaScript as the error it was. + +use napi::{Error, Status}; +use vitaminc_aead::plaintext::{self, SourceError}; + +use crate::scalar::ConversionError; + +/// Why a JavaScript value was refused, for a caller that reports it by +/// its code. +/// +/// Each variant is a diagnostic: a stable code, a message, and help where +/// there is something to do. No message holds any part of the value. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error, miette::Diagnostic)] +#[non_exhaustive] +pub enum Refusal { + /// An object that is neither plain nor one of the wrapper classes. + #[error( + "a Map, a Set, a class instance or another object that is not plain cannot be encrypted" + )] + #[diagnostic(code(recipher::not_plain), help("Make it a plain object first."))] + NotPlain, + /// A property named `__proto__`, `constructor` or `prototype`. + #[error("an object has a property named `__proto__`, `constructor` or `prototype`, which is refused in both directions")] + #[diagnostic(code(recipher::reserved_key))] + ReservedKey, + /// A value nested past [`MAX_DEPTH`](crate::MAX_DEPTH). + #[error("the value is nested deeper than 128 levels")] + #[diagnostic(code(recipher::too_deep))] + TooDeep, + /// An array with a hole. + #[error("an array has a hole")] + #[diagnostic( + code(recipher::sparse_array), + help("Write `undefined` or `null` where a value is missing.") + )] + SparseArray, + /// A typed array other than a `Uint8Array`, or a `DataView`. + #[error( + "only a Buffer or a Uint8Array is bytes; another typed array or a DataView is refused" + )] + #[diagnostic(code(recipher::not_bytes))] + NotBytes, + /// A function, a symbol or another type with no value in the model. + #[error("a function, a symbol or another type JavaScript has no value of cannot be encrypted")] + #[diagnostic(code(recipher::not_a_value))] + NotAValue, + /// A property removed while its object was being read. + #[error("an object changed while it was read")] + #[diagnostic(code(recipher::changed_while_read))] + ChangedWhileRead, + /// A string or a property name with an unpaired surrogate. + #[error( + "a string or a property name has an unpaired surrogate, so it has no exact UTF-8 form" + )] + #[diagnostic(code(recipher::unpaired_surrogate))] + UnpairedSurrogate, + /// A scalar outside what its type holds. A `TypeError` with the same + /// code is pending in JavaScript. + #[error(transparent)] + #[diagnostic(transparent)] + Scalar(#[from] ConversionError), +} + +/// A failure on the JavaScript side of a walk or a build: a getter threw, a +/// string had an unpaired surrogate, a value was of a type that cannot be +/// encrypted, a tree was too deep. +/// +/// A napi [`Error`] is not `Send`, so it cannot travel inside a +/// [`SourceError`]; this carries its status and reason, which is all a +/// caller needs to hand it back to JavaScript. A [`Status::PendingException`] +/// means the original JavaScript exception is still pending in the engine, +/// and returning this error lets it surface unchanged. +/// +/// When the fault is this crate's refusal of a value, [`refusal`](Self::refusal) +/// says which one, so a caller never reads the reason's text to find out. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("{reason}")] +pub struct JsFault { + status: Status, + reason: String, + refusal: Option, +} + +impl JsFault { + pub(crate) fn new(status: Status, reason: impl Into) -> Self { + Self { + status, + reason: reason.into(), + refusal: None, + } + } + + /// This crate's refusal of a value, with the reason JavaScript sees. + pub(crate) fn refused(refusal: Refusal, reason: impl Into) -> Self { + Self { + status: Status::InvalidArg, + reason: reason.into(), + refusal: Some(refusal), + } + } + + /// A refused scalar, whose `TypeError` is pending in JavaScript. + pub(crate) fn pending(error: ConversionError) -> Self { + Self { + status: Status::PendingException, + reason: error.to_string(), + refusal: Some(Refusal::Scalar(error)), + } + } + + /// Which refusal this is, when it is one of this crate's. `None` for a + /// failure of Node-API itself, or an exception the application threw. + pub fn refusal(&self) -> Option { + self.refusal + } + + /// The fault a sink's source error carries, or the error's own text + /// when it carries none. + pub(crate) fn of_source(error: &SourceError) -> Self { + match error.inner().downcast_ref::() { + Some(fault) => fault.clone(), + None => Self::new(Status::InvalidArg, error.to_string()), + } + } + + /// The napi status of the failure. [`Status::PendingException`] means a + /// JavaScript exception is still pending: return this error to + /// JavaScript before running any more JavaScript, so the exception + /// surfaces as it was thrown. + pub fn status(&self) -> Status { + self.status + } + + /// The failure's message. + pub fn reason(&self) -> &str { + &self.reason + } + + /// The napi error for a source error, which is a [`JsFault`] when the + /// source was a JavaScript value and some other error otherwise. + pub fn from_source(error: &SourceError) -> Error { + match error.inner().downcast_ref::() { + Some(fault) => fault.clone().into(), + None => Error::new(Status::InvalidArg, error.to_string()), + } + } +} + +impl From for JsFault { + fn from(error: Error) -> Self { + Self { + status: error.status, + reason: error.reason.clone(), + refusal: None, + } + } +} + +impl From for Error { + fn from(fault: JsFault) -> Self { + Error::new(fault.status, fault.reason) + } +} + +impl plaintext::Error for JsFault { + fn source(error: SourceError) -> Self { + Self::of_source(&error) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use vitaminc_aead::plaintext::Error as _; + + #[test] + fn a_fault_reports_the_status_and_reason_it_was_made_with() { + let fault = JsFault::new(Status::GenericFailure, "the getter threw"); + assert_eq!(fault.status(), Status::GenericFailure); + assert_eq!(fault.reason(), "the getter threw"); + } + + #[test] + fn a_fault_round_trips_through_a_napi_error() { + let fault = JsFault::new(Status::PendingException, "getter threw"); + let error: Error = fault.clone().into(); + assert_eq!(error.status, Status::PendingException); + assert_eq!(error.reason, "getter threw"); + assert_eq!(JsFault::from(error), fault); + } + + #[test] + fn a_source_error_carrying_a_fault_is_that_fault() { + let fault = JsFault::new(Status::InvalidArg, "unpaired surrogate"); + let wrapped = SourceError::new(fault.clone()); + assert_eq!(JsFault::source(wrapped), fault); + let wrapped = SourceError::new(fault.clone()); + let error = JsFault::from_source(&wrapped); + assert_eq!( + (error.status, error.reason.as_str()), + (Status::InvalidArg, "unpaired surrogate") + ); + } + + #[test] + fn a_source_error_from_elsewhere_keeps_its_message() { + let wrapped = SourceError::msg("frame is malformed"); + assert_eq!( + JsFault::source(wrapped), + JsFault::new(Status::InvalidArg, "frame is malformed") + ); + let error = JsFault::from_source(&SourceError::msg("frame is malformed")); + assert_eq!(error.status, Status::InvalidArg); + assert_eq!(error.reason, "frame is malformed"); + } + + /// One of every refusal. The match has no wildcard, so a variant added + /// without a row here does not compile. + fn every_refusal() -> Vec { + use crate::scalar::ConversionError as C; + let all = vec![ + Refusal::NotPlain, + Refusal::ReservedKey, + Refusal::TooDeep, + Refusal::SparseArray, + Refusal::NotBytes, + Refusal::NotAValue, + Refusal::ChangedWhileRead, + Refusal::UnpairedSurrogate, + Refusal::Scalar(C::IntegerRange), + Refusal::Scalar(C::InvalidDate), + Refusal::Scalar(C::InvalidTimestamp), + Refusal::Scalar(C::InvalidDecimal), + Refusal::Scalar(C::NonFiniteDecimal), + Refusal::Scalar(C::InvalidUuid), + ]; + for refusal in &all { + match refusal { + Refusal::NotPlain + | Refusal::ReservedKey + | Refusal::TooDeep + | Refusal::SparseArray + | Refusal::NotBytes + | Refusal::NotAValue + | Refusal::ChangedWhileRead + | Refusal::UnpairedSurrogate => {} + Refusal::Scalar(scalar) => match scalar { + C::IntegerRange + | C::InvalidDate + | C::InvalidTimestamp + | C::InvalidDecimal + | C::NonFiniteDecimal + | C::InvalidUuid => {} + }, + } + } + all + } + + #[test] + fn every_refusal_has_a_code_of_its_own() { + use miette::Diagnostic; + let mut codes = std::collections::BTreeSet::new(); + for refusal in every_refusal() { + let code = refusal.code().expect("a code").to_string(); + match refusal { + // A refused scalar keeps the code its `TypeError` is thrown + // with. + Refusal::Scalar(scalar) => assert_eq!(code, scalar.code()), + _ => { + let name = code.strip_prefix("recipher::").expect("the namespace"); + assert!( + !name.is_empty() + && name.chars().all(|c| c.is_ascii_lowercase() || c == '_'), + "{code}" + ); + } + } + assert!(codes.insert(code.clone()), "{code} is used twice"); + } + } + + #[test] + fn a_fault_says_which_refusal_it_is() { + let refused = JsFault::refused(Refusal::NotPlain, "only plain objects"); + assert_eq!(refused.refusal(), Some(Refusal::NotPlain)); + assert_eq!(refused.status(), Status::InvalidArg); + // The reason JavaScript sees is unchanged by the variant. + assert_eq!(refused.reason(), "only plain objects"); + + let pending = JsFault::pending(crate::scalar::ConversionError::InvalidUuid); + assert_eq!(pending.status(), Status::PendingException); + assert_eq!( + pending.refusal(), + Some(Refusal::Scalar(crate::scalar::ConversionError::InvalidUuid)) + ); + + // A failure of Node-API's own is no refusal. + let napi = JsFault::from(Error::new(Status::GenericFailure, "napi failed")); + assert_eq!(napi.refusal(), None); + } +} diff --git a/languages/typescript/packages/recipher-js/value-napi/src/js.rs b/languages/typescript/packages/recipher-js/value-napi/src/js.rs new file mode 100644 index 000000000..ac61a7234 --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/src/js.rs @@ -0,0 +1,279 @@ +//! What the walk and the build share about JavaScript objects: which keys +//! are read, how properties are written, and the limits both directions +//! apply. Everything here needs a live `Env`, so it runs on the +//! JavaScript thread. + +use napi::bindgen_prelude::{ + FromNapiValue, JsObjectValue, JsValue, KeyCollectionMode, KeyConversion, KeyFilter, Object, + ToNapiValue, Unknown, +}; +use napi::{check_status, sys, Env, Error, Property, Result, Status, ValueType}; +use zeroize::Zeroizing; + +use crate::error::{JsFault, Refusal}; + +/// Maximum nesting depth, in both directions: walking a JavaScript value +/// and building one. Bounds recursion so a deeply nested input cannot +/// overflow the stack. The same limit, counted the same way, as the +/// frame's, so any frame builds and any value that walks frames. +pub const MAX_DEPTH: usize = vitaminc_aead::frame::MAX_DEPTH; + +/// Property names that must never be read from or written onto a plain JS +/// object: assigning them via `napi_set_property` triggers prototype-chain +/// semantics (prototype pollution), and accepting them on input would let a +/// value round-trip into that hazard. +pub(crate) fn forbidden_key(key: &str) -> bool { + matches!(key, "__proto__" | "constructor" | "prototype") +} + +pub(crate) fn depth_error() -> JsFault { + JsFault::refused(Refusal::TooDeep, "value is nested too deeply") +} + +pub(crate) fn forbidden_key_error(key: &str) -> JsFault { + JsFault::refused( + Refusal::ReservedKey, + format!("property name is not allowed: {key}"), + ) +} + +/// Initial `Vec` capacity granted to a JS-reported length before any element +/// has been validated. An array's reported length is attacker-cheap — +/// `new Array(2**32 - 1)` materialises no elements — so reserving the full +/// reported length up front would let a one-line input demand hundreds of +/// gigabytes and abort the whole Node process on allocation failure +/// (`handle_alloc_error` is not a catchable JS throw). Real elements grow +/// the `Vec` amortised past this cap. +const MAX_EAGER_CAPACITY: usize = 1024; + +pub(crate) fn eager_capacity(reported_len: u32) -> usize { + (reported_len as usize).min(MAX_EAGER_CAPACITY) +} + +/// An own property key: the JS key itself, for reading the property back +/// exactly, and its text. +pub(crate) struct OwnKey<'e> { + handle: Unknown<'e>, + pub(crate) name: Zeroizing, +} + +/// Own, enumerable, string-keyed properties of `obj`. +/// +/// `Object::keys` (`napi_get_property_names`) walks the prototype chain — +/// per the Node-API spec it equals `napi_get_all_property_names` with +/// `include_prototypes | enumerable` — so a polluted `Object.prototype` +/// (or an instance with enumerable prototype members) would inject its +/// keys into the result, and inherited getters would run when the values +/// are read. Own-only enumeration forecloses both. +/// +/// A key holding an unpaired surrogate is refused, as string values are: it +/// has no UTF-8 spelling, so it could not be sealed as written. +pub(crate) fn own_enumerable_keys<'e>( + obj: &Object<'e>, +) -> std::result::Result>, JsFault> { + // napi-rs takes a single key filter, so symbol keys are skipped below + // rather than by an `enumerable | skip_symbols` filter. + let names = obj.get_all_property_names( + KeyCollectionMode::OwnOnly, + KeyFilter::Enumerable, + KeyConversion::NumbersToStrings, + )?; + let len = names.get_array_length()?; + let mut keys = Vec::with_capacity(eager_capacity(len)); + for i in 0..len { + let handle = names.get_element::(i)?; + if handle.get_type()? == ValueType::Symbol { + continue; + } + let name = lossless_string(handle, "property name")?; + keys.push(OwnKey { handle, name }); + } + Ok(keys) +} + +/// Read the own property `key` names, by the key's own JS handle. +/// +/// The key list is a snapshot, and a getter that ran since may have deleted +/// this property; `[[Get]]` would then read it from a (possibly polluted) +/// prototype. So ownership is checked again immediately before the read, +/// where no JS can run in between for an ordinary object. +pub(crate) fn get_own<'e>( + obj: &Object<'e>, + key: &OwnKey<'e>, +) -> std::result::Result, JsFault> { + if !obj.has_own_property_js(key.handle)? { + // The key is not named: it is part of the value. + return Err(JsFault::refused( + Refusal::ChangedWhileRead, + "a property was removed while it was being read", + )); + } + Ok(obj.get_property_unchecked(key.handle)?) +} + +/// A JS string as Rust text. Fetched as UTF-16 (JS's native representation) +/// and decoded with `char::decode_utf16`, which errors on unpaired +/// surrogates. The UTF-8 fetch (`napi_get_value_string_utf8`) would silently +/// replace them with U+FFFD, so a value would seal *mutated* and a key would +/// stop naming its property; refuse loudly instead. +/// +/// The text may be plaintext, so both Rust copies, the code units and the +/// UTF-8, are wiped on drop. The V8 original cannot be wiped from here. The +/// code units are read straight from Node-API rather than through +/// napi-rs's `Utf16String`, whose buffer cannot be reached to wipe. +pub(crate) fn lossless_string( + value: Unknown<'_>, + what: &str, +) -> std::result::Result, JsFault> { + let env = value.value().env; + let raw = value.raw(); + let mut len = 0usize; + // SAFETY: `value` is a live string handle of `env` (the caller checked + // its type), and a null buffer with size 0 asks for the length only. + let status = + unsafe { sys::napi_get_value_string_utf16(env, raw, std::ptr::null_mut(), 0, &mut len) }; + check_status!(status, "failed to measure a {what}")?; + // Room for the terminating NUL Node-API writes. + let mut units = Zeroizing::new(vec![0u16; len + 1]); + let mut written = 0usize; + // SAFETY: as above, and `units` holds `len + 1` code units, which is the + // size passed, so the write stays inside the buffer. + let status = unsafe { + sys::napi_get_value_string_utf16(env, raw, units.as_mut_ptr(), len + 1, &mut written) + }; + check_status!(status, "failed to read a {what}")?; + from_utf16(&units[..written.min(len)]).ok_or_else(|| { + JsFault::refused( + Refusal::UnpairedSurrogate, + format!("{what} contains an unpaired surrogate and cannot be encrypted losslessly"), + ) + }) +} + +/// UTF-16 code units as UTF-8 text, or `None` if any surrogate is unpaired. +/// +/// The UTF-8 length is measured first, so the text is built in a wiped +/// buffer of its final size: a `String` that grows leaves its old buffer +/// unwiped, as `String::from_utf16` does for any text outside ASCII. +fn from_utf16(units: &[u16]) -> Option> { + let mut utf8_len = 0usize; + for c in char::decode_utf16(units.iter().copied()) { + utf8_len += c.ok()?.len_utf8(); + } + let mut text = Zeroizing::new(String::with_capacity(utf8_len)); + // Every unit was checked above, so `flatten` drops nothing. + for c in char::decode_utf16(units.iter().copied()).flatten() { + text.push(c); + } + Some(text) +} + +/// Fetch a property as the raw JS value, without [`Object::get`]'s +/// `undefined`-to-`None` mapping — `{ x: undefined }` has an own property +/// `x` (`Object.hasOwn` says so) and must round-trip, but `Object::get` +/// cannot distinguish its value from a missing property. A genuinely +/// missing property also comes back as `undefined`, which is exactly JS +/// property semantics. +pub(crate) fn get_property_unknown<'e>(obj: &Object<'e>, key: &str) -> Result> { + // The key goes over as a JS string with an explicit length, so a key + // holding NUL survives (`get_named_property` would refuse it). + let env = Env::from_raw(obj.value().env); + let js_key = key.into_unknown(&env)?; + obj.get_property_unchecked(js_key) +} + +/// The refusal of anything but a plain object or a wrapper instance; the +/// check itself is [`Wrappers::is_plain`](crate::Wrappers::is_plain). +pub(crate) fn not_plain_error() -> JsFault { + JsFault::refused( + Refusal::NotPlain, + "only plain objects and the wrapper classes can be encrypted; Map, Set, class instances \ + and other exotic objects lose their contents under key enumeration — convert the value \ + to a plain object, array, string, number, Buffer, or Uint8Array first", + ) +} + +/// One own data property, for [`define_own_properties`]. `Property::new()` +/// defaults to writable, enumerable and configurable, the attributes +/// `obj.key = value` would give. +pub(crate) fn own_property<'e, V: JsValue<'e>>( + env: &Env, + key: &str, + value: &V, +) -> Result { + // A JS string name, not a UTF-8 C string, so a key holding NUL works. + Ok(Property::new().with_name(env, key)?.with_value(value)) +} + +/// Write `properties` onto `obj` as **own data properties** +/// (`defineProperty` semantics) rather than through [`Object::set`] or +/// `Array::set` (`napi_set_property` / `napi_set_element`, `[[Set]]` +/// semantics), which walk the prototype chain: a polluted inherited setter on +/// a key or array index would receive the decrypted plaintext (leak) and +/// leave the result without the own property (drop). The intake side already +/// treats prototype pollution as in-threat-model (`own_enumerable_keys`, +/// `is_plain_object`); this closes the output side. One call per object. +pub(crate) fn define_own_properties(obj: &mut Object<'_>, properties: &[Property]) -> Result<()> { + obj.define_properties(properties) +} + +/// A new JS array of `len` holes, seen as an object so its elements can be +/// defined with [`define_own_properties`]. +pub(crate) fn new_array<'e>(env: &'e Env, len: usize) -> Result> { + let len = u32::try_from(len) + .map_err(|_| Error::new(Status::InvalidArg, "array is too long for JS"))?; + Object::from_unknown(env.create_array(len)?.to_unknown()) +} + +#[cfg(test)] +mod tests { + use super::{eager_capacity, forbidden_key, from_utf16, MAX_EAGER_CAPACITY}; + + #[test] + fn forbidden_keys_are_rejected() { + assert!(forbidden_key("__proto__")); + assert!(forbidden_key("constructor")); + assert!(forbidden_key("prototype")); + assert!(!forbidden_key("proto")); + assert!(!forbidden_key("name")); + assert!(!forbidden_key("")); + } + + #[test] + fn eager_capacity_passes_small_lengths_through() { + assert_eq!(eager_capacity(0), 0); + assert_eq!(eager_capacity(1), 1); + assert_eq!(eager_capacity(37), 37); + assert_eq!( + eager_capacity(MAX_EAGER_CAPACITY as u32), + MAX_EAGER_CAPACITY + ); + } + + #[test] + fn eager_capacity_caps_attacker_reported_lengths() { + assert_eq!( + eager_capacity(MAX_EAGER_CAPACITY as u32 + 1), + MAX_EAGER_CAPACITY + ); + assert_eq!(eager_capacity(u32::MAX), MAX_EAGER_CAPACITY); + } + + #[test] + fn utf16_text_is_built_at_its_final_size() { + for text in ["", "a", "José", "😀b", "\u{10FFFF}"] { + let units: Vec = text.encode_utf16().collect(); + let built = from_utf16(&units).expect("well formed"); + assert_eq!(built.as_str(), text); + // A buffer that grew would have left a smaller one unwiped. + assert_eq!(built.capacity(), text.len(), "{text}"); + } + } + + #[test] + fn an_unpaired_surrogate_is_refused() { + for units in [&[0xD800][..], &[0x61, 0xDC00, 0x62], &[0xD83D, 0x61]] { + assert!(from_utf16(units).is_none(), "{units:x?}"); + } + } +} diff --git a/languages/typescript/packages/recipher-js/value-napi/src/js_builder.rs b/languages/typescript/packages/recipher-js/value-napi/src/js_builder.rs new file mode 100644 index 000000000..89dc5a2e9 --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/src/js_builder.rs @@ -0,0 +1,411 @@ +//! [`JsBuilder`]: a [`Sink`] that builds JavaScript values. +//! +//! The build runs on the JavaScript thread. Each scalar becomes the +//! JavaScript value of its kind, the inverse of the mapping in +//! [`js_ref`](crate::js_ref): a null, a boolean, a `number` for a float, a +//! `BigInt` for any int width, a string, a `Buffer`, a `Date` for a +//! timestamp that is whole milliseconds inside `Date`'s range, and a +//! wrapper class instance for a calendar date, a finer timestamp, a decimal +//! or a UUID. A sequence becomes an array and a map a plain object, both +//! written as own data properties so a polluted prototype never sees the +//! plaintext. A passthrough subtree is built like the rest. +//! +//! A logical type this build does not know cannot be shown to JavaScript +//! and is refused. + +use napi::bindgen_prelude::{BigInt, Buffer, JsValue, Null, Object, ToNapiValue, Unknown}; +use napi::{Env, Error, Status}; +use vitaminc_aead::{ + Encrypt, EncryptRef, FixedType, Float, Frame, Int, Logical, MapSink, Physical, SeqSink, Sink, +}; + +use crate::error::JsFault; +use crate::js::{ + define_own_properties, depth_error, eager_capacity, forbidden_key, forbidden_key_error, + new_array, own_property, MAX_DEPTH, +}; +use crate::scalar; +use crate::wrappers::{Wrapper, Wrappers}; + +/// Where a built value goes: the root hands it back, a child writes it into +/// its parent. +mod out { + use napi::bindgen_prelude::Unknown; + + pub trait Out<'e> { + type Ok; + fn put(self, value: Unknown<'e>) -> Self::Ok; + } + + /// The root of the build: the value is the result. + pub struct Root; + + impl<'e> Out<'e> for Root { + type Ok = Unknown<'e>; + fn put(self, value: Unknown<'e>) -> Unknown<'e> { + value + } + } + + /// An element slot in a parent sequence. + pub struct Slot<'s, 'e>(pub(super) &'s mut Vec>); + + impl<'e> Out<'e> for Slot<'_, 'e> { + type Ok = (); + fn put(self, value: Unknown<'e>) { + self.0.push(value); + } + } + + /// An entry in a parent map. + pub struct Entry<'s, 'e> { + pub(super) entries: &'s mut Vec<(String, Unknown<'e>)>, + pub(super) key: String, + } + + impl<'e> Out<'e> for Entry<'_, 'e> { + type Ok = (); + fn put(self, value: Unknown<'e>) { + self.entries.push((self.key, value)); + } + } +} + +use out::{Entry, Out, Root, Slot}; + +/// A sink that builds a JavaScript value, on the JavaScript thread. +/// +/// `O` is where the value goes; a caller only meets the root form, whose +/// `Ok` is the built value. +pub struct JsBuilder<'e, O = Root> { + env: &'e Env, + depth: usize, + out: O, +} + +impl<'e> JsBuilder<'e> { + /// A build of a root value in `env`. + pub fn new(env: &'e Env) -> Self { + Self::at_depth(env, 0) + } + + /// A build whose root sits `depth` levels down in a larger structure, + /// so the nesting limit counts the whole structure. + pub(crate) fn at_depth(env: &'e Env, depth: usize) -> Self { + Self { + env, + depth, + out: Root, + } + } + + /// The JavaScript value of a frame. + /// + /// # Errors + /// + /// A [`JsFault`]: its [`refusal`](JsFault::refusal) names the rule a + /// value JavaScript cannot hold broke. + pub fn build(env: &'e Env, frame: Frame<'_>) -> Result, JsFault> { + frame.visit(Self::new(env)) + } +} + +impl JsBuilder<'_, O> { + fn check_depth(&self) -> Result<(), JsFault> { + if self.depth > MAX_DEPTH { + return Err(depth_error()); + } + Ok(()) + } +} + +impl<'e, O: Out<'e>> Sink for JsBuilder<'e, O> { + type Ok = O::Ok; + type Error = JsFault; + type Seq = JsSeq<'e, O>; + type Map = JsMap<'e, O>; + + fn scalar(self, ty: Option, value: Physical<'_>) -> Result { + self.check_depth()?; + let built = scalar_to_js(self.env, ty, value)?; + Ok(self.out.put(built)) + } + + /// An absent value is JavaScript's `null`, whatever its type. + fn typed_null(self, _: FixedType) -> Result { + self.scalar(None, Physical::Null) + } + + fn seq(self, len: Option) -> Result, JsFault> { + self.check_depth()?; + Ok(JsSeq { + env: self.env, + depth: self.depth, + out: self.out, + items: Vec::with_capacity(capacity(len)), + }) + } + + fn map(self, len: Option) -> Result, JsFault> { + self.check_depth()?; + Ok(JsMap { + env: self.env, + depth: self.depth, + out: self.out, + entries: Vec::with_capacity(capacity(len)), + }) + } + + /// A passthrough subtree is plaintext to the application, so it is + /// built like anything else, one level down as the frame counts it. + fn passthrough(self, value: &P) -> Result { + self.check_depth()?; + let built = value.visit_ref(JsBuilder::at_depth(self.env, self.depth + 1))?; + Ok(self.out.put(built)) + } +} + +/// A length hint is only a hint, and a hostile one costs the source +/// nothing, so it buys at most a bounded reservation. +fn capacity(len: Option) -> usize { + eager_capacity(u32::try_from(len.unwrap_or(0)).unwrap_or(u32::MAX)) +} + +/// The sequence side of [`JsBuilder`]: an array, written once its +/// elements are built. +pub struct JsSeq<'e, O> { + env: &'e Env, + depth: usize, + out: O, + items: Vec>, +} + +impl<'e, O: Out<'e>> SeqSink for JsSeq<'e, O> { + type Ok = O::Ok; + type Error = JsFault; + type Element<'s> + = JsBuilder<'e, Slot<'s, 'e>> + where + Self: 's; + + fn element(&mut self) -> Result, JsFault> { + Ok(JsBuilder { + env: self.env, + depth: self.depth + 1, + out: Slot(&mut self.items), + }) + } + + fn end(self) -> Result { + let env = self.env; + let mut array = new_array(env, self.items.len())?; + let mut elements = Vec::with_capacity(self.items.len()); + for (i, item) in self.items.iter().enumerate() { + elements.push(own_property(env, &i.to_string(), item)?); + } + define_own_properties(&mut array, &elements)?; + Ok(self.out.put(array.to_unknown())) + } +} + +/// The map side of [`JsBuilder`]: a plain object, written once its +/// entries are built. +pub struct JsMap<'e, O> { + env: &'e Env, + depth: usize, + out: O, + entries: Vec<(String, Unknown<'e>)>, +} + +impl<'e, O: Out<'e>> MapSink for JsMap<'e, O> { + type Ok = O::Ok; + type Error = JsFault; + type Entry<'s> + = JsBuilder<'e, Entry<'s, 'e>> + where + Self: 's; + + fn entry(&mut self, key: &str) -> Result, JsFault> { + // Keys decrypted from a ciphertext are attacker-influenced in + // principle; never assign prototype-polluting names. + if forbidden_key(key) { + return Err(forbidden_key_error(key)); + } + Ok(JsBuilder { + env: self.env, + depth: self.depth + 1, + out: Entry { + entries: &mut self.entries, + key: key.to_owned(), + }, + }) + } + + fn end(self) -> Result { + let env = self.env; + let mut object = Object::new(env)?; + let mut properties = Vec::with_capacity(self.entries.len()); + for (key, value) in &self.entries { + properties.push(own_property(env, key, value)?); + } + define_own_properties(&mut object, &properties)?; + Ok(self.out.put(object.to_unknown())) + } +} + +fn malformed(what: &str) -> Error { + Error::new( + Status::GenericFailure, + format!("{what} is not a value this binding can build"), + ) +} + +/// One scalar as its JavaScript value. +fn scalar_to_js<'e>( + env: &'e Env, + ty: Option, + value: Physical<'_>, +) -> napi::Result> { + let Some(ty) = ty else { + return match value { + Physical::Null => Null.into_unknown(env), + Physical::Bool(b) => b.into_unknown(env), + Physical::Int(int) => bigint(int).into_unknown(env), + // Both float widths surface as a JS `number`; `f32` widens exactly. + Physical::Float(Float::F32(f)) => f64::from(f).into_unknown(env), + Physical::Float(Float::F64(f)) => f.into_unknown(env), + Physical::Text(s) => s.into_unknown(env), + Physical::Bytes(b) => Buffer::from(b.to_vec()).into_unknown(env), + }; + }; + let wrap = |wrapper: Wrapper, text: Option| -> napi::Result> { + let text = text.ok_or_else(|| malformed(wrapper.class_name()))?; + Wrappers::get(env)?.construct(wrapper, &text) + }; + match (ty, value) { + (Logical::Undefined, Physical::Null) => ().into_unknown(env), + (Logical::Date, Physical::Int(days)) => wrap(Wrapper::Date, scalar::date_text(days)), + (Logical::Timestamp(unit), Physical::Int(count)) => { + match scalar::timestamp_js_millis(unit, count) { + Some(ms) => Ok(env.create_date(ms)?.to_unknown()), + None => wrap(Wrapper::Timestamp, scalar::timestamp_text(unit, count)), + } + } + (Logical::Decimal { scale }, Physical::Int(mantissa)) => { + wrap(Wrapper::Decimal, scalar::decimal_text(scale, mantissa)) + } + (Logical::Uuid, Physical::Bytes(bytes)) => wrap(Wrapper::Uuid, scalar::uuid_text(bytes)), + (Logical::Unknown(unknown), _) => Err(Error::new( + Status::GenericFailure, + format!( + "logical type {} is not known to this binding and has no JavaScript value", + unknown.id() + ), + )), + (ty, _) => Err(malformed(&ty.to_string())), + } +} + +fn bigint(int: Int) -> BigInt { + match int.to_i128() { + Some(v) => BigInt::from(v), + // Only a u128 above i128::MAX has no i128. + None => BigInt::from(int.to_u128().unwrap_or(u128::MAX)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::js::MAX_DEPTH; + + #[test] + fn a_length_hint_buys_a_bounded_reservation() { + assert_eq!(capacity(None), 0); + assert_eq!(capacity(Some(0)), 0); + assert_eq!(capacity(Some(37)), 37); + assert_eq!(capacity(Some(usize::MAX)), eager_capacity(u32::MAX)); + assert_eq!(capacity(Some(1 << 40)), eager_capacity(u32::MAX)); + } + + #[test] + fn every_int_width_becomes_a_bigint_of_its_sign_and_magnitude() { + // Every width goes through i128 when it fits, so two words always. + let big = bigint(Int::I8(-1)); + assert!(big.sign_bit, "negative"); + assert_eq!(big.words, [1, 0]); + let big = bigint(Int::U64(u64::MAX)); + assert!(!big.sign_bit); + assert_eq!(big.words, [u64::MAX, 0]); + let big = bigint(Int::I128(i128::MIN)); + assert!(big.sign_bit); + assert_eq!(big.words, [0, 1 << 63]); + // Above i128::MAX there is no i128, so the u128 path carries it. + let big = bigint(Int::U128(u128::MAX)); + assert!(!big.sign_bit); + assert_eq!(big.words, [u64::MAX, u64::MAX]); + } + + #[test] + fn the_depth_check_refuses_one_past_the_limit() { + let env = Env::from_raw(std::ptr::null_mut()); + assert!(JsBuilder::at_depth(&env, MAX_DEPTH).check_depth().is_ok()); + let error = JsBuilder::at_depth(&env, MAX_DEPTH + 1) + .check_depth() + .expect_err("past the limit"); + assert_eq!(error.status(), Status::InvalidArg); + assert!(error.reason().contains("nested too deeply"), "{error}"); + } + + // A container at the limit may itself be built, but each of its + // children sits one level deeper and must be refused. The builders + // below never reach the environment: the depth check comes first. + + #[test] + fn a_sequence_at_the_limit_refuses_its_elements() { + let env = Env::from_raw(std::ptr::null_mut()); + let mut seq = JsSeq { + env: &env, + depth: MAX_DEPTH, + out: Root, + items: Vec::new(), + }; + let element = seq.element().expect("the element slot itself"); + assert_eq!(element.depth, MAX_DEPTH + 1); + element.check_depth().expect_err("one level deeper"); + } + + #[test] + fn a_map_at_the_limit_refuses_its_entries() { + let env = Env::from_raw(std::ptr::null_mut()); + let mut map = JsMap { + env: &env, + depth: MAX_DEPTH, + out: Root, + entries: Vec::new(), + }; + let entry = map.entry("k").expect("the entry slot itself"); + assert_eq!(entry.depth, MAX_DEPTH + 1); + entry.check_depth().expect_err("one level deeper"); + } + + #[test] + fn a_passthrough_at_the_limit_builds_its_value_one_level_deeper() { + /// A value that opens a sequence and reports whether the sink let it. + struct Probe; + impl Encrypt for &Probe { + fn visit(self, sink: S) -> Result { + match sink.seq(Some(0)) { + Ok(_) => panic!("a sequence one level past the limit was accepted"), + Err(error) => Err(error), + } + } + } + let env = Env::from_raw(std::ptr::null_mut()); + let error = JsBuilder::at_depth(&env, MAX_DEPTH) + .passthrough(&Probe) + .err() + .expect("the passthrough's value sits one level deeper"); + assert!(error.reason().contains("nested too deeply"), "{error:?}"); + } +} diff --git a/languages/typescript/packages/recipher-js/value-napi/src/js_ref.rs b/languages/typescript/packages/recipher-js/value-napi/src/js_ref.rs new file mode 100644 index 000000000..5bb183def --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/src/js_ref.rs @@ -0,0 +1,339 @@ +//! [`JsRef`]: a live JavaScript value as an [`Encrypt`] source. +//! +//! The walk runs on the JavaScript thread, reading each value as it goes: +//! no tree is built, and a scalar leaves the engine only to go straight to +//! the sink. Values map to sink calls as follows: +//! +//! | JavaScript | `Sink` call | +//! | ---------------------- | ----------------------------------------------- | +//! | `null` | `scalar(None, Null)` | +//! | `undefined` | `scalar(Some(Undefined), Null)` | +//! | `boolean` | `scalar(None, Bool)` | +//! | `number` | `scalar(None, Float(F64))` | +//! | `bigint` | `scalar(None, Int(narrowest fitting width))` | +//! | `string` | `scalar(None, Text)` | +//! | `Buffer`, `Uint8Array` | `scalar(None, Bytes)`; any other view is refused | +//! | `Date` | `scalar(Some(Timestamp(Millis)), Int(I64(ms)))` | +//! | `Array` | `seq`, then `element()` per index | +//! | plain object | `map`, then `entry(key)` per own property | +//! +//! The wrapper classes carry the scalars JavaScript has no type for: +//! `VcDate` is `Date` over the day count, `VcTimestamp` is +//! `Timestamp(Nanos)` over the nanosecond count, `VcDecimal` is `Decimal` +//! over the mantissa and `VcUuid` is `Uuid` over sixteen bytes. +//! +//! A getter that throws, a string with an unpaired surrogate, a BigInt out +//! of range or a `Date` outside the wire's range stops the walk through +//! [`Error::source`](vitaminc_aead::plaintext::Error::source), and comes +//! back to JavaScript as that error: see [`JsFault`]. + +use napi::bindgen_prelude::{ + Array, BigInt, FromNapiValue, JsObjectValue, JsValue, Object, Uint8ArraySlice, Unknown, +}; +use napi::{Env, Status, ValueType}; +use vitaminc_aead::frame::FrameWriteError; +use vitaminc_aead::plaintext::{Error as _, SourceError}; +use vitaminc_aead::{ + to_frame, Encrypt, Float, Logical, MapSink, Physical, SeqSink, Sink, TimeUnit, +}; +use vitaminc_protected::Buffer; + +use crate::error::{JsFault, Refusal}; +use crate::js::{ + depth_error, forbidden_key, forbidden_key_error, get_own, lossless_string, not_plain_error, + own_enumerable_keys, MAX_DEPTH, +}; +use crate::scalar::{self, ConversionError}; +use crate::wrappers::{Wrapper, Wrappers}; + +/// A live JavaScript value, walked in place on the JavaScript thread. +pub struct JsRef<'e> { + value: Unknown<'e>, + depth: usize, +} + +impl<'e> JsRef<'e> { + /// The value to walk, as the root of the structure. + pub fn new(value: Unknown<'e>) -> Self { + Self { value, depth: 0 } + } + + /// A value that sits `depth` levels down in a larger structure, so + /// the nesting limit counts the whole structure. + pub(crate) fn at_depth(value: Unknown<'e>, depth: usize) -> Self { + Self { value, depth } + } + + /// Snapshot the value as a frame, on the JavaScript thread, so it can be + /// encrypted on a worker with no JavaScript access. The frame is + /// plaintext and comes back wiped on drop. + /// + /// # Errors + /// + /// A [`JsFault`]: its [`refusal`](JsFault::refusal) names the rule a + /// refused value broke. + pub fn to_frame(self) -> Result { + to_frame(self).map_err(frame_error) + } +} + +impl Encrypt for JsRef<'_> { + fn visit(self, sink: S) -> Result { + js_walk(self.value, self.depth, sink) + } +} + +/// A frame writer's refusal as the fault to hand back. +pub(crate) fn frame_error(error: FrameWriteError) -> JsFault { + match error { + FrameWriteError::Source(source) => JsFault::of_source(&source), + FrameWriteError::TooDeep => depth_error(), + other => JsFault::new(Status::InvalidArg, other.to_string()), + } +} + +/// A JavaScript-side failure, as the sink's error. +fn js_fault(error: impl Into) -> S::Error { + S::Error::source(SourceError::new(error.into())) +} + +/// A scalar conversion failure: thrown into JavaScript as a `TypeError` +/// with the error's stable code, and carried as the pending exception. +fn js_conversion(env: &Env, error: ConversionError) -> S::Error { + match env.throw_type_error(&error.to_string(), Some(error.code())) { + Ok(()) => js_fault::(JsFault::pending(error)), + Err(error) => js_fault::(error), + } +} + +fn js_walk(value: Unknown<'_>, depth: usize, sink: S) -> Result { + if depth > MAX_DEPTH { + return Err(js_fault::(depth_error())); + } + match value.get_type().map_err(js_fault::)? { + ValueType::Null => sink.scalar(None, Physical::Null), + ValueType::Undefined => sink.scalar(Some(Logical::Undefined), Physical::Null), + ValueType::Boolean => { + let b = bool::from_unknown(value).map_err(js_fault::)?; + sink.scalar(None, Physical::Bool(b)) + } + ValueType::Number => { + let n = f64::from_unknown(value).map_err(js_fault::)?; + sink.scalar(None, Physical::Float(Float::F64(n))) + } + ValueType::BigInt => { + let env = Env::from_raw(value.value().env); + let big = BigInt::from_unknown(value).map_err(js_fault::)?; + let int = scalar::bigint(big.sign_bit, &big.words) + .map_err(|e| js_conversion::(&env, e))?; + sink.scalar(None, Physical::Int(int)) + } + ValueType::String => { + // The text is copied out of the engine to check it and goes + // straight to the sink; the V8 original cannot be wiped from here. + let text = lossless_string(value, "string").map_err(js_fault::)?; + sink.scalar(None, Physical::Text(&text)) + } + ValueType::Object => js_object(value, depth, sink), + other => Err(js_fault::(JsFault::refused( + Refusal::NotAValue, + format!("JS type cannot be encrypted: {other}"), + ))), + } +} + +/// Dispatch an object. The scalar shapes are read in helpers whose frames +/// are gone before the containers recurse, so the stack a nested level +/// costs is the recursion's own and a document at the depth limit walks +/// in a debug build too. +fn js_object(value: Unknown<'_>, depth: usize, sink: S) -> Result { + // Typed arrays before anything else: `napi_is_buffer` is true for every + // `ArrayBufferView`, so a `Buffer` check first would take a + // `Float64Array` as raw bytes. + if value.is_typedarray().map_err(js_fault::)? { + return js_bytes(value, sink); + } + if value.is_dataview().map_err(js_fault::)? { + return Err(js_fault::(not_bytes_error("DataView"))); + } + if value.is_array().map_err(js_fault::)? { + return js_array(value, depth, sink); + } + if value.is_date().map_err(js_fault::)? { + return js_date(value, sink); + } + match js_classify(value).map_err(js_fault::)? { + Some(wrapper) => js_wrapped(value, wrapper, sink), + None => js_map(value, depth, sink), + } +} + +/// A `Buffer` or `Uint8Array` as bytes. Only byte views are meaningful +/// plaintext: a `Float64Array`, an `Int16Array`, a `BigInt64Array` or a +/// `Uint8ClampedArray` would seal as its raw bytes and silently decrypt +/// as a `Buffer`, so the cast, which checks the element type, refuses +/// them. A `Buffer` is a `Uint8Array` and passes. +/// +/// The view is borrowed as a slice, which holds no reference. napi-rs's +/// `Uint8Array` takes a reference before it checks the element type and +/// never releases it when the check fails, so every refused array would +/// stay alive until the environment exits. +fn js_bytes(value: Unknown<'_>, sink: S) -> Result { + let arr = Uint8ArraySlice::from_unknown(value) + .map_err(|_| js_fault::(not_bytes_error("typed array")))?; + sink.scalar(None, Physical::Bytes(&arr)) +} + +fn not_bytes_error(what: &str) -> JsFault { + JsFault::refused( + Refusal::NotBytes, + format!("only a Buffer or a Uint8Array can be encrypted as bytes, not a {what}"), + ) +} + +fn js_date(value: Unknown<'_>, sink: S) -> Result { + let env = Env::from_raw(value.value().env); + let date = napi::JsDate::from_unknown(value).map_err(js_fault::)?; + let ms = date.value_of().map_err(js_fault::)?; + let count = scalar::date_millis(ms).map_err(|e| js_conversion::(&env, e))?; + sink.scalar( + Some(Logical::Timestamp(TimeUnit::Millis)), + Physical::Int(count), + ) +} + +/// Which wrapper class an object is an instance of, or none for a plain +/// object. Anything else is refused. +fn js_classify(value: Unknown<'_>) -> Result, JsFault> { + let env = Env::from_raw(value.value().env); + let wrappers = Wrappers::get(&env)?; + // Most objects are plain, and a plain object has no wrapper prototype + // in its chain, so it is asked first and the class checks are skipped. + if wrappers.is_plain(value)? { + return Ok(None); + } + match wrappers.classify(&value)? { + Some(wrapper) => Ok(Some(wrapper)), + None => Err(not_plain_error()), + } +} + +fn js_map(value: Unknown<'_>, depth: usize, sink: S) -> Result { + let obj = Object::from_unknown(value).map_err(js_fault::)?; + let keys = own_enumerable_keys(&obj).map_err(js_fault::)?; + let mut map = sink.map(Some(keys.len()))?; + for key in keys { + if forbidden_key(&key.name) { + return Err(js_fault::(forbidden_key_error(&key.name))); + } + // Raw fetch so an explicit `undefined` value survives as + // `Undefined` instead of reading as a missing property. + let value = get_own(&obj, &key).map_err(js_fault::)?; + js_walk(value, depth + 1, map.entry(&key.name)?)?; + } + map.end() +} + +fn js_array(value: Unknown<'_>, depth: usize, sink: S) -> Result { + let arr = Array::from_unknown(value).map_err(js_fault::)?; + // The same JS value seen as an object, for per-index own-property + // checks: `Array::get` wraps every in-bounds hole in `Some(undefined)`, + // so on its own it can neither reject sparseness nor resist a polluted + // `Array.prototype` filling holes with inherited elements. + let obj = Object::from_unknown(value).map_err(js_fault::)?; + let len = arr.len(); + let mut seq = sink.seq(Some(len as usize))?; + for i in 0..len { + // A hole has no own property; an explicit `undefined` element does. + // `[undefined]` round-trips; `[, , "x"]` and `new Array(n)` are + // rejected. + let sparse = || JsFault::refused(Refusal::SparseArray, "sparse arrays are not supported"); + if !obj + .has_own_property(&i.to_string()) + .map_err(js_fault::)? + { + return Err(js_fault::(sparse())); + } + let element: Unknown = arr + .get(i) + .map_err(js_fault::)? + .ok_or_else(|| js_fault::(sparse()))?; + js_walk(element, depth + 1, seq.element()?)?; + } + seq.end() +} + +/// A wrapper instance as its scalar. The text is read as an own string +/// property and checked here, so an instance made without the constructor +/// is held to the same rule. +fn js_wrapped(value: Unknown<'_>, wrapper: Wrapper, sink: S) -> Result { + let env = &Env::from_raw(value.value().env); + let wrappers = Wrappers::get(env).map_err(js_fault::)?; + let instance = &Object::from_unknown(value).map_err(js_fault::)?; + let invalid = match wrapper { + Wrapper::Date => ConversionError::InvalidDate, + Wrapper::Timestamp => ConversionError::InvalidTimestamp, + Wrapper::Decimal => ConversionError::InvalidDecimal, + Wrapper::Uuid => ConversionError::InvalidUuid, + }; + let text = match wrappers.text(instance).map_err(js_fault::)? { + Some(text) => lossless_string(text, wrapper.class_name()).map_err(js_fault::)?, + None => return Err(js_conversion::(env, invalid)), + }; + let convert = |e| js_conversion::(env, e); + match wrapper { + Wrapper::Date => { + let days = scalar::date(&text).map_err(convert)?; + sink.scalar(Some(Logical::Date), Physical::Int(days)) + } + Wrapper::Timestamp => { + let nanos = scalar::timestamp(&text).map_err(convert)?; + sink.scalar( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(nanos), + ) + } + Wrapper::Decimal => { + let (scale, mantissa) = scalar::decimal(&text).map_err(convert)?; + sink.scalar(Some(Logical::Decimal { scale }), Physical::Int(mantissa)) + } + Wrapper::Uuid => { + let bytes = scalar::uuid(&text).map_err(convert)?; + sink.scalar(Some(Logical::Uuid), Physical::Bytes(&bytes)) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_frame_writers_refusal_becomes_the_napi_error_the_host_expects() { + let too_deep = frame_error(FrameWriteError::TooDeep); + assert_eq!(too_deep.status(), Status::InvalidArg); + assert!( + too_deep.reason().contains("nested too deeply"), + "{too_deep}" + ); + assert_eq!(too_deep.refusal(), Some(Refusal::TooDeep)); + + let too_long = frame_error(FrameWriteError::TooLong); + assert_eq!(too_long.status(), Status::InvalidArg); + assert_eq!(too_long.reason(), FrameWriteError::TooLong.to_string()); + + // A getter that threw comes back as the error it threw. + let thrown = napi::Error::new(Status::PendingException, "the getter threw"); + let source = FrameWriteError::Source(SourceError::new(JsFault::from(thrown))); + let back = frame_error(source); + assert_eq!(back.status(), Status::PendingException); + assert_eq!(back.reason(), "the getter threw"); + // What the application threw is no refusal of this crate's. + assert_eq!(back.refusal(), None); + + // A refusal keeps its variant through the sink's source error. + let sparse = JsFault::refused(Refusal::SparseArray, "sparse arrays are not supported"); + let back = frame_error(FrameWriteError::Source(SourceError::new(sparse))); + assert_eq!(back.refusal(), Some(Refusal::SparseArray)); + } +} diff --git a/languages/typescript/packages/recipher-js/value-napi/src/lib.rs b/languages/typescript/packages/recipher-js/value-napi/src/lib.rs new file mode 100644 index 000000000..4288bb659 --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/src/lib.rs @@ -0,0 +1,41 @@ +// These definitions precede the README so rustdoc links to the version being built. +// The README supplies published-API URLs for GitHub. +//! [`JsFault`]: crate::JsFault +//! +// Cross-crate links name the vitaminc version this crate is built with. +#![deny(missing_docs)] +#![doc = concat!( + "\n[`Encrypt`]: https://docs.rs/vitaminc-aead/0.10.0/vitaminc_aead/trait.Encrypt.html\n", + "\n[`Sink`]: https://docs.rs/vitaminc-aead/0.10.0/vitaminc_aead/trait.Sink.html\n", +)] +#![deny(clippy::unwrap_used, clippy::todo, unused_imports)] +// The crate handles plaintext: nothing may print it, and a failure is an +// error JavaScript can catch, never a panic. +#![deny(clippy::expect_used, clippy::panic)] +#![warn(clippy::mem_forget)] +#![warn(clippy::print_stdout)] +#![warn(clippy::print_stderr)] +#![warn(clippy::dbg_macro)] +#![cfg_attr(test, allow(clippy::unwrap_used))] +#![cfg_attr(test, allow(clippy::expect_used))] +#![cfg_attr(test, allow(clippy::panic))] +// The only unsafe left is where napi-rs's conversion traits require it. +// Each block has to say why it is sound, and unsafe calls inside those trait +// methods still need their own block. +#![deny(unsafe_op_in_unsafe_fn, clippy::undocumented_unsafe_blocks)] +#![doc = include_str!("../README.md")] +mod ciphertext; +mod error; +mod js; +mod js_builder; +mod js_ref; +mod scalar; +mod wrappers; + +pub use ciphertext::{JsCipherText, NapiPassthrough}; +pub use error::{JsFault, Refusal}; +pub use js::MAX_DEPTH; +pub use js_builder::JsBuilder; +pub use js_ref::JsRef; +pub use scalar::ConversionError; +pub use wrappers::{Wrapper, Wrappers}; diff --git a/languages/typescript/packages/recipher-js/value-napi/src/scalar.rs b/languages/typescript/packages/recipher-js/value-napi/src/scalar.rs new file mode 100644 index 000000000..d4efb9a37 --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/src/scalar.rs @@ -0,0 +1,780 @@ +//! Host scalars as the ints and bytes their logical types are stored over, +//! and back: BigInt widths, and the text of a calendar date, a timestamp, +//! a decimal and a UUID. +//! +//! These conversions do not require a JavaScript environment. + +use std::fmt; + +use jiff::fmt::temporal::Pieces; +use rust_decimal::Decimal; +use vitaminc_aead::plaintext::kinds::{decimal as kinds_decimal, jiff as kinds_jiff}; +use vitaminc_aead::{Int, Logical, TimeUnit}; + +/// Host scalar conversion errors. Node receives a TypeError with the same +/// stable code; errors contain no user plaintext. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error, miette::Diagnostic)] +#[non_exhaustive] +pub enum ConversionError { + /// The integer fits neither `i128` nor `u128`. + #[error("BigInt is outside the signed/unsigned 128-bit range")] + #[diagnostic(code("ERR_INTEGER_RANGE"))] + IntegerRange, + /// The calendar date is malformed or outside the supported range. + #[error("invalid calendar date")] + #[diagnostic(code("ERR_INVALID_DATE"))] + InvalidDate, + /// The timestamp is malformed or outside the supported range. + #[error("invalid or out-of-range timestamp")] + #[diagnostic(code("ERR_INVALID_TIMESTAMP"))] + InvalidTimestamp, + /// The decimal is malformed or exceeds the supported precision or scale. + #[error("invalid or out-of-range decimal")] + #[diagnostic(code("ERR_INVALID_DECIMAL"))] + InvalidDecimal, + /// The decimal is NaN or infinite. + #[error("decimal must be finite")] + #[diagnostic(code("ERR_NON_FINITE_DECIMAL"))] + NonFiniteDecimal, + /// The UUID text is malformed. + #[error("invalid UUID")] + #[diagnostic(code("ERR_INVALID_UUID"))] + InvalidUuid, +} + +impl ConversionError { + /// Return the stable `ERR_*` code exposed to JavaScript callers. + pub fn code(self) -> &'static str { + match self { + Self::IntegerRange => "ERR_INTEGER_RANGE", + Self::InvalidDate => "ERR_INVALID_DATE", + Self::InvalidTimestamp => "ERR_INVALID_TIMESTAMP", + Self::InvalidDecimal => "ERR_INVALID_DECIMAL", + Self::NonFiniteDecimal => "ERR_NON_FINITE_DECIMAL", + Self::InvalidUuid => "ERR_INVALID_UUID", + } + } +} + +/// A BigInt as the narrowest int that holds it. Smallest width first, +/// preferring signed when both signed and unsigned at that width fit. This +/// rule is frozen for JS BigInt host conversion. +pub(crate) fn bigint(negative: bool, words: &[u64]) -> Result { + if words + .get(2..) + .is_some_and(|tail| tail.iter().any(|&word| word != 0)) + { + return Err(ConversionError::IntegerRange); + } + let magnitude = u128::from(words.first().copied().unwrap_or(0)) + .wrapping_add(u128::from(words.get(1).copied().unwrap_or(0)) << 64); + if negative && magnitude != 0 { + if magnitude > (1u128 << 127) { + return Err(ConversionError::IntegerRange); + } + Ok(signed((magnitude as i128).wrapping_neg())) + } else { + Ok(unsigned(magnitude)) + } +} + +fn signed(value: i128) -> Int { + if let Ok(v) = i8::try_from(value) { + Int::I8(v) + } else if let Ok(v) = i16::try_from(value) { + Int::I16(v) + } else if let Ok(v) = i32::try_from(value) { + Int::I32(v) + } else if let Ok(v) = i64::try_from(value) { + Int::I64(v) + } else { + Int::I128(value) + } +} + +fn unsigned(value: u128) -> Int { + if let Ok(v) = i8::try_from(value) { + Int::I8(v) + } else if let Ok(v) = u8::try_from(value) { + Int::U8(v) + } else if let Ok(v) = i16::try_from(value) { + Int::I16(v) + } else if let Ok(v) = u16::try_from(value) { + Int::U16(v) + } else if let Ok(v) = i32::try_from(value) { + Int::I32(v) + } else if let Ok(v) = u32::try_from(value) { + Int::U32(v) + } else if let Ok(v) = i64::try_from(value) { + Int::I64(v) + } else if let Ok(v) = u64::try_from(value) { + Int::U64(v) + } else if let Ok(v) = i128::try_from(value) { + Int::I128(v) + } else { + Int::U128(value) + } +} + +/// A nanosecond count as the narrowest int the leaf codec can carry it in. +fn nanos_int(nanos: i128) -> Int { + match i64::try_from(nanos) { + Ok(v) => Int::I64(v), + Err(_) => Int::I128(nanos), + } +} + +/// `YYYY-MM-DD` as days since 1970-01-01, spelled as jiff and JavaScript +/// write it: a year from 0000 to 9999 in four digits, and a negative year +/// as a sign and six digits (`-000005-03-01`). +pub(crate) fn date(text: &str) -> Result { + let value: jiff::civil::Date = text.parse().map_err(|_| ConversionError::InvalidDate)?; + // jiff reads other spellings too (`20240229`, `+002024-02-29`, a date + // with a time). Only the one it writes is taken, so a date has one. + if !displays_as(&value, text) { + return Err(ConversionError::InvalidDate); + } + Ok(Int::I32(kinds_jiff::date_days(value))) +} + +/// Whether `value` displays as exactly `text`. The display is compared as it +/// is written rather than collected into a `String`, so no unwiped copy of +/// the plaintext is left behind. +fn displays_as(value: &impl fmt::Display, text: &str) -> bool { + struct Rest<'a>(&'a str); + impl fmt::Write for Rest<'_> { + fn write_str(&mut self, part: &str) -> fmt::Result { + self.0 = self.0.strip_prefix(part).ok_or(fmt::Error)?; + Ok(()) + } + } + let mut rest = Rest(text); + fmt::write(&mut rest, format_args!("{value}")).is_ok() && rest.0.is_empty() +} + +/// A day count as `YYYY-MM-DD`, if it is within the wire's range. +pub(crate) fn date_text(days: Int) -> Option { + kinds_jiff::date(days).map(|date| date.to_string()) +} + +/// RFC 3339 text as nanoseconds since the epoch, with a negative year +/// spelled as a sign and six digits, as jiff and JavaScript write it +/// (`-000005-03-01T12:00:00Z`), so a decrypted timestamp encrypts again. A +/// leap second has no count and is refused, as the leaf codec refuses it. +pub(crate) fn timestamp(text: &str) -> Result { + if !is_rfc3339(text) { + return Err(ConversionError::InvalidTimestamp); + } + // jiff reads the fields and checks their values. The instant is + // counted here, not by jiff's `Offset::to_timestamp`, which in jiff + // 1.0.0 can return one before jiff's minimum (BurntSushi/jiff#714). + let pieces = Pieces::parse(text).map_err(|_| ConversionError::InvalidTimestamp)?; + let (Some(time), Some(offset)) = (pieces.time(), pieces.to_numeric_offset()) else { + return Err(ConversionError::InvalidTimestamp); + }; + let seconds = i128::from(kinds_jiff::date_days(pieces.date())) * 86_400 + + i128::from(time.hour()) * 3_600 + + i128::from(time.minute()) * 60 + + i128::from(time.second()) + - i128::from(offset.seconds()); + let nanos = seconds * 1_000_000_000 + i128::from(time.subsec_nanosecond()); + vitaminc_aead::plaintext::kinds::timestamp_nanos(TimeUnit::Nanos, Int::I128(nanos)) + .map(nanos_int) + .ok_or(ConversionError::InvalidTimestamp) +} + +/// Whether `text` has RFC 3339's shape: a date, `T`, `HH:MM:SS`, a +/// fraction of one to nine digits or none, and `Z` or `±HH:MM` with an +/// hour of at most 23. `t` and `z` may be lower case, and a space may +/// stand for `T`. +/// +/// jiff's parser reads much more than this (no seconds, the basic format, +/// a comma, a time zone annotation, an offset of 24 or 25 hours), and +/// reads a leap second as the second before it. So the shape is checked +/// first, and a leap second and such an offset refused; jiff checks the +/// other values. +fn is_rfc3339(text: &str) -> bool { + let year = if text.starts_with(['+', '-']) { + "s999999" + } else { + "9999" + }; + let Some(rest) = after(text, year).and_then(|rest| after(rest, "-99-99T99:99:99")) else { + return false; + }; + if text[..text.len() - rest.len()].ends_with("60") { + return false; + } + let rest = match rest.strip_prefix('.') { + Some(fraction) => { + let digits = fraction.bytes().take_while(u8::is_ascii_digit).count(); + if !(1..=9).contains(&digits) { + return false; + } + &fraction[digits..] + } + None => rest, + }; + // The offset's two hour digits compare as text, since both are ASCII + // digits. + matches!(rest, "Z" | "z") || (after(rest, "s99:99") == Some("") && &rest[1..3] < "24") +} + +/// What follows a prefix of `text` that has `shape`, where `9` stands for +/// an ASCII digit, `s` for `+` or `-`, `T` for `T`, `t` or a space, and +/// any other byte for itself. +fn after<'a>(text: &'a str, shape: &str) -> Option<&'a str> { + let head = text.as_bytes().get(..shape.len())?; + head.iter() + .zip(shape.bytes()) + .all(|(&byte, want)| match want { + b'9' => byte.is_ascii_digit(), + b's' => matches!(byte, b'+' | b'-'), + b'T' => matches!(byte, b'T' | b't' | b' '), + _ => byte == want, + }) + // The prefix is ASCII, so it ends on a character boundary. + .then(|| &text[shape.len()..]) +} + +/// A JavaScript `Date`'s millisecond count, as the `I64` it is stored as +/// under `Timestamp(Millis)`. Refused when it is not a whole number of +/// milliseconds (`Invalid Date` is NaN) or lies outside the wire's range. +pub(crate) fn date_millis(ms: f64) -> Result { + if !ms.is_finite() || ms.fract() != 0.0 { + return Err(ConversionError::InvalidTimestamp); + } + // `as` saturates, and anything that saturates is out of range anyway. + let count = Int::I64(ms as i64); + if Logical::Timestamp(TimeUnit::Millis).admits(&vitaminc_aead::Physical::Int(count)) { + Ok(count) + } else { + Err(ConversionError::InvalidTimestamp) + } +} + +/// The millisecond count a stored timestamp has as a JavaScript `Date`, if +/// it is whole milliseconds. Every stored timestamp is inside the wire's +/// range, which is narrower than `Date`'s, so the count always fits. +pub(crate) fn timestamp_js_millis(unit: TimeUnit, count: Int) -> Option { + let nanos = vitaminc_aead::plaintext::kinds::timestamp_nanos(unit, count)?; + kinds_jiff::timestamp_count(TimeUnit::Millis, nanos).map(|ms| ms as f64) +} + +/// A stored timestamp as RFC 3339 text with nanoseconds, for the +/// `VcTimestamp` wrapper. +pub(crate) fn timestamp_text(unit: TimeUnit, count: Int) -> Option { + kinds_jiff::timestamp(unit, count).map(|instant| format!("{instant:.9}")) +} + +/// Fixed-point decimal text as a scale and mantissa. +pub(crate) fn decimal(text: &str) -> Result<(u8, Int), ConversionError> { + let unsigned = text.strip_prefix(['+', '-']).unwrap_or(text); + // Compared in place, without a lowercase copy of the plaintext. + let non_finite = ["nan", "inf", "infinity"]; + if non_finite.iter().any(|s| unsigned.eq_ignore_ascii_case(s)) { + return Err(ConversionError::NonFiniteDecimal); + } + // Fixed-point only, matching Go. Refuse separators/exponents rather than + // letting a library parser choose rounding or representation policy. + let mut parts = unsigned.split('.'); + let integral = parts.next().unwrap_or(""); + let fraction = parts.next(); + if integral.is_empty() + || !integral.bytes().all(|c| c.is_ascii_digit()) + || fraction.is_some_and(|part| { + part.is_empty() || part.len() > 28 || !part.bytes().all(|c| c.is_ascii_digit()) + }) + || parts.next().is_some() + { + return Err(ConversionError::InvalidDecimal); + } + // A negative zero parses as zero, which is what the leaf codec stores. + let (scale, mantissa) = Decimal::from_str_exact(text) + .map(kinds_decimal::parts) + .map_err(|_| ConversionError::InvalidDecimal)?; + Ok((scale, Int::I128(mantissa))) +} + +/// A stored decimal as fixed-point text with its scale, for the `VcDecimal` +/// wrapper. +pub(crate) fn decimal_text(scale: u8, mantissa: Int) -> Option { + kinds_decimal::decimal(scale, mantissa).map(|value| value.to_string()) +} + +/// Hyphenated hexadecimal UUID text as its sixteen bytes. Case is accepted +/// either way; braces, URNs and other spellings are not. +pub(crate) fn uuid(text: &str) -> Result<[u8; 16], ConversionError> { + let bytes = text.as_bytes(); + if bytes.len() != 36 || [8, 13, 18, 23].iter().any(|&i| bytes[i] != b'-') { + return Err(ConversionError::InvalidUuid); + } + let mut out = [0u8; 16]; + let mut digits = bytes.iter().filter(|&&b| b != b'-'); + for byte in &mut out { + let hi = digits.next().and_then(|&d| (d as char).to_digit(16)); + let lo = digits.next().and_then(|&d| (d as char).to_digit(16)); + match (hi, lo) { + (Some(hi), Some(lo)) => *byte = (hi * 16 + lo) as u8, + _ => return Err(ConversionError::InvalidUuid), + } + } + Ok(out) +} + +/// Sixteen bytes as lowercase hyphenated UUID text. +pub(crate) fn uuid_text(bytes: &[u8]) -> Option { + let bytes: &[u8; 16] = bytes.try_into().ok()?; + let hex: String = bytes.iter().map(|b| format!("{b:02x}")).collect(); + Some(format!( + "{}-{}-{}-{}-{}", + &hex[0..8], + &hex[8..12], + &hex[12..16], + &hex[16..20], + &hex[20..32] + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use vitaminc_aead::plaintext::kinds::{MAX_TIMESTAMP_NANOS, MIN_TIMESTAMP_NANOS}; + + fn width(int: Int) -> &'static str { + match int { + Int::I8(_) => "i8", + Int::U8(_) => "u8", + Int::I16(_) => "i16", + Int::U16(_) => "u16", + Int::I32(_) => "i32", + Int::U32(_) => "u32", + Int::I64(_) => "i64", + Int::U64(_) => "u64", + Int::I128(_) => "i128", + Int::U128(_) => "u128", + } + } + + #[test] + fn bigint_boundaries_choose_the_smallest_width() { + let positive = [ + (0, "i8"), + (127, "i8"), + (128, "u8"), + (255, "u8"), + (256, "i16"), + (32767, "i16"), + (32768, "u16"), + (65535, "u16"), + (65536, "i32"), + (i32::MAX as u128, "i32"), + (i32::MAX as u128 + 1, "u32"), + (u32::MAX as u128, "u32"), + (u32::MAX as u128 + 1, "i64"), + (i64::MAX as u128, "i64"), + (i64::MAX as u128 + 1, "u64"), + (u64::MAX as u128, "u64"), + (u64::MAX as u128 + 1, "i128"), + (i128::MAX as u128, "i128"), + (i128::MAX as u128 + 1, "u128"), + (u128::MAX, "u128"), + ]; + for (value, expected) in positive { + let words = [value as u64, (value >> 64) as u64]; + let int = bigint(false, &words).expect("in range"); + assert_eq!(width(int), expected, "{value}"); + assert_eq!(int.to_u128(), Some(value)); + } + let negative = [ + (128u128, "i8"), + (129, "i16"), + (32768, "i16"), + (32769, "i32"), + (1 << 31, "i32"), + ((1 << 31) + 1, "i64"), + (1 << 63, "i64"), + ((1 << 63) + 1, "i128"), + (1 << 127, "i128"), + ]; + for (magnitude, expected) in negative { + let int = + bigint(true, &[magnitude as u64, (magnitude >> 64) as u64]).expect("in range"); + assert_eq!(width(int), expected, "-{magnitude}"); + assert_eq!(int.to_i128(), Some((magnitude as i128).wrapping_neg())); + } + assert_eq!(bigint(true, &[0, 1 << 63]), Ok(Int::I128(i128::MIN))); + assert_eq!(bigint(false, &[]), Ok(Int::I8(0))); + assert_eq!(bigint(true, &[0]), Ok(Int::I8(0)), "negative zero"); + assert_eq!( + bigint(false, &[1, 0, 0]), + Ok(Int::I8(1)), + "leading zero word" + ); + assert_eq!( + bigint(true, &[1, 1 << 63]), + Err(ConversionError::IntegerRange) + ); + assert_eq!( + bigint(false, &[0, 0, 1]), + Err(ConversionError::IntegerRange) + ); + } + + #[test] + fn dates_are_day_counts_and_round_trip_as_text() { + assert_eq!(date("1970-01-01"), Ok(Int::I32(0))); + assert_eq!(date("2024-02-29"), Ok(Int::I32(19782))); + assert_eq!(date("0000-01-01"), Ok(Int::I32(-719_528))); + assert_eq!(date("-009999-01-01"), Ok(Int::I32(-4_371_587))); + assert_eq!(date("9999-12-31"), Ok(Int::I32(2_932_896))); + for text in [ + "2024-02-29", + "0000-01-01", + "9999-12-31", + "-000005-03-01", + "-009999-01-01", + ] { + assert_eq!(date_text(date(text).expect("valid")).as_deref(), Some(text)); + } + for invalid in [ + "2023-02-29", + "2024-2-9", + "", + "2024-01-01T00:00:00Z", + "2024-01-01T00:00", + // Spellings jiff reads but does not write. + "20240229", + "+002024-02-29", + "-0005-03-01", + // Past the wire's range, which is jiff's. + "10000-01-01", + "+010000-01-01", + "-010000-01-01", + ] { + assert_eq!( + date(invalid), + Err(ConversionError::InvalidDate), + "{invalid}" + ); + } + assert_eq!(date_text(Int::I128(i128::MAX)), None); + } + + #[test] + fn a_value_displays_as_text_only_when_every_byte_matches() { + assert!(displays_as(&"2024-02-29", "2024-02-29")); + assert!(displays_as(&"", "")); + assert!(!displays_as(&"2024-02-29", "2024-02-2"), "text too short"); + assert!(!displays_as(&"2024-02-29", "2024-02-290"), "text too long"); + assert!(!displays_as(&"2024-02-29", "2024-02-28"), "a byte differs"); + } + + #[test] + fn timestamps_are_nanosecond_counts_and_refuse_leap_seconds() { + assert_eq!( + timestamp("1970-01-01T00:00:00.123Z"), + Ok(Int::I64(123_000_000)) + ); + assert_eq!( + timestamp("1969-12-31T23:59:59.999999999Z"), + Ok(Int::I64(-1)) + ); + // ADR 0001 section 3: a leap second has no count and is refused. + assert_eq!( + timestamp("2016-12-31T23:59:60.123456789Z"), + Err(ConversionError::InvalidTimestamp) + ); + // Each comes back as the text it went in as, in i128 when i64 is + // too narrow. A negative year has a sign and six digits. + for (text, expected_width) in [ + ("-000005-03-01T12:00:00.000000001Z", "i128"), + ("2262-04-11T23:47:16.854775807Z", "i64"), + ("2262-04-11T23:47:16.854775808Z", "i128"), + // The ends of the wire's range, which is jiff's. + ("-009999-01-02T01:59:59.000000000Z", "i128"), + ("9999-12-30T22:00:00.999999999Z", "i128"), + ] { + let count = timestamp(text).expect("valid"); + assert_eq!(width(count), expected_width, "{text}"); + assert_eq!( + timestamp_text(TimeUnit::Nanos, count).as_deref(), + Some(text) + ); + } + // An offset is applied, the other spellings RFC 3339 allows are + // read, and so is a year with a `+` and six digits, as ISO 8601 + // writes it. + for (text, utc) in [ + ( + "-000005-03-01T12:00:00+01:00", + "-000005-03-01T11:00:00.000000000Z", + ), + ( + "2024-02-29T12:00:00.5-01:30", + "2024-02-29T13:30:00.500000000Z", + ), + ("2024-02-29t12:00:00z", "2024-02-29T12:00:00.000000000Z"), + ( + "2024-02-29 12:00:00-00:00", + "2024-02-29T12:00:00.000000000Z", + ), + ( + "+002024-02-29T12:00:00.1Z", + "2024-02-29T12:00:00.100000000Z", + ), + // The widest offsets RFC 3339 allows. + ( + "2024-02-29T12:00:00+23:59", + "2024-02-28T12:01:00.000000000Z", + ), + ( + "2024-02-29T12:00:00-23:59", + "2024-03-01T11:59:00.000000000Z", + ), + ] { + let count = timestamp(text).expect(text); + assert_eq!(timestamp_text(TimeUnit::Nanos, count).as_deref(), Some(utc)); + } + for invalid in [ + "", + "bad", + "+012000-01-01T00:00:00Z", + "+012000-13-01T00:00:00Z", + "-0005-03-01T12:00:00Z", + "-000005-03-01T12:00:00", + "-000005-03-01", + // Past either end of the wire's range: jiff 1.0.0 would make + // the first an instant before its own minimum. + "-009999-01-02T01:59:58.5Z", + "-009999-01-01T00:00:00Z", + "9999-12-30T22:00:01Z", + "9999-12-31T00:00:00+01:00", + // Spellings jiff reads that are not RFC 3339. + "2024-02-29T12:00Z", + "20240229T120000Z", + "2024-02-29T12:00:00Z[UTC]", + "2024-02-29T12:00:00,5Z", + "2024-02-29T12:00:00+0100", + "2024-02-29T12:00:00+01", + "2024-02-29T12:00:00.Z", + "2024-02-29T12:00:00.1234567891Z", + "2024-02-29X12:00:00Z", + "2024-02-29T12:00:00Zx", + // Values out of range in each field. + "2024-02-30T12:00:00Z", + "2024-02-29T24:00:00Z", + "2024-02-29T12:60:00Z", + "2024-02-29T12:00:61Z", + "2024-02-29T12:00:00+23:60", + // jiff reads an offset of up to 25 hours; RFC 3339 stops at 23. + "2024-02-29T12:00:00+24:00", + "2024-02-29T12:00:00-25:59", + "2024-02-29T12:00:00+26:00", + ] { + assert_eq!( + timestamp(invalid), + Err(ConversionError::InvalidTimestamp), + "{invalid}" + ); + } + } + + /// `timestamp` counts the instant itself, so compare its count with + /// jiff's own for many dates, times, fractions and offsets. The years + /// stay away from the ends of the range, where jiff 1.0.0 miscounts + /// (BurntSushi/jiff#714) and an offset can carry the instant out. + #[test] + fn a_timestamp_count_is_the_one_jiff_counts() { + // A fixed xorshift sequence, so a failure can be reproduced. + let mut state = 0x9E37_79B9_7F4A_7C15_u64; + let mut below = |n: u64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state % n) as i64 + }; + for _ in 0..20_000 { + let year = below(19_981) - 9_990; + let month = below(12) + 1; + let days_in_month = jiff::civil::Date::new(year as i16, month as i8, 1) + .expect("a date in range") + .days_in_month(); + let day = below(days_in_month as u64) + 1; + let year = if (0..=9_999).contains(&year) { + format!("{year:04}") + } else { + format!("{}{:06}", if year < 0 { '-' } else { '+' }, year.abs()) + }; + let (hour, minute, second) = (below(24), below(60), below(60)); + let fraction = match below(10) as usize { + 0 => String::new(), + digits => format!(".{:09}", below(1_000_000_000))[..=digits].to_owned(), + }; + let offset = match below(3) { + 0 => "Z".to_owned(), + sign => format!( + "{}{:02}:{:02}", + if sign == 1 { '+' } else { '-' }, + below(24), + below(60) + ), + }; + let text = format!( + "{year}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}{fraction}{offset}" + ); + let expected = text + .parse::() + .unwrap_or_else(|e| panic!("jiff reads {text}: {e}")) + .as_nanosecond(); + assert_eq!( + timestamp(&text).ok().and_then(|count| count.to_i128()), + Some(expected), + "{text}" + ); + } + } + + #[test] + fn a_js_date_is_its_millisecond_count() { + assert_eq!(date_millis(-1.0), Ok(Int::I64(-1))); + assert_eq!(date_millis(0.0), Ok(Int::I64(0))); + assert_eq!( + date_millis(1_700_000_000_000.0), + Ok(Int::I64(1_700_000_000_000)) + ); + for invalid in [ + f64::NAN, + f64::INFINITY, + f64::NEG_INFINITY, + 0.5, + // Inside `Date`'s range but outside the wire's. + 8_640_000_000_000_000.0, + -8_640_000_000_000_000.0, + ] { + assert_eq!( + date_millis(invalid), + Err(ConversionError::InvalidTimestamp), + "{invalid}" + ); + } + } + + #[test] + fn a_stored_timestamp_is_a_js_date_only_when_it_is_whole_milliseconds() { + assert_eq!( + timestamp_js_millis(TimeUnit::Millis, Int::I64(123)), + Some(123.0) + ); + assert_eq!( + timestamp_js_millis(TimeUnit::Nanos, Int::I64(123_000_000)), + Some(123.0) + ); + assert_eq!( + timestamp_js_millis(TimeUnit::Micros, Int::I64(-1_000)), + Some(-1.0) + ); + // Sub-millisecond precision needs the wrapper. + assert_eq!(timestamp_js_millis(TimeUnit::Nanos, Int::I64(-1)), None); + assert_eq!(timestamp_js_millis(TimeUnit::Micros, Int::I64(1)), None); + // The wire's whole range fits a `Date`: its limits are under + // 4e14 milliseconds either way, inside `Date`'s ±8.64e15. + for limit in [MIN_TIMESTAMP_NANOS, MAX_TIMESTAMP_NANOS] { + let ms = timestamp_js_millis(TimeUnit::Millis, Int::I64((limit / 1_000_000) as i64)) + .expect("whole milliseconds at the bound"); + assert!(ms.abs() <= 8_640_000_000_000_000.0, "{ms}"); + } + // Out of the wire's range entirely. + assert_eq!( + timestamp_js_millis(TimeUnit::Nanos, Int::I128(i128::MAX)), + None + ); + assert_eq!(timestamp_text(TimeUnit::Nanos, Int::I128(i128::MAX)), None); + } + + #[test] + fn decimals_are_exact_and_negative_zero_is_zero() { + for text in ["NaN", "+nan", "-NaN", "inf", "+Infinity", "-Infinity"] { + assert_eq!( + decimal(text), + Err(ConversionError::NonFiniteDecimal), + "{text}" + ); + } + for text in [ + "", + "1e2", + "1_000", + "1.5_0", + ".1", + "1.", + "1.2.3", + " 1", + "1a", + "1.a", + "0.00000000000000000000000000001", + "79228162514264337593543950336", + ] { + assert_eq!( + decimal(text), + Err(ConversionError::InvalidDecimal), + "{text}" + ); + } + assert_eq!(decimal("1.50"), Ok((2, Int::I128(150)))); + assert_eq!(decimal("+1.50"), Ok((2, Int::I128(150)))); + assert_eq!(decimal("-1.50"), Ok((2, Int::I128(-150)))); + // ADR 0001 section 3: a negative zero reads back as zero, scale kept. + assert_eq!(decimal("-0.00"), Ok((2, Int::I128(0)))); + assert_eq!(decimal_text(2, Int::I128(0)).as_deref(), Some("0.00")); + for text in [ + "1.50", + "-79228162514264337593543950335", + "0.0000000000000000000000000001", + ] { + let (scale, mantissa) = decimal(text).expect("valid"); + assert_eq!(decimal_text(scale, mantissa).as_deref(), Some(text)); + } + assert_eq!(decimal_text(29, Int::I128(1)), None); + } + + #[test] + fn uuids_are_sixteen_bytes_in_hyphenated_hex() { + let text = "123e4567-e89b-12d3-a456-426614174000"; + let bytes = uuid(text).expect("valid"); + assert_eq!(bytes[0..4], [0x12, 0x3e, 0x45, 0x67]); + assert_eq!(uuid_text(&bytes).as_deref(), Some(text)); + assert_eq!(uuid(&text.to_uppercase()), Ok(bytes)); + for invalid in [ + "", + "123e4567e89b12d3a456426614174000", + "{123e4567-e89b-12d3-a456-426614174000}", + "123e4567-e89b-12d3-a456-42661417400g", + "123e4567-e89b-12d3-a456-4266141740000", + "123e4567-e89b-12d3-a456-42661417400", + "123e4567-e89b-12d3-a456-4266141740\u{e9}", + ] { + assert_eq!( + uuid(invalid), + Err(ConversionError::InvalidUuid), + "{invalid:?}" + ); + } + assert_eq!(uuid_text(&[0; 15]), None); + } + + #[test] + fn every_error_has_a_stable_code_and_a_message() { + for error in [ + ConversionError::IntegerRange, + ConversionError::InvalidDate, + ConversionError::InvalidTimestamp, + ConversionError::InvalidDecimal, + ConversionError::NonFiniteDecimal, + ConversionError::InvalidUuid, + ] { + assert!(error.code().starts_with("ERR_")); + assert!(!error.to_string().is_empty()); + } + } +} diff --git a/languages/typescript/packages/recipher-js/value-napi/src/wrappers.js b/languages/typescript/packages/recipher-js/value-napi/src/wrappers.js new file mode 100644 index 000000000..17ae061c1 --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/src/wrappers.js @@ -0,0 +1,91 @@ +// The wrapper classes for the scalars JavaScript has no type of its own +// for. Evaluated once per environment by `wrappers.rs`, which keeps the +// classes and recognises instances with `instanceof`. +// +// A wrapper holds its text and nothing else: the text is checked, and the +// scalar built from it, in Rust when the value is encrypted, so one rule +// applies however the instance was made. `value` is an own, enumerable, +// read-only property, so `JSON.stringify`, `structuredClone` and a deep +// equality see it. +// +// Everything the constructor needs from the global object is captured +// here, when the script is evaluated, and the classes, their prototypes and +// every instance are frozen. So a later change to `Object.prototype` or to +// a class (a polluted `writable`, a `Symbol.hasInstance` override) cannot +// make `value` writable, break construction during a decrypt, or turn a +// plain `{ value }` object back into a wrapper. +(function () { + "use strict"; + const defineProperty = Object.defineProperty; + const freeze = Object.freeze; + const getPrototypeOf = Object.getPrototypeOf; + const objectPrototype = Object.prototype; + const apply = Reflect.apply; + // Methods and getters that throw on any receiver but their own type, so a + // call that returns is a brand check a prototype cannot forge. + const getter = (proto, name) => Object.getOwnPropertyDescriptor(proto, name).get; + const brands = freeze([ + Map.prototype.has, + Set.prototype.has, + WeakMap.prototype.has, + WeakSet.prototype.has, + getter(RegExp.prototype, "source"), + getter(ArrayBuffer.prototype, "byteLength"), + getter(SharedArrayBuffer.prototype, "byteLength"), + ]); + const brandCount = brands.length; + const isSlotted = (value) => { + for (let i = 0; i < brandCount; i++) { + try { + apply(brands[i], value, [undefined]); + return true; + } catch { + // Not this collection type. + } + } + return false; + }; + const define = (name) => { + const cls = { + [name]: class { + constructor(value) { + if (typeof value !== "string") { + throw new TypeError(name + " takes a string"); + } + defineProperty(this, "value", { __proto__: null, value, enumerable: true }); + freeze(this); + } + toJSON() { + return this.value; + } + toString() { + return this.value; + } + [Symbol.for("nodejs.util.inspect.custom")]() { + return name + "(" + this.value + ")"; + } + }, + }[name]; + freeze(cls.prototype); + return freeze(cls); + }; + return freeze({ + __proto__: null, + VcDate: define("VcDate"), + VcTimestamp: define("VcTimestamp"), + VcDecimal: define("VcDecimal"), + VcUuid: define("VcUuid"), + // Whether a value is a plain object: prototype `Object.prototype` or + // `null`. Asked through `Object.getPrototypeOf`, not `napi_get_prototype`, + // because the latter reads a Proxy's own map and reports `null` for + // every proxy; this runs the proxy's trap instead, so a proxied Map or + // Date reports its target's prototype and is refused. A Map, Set, + // WeakMap, WeakSet, RegExp or ArrayBuffer is refused whatever its + // prototype: its state is no own property, so given a plain prototype + // it would read as an empty object. + isPlain: (value) => { + const proto = getPrototypeOf(value); + return (proto === null || proto === objectPrototype) && !isSlotted(value); + }, + }); +})() diff --git a/languages/typescript/packages/recipher-js/value-napi/src/wrappers.rs b/languages/typescript/packages/recipher-js/value-napi/src/wrappers.rs new file mode 100644 index 000000000..060de89b0 --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/src/wrappers.rs @@ -0,0 +1,222 @@ +//! The wrapper classes: `VcDate`, `VcTimestamp`, `VcDecimal` and `VcUuid`. +//! +//! JavaScript has no type of its own for a calendar date, a timestamp finer +//! than a millisecond, a decimal or a UUID, so the binding represents each +//! as an instance of a small class holding its text. A class instance is +//! not a plain object, so it can never be confused with data another +//! language wrote as an ordinary one-key object (#382). +//! +//! The classes are defined by the JavaScript in `wrappers.js`, evaluated +//! once per environment. The object it returns (the classes and the +//! plain-object check, frozen) is kept in a registry keyed by the +//! environment and released by an environment cleanup hook, so the +//! addon's own instance data (`napi_set_instance_data`) is never touched. +//! An addon exports the classes with [`Wrappers::exports`] so applications +//! can construct them; the walk recognises instances with `instanceof`, +//! and the build constructs them. + +use std::collections::HashMap; +use std::sync::{LazyLock, Mutex}; + +use napi::bindgen_prelude::{Function, JsObjectValue, JsValue, Object, ObjectRef, Unknown}; +use napi::{Env, Error, Result, Status}; + +/// Which wrapper class a value is an instance of. +/// +/// A logical type JavaScript has no value for needs a new class, so more +/// variants may come. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum Wrapper { + /// `VcDate`: a calendar date as `YYYY-MM-DD`. + Date, + /// `VcTimestamp`: an instant as RFC 3339 text, to the nanosecond. + Timestamp, + /// `VcDecimal`: a fixed-point decimal as text. + Decimal, + /// `VcUuid`: a UUID as hyphenated hexadecimal. + Uuid, +} + +impl Wrapper { + /// Every wrapper class, in the order the walk asks them. + pub const ALL: &'static [Wrapper] = &[ + Wrapper::Date, + Wrapper::Timestamp, + Wrapper::Decimal, + Wrapper::Uuid, + ]; + + /// The class name, as JavaScript sees it. + pub fn class_name(self) -> &'static str { + match self { + Wrapper::Date => "VcDate", + Wrapper::Timestamp => "VcTimestamp", + Wrapper::Decimal => "VcDecimal", + Wrapper::Uuid => "VcUuid", + } + } +} + +const SOURCE: &str = include_str!("wrappers.js"); + +/// The own property a wrapper instance holds its text in. +const VALUE: &str = "value"; + +/// The property of the script's result that answers the plain-object check. +const IS_PLAIN: &str = "isPlain"; + +/// One environment's evaluated `wrappers.js`, by the environment's raw +/// handle. An entry is added on first use and removed by the cleanup hook +/// registered then, so a handle a later environment reuses starts fresh. +/// The reference is dropped without the leak warning: it is released by +/// the hook while the environment is still live. +static REALMS: LazyLock>>> = + LazyLock::new(|| Mutex::new(HashMap::new())); + +fn registry_poisoned() -> Error { + Error::new(Status::GenericFailure, "wrapper class registry is poisoned") +} + +/// The wrapper classes of one environment, for one call: a borrowed view +/// that cannot outlive the environment it was taken from. +pub struct Wrappers<'e> { + classes: Object<'e>, +} + +impl<'e> Wrappers<'e> { + /// The wrapper classes of `env`, defined on first use. + pub fn get(env: &'e Env) -> Result { + let key = env.raw() as usize; + let existing = REALMS + .lock() + .map_err(|_| registry_poisoned())? + .get(&key) + .map(|classes| classes.get_value(env)) + .transpose()?; + let classes = match existing { + Some(classes) => classes, + // The script runs outside the lock: it is self-contained, but + // nothing that runs JavaScript should hold a lock the + // JavaScript thread may take again. + None => { + let classes: Object<'e> = env.run_script(SOURCE)?; + let reference = classes.create_ref::()?; + REALMS + .lock() + .map_err(|_| registry_poisoned())? + .insert(key, reference); + env.add_env_cleanup_hook(key, release_wrappers)?; + classes + } + }; + Ok(Self { classes }) + } + + /// An object holding every class under its name, for an addon to + /// re-export: `VcDate`, `VcTimestamp`, `VcDecimal` and `VcUuid`. + pub fn exports(env: &'e Env) -> Result> { + let wrappers = Self::get(env)?; + let mut exports = Object::new(env)?; + for &wrapper in Wrapper::ALL { + exports.set_named_property(wrapper.class_name(), wrappers.constructor(wrapper)?)?; + } + Ok(exports) + } + + fn constructor(&self, wrapper: Wrapper) -> Result>> { + self.classes.get_named_property(wrapper.class_name()) + } + + /// Which wrapper class `value` is an instance of, if any. + pub fn classify(&self, value: &Unknown<'e>) -> Result> { + for &wrapper in Wrapper::ALL { + if value.instanceof(self.constructor(wrapper)?)? { + return Ok(Some(wrapper)); + } + } + Ok(None) + } + + /// Whether `value` is a plain object: prototype `Object.prototype` or + /// `null` (`Object.create(null)`). A `Map`, `Set`, `WeakMap`, `WeakSet`, + /// `RegExp`, `ArrayBuffer` or `SharedArrayBuffer` is not, whatever its + /// prototype has been set to. + /// + /// Anything else stores its state in internal slots or carries class + /// behaviour that key/value enumeration silently loses: a `Map`'s or + /// `Set`'s contents enumerate as `{}`, a `RegExp` drops its pattern and + /// flags, an `ArrayBuffer` or `DataView` its bytes. Encrypting such a + /// value would destroy the payload with no error at either end, so the + /// walk refuses it instead, unless it is an instance of a wrapper class. + /// The question is put to the `Object.getPrototypeOf` captured when the + /// script was evaluated, which runs a `Proxy`'s trap; `napi_get_prototype` + /// reports `null` for every proxy, which would pass a proxied `Map` as + /// `Object.create(null)`. + /// + /// A trap that throws leaves its exception pending, so the caller hands + /// back the very value thrown, as it would for a getter that throws. + pub fn is_plain(&self, value: Unknown<'e>) -> Result { + let is_plain: Function<'e, Unknown<'e>, bool> = + self.classes.get_named_property(IS_PLAIN)?; + // napi-rs clears the exception a called function throws and keeps + // it inside the error, which a `JsFault` cannot carry, so it is + // thrown again here. + is_plain.call(value).map_err(|error| { + let reason = error.reason.clone(); + match Env::from_raw(self.classes.value().env).throw(error) { + Ok(()) => Error::new(Status::PendingException, reason), + Err(error) => error, + } + }) + } + + /// The text a wrapper instance holds. The class keeps `value` as an + /// own, read-only string, but an instance can be made without the + /// constructor (`Object.create`), so the property is read as an own + /// property and its type checked. + pub fn text(&self, instance: &Object<'e>) -> Result>> { + if !instance.has_own_property(VALUE)? { + return Ok(None); + } + let text = crate::js::get_property_unknown(instance, VALUE)?; + Ok((text.get_type()? == napi::ValueType::String).then_some(text)) + } + + /// A new instance of `wrapper` holding `text`. + pub fn construct(&self, wrapper: Wrapper, text: &str) -> Result> { + self.constructor(wrapper)?.new_instance(text.to_owned()) + } +} + +/// The environment cleanup hook: delete the reference while the +/// environment can still do so, and forget the entry. +/// +/// Only a live environment can run this, so no unit test reaches it; the +/// Worker teardown check in `tests/object-safety.cjs` does. +#[cfg_attr(test, mutants::skip)] +fn release_wrappers(key: usize) { + let Ok(mut realms) = REALMS.lock() else { + return; + }; + if let Some(reference) = realms.remove(&key) { + let env = Env::from_raw(key as napi::sys::napi_env); + // A failure here leaves a reference the environment is about to + // reclaim anyway; there is nobody to report it to. + let _ = reference.unref(&env); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_wrapper_has_the_class_name_javascript_sees() { + let names: Vec<&str> = Wrapper::ALL.iter().map(|w| w.class_name()).collect(); + assert_eq!(names, ["VcDate", "VcTimestamp", "VcDecimal", "VcUuid"]); + for &wrapper in Wrapper::ALL { + assert_eq!(wrapper.class_name(), format!("Vc{wrapper:?}")); + } + } +} diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/addon/.gitignore b/languages/typescript/packages/recipher-js/value-napi/tests/addon/.gitignore new file mode 100644 index 000000000..388c77b5f --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/tests/addon/.gitignore @@ -0,0 +1,2 @@ +/target +/*.node diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.lock b/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.lock new file mode 100644 index 000000000..e03f47127 --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.lock @@ -0,0 +1,1364 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common 0.1.7", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", + "zeroize", +] + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "aws-lc-rs" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" +dependencies = [ + "aws-lc-sys", + "untrusted", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bitvec" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + +[[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 = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +dependencies = [ + "serde", +] + +[[package]] +name = "cc" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", + "zeroize", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common 0.1.7", + "inout", +] + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "convert_case" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1af709f1f33454bf52eadfc8c78b3b9ef9cb26fb54d16dc9cd9a7299f899fd1b" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctor" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d" + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "ctutils" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2376ffd6f96d8a9db59875b4b6b0237d6900b5baf64279714e05493ce64828a" +dependencies = [ + "cmov", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "crypto-common 0.2.2", + "ctutils", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jiff" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cc767b5763de45e810109520123bb2829a653f3a7ed9be40b2bc4f81158f595" +dependencies = [ + "jiff-core", + "jiff-static", + "portable-atomic", + "portable-atomic-util", +] + +[[package]] +name = "jiff-core" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "894f7ac42105f584100691b3bf6e6b92dd12fcfa225f6c397f95c8a94b47b68f" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "955491488dc99b572ea6d67b172dcd98787d00744b1fb44a5689b4e6413695a6" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libloading" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "754ca22de805bb5744484a5b151a9e1a8e837d5dc232c2d7d8c2e3492edc8b60" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "log" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miette" +version = "7.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7" +dependencies = [ + "cfg-if", + "miette-derive", + "unicode-width", +] + +[[package]] +name = "miette-derive" +version = "7.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "mutants" +version = "0.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "add0ac067452ff1aca8c5002111bd6b1c895baee6e45fcbc44e0193aea17be56" + +[[package]] +name = "napi" +version = "3.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "567c62b9c2d0fae123713f766686ad66a2c75b45ba3ee01ed8b06a7e99bc435b" +dependencies = [ + "bitflags", + "ctor", + "futures", + "libc", + "napi-build", + "napi-sys", + "nohash-hasher", + "rustc-hash", +] + +[[package]] +name = "napi-build" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b899b545d3aa6dca985939059f258c5488d34e4ecf39c274e20009748f4b846d" + +[[package]] +name = "napi-derive" +version = "3.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94c8098ed9d61a1bbd019519c637817531b0e24023ef4b5678f2f0cbe24bed9c" +dependencies = [ + "convert_case", + "ctor", + "napi-derive-backend", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "napi-derive-backend" +version = "7.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "314cd6ca42bd978fd8bae84b4137e1322bbf3e83552fca8dbd7d18034188ff3a" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "semver", + "syn 3.0.10", +] + +[[package]] +name = "napi-sys" +version = "3.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d153beb7d5c973f4b9395be8a83054a28968b61188f1dd1a2cc2321af22daea2" +dependencies = [ + "libloading", +] + +[[package]] +name = "nohash-hasher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[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 = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "recipher-value-napi" +version = "0.0.0" +dependencies = [ + "jiff", + "miette", + "mutants", + "napi", + "rust_decimal", + "thiserror", + "vitaminc-aead", + "vitaminc-protected", + "zeroize", +] + +[[package]] +name = "recipher-value-napi-test-addon" +version = "0.0.0" +dependencies = [ + "napi", + "napi-build", + "napi-derive", + "recipher-value-napi", + "vitaminc-aead", + "vitaminc-encrypt", + "vitaminc-protected", +] + +[[package]] +name = "rust_decimal" +version = "1.43.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7653272e75dcac41dc199fbea6f5797633994fafd339943c06c9af16bf29cd3a" +dependencies = [ + "arrayvec", + "borsh", + "bytes", + "num-traits", + "rand 0.8.8", + "rand 0.9.5", + "serde", + "serde_json", + "wasm-bindgen", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[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_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + +[[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 = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[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 = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.16+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88f38f3af8bf71841c67a990f4e2b52143b2d0a1a994c72513ff4c14977fc722" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.4+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bed810ee007d8e7f9cf20b4774e7198142fa27186e0f805871da7f3c39eaf333" +dependencies = [ + "winnow", +] + +[[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.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "untrusted" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "vitaminc-aead" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fcccedca9d80812af295cba43dc2ac388f4fbb0415faa3ebec783d072d014d8" +dependencies = [ + "bytes", + "futures-util", + "jiff", + "rust_decimal", + "serde", + "thiserror", + "vitaminc-aead-derive", + "vitaminc-context", + "vitaminc-protected", + "vitaminc-random", + "zeroize", +] + +[[package]] +name = "vitaminc-aead-derive" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3de85a0ff50572db91a5528b72775f63d57a2b24b8263fb8e728baf6a7731502" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "vitaminc-context" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "431a7fb023688dba855e52b9c4e44c942418dde8ea08a2b115cf6a7f762fa5b9" +dependencies = [ + "mutants", + "vitaminc-protected", +] + +[[package]] +name = "vitaminc-encrypt" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e68d89e2587529db55a10fa59cb11be8a7505b4af473c8a0bec238c803190ec5" +dependencies = [ + "aes-gcm", + "aws-lc-rs", + "vitaminc-aead", + "vitaminc-protected", + "vitaminc-random", + "zeroize", +] + +[[package]] +name = "vitaminc-protected" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2153981f290343dffa8f618277c46a13b5a1e8131b4120760e9a1795ae1cb55b" +dependencies = [ + "bitvec", + "digest", + "libc", + "serde", + "serde_bytes", + "subtle", + "thiserror", + "vitaminc-protected-derive", + "zeroize", +] + +[[package]] +name = "vitaminc-protected-derive" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32eb239bc9aae16ef0320076934f3f592606960d42d0b5fdadafc0298f635221" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "vitaminc-random" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fae7eccb46ddc6f199cf5c934469fd5b199514f42e11579c46882b784ed992c8" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand 0.10.3", + "thiserror", + "vitaminc-protected", + "vitaminc-random-derives", + "zeroize", +] + +[[package]] +name = "vitaminc-random-derives" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e48c940c93c9ddb04a66d81ca42ca574826ddbbeece6a7c87c5d1ab31893e692" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wyz" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" +dependencies = [ + "tap", +] + +[[package]] +name = "zerocopy" +version = "0.8.62" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86502bf56ac7c77571a32e2647bb2a15894565e981fb2a48d7bde2d91c965a9d" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.62" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5457206954b06561e2608c7e19cf58b1926586d999c246eebe4502f7e2039d1a" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.toml b/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.toml new file mode 100644 index 000000000..5f3796b98 --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "recipher-value-napi-test-addon" +version = "0.0.0" +edition = "2021" +publish = false + +[workspace] + +[lib] +crate-type = ["cdylib"] + +[dependencies] +napi = { version = "3", default-features = false, features = ["napi6"] } +napi-derive = "3" +vitaminc-aead = { version = "0.10.0", features = ["rust_decimal"] } +recipher-value-napi = { path = "../.." } +vitaminc-encrypt = "0.10.0" +vitaminc-protected = "0.10.0" + +[build-dependencies] +napi-build = "2" diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/addon/build.rs b/languages/typescript/packages/recipher-js/value-napi/tests/addon/build.rs new file mode 100644 index 000000000..0f1b01002 --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/tests/addon/build.rs @@ -0,0 +1,3 @@ +fn main() { + napi_build::setup(); +} diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/addon/src/lib.rs b/languages/typescript/packages/recipher-js/value-napi/tests/addon/src/lib.rs new file mode 100644 index 000000000..fa8340db1 --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/tests/addon/src/lib.rs @@ -0,0 +1,417 @@ +//! The addon the Node suites load: the binding's walk and build, the +//! ciphertext projection, and real AES-256-GCM through the sink-based +//! `Cipher`, so every row of the ADR 0001 section 6 mapping encrypts and +//! decrypts inside a live Node. + +use napi::bindgen_prelude::{AsyncTask, Buffer, JsObjectValue, Object, Unknown}; +use napi::{Env, Error, Result, Status, Task}; +use napi_derive::napi; +use recipher_value_napi::{JsBuilder, JsCipherText, JsFault, JsRef, Wrappers}; +use vitaminc_aead::seal::Cipher; +use vitaminc_aead::{ + decrypt, decrypt_into, encrypt, to_frame, CipherText, Context, DecryptError, Encrypt, + EncryptError, Float, Frame, Int, Logical, MapSink, Node, PassthroughFrame, Physical, SeqSink, + Sink, TimeUnit, +}; +use vitaminc_encrypt::{Aes256Cipher, Key, LocalCipherText}; +use vitaminc_protected::{Controlled, Protected}; + +/// The wrapper classes, exported so JavaScript can construct them. +#[napi(module_exports)] +fn init(mut exports: Object<'_>, env: Env) -> Result<()> { + let wrappers = Wrappers::exports(&env)?; + for name in ["VcDate", "VcTimestamp", "VcDecimal", "VcUuid"] { + exports.set_named_property(name, wrappers.get_named_property::(name)?)?; + } + Ok(()) +} + +/// Take the environment's instance data for the addon itself, as an addon +/// author may: the binding must not depend on that slot. +#[napi] +pub fn claim_instance_data(env: Env) -> Result<()> { + struct Mine; + env.set_instance_data(Mine, (), |_| {}) +} + +fn fixed_cipher() -> Result { + // Test data, not a secret. + Aes256Cipher::new(&Key::from([42u8; 32])) + .map_err(|_| Error::new(Status::GenericFailure, "cipher")) +} + +/// An encryption failure as the error JavaScript sees. A failure reading +/// the value (a getter threw) is handed back as that error. +fn encrypt_error(error: EncryptError) -> Error { + match error { + EncryptError::Source(source) => JsFault::from_source(&source), + EncryptError::Shape(shape) => Error::new(Status::InvalidArg, format!("encrypt: {shape}")), + EncryptError::Cipher(_) => Error::new(Status::GenericFailure, "encrypt: cipher failed"), + EncryptError::Count(count) => { + Error::new(Status::GenericFailure, format!("encrypt: {count}")) + } + } +} + +fn decrypt_error(error: DecryptError) -> Error { + match error { + DecryptError::Cipher(_) => Error::new(Status::GenericFailure, "decrypt: cipher failed"), + DecryptError::Auth => Error::new(Status::GenericFailure, "decrypt: authentication failed"), + DecryptError::Malformed => { + Error::new(Status::GenericFailure, "decrypt: malformed ciphertext") + } + DecryptError::Sink(sink) => Error::new(Status::InvalidArg, format!("decrypt: {sink}")), + } +} + +type Ct = JsCipherText; + +/// Walk a JavaScript value into a frame. +#[napi] +pub fn encode(value: Unknown<'_>) -> Result { + let frame = JsRef::new(value).to_frame()?; + Ok(Buffer::from(frame.risky_ref().to_vec())) +} + +/// Walk a JavaScript value and drop the frame, to test the walk alone. +#[napi] +pub fn convert(value: Unknown<'_>) -> Result<()> { + Ok(JsRef::new(value).to_frame().map(drop)?) +} + +/// Build a JavaScript value from a frame. +#[napi] +pub fn decode<'e>(env: &'e Env, bytes: Buffer) -> Result> { + let frame = Frame::parse(&bytes).map_err(|_| Error::from_reason("frame decode failed"))?; + Ok(JsBuilder::build(env, frame)?) +} + +/// Parse a frame and write it again from its own walk. +#[napi] +pub fn codec_round_trip(bytes: Buffer) -> Result { + let frame = Frame::parse(&bytes).map_err(|_| Error::from_reason("frame decode failed"))?; + let written = to_frame(frame).map_err(|_| Error::from_reason("frame encode failed"))?; + Ok(Buffer::from(written.risky_ref().to_vec())) +} + +/// Encrypt a JavaScript value, walked in place, under `aad`. +#[napi(ts_return_type = "unknown")] +pub fn encrypt_value(value: Unknown<'_>, aad: String) -> Result { + let cipher = fixed_cipher()?; + let node = encrypt(JsRef::new(value), &cipher, aad.as_str()).map_err(encrypt_error)?; + Ok(JsCipherText(node)) +} + +/// Decrypt a ciphertext into a JavaScript value, built by the sink. +#[napi] +pub fn decrypt_value<'e>( + env: &'e Env, + #[napi(ts_arg_type = "unknown")] ct: Ct, + aad: String, +) -> Result> { + let cipher = fixed_cipher()?; + decrypt_into(&cipher, ct.0, aad.as_str(), JsBuilder::new(env)).map_err(decrypt_error) +} + +/// Decrypt a ciphertext as a Rust `Option` and report whether it +/// is `None`: a JavaScript `null` sealed by the binding reads as `None`. +#[napi] +pub fn decrypts_as_none(#[napi(ts_arg_type = "unknown")] ct: Ct, aad: String) -> Result { + let cipher = fixed_cipher()?; + let value: Option = decrypt(&cipher, ct.0, aad.as_str()).map_err(decrypt_error)?; + Ok(value.is_none()) +} + +/// Encrypt off the JavaScript thread: the value is snapshotted as a frame +/// here, on the JavaScript thread, and the worker seals the frame with no +/// JavaScript access at all. +pub struct EncryptFrame { + frame: Option, + aad: String, +} + +impl Task for EncryptFrame { + type Output = Node; + type JsValue = Ct; + + fn compute(&mut self) -> Result { + let frame = self + .frame + .take() + .ok_or_else(|| Error::from_reason("frame already sealed"))?; + let cipher = fixed_cipher()?; + let parsed = Frame::parse(frame.risky_ref()) + .map_err(|_| Error::from_reason("snapshot is not a frame"))?; + encrypt(parsed, &cipher, self.aad.as_str()).map_err(encrypt_error) + } + + fn resolve(&mut self, _env: Env, output: Self::Output) -> Result { + Ok(JsCipherText(output)) + } +} + +#[napi(ts_return_type = "Promise")] +pub fn encrypt_value_async(value: Unknown<'_>, aad: String) -> Result> { + let frame = JsRef::new(value).to_frame()?; + Ok(AsyncTask::new(EncryptFrame { + frame: Some(frame), + aad, + })) +} + +/// A leaf sealed under the given AAD, for ciphertext nodes built here. +fn sealed_leaf(aad: &str) -> Result { + fixed_cipher()? + .seal( + Protected::new(vec![0x03]), + &Context::from_encoded(aad.as_bytes()), + ) + .map_err(|_| Error::from_reason("seal")) +} + +/// Read a ciphertext node tree into Rust and project it back to JS. +#[napi(ts_return_type = "unknown")] +pub fn ciphertext_round_trip(#[napi(ts_arg_type = "unknown")] ct: Ct) -> Ct { + ct +} + +/// `levels` containers of one `wrap` kind ("array", "object" or +/// "passthrough") around `true`, written as a frame in Rust and built from +/// it, so the build's own depth limit is what applies. +#[napi] +pub fn nested_value<'e>(env: &'e Env, levels: u32, wrap: String) -> Result> { + let frame = to_frame(Nest { + levels: levels as usize, + wrap, + }) + .map_err(|e| Error::from_reason(format!("frame: {e}")))?; + let frame = Frame::parse(frame.risky_ref()).map_err(|_| Error::from_reason("frame"))?; + Ok(JsBuilder::build(env, frame)?) +} + +#[derive(Clone)] +struct Nest { + levels: usize, + wrap: String, +} + +/// Passthrough lends its value, so the nested source walks by reference too. +impl Encrypt for &Nest { + fn visit(self, sink: S) -> std::result::Result { + self.clone().visit(sink) + } +} + +impl Encrypt for Nest { + fn visit(self, sink: S) -> std::result::Result { + if self.levels == 0 { + return sink.scalar(None, Physical::Bool(true)); + } + let inner = Nest { + levels: self.levels - 1, + wrap: self.wrap.clone(), + }; + match self.wrap.as_str() { + "array" => { + let mut seq = sink.seq(Some(1))?; + inner.visit(seq.element()?)?; + seq.end() + } + "object" => { + let mut map = sink.map(Some(1))?; + inner.visit(map.entry("k")?)?; + map.end() + } + _ => sink.passthrough(&inner), + } + } +} + +/// `levels` ciphertext containers of one `wrap` kind ("seq" or "map") +/// around one sealed leaf. +#[napi(ts_return_type = "unknown")] +pub fn nested_ciphertext(levels: u32, wrap: String) -> Result { + let mut node = CipherText::Single(sealed_leaf("nested")?); + for _ in 0..levels { + node = match wrap.as_str() { + "seq" => CipherText::Sequence(vec![node]), + _ => CipherText::Map(vec![("k".into(), node)]), + }; + } + Ok(JsCipherText(node)) +} + +/// `ct_levels` ciphertext sequences around a passthrough node whose payload +/// is `value_levels` arrays around `true`: one tree whose depth spans both. +#[napi(ts_return_type = "unknown")] +pub fn ciphertext_with_payload(ct_levels: u32, value_levels: u32) -> Result { + // Written at the payload's depth, as the encrypt sink writes it, so a + // payload too deep for the frame's own limit is still a frame here and + // the projection's limit is what refuses it. + let payload = vitaminc_aead::to_frame(Nest { + levels: value_levels as usize, + wrap: "array".into(), + }); + let payload = match payload { + Ok(frame) => frame.risky_ref().to_vec(), + // Past the frame writer's bound: hand-write the frame bytes. + Err(_) => { + let mut bytes = Vec::new(); + for _ in 0..value_levels { + bytes.extend_from_slice(&[0xF0, 1, 0, 0, 0]); + } + bytes.push(0x03); + bytes + } + }; + let mut node = CipherText::Passthrough(PassthroughFrame(payload)); + for _ in 0..ct_levels { + node = CipherText::Sequence(vec![node]); + } + Ok(JsCipherText(node)) +} + +/// Read a ciphertext node tree into Rust and drop it, to test reading alone. +#[napi] +pub fn read_ciphertext(#[napi(ts_arg_type = "unknown")] ct: Ct) { + drop(ct); +} + +/// As `read_ciphertext`, for a cipher with no passthrough payload. +#[napi] +pub fn read_unit_ciphertext(#[napi(ts_arg_type = "unknown")] ct: JsCipherText, ()>) { + drop(ct); +} + +/// `levels` ciphertext sequences around a passthrough node with no payload. +#[napi(ts_return_type = "unknown")] +pub fn unit_ciphertext(levels: u32) -> JsCipherText, ()> { + let mut node = CipherText::Passthrough(()); + for _ in 0..levels { + node = CipherText::Sequence(vec![node]); + } + JsCipherText(node) +} + +/// Every scalar kind the binding can build, each from one `Sink::scalar` +/// call, keyed by name: the inventory `tests/kind_inventory.cjs` checks. +#[napi] +pub fn kind_inventory<'e>(env: &'e Env) -> Result> { + let samples: Vec<(&str, Option, Physical<'_>)> = vec![ + ("null", None, Physical::Null), + ("undefined", Some(Logical::Undefined), Physical::Null), + ("bool", None, Physical::Bool(true)), + ("int8", None, Physical::Int(Int::I8(i8::MIN))), + ("uint8", None, Physical::Int(Int::U8(u8::MAX))), + ("int16", None, Physical::Int(Int::I16(i16::MIN))), + ("uint16", None, Physical::Int(Int::U16(u16::MAX))), + ("int32", None, Physical::Int(Int::I32(-32))), + ("uint32", None, Physical::Int(Int::U32(u32::MAX))), + ("int64", None, Physical::Int(Int::I64(i64::MIN))), + ("uint64", None, Physical::Int(Int::U64(u64::MAX))), + ("int128", None, Physical::Int(Int::I128(i128::MIN))), + ("uint128", None, Physical::Int(Int::U128(u128::MAX))), + ("float32", None, Physical::Float(Float::F32(1.5))), + ("float64", None, Physical::Float(Float::F64(2.5))), + ("string", None, Physical::Text("hello")), + ("bytes", None, Physical::Bytes(&[0, 255])), + ("date", Some(Logical::Date), Physical::Int(Int::I32(19782))), + ( + "timestamp", + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I64(0)), + ), + ( + "timestampMillis", + Some(Logical::Timestamp(TimeUnit::Millis)), + Physical::Int(Int::I64(-1)), + ), + ( + "timestampMicros", + Some(Logical::Timestamp(TimeUnit::Micros)), + Physical::Int(Int::I64(1)), + ), + ( + "timestampNanos", + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I64(-1)), + ), + ( + "decimal", + Some(Logical::Decimal { scale: 2 }), + Physical::Int(Int::I128(150)), + ), + ( + "uuid", + Some(Logical::Uuid), + Physical::Bytes(&[ + 0x12, 0x3e, 0x45, 0x67, 0xe8, 0x9b, 0x12, 0xd3, 0xa4, 0x56, 0x42, 0x66, 0x14, 0x17, + 0x40, 0x00, + ]), + ), + ]; + let mut exports = Object::new(env)?; + for (name, ty, value) in samples { + let built = JsBuilder::new(env).scalar(ty, value)?; + exports.set_named_property(name, built)?; + } + // Containers and passthrough, built through the whole walk. + let frame = to_frame(Nest { + levels: 1, + wrap: "array".into(), + }) + .map_err(|_| Error::from_reason("frame"))?; + let array = JsBuilder::build( + env, + Frame::parse(frame.risky_ref()).map_err(|_| Error::from_reason("frame"))?, + )?; + exports.set_named_property("array", array)?; + let frame = to_frame(Nest { + levels: 1, + wrap: "object".into(), + }) + .map_err(|_| Error::from_reason("frame"))?; + let object = JsBuilder::build( + env, + Frame::parse(frame.risky_ref()).map_err(|_| Error::from_reason("frame"))?, + )?; + exports.set_named_property("object", object)?; + let frame = to_frame(Nest { + levels: 1, + wrap: "passthrough".into(), + }) + .map_err(|_| Error::from_reason("frame"))?; + let passthrough = JsBuilder::build( + env, + Frame::parse(frame.risky_ref()).map_err(|_| Error::from_reason("frame"))?, + )?; + exports.set_named_property("passthrough", passthrough)?; + Ok(exports) +} + +/// A known logical type over a value it does not admit, sent straight to +/// the build, which must refuse it rather than show the physical value. A +/// frame never gets this far: `Frame::parse` checks what each type admits. +#[napi] +pub fn build_mismatched<'e>(env: &'e Env, case: String) -> Result> { + let (ty, value) = match case.as_str() { + "date-over-text" => (Logical::Date, Physical::Text("2024-02-29")), + "date-out-of-range" => (Logical::Date, Physical::Int(Int::I128(i128::MAX))), + "timestamp-out-of-range" => ( + Logical::Timestamp(TimeUnit::Nanos), + Physical::Int(Int::I128(i128::MAX)), + ), + "uuid-short" => (Logical::Uuid, Physical::Bytes(&[0; 15])), + "decimal-scale" => (Logical::Decimal { scale: 29 }, Physical::Int(Int::I128(1))), + other => return Err(Error::from_reason(format!("no such case: {other}"))), + }; + Ok(JsBuilder::new(env).scalar(Some(ty), value)?) +} + +/// A frame carrying a logical type this binding does not know, to pin that +/// the build refuses it rather than dropping the type. +#[napi] +pub fn unknown_logical_frame() -> Buffer { + // The `0xF3` envelope: id 200, parameter 0, over an int8 of 7. + Buffer::from(vec![0xF3, 200, 0, 0x0C, 7]) +} diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/encrypt.cjs b/languages/typescript/packages/recipher-js/value-napi/tests/encrypt.cjs new file mode 100644 index 000000000..21ed32bf3 --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/tests/encrypt.cjs @@ -0,0 +1,129 @@ +// Every row of the ADR 0001 section 6 mapping, encrypted and decrypted +// through real AES-256-GCM by the sink-based cipher, with the value walked +// in place on the way in and built by the sink on the way out. Run by +// tests/node.rs with the test addon's path. +const assert = require('node:assert/strict'); +const path = require('node:path'); +const addon = require(path.resolve(process.argv[2])); +const { VcDate, VcTimestamp, VcDecimal, VcUuid } = addon; +const aad = 'section-6'; + +const rows = { + null: null, + undefined: undefined, + boolean: true, + number: 1.5, + 'number (integral)': 42, + bigint: 42n, + 'bigint (wide)': -(1n << 100n), + string: 'Ada Lovelace', + Buffer: Buffer.from([0xde, 0xad, 0xbe, 0xef]), + Uint8Array: new Uint8Array([1, 2, 3]), + Date: new Date(1_700_000_000_123), + 'Date (before the epoch)': new Date(-1), + Array: [1n, 'two', [3.0], { four: null }], + 'plain object': { name: 'Ada', tags: ['math'], born: new VcDate('1815-12-10'), x: undefined }, + 'null prototype': Object.assign(Object.create(null), { k: 'v' }), + VcDate: new VcDate('2024-02-29'), + VcTimestamp: new VcTimestamp('1969-12-31T23:59:59.999999999Z'), + VcDecimal: new VcDecimal('-1.50'), + VcUuid: new VcUuid('123e4567-e89b-12d3-a456-426614174000'), + 'empty array': [], + 'empty object': {}, +}; +for (const [name, value] of Object.entries(rows)) { + const ct = addon.encryptValue(value, aad); + const got = addon.decryptValue(ct, aad); + const want = name === 'Uint8Array' ? Buffer.from(value) : name === 'null prototype' ? { k: 'v' } : value; + assert.deepEqual(got, want, name); + if (name !== 'null' && name !== 'undefined') { + assert.throws(() => addon.decryptValue(ct, 'other'), /decrypt: cipher failed/, name); + } +} +// A Date keeps its exact millisecond count: no trip through seconds and +// nanoseconds, and no rounding. +// The last two are the ends of the wire's range, which is jiff's. +for (const ms of [0, -1, 1, 1_700_000_000_123, -62_135_596_800_000, -377_705_023_201_000, 253_402_207_200_999]) { + const got = addon.decryptValue(addon.encryptValue(new Date(ms), aad), aad); + assert.ok(got instanceof Date, `${ms}`); + assert.equal(got.getTime(), ms); +} +// A Date just past either end is refused. +for (const ms of [-377_705_023_201_001, 253_402_207_201_000]) { + assert.throws(() => addon.encryptValue(new Date(ms), aad), {code: 'ERR_INVALID_TIMESTAMP'}, `${ms}`); +} + +// A getter that throws stops the walk and rejects with that same error. +const boom = new RangeError('the getter threw'); +assert.throws(() => addon.encryptValue({ get a() { throw boom; } }, aad), (e) => e === boom); +assert.throws(() => addon.encryptValue([{ get a() { throw boom; } }], aad), (e) => e === boom); +// A string with an unpaired surrogate is refused, not sealed mutated. +assert.throws(() => addon.encryptValue('\ud800', aad), /unpaired surrogate/); +assert.throws(() => addon.encryptValue({ s: 'a\udc00b' }, aad), /unpaired surrogate/); +assert.throws(() => addon.encryptValue({ '\ud800': 1 }, aad), /unpaired surrogate/); +// A valid surrogate pair is one character and is kept; only an unpaired +// half is refused. The empty string is the smallest read. +for (const s of ['', '😀', 'a😀', '😀b', '\u{10FFFF}', 'José']) { + assert.equal(addon.decryptValue(addon.encryptValue(s, aad), aad), s, JSON.stringify(s)); + assert.deepEqual(addon.decryptValue(addon.encryptValue({ [s]: s }, aad), aad), { [s]: s }); +} +// A Proxy trap that throws is like a getter that throws: the walk stops and +// encryption rejects with that same error. +const trapError = new RangeError('the trap threw'); +for (const handler of [ + { getPrototypeOf() { throw trapError; } }, + { ownKeys() { throw trapError; } }, + { get() { throw trapError; } }, +]) { + const trap = Object.keys(handler)[0]; + assert.throws(() => addon.encryptValue(new Proxy({ a: 1 }, handler), aad), (e) => e === trapError, trap); +} +// A value with no place in the mapping is refused, wherever it sits. +for (const value of [Symbol('s'), () => 1, { f() {} }, [Symbol.iterator]]) { + assert.throws(() => addon.encryptValue(value, aad), /JS type cannot be encrypted/, String(typeof value)); +} + +// Nesting past the limit and the forbidden keys are refused on the way in. +const MAX_DEPTH = 128; +const nest = (levels, wrap, leaf) => { let v = leaf; for (let i = 0; i < levels; i++) v = wrap(v); return v; }; +for (const wrap of [(v) => [v], (v) => ({ k: v })]) { + addon.decryptValue(addon.encryptValue(nest(MAX_DEPTH, wrap, 1n), aad), aad); + assert.throws(() => addon.encryptValue(nest(MAX_DEPTH + 1, wrap, 1n), aad), /nested too deeply/); +} +assert.throws(() => addon.encryptValue(JSON.parse('{"__proto__": 1}'), aad), /not allowed/); +assert.throws(() => addon.encryptValue({ constructor: 1 }, aad), /not allowed/); +assert.throws(() => addon.encryptValue({ prototype: 1 }, aad), /not allowed/); +// And on the way out: a ciphertext map key is attacker-writable. This is +// the ciphertext reader's refusal; the build's own, from a frame, is pinned +// in object-safety.cjs. +{ + const ct = addon.encryptValue({ a: 1n }, aad); + const v = JSON.parse('{"__proto__": null}'); + v.__proto__ = ct.v.a; + assert.throws(() => addon.decryptValue({ t: 'map', v }, aad), /not allowed/); +} + +// Async encryption snapshots the value on the JavaScript thread and seals +// the frame on a worker: the getter runs before the promise exists, and the +// result decrypts like a synchronous one. +(async () => { + let reads = 0; + const value = { get secret() { reads++; return 'hush'; }, n: 7n }; + const promise = addon.encryptValueAsync(value, aad); + assert.equal(reads, 1, 'the value is walked before encryptValueAsync returns'); + const ct = await promise; + assert.equal(reads, 1, 'nothing is read on the worker'); + assert.deepEqual(addon.decryptValue(ct, aad), { secret: 'hush', n: 7n }); + // The walk is synchronous, so a getter that throws does so before there + // is a promise to reject. + assert.throws(() => addon.encryptValueAsync({ get a() { throw boom; } }, aad), (e) => e === boom); + + // A JavaScript null sealed by the binding decrypts into a Rust Option as + // None, and so does undefined, which is null under its logical type. + assert.equal(addon.decryptsAsNone(addon.encryptValue(null, aad), aad), true); + assert.equal(addon.decryptsAsNone(addon.encryptValue(undefined, aad), aad), true); + assert.equal(addon.decryptsAsNone(addon.encryptValue('present', aad), aad), false); + assert.throws(() => addon.decryptsAsNone(addon.encryptValue(7n, aad), aad), /decrypt/); + + console.log(`Encrypt/decrypt: ${Object.keys(rows).length} mapping rows round-tripped`); +})().catch((e) => { console.error(e); process.exit(1); }); diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/kind_inventory.cjs b/languages/typescript/packages/recipher-js/value-napi/tests/kind_inventory.cjs new file mode 100644 index 000000000..4fa03a4d6 --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/tests/kind_inventory.cjs @@ -0,0 +1,45 @@ +// Every scalar kind the build can produce, from one Sink::scalar call each, +// converts to its expected JavaScript value, and containers and passthrough +// build through the whole walk. Run by tests/node.rs with the test addon's +// path. +const assert = require('node:assert/strict'); +const path = require('node:path'); +const addon = require(path.resolve(process.argv[2])); +const { VcDate, VcTimestamp, VcDecimal, VcUuid } = addon; +assert.deepStrictEqual(addon.kindInventory(), { + null: null, + undefined: undefined, + bool: true, + int8: -128n, + uint8: 255n, + int16: -32768n, + uint16: 65535n, + int32: -32n, + uint32: 0xffffffffn, + int64: -(1n << 63n), + uint64: (1n << 64n) - 1n, + int128: -(1n << 127n), + uint128: (1n << 128n) - 1n, + float32: 1.5, + float64: 2.5, + string: 'hello', + bytes: Buffer.from([0, 255]), + date: new VcDate('2024-02-29'), + timestamp: new Date(0), + timestampMillis: new Date(-1), + timestampMicros: new VcTimestamp('1970-01-01T00:00:00.000001000Z'), + timestampNanos: new VcTimestamp('1969-12-31T23:59:59.999999999Z'), + decimal: new VcDecimal('1.50'), + uuid: new VcUuid('123e4567-e89b-12d3-a456-426614174000'), + array: [true], + object: { k: true }, + passthrough: true, +}); +// A logical type this binding does not know has no JavaScript value and is +// refused, rather than shown as its physical value with the type dropped. +assert.throws(() => addon.decode(addon.unknownLogicalFrame()), /not known to this binding/); +// A known logical type over a value it does not admit is refused too. +for (const c of ['date-over-text', 'date-out-of-range', 'timestamp-out-of-range', 'uuid-short', 'decimal-scale']) { + assert.throws(() => addon.buildMismatched(c), /not a value this binding can build/, c); +} +console.log('Every scalar kind converts to its expected JavaScript value'); diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/node.rs b/languages/typescript/packages/recipher-js/value-napi/tests/node.rs new file mode 100644 index 000000000..823cdaed8 --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/tests/node.rs @@ -0,0 +1,86 @@ +//! Exercise live N-API conversions, including in package-scoped mutation runs. + +/// A directory of this run's own under the build directory, removed when +/// the run ends. +struct Stage(std::path::PathBuf); + +impl Stage { + fn new(target: &std::path::Path) -> Self { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("clock after 1970") + .as_nanos(); + let dir = target.join(format!("run-{}-{nanos}", std::process::id())); + std::fs::create_dir_all(&dir).expect("create the run's directory"); + Self(dir) + } +} + +impl Drop for Stage { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +#[test] +fn node_value_conformance() { + use std::{path::Path, process::Command}; + let package = Path::new(env!("CARGO_MANIFEST_DIR")); + let workspace = package.parent().expect("workspace"); + let addon = package.join("tests/addon/Cargo.toml"); + let target = workspace.join("target/napi-test-addon"); + let build = Command::new(env!("CARGO")) + .args(["build", "--locked", "--quiet", "--manifest-path"]) + .arg(addon) + .arg("--target-dir") + .arg(&target) + .output() + .expect("run Cargo for the test addon"); + assert!( + build.status.success(), + "addon build: {}", + String::from_utf8_lossy(&build.stderr) + ); + let library = target.join("debug").join(format!( + "{}recipher_value_napi_test_addon{}", + std::env::consts::DLL_PREFIX, + std::env::consts::DLL_SUFFIX + )); + // The build is shared, and Cargo locks it; the files Node loads are + // staged per run, so a concurrent run cannot rewrite them mid-load. + let stage = Stage::new(&target); + let module = stage.0.join("addon.node"); + std::fs::copy(library, &module).expect("copy Node module"); + let example = include_str!("../README.md") + .split_once("```javascript\n") + .expect("README JavaScript example") + .1 + .split_once("\n```") + .expect("end of README JavaScript example") + .0; + let example_path = stage.0.join("readme-example.cjs"); + std::fs::write(&example_path, example).expect("write README example"); + for suite in [ + "tests/value-conformance.cjs", + "tests/object-safety.cjs", + "tests/kind_inventory.cjs", + "tests/encrypt.cjs", + ] + .map(|suite| package.join(suite)) + .into_iter() + .chain([example_path]) + { + let result = Command::new("node") + .arg(&suite) + .arg(&module) + .output() + .expect("Node.js is required for binding tests"); + assert!( + result.status.success(), + "{}:\n{}\n{}", + suite.display(), + String::from_utf8_lossy(&result.stdout), + String::from_utf8_lossy(&result.stderr) + ); + } +} diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/object-safety.cjs b/languages/typescript/packages/recipher-js/value-napi/tests/object-safety.cjs new file mode 100644 index 000000000..b61c1d4c9 --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/tests/object-safety.cjs @@ -0,0 +1,437 @@ +// Object handling at the N-API boundary: which keys are read, how output +// properties are written, and the ciphertext node projection. Run by +// tests/node.rs with the test addon's path. +const assert = require('node:assert/strict'); +const path = require('node:path'); +const addon = require(path.resolve(process.argv[2])); + +const roundTrip = (value) => addon.decode(addon.encode(value)); + +// Only own, enumerable, string keys are read. +const mixed = { own: 2 }; +Object.defineProperty(mixed, 'hidden', { value: 3, enumerable: false }); +mixed[Symbol('s')] = 4; +assert.deepEqual(Object.keys(roundTrip(mixed)), ['own']); +const bare = Object.create(null); +bare.own = 1; +assert.deepEqual(Object.keys(roundTrip(bare)), ['own']); +// An object with any other prototype is refused rather than read. +assert.throws(() => addon.encode(Object.create({ inherited: 1 }))); + +// A polluted Object.prototype contributes no keys. +Object.prototype.polluted = 'x'; +try { + assert.deepEqual(Object.keys(roundTrip({ a: 1 })), ['a']); +} finally { + delete Object.prototype.polluted; +} + +// An own property explicitly set to undefined round-trips. +const explicit = roundTrip({ x: undefined }); +assert.ok(Object.hasOwn(explicit, 'x')); +assert.equal(explicit.x, undefined); + +// Keys holding NUL, and numeric keys, keep their exact text. +assert.deepEqual(Object.keys(roundTrip({ 'a\0b': 1, 7: 2 })), ['7', 'a\0b']); + +// Output properties are own data properties, defined without running a +// polluted inherited setter. +let captured = 'untouched'; +Object.defineProperty(Object.prototype, 'leak', { + set(v) { captured = v; }, + configurable: true, +}); +try { + const out = roundTrip({ leak: 'secret' }); + assert.equal(captured, 'untouched'); + assert.ok(Object.hasOwn(out, 'leak')); + assert.equal(out.leak, 'secret'); +} finally { + delete Object.prototype.leak; +} + +// Output properties are writable, enumerable and configurable, like ones +// created by assignment. +assert.deepEqual(Object.getOwnPropertyDescriptor(roundTrip({ k: 1 }), 'k'), { + value: 1, writable: true, enumerable: true, configurable: true, +}); + +// Prototype-touching keys are refused, walking a value and building one. +assert.throws(() => addon.encode(JSON.parse('{"__proto__": 1}'))); +assert.throws(() => addon.encode({ constructor: 1 })); +for (const key of ['__proto__', 'constructor', 'prototype']) { + // The frame of `{ [key]: 1n }`: a one-entry map whose key is attacker-written. + const len = Buffer.alloc(4); + len.writeUInt32LE(key.length); + const frame = Buffer.concat([Buffer.from('f101000000', 'hex'), len, Buffer.from(key), Buffer.from('0c01', 'hex')]); + assert.throws(() => addon.decode(frame), /not allowed/, key); +} + +// A Proxy reports its target's prototype, so a proxied Map, Date, array or +// class instance is refused like the target would be, rather than read +// through `napi_get_prototype` (which says `null` for every proxy) as a +// null-prototype object. +assert.throws(() => addon.encode(new Proxy(new Map([['k', 'secret']]), {}))); +assert.throws(() => addon.encode(new Proxy(new Date(5), {}))); +assert.throws(() => addon.encode(new Proxy([1, 2], {}))); +assert.throws(() => addon.encode(new Proxy(new (class { #x = 1 })(), {}))); +assert.deepEqual(roundTrip(new Proxy({ a: 1 }, {})), { a: 1 }); + +// An object whose state is in internal slots is refused whatever its +// prototype says. Given a plain prototype, it would pass as a plain object +// and seal as an empty map. +for (const make of [ + () => new Map([['k', 'secret']]), + () => new Set(['secret']), + () => new WeakMap([[{}, 'secret']]), + () => new WeakSet([{}]), + () => /secret/g, + () => Buffer.from('secret').buffer, + () => new SharedArrayBuffer(8), +]) { + for (const proto of [null, Object.prototype]) { + const collection = Object.setPrototypeOf(make(), proto); + assert.throws(() => addon.encode(collection), /not plain|only plain objects/, String(proto)); + } +} + +// Only a Buffer or a Uint8Array is bytes. Every other view would seal as +// its raw bytes and come back as a Buffer, so it is refused. +assert.deepEqual(roundTrip(new Uint8Array([1, 2, 3])), Buffer.from([1, 2, 3])); +assert.deepEqual(roundTrip(new Uint8Array(new Uint8Array([9, 1, 2]).buffer, 1)), Buffer.from([1, 2])); +for (const view of [ + new Float64Array([1.5]), new Int16Array([-1]), new BigInt64Array([1n]), + new Uint8ClampedArray([1]), new DataView(new ArrayBuffer(2)), +]) { + assert.throws(() => addon.encode(view), /only a Buffer or a Uint8Array/, view.constructor.name); +} + +// The binding keeps the wrapper classes in its own registry, so an addon +// that uses the environment's instance data for itself loses nothing. +addon.claimInstanceData(); +assert.equal(roundTrip(new addon.VcDecimal('2.50')).value, '2.50'); +assert.deepEqual(roundTrip({ k: 'v' }), { k: 'v' }); + +// A wrapper instance is built by its constructor, so it is a real instance. +const date = roundTrip(new addon.VcDate('2026-10-09')); +assert.ok(date instanceof addon.VcDate); +assert.equal(date.value, '2026-10-09'); +// The classes, their prototypes and their instances are frozen, and the +// constructor uses what it captured when the classes were defined, so +// neither prototype pollution nor a later edit of a class can make +// `value` writable, break construction, hide extra state in an instance, +// or turn a plain `{ value }` object back into a wrapper. +assert.ok(Object.isFrozen(addon.VcUuid) && Object.isFrozen(addon.VcUuid.prototype) && Object.isFrozen(date)); +Object.prototype.writable = true; +Object.prototype.get = () => 'polluted'; +try { + const decimal = new addon.VcDecimal('1.50'); + assert.throws(() => { 'use strict'; decimal.value = '999.99'; }, TypeError); + assert.equal(decimal.value, '1.50'); + assert.equal(roundTrip(decimal).value, '1.50'); +} finally { + delete Object.prototype.writable; + delete Object.prototype.get; +} +assert.throws(() => Object.defineProperty(addon.VcUuid, Symbol.hasInstance, { value: () => true }), TypeError); +assert.deepEqual(roundTrip({ value: '123e4567-e89b-12d3-a456-426614174000' }), { value: '123e4567-e89b-12d3-a456-426614174000' }); +assert.throws(() => { 'use strict'; date.extra = 'secret'; }, TypeError); +assert.equal('extra' in date, false); + +// The ciphertext node projection survives a trip through Rust. +const leaf = Buffer.from('a1b2', 'hex'); +const ct = { + t: 'map', + v: { + a: { t: 'ct', v: leaf }, + 'k\0': { t: 'seq', v: [{ t: 'eseq', v: leaf }, { t: 'pt', v: 5n }, { t: 'pt', v: { a: [new addon.VcDecimal('1.50')] } }] }, + e: { t: 'eseq', v: leaf }, + m: { t: 'emap', v: leaf }, + u: { t: 'pt', v: undefined }, + }, +}; +assert.deepEqual(addon.ciphertextRoundTrip(ct), ct); +// The retired absent marker is no node kind: a `None` is a sealed null leaf. +assert.throws(() => addon.ciphertextRoundTrip({ t: 'none', v: leaf }), /malformed ciphertext/); + +// A ciphertext map reads own keys only and writes own properties. +const map = { own: { t: 'ct', v: leaf } }; +map[Symbol('s')] = { t: 'ct', v: leaf }; +Object.prototype.inherited = { t: 'ct', v: leaf }; +Object.defineProperty(Object.prototype, 'own', { + set(v) { captured = v; }, + configurable: true, +}); +try { + const out = addon.ciphertextRoundTrip({ t: 'map', v: map }); + assert.equal(captured, 'untouched'); + assert.deepEqual(Object.keys(out.v), ['own']); +} finally { + delete Object.prototype.own; + delete Object.prototype.inherited; +} +// Its entries object is plain, as a value's is: any other prototype is refused. +assert.throws( + () => addon.ciphertextRoundTrip({ t: 'map', v: Object.create({ inherited: { t: 'ct', v: leaf } }) }), + /malformed ciphertext/, +); +{ + const v = JSON.parse('{"__proto__": {"t": "ct"}}'); + v.__proto__.v = leaf; + assert.throws(() => addon.ciphertextRoundTrip({ t: 'map', v }), /not allowed/); +} + +// Nesting is limited to 128 levels below the root, converting JS to Rust +// and reading a ciphertext tree. +const MAX_DEPTH = 128; +const nest = (levels, wrap, leaf) => { + let v = leaf; + for (let i = 0; i < levels; i++) v = wrap(v); + return v; +}; +for (const wrap of [(v) => [v], (v) => ({ k: v })]) { + addon.convert(nest(MAX_DEPTH, wrap, 1)); + assert.throws(() => addon.convert(nest(MAX_DEPTH + 1, wrap, 1)), /nested too deeply/); +} +for (const wrap of [(v) => ({ t: 'seq', v: [v] }), (v) => ({ t: 'map', v: { k: v } })]) { + const deepest = nest(MAX_DEPTH, wrap, { t: 'ct', v: leaf }); + assert.deepEqual(addon.ciphertextRoundTrip(deepest), deepest); + // Reading alone, so the output limit cannot be what refuses it. + assert.throws( + () => addon.readCiphertext(nest(MAX_DEPTH + 1, wrap, { t: 'ct', v: leaf })), + /nested too deeply/, + ); +} + +// A leap second has no count since the epoch, so it is refused rather than +// shown as a Date (ADR 0001 section 3). +assert.throws(() => addon.encode(new addon.VcTimestamp('2016-12-31T23:59:60Z')), { code: 'ERR_INVALID_TIMESTAMP' }); + +// A passthrough value decodes to its plain JS value, at the root and nested. +assert.equal(addon.decode(Buffer.from('f203', 'hex')), true); +assert.deepEqual(addon.decode(Buffer.from('f0010000' + '00f20a0100000061', 'hex')), ['a']); + +// Building JS from Rust is limited to the same depth. A frame cannot nest +// past it, so a tree that deep fails when it is framed, before any JS is built. +for (const wrap of ['array', 'object', 'passthrough']) { + addon.nestedValue(MAX_DEPTH, wrap); + assert.throws(() => addon.nestedValue(MAX_DEPTH + 1, wrap), /nests deeper than 128 levels/, wrap); +} +assert.equal(nest(MAX_DEPTH, (v) => v[0], addon.nestedValue(MAX_DEPTH, 'array')), true); +for (const wrap of ['seq', 'map']) { + addon.nestedCiphertext(MAX_DEPTH, wrap); + assert.throws(() => addon.nestedCiphertext(MAX_DEPTH + 1, wrap), /nested too deeply/, wrap); +} + +// Array elements are own properties too: a polluted index setter on +// Array.prototype sees nothing, and the result has no hole. +for (const make of [ + () => addon.decode(addon.encode(['secret'])), + () => addon.ciphertextRoundTrip({ t: 'seq', v: [{ t: 'ct', v: leaf }] }).v, +]) { + let stolen = 'untouched'; + Object.defineProperty(Array.prototype, '0', { + set(v) { stolen = v; }, + configurable: true, + }); + try { + const out = make(); + assert.equal(stolen, 'untouched'); + assert.ok(Object.hasOwn(out, 0)); + } finally { + delete Array.prototype[0]; + } +} + +// So are a ciphertext node's `t` and `v`. +for (const key of ['t', 'v']) { + let stolen = 'untouched'; + Object.defineProperty(Object.prototype, key, { + set(v) { stolen = v; }, + configurable: true, + }); + try { + const out = addon.ciphertextRoundTrip({ t: 'ct', v: leaf }); + assert.equal(stolen, 'untouched'); + assert.deepEqual(Object.keys(out), ['t', 'v']); + } finally { + delete Object.prototype[key]; + } +} + +// A key holding an unpaired surrogate is refused, not sealed under U+FFFD +// with its value lost. +assert.throws(() => addon.encode({ '\uD800': 'secret' }), /unpaired surrogate/); +assert.throws( + () => addon.ciphertextRoundTrip({ t: 'map', v: { '\uDC00': { t: 'ct', v: leaf } } }), + /unpaired surrogate/, +); + +// A ciphertext node must be an object. N-API would otherwise read `t` and +// `v` of a primitive from its (here polluted) prototype. +String.prototype.t = 'pt'; +Number.prototype.t = 'pt'; +try { + assert.throws(() => addon.ciphertextRoundTrip('abc'), /malformed ciphertext/); + assert.throws(() => addon.ciphertextRoundTrip({ t: 'map', v: { k: 5 } }), /malformed ciphertext/); + assert.throws(() => addon.ciphertextRoundTrip({ t: 'map', v: 'abc' }), /malformed ciphertext/); +} finally { + delete String.prototype.t; + delete Number.prototype.t; +} + +// A node's `t` and `v` must be its own: a polluted prototype cannot supply +// either. An own `v: undefined` is still accepted (see `u` above). +for (const [key, value] of [['t', 'pt'], ['v', leaf]]) { + Object.prototype[key] = value; + try { + assert.throws(() => addon.readCiphertext(key === 't' ? { v: leaf } : { t: 'ct' }), /malformed ciphertext/); + } finally { + delete Object.prototype[key]; + } +} + +// A passthrough of undefined loses its `v` key through JSON, so a missing +// `v` reads as undefined there, and never from the prototype. +Object.prototype.v = 'injected'; +try { + const out = addon.ciphertextRoundTrip(JSON.parse(JSON.stringify({ t: 'pt', v: undefined }))); + assert.ok(Object.hasOwn(out, 'v')); + assert.equal(out.v, undefined); +} finally { + delete Object.prototype.v; +} + +// Ownership is checked right before each read, so a getter that deletes a +// later property cannot make that read fall through to the prototype. The +// refusal does not name the property: a key is part of the value. +const removedWithoutItsName = (error) => + /removed while it was being read/.test(error.message) && !error.message.includes('secretField'); +Object.prototype.secretField = 'injected'; +Object.prototype.v = leaf; +try { + assert.throws( + () => addon.encode({ get a() { delete this.secretField; return 1; }, secretField: 2 }), + removedWithoutItsName, + ); + assert.throws( + () => addon.readCiphertext({ get t() { delete this.v; return 'ct'; }, v: leaf }), + /malformed ciphertext/, + ); + assert.throws( + () => addon.readCiphertext({ + t: 'map', + v: { + get a() { delete this.secretField; return { t: 'ct', v: leaf }; }, + secretField: { t: 'ct', v: leaf }, + }, + }), + removedWithoutItsName, + ); +} finally { + delete Object.prototype.secretField; + delete Object.prototype.v; +} + +// A ciphertext map's entries are a plain object's own properties. A Map +// has none, so reading one would give an empty map; it is refused instead. +assert.throws( + () => addon.readCiphertext({ t: 'map', v: new Map([['a', { t: 'ct', v: leaf }]]) }), + /malformed ciphertext/, +); +const bareNodes = Object.create(null); +bareNodes.a = { t: 'ct', v: leaf }; +assert.deepEqual(Object.keys(addon.ciphertextRoundTrip({ t: 'map', v: bareNodes }).v), ['a']); +Object.prototype.t = 'pt'; +Object.prototype.v = 'injected'; +try { + assert.throws(() => addon.readCiphertext({}), /malformed ciphertext/); +} finally { + delete Object.prototype.t; + delete Object.prototype.v; +} + +// Sequence elements must be own: a hole cannot be filled by a node on a +// polluted Array.prototype. +Array.prototype[0] = { t: 'ct', v: leaf }; +try { + assert.throws(() => addon.readCiphertext({ t: 'seq', v: new Array(1) }), /malformed ciphertext/); +} finally { + delete Array.prototype[0]; +} + +// A passthrough payload continues the tree's depth count, in both +// directions, as it does in the transport encoding: 60 sequences, the +// passthrough node, then 67 arrays reach exactly 128. +addon.ciphertextWithPayload(60, 67); +assert.throws(() => addon.ciphertextWithPayload(60, 68), /nested too deeply/); +const payloadTree = (arrays) => + nest(60, (v) => ({ t: 'seq', v: [v] }), { t: 'pt', v: nest(arrays, (v) => [v], true) }); +addon.readCiphertext(payloadTree(67)); +assert.throws(() => addon.readCiphertext(payloadTree(68)), /nested too deeply/); + +// With no passthrough payload type, a passthrough node must carry undefined. +addon.readUnitCiphertext({ t: 'pt', v: undefined }); +assert.throws(() => addon.readUnitCiphertext({ t: 'pt', v: 1 }), /malformed ciphertext/); + +// A `()` payload counts like any other: it sits one level below its +// passthrough node, so 127 sequences are the most it allows. +addon.unitCiphertext(127); +assert.throws(() => addon.unitCiphertext(128), /nested too deeply/); +addon.readUnitCiphertext(nest(127, (v) => ({ t: 'seq', v: [v] }), { t: 'pt' })); +assert.throws( + () => addon.readUnitCiphertext(nest(128, (v) => ({ t: 'seq', v: [v] }), { t: 'pt' })), + /nested too deeply/, +); + +// A Rust-built tree far too deep for the stack is refused cleanly: it is +// measured and then dropped without recursing once per level, so neither +// step can overflow the stack and abort Node. +const HUGE = 1_000_000; +for (const wrap of ['array', 'object', 'passthrough']) { + assert.throws(() => addon.nestedValue(HUGE, wrap), /nests deeper than 128 levels/, wrap); +} +for (const wrap of ['seq', 'map']) { + assert.throws(() => addon.nestedCiphertext(HUGE, wrap), /nested too deeply/, wrap); +} +assert.throws(() => addon.ciphertextWithPayload(60, HUGE), /nested too deeply/); + +// A Worker that loads the addon and uses the wrapper classes tears its +// environment down through the registry's cleanup hook; the process must +// outlive it, and the main environment's classes are untouched. +(async () => { + const { Worker } = require('node:worker_threads'); + const script = ` + const addon = require(${JSON.stringify(path.resolve(process.argv[2]))}); + const date = addon.decode(addon.encode(new addon.VcDate('2024-02-29'))); + require('node:worker_threads').parentPort.postMessage(date instanceof addon.VcDate ? date.value : 'not a wrapper'); + `; + const reply = await new Promise((resolve, reject) => { + const worker = new Worker(script, { eval: true }); + worker.on('message', resolve); + worker.on('error', reject); + worker.on('exit', (code) => code === 0 || reject(new Error(`worker exited with ${code}`))); + }); + assert.equal(reply, '2024-02-29'); + assert.equal(roundTrip(new addon.VcDate('2024-02-29')).value, '2024-02-29'); + + // A value the binding refuses is not kept alive by the refusal: once + // nothing in JavaScript holds it, a collection frees it. + require('node:v8').setFlagsFromString('--expose-gc'); + const gc = require('node:vm').runInNewContext('gc'); + const refused = (() => { + const views = [new Float64Array([1.5]), new Int16Array([-1]), new Uint8ClampedArray([1])]; + for (const view of views) { + assert.throws(() => addon.encode(view), /only a Buffer or a Uint8Array/, view.constructor.name); + } + const leaf = { not: 'bytes' }; + assert.throws(() => addon.ciphertextRoundTrip({ t: 'ct', v: leaf })); + return [...views, leaf].map((value) => new WeakRef(value)); + })(); + // A WeakRef keeps its target alive until the current job ends. + await new Promise(setImmediate); + gc(); + for (const [i, ref] of refused.entries()) { + assert.equal(ref.deref(), undefined, `refused value ${i} is still alive`); + } +})().catch((e) => { console.error(e); process.exit(1); }); diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/testdata/value-conformance.json b/languages/typescript/packages/recipher-js/value-napi/tests/testdata/value-conformance.json new file mode 100644 index 000000000..4f14978d1 --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/tests/testdata/value-conformance.json @@ -0,0 +1,812 @@ +{ + "vectors": [ + { + "name": "null", + "kind": "null", + "value": null, + "transport": "00" + }, + { + "name": "undefined", + "kind": "undefined", + "value": null, + "transport": "01", + "go_reencode": "00" + }, + { + "name": "false", + "kind": "bool", + "value": false, + "transport": "02" + }, + { + "name": "true", + "kind": "bool", + "value": true, + "transport": "03" + }, + { + "name": "int8", + "kind": "int8", + "value": "-128", + "transport": "0c80" + }, + { + "name": "uint8", + "kind": "uint8", + "value": "255", + "transport": "0dff" + }, + { + "name": "int16", + "kind": "int16", + "value": "-32768", + "transport": "0e0080" + }, + { + "name": "uint16", + "kind": "uint16", + "value": "65535", + "transport": "0fffff" + }, + { + "name": "int32", + "kind": "int32", + "value": "-2147483648", + "transport": "0400000080" + }, + { + "name": "uint32", + "kind": "uint32", + "value": "4294967295", + "transport": "06ffffffff" + }, + { + "name": "int64", + "kind": "int64", + "value": "-9223372036854775808", + "transport": "050000000000000080" + }, + { + "name": "uint64", + "kind": "uint64", + "value": "18446744073709551615", + "transport": "07ffffffffffffffff" + }, + { + "name": "int128", + "kind": "int128", + "value": "-170141183460469231731687303715884105728", + "transport": "1000000000000000000000000000000080" + }, + { + "name": "uint128", + "kind": "uint128", + "value": "340282366920938463463374607431768211455", + "transport": "11ffffffffffffffffffffffffffffffff" + }, + { + "name": "float32", + "kind": "float32", + "value": 1.5, + "transport": "080000c03f", + "js_reencode": "09000000000000f83f" + }, + { + "name": "float64", + "kind": "float64", + "value": -1.5, + "transport": "09000000000000f8bf" + }, + { + "name": "text", + "kind": "string", + "value": "é", + "transport": "0a02000000c3a9" + }, + { + "name": "text-nul", + "kind": "string", + "value": "a\u0000b", + "transport": "0a03000000610062" + }, + { + "name": "bytes", + "kind": "bytes", + "value": "00ff07", + "transport": "0b0300000000ff07" + }, + { + "name": "date", + "kind": "date", + "value": "2024-02-29", + "transport": "1281460b00" + }, + { + "name": "date-year-zero", + "kind": "date", + "value": "0000-01-01", + "transport": "1293feffff" + }, + { + "name": "date-min", + "kind": "date", + "value": "-009999-01-01", + "transport": "12b844c8ff" + }, + { + "name": "date-max", + "kind": "date", + "value": "9999-12-31", + "transport": "12dbb93700" + }, + { + "name": "timestamp", + "kind": "timestamp", + "value": "1970-01-01T00:00:00.123Z", + "transport": "130000000000000000c0d45407", + "js_date": true, + "js_reencode": "f30301057b00000000000000" + }, + { + "name": "timestamp-nanos", + "kind": "timestamp", + "value": "1969-12-31T23:59:59.999999999Z", + "transport": "13ffffffffffffffffffc99a3b", + "js_date": false + }, + { + "name": "timestamp-negative-year", + "kind": "timestamp", + "value": "-000005-03-01T12:00:00.000000001Z", + "transport": "1340a2727df1ffffff01000000", + "js_date": false + }, + { + "name": "timestamp-min", + "kind": "timestamp", + "value": "-009999-01-02T01:59:59Z", + "transport": "131fb9060fa8ffffff00000000", + "js_date": true, + "js_reencode": "f3030105182143b27aa8feff" + }, + { + "name": "timestamp-max", + "kind": "timestamp", + "value": "9999-12-30T22:00:00.999999999Z", + "transport": "13e0d3f2ff3a000000ffc99a3b", + "js_date": false + }, + { + "name": "decimal", + "kind": "decimal", + "value": "1.50", + "transport": "1400000200960000000000000000000000" + }, + { + "name": "decimal-min", + "kind": "decimal", + "value": "-79228162514264337593543950335", + "transport": "1400000080ffffffffffffffffffffffff" + }, + { + "name": "decimal-small", + "kind": "decimal", + "value": "0.0000000000000000000000000001", + "transport": "1400001c00010000000000000000000000" + }, + { + "name": "empty-array", + "kind": "array", + "value": [], + "transport": "f000000000" + }, + { + "name": "empty-object", + "kind": "object", + "value": {}, + "transport": "f100000000" + }, + { + "name": "uuid", + "kind": "uuid", + "value": "123e4567-e89b-12d3-a456-426614174000", + "transport": "f305000b10000000123e4567e89b12d3a456426614174000", + "rule": "ADR 0001 section 3: Uuid has no shorthand tag, so it travels in the 0xF3 envelope over sixteen bytes" + }, + { + "name": "timestamp-millis", + "kind": "timestamp", + "unit": "millis", + "value": "1970-01-01T00:00:00.123Z", + "transport": "f30301057b00000000000000", + "js_date": true, + "go_reencode": "130000000000000000c0d45407", + "rule": "ADR 0001 section 3: Timestamp(Millis) over an i64 count travels in the 0xF3 envelope; Go reads it as time.Time and writes nanoseconds" + }, + { + "name": "timestamp-seconds", + "kind": "timestamp", + "unit": "seconds", + "value": "1970-01-01T00:00:10Z", + "transport": "f30300050a00000000000000", + "js_date": true, + "go_reencode": "130a0000000000000000000000", + "js_reencode": "f30301051027000000000000", + "rule": "ADR 0001 section 3: Timestamp(Seconds) travels in the 0xF3 envelope; Go writes it back in nanoseconds and Node writes a Date back in milliseconds" + }, + { + "name": "timestamp-micros", + "kind": "timestamp", + "unit": "micros", + "value": "1970-01-01T00:00:00.000001000Z", + "transport": "f30302050100000000000000", + "go_reencode": "130000000000000000e8030000", + "js_reencode": "130000000000000000e8030000", + "rule": "ADR 0001 section 3: Timestamp(Micros) travels in the 0xF3 envelope; Go and Node write it back in nanoseconds" + }, + { + "name": "unknown-logical", + "kind": "unknown", + "value": { + "id": 200, + "param": 9, + "kind": "uint32", + "value": "34" + }, + "transport": "f3c8090622000000", + "js": "refused", + "rule": "ADR 0001 section 3: a logical id this build does not know is read and re-encoded unchanged (Rust, and Go through Tagged); a host builder with no value to carry it in refuses the leaf rather than dropping the annotation, which is what Node does today (#446 tracks a carrier)" + } + ], + "malformed": [ + { + "name": "unknown-tag", + "transport": "ef" + }, + { + "name": "invalid-utf8", + "transport": "0a01000000ff" + }, + { + "name": "trailing", + "transport": "0000" + }, + { + "name": "invalid-date", + "transport": "12ffffff7f" + }, + { + "name": "invalid-timestamp-nanos", + "transport": "13000000000000000000ca9a3b" + }, + { + "name": "invalid-timestamp-range", + "transport": "13ffffffffffffff7f00000000" + }, + { + "name": "date-before-min", + "transport": "12b744c8ff", + "rule": "The wire's range is jiff's (vitaminc#626): dates -009999-01-01 to 9999-12-31, instants -009999-01-02T01:59:59Z to 9999-12-30T22:00:00.999999999Z, and a count outside it is refused" + }, + { + "name": "date-past-max", + "transport": "12dcb93700", + "rule": "The wire's range is jiff's (vitaminc#626): dates -009999-01-01 to 9999-12-31, instants -009999-01-02T01:59:59Z to 9999-12-30T22:00:00.999999999Z, and a count outside it is refused" + }, + { + "name": "timestamp-before-min", + "transport": "131eb9060fa8ffffffffc99a3b", + "rule": "The wire's range is jiff's (vitaminc#626): dates -009999-01-01 to 9999-12-31, instants -009999-01-02T01:59:59Z to 9999-12-30T22:00:00.999999999Z, and a count outside it is refused" + }, + { + "name": "timestamp-past-max", + "transport": "13e1d3f2ff3a00000000000000", + "rule": "The wire's range is jiff's (vitaminc#626): dates -009999-01-01 to 9999-12-31, instants -009999-01-02T01:59:59Z to 9999-12-30T22:00:00.999999999Z, and a count outside it is refused" + }, + { + "name": "timestamp-expanded-year", + "transport": "130001d6b14900000001000000", + "rule": "The wire's range is jiff's (vitaminc#626): dates -009999-01-01 to 9999-12-31, instants -009999-01-02T01:59:59Z to 9999-12-30T22:00:00.999999999Z, and a count outside it is refused; this instant in year 12000 opened before the move from chrono" + }, + { + "name": "decimal-reserved-bits", + "transport": "1401000000000000000000000000000000" + }, + { + "name": "decimal-scale", + "transport": "1400001d00000000000000000000000000" + }, + { + "name": "tag-0c-width-0", + "transport": "0c" + }, + { + "name": "tag-0c-width-2", + "transport": "0c0000" + }, + { + "name": "tag-0d-width-0", + "transport": "0d" + }, + { + "name": "tag-0d-width-2", + "transport": "0d0000" + }, + { + "name": "tag-0e-width-1", + "transport": "0e00" + }, + { + "name": "tag-0e-width-3", + "transport": "0e000000" + }, + { + "name": "tag-0f-width-1", + "transport": "0f00" + }, + { + "name": "tag-0f-width-3", + "transport": "0f000000" + }, + { + "name": "tag-10-width-15", + "transport": "10000000000000000000000000000000" + }, + { + "name": "tag-10-width-17", + "transport": "100000000000000000000000000000000000" + }, + { + "name": "tag-11-width-15", + "transport": "11000000000000000000000000000000" + }, + { + "name": "tag-11-width-17", + "transport": "110000000000000000000000000000000000" + }, + { + "name": "tag-12-width-3", + "transport": "12000000" + }, + { + "name": "tag-12-width-5", + "transport": "120000000000" + }, + { + "name": "tag-13-width-11", + "transport": "130000000000000000000000" + }, + { + "name": "tag-13-width-13", + "transport": "1300000000000000000000000000" + }, + { + "name": "tag-14-width-15", + "transport": "14000000000000000000000000000000" + }, + { + "name": "tag-14-width-17", + "transport": "140000000000000000000000000000000000" + }, + { + "name": "timestamp-leap-second", + "transport": "133b000000000000001597f642", + "rule": "ADR 0001 section 3: a leap second has no count since the epoch in any unit and is refused" + }, + { + "name": "envelope-over-shorthand", + "transport": "f302000400000000", + "rule": "ADR 0001 section 3: there is one encoding per value, so an envelope over a type with a shorthand tag is refused" + }, + { + "name": "envelope-id-zero", + "transport": "f3000000", + "rule": "ADR 0001 section 3: id 0 means no logical type and has no envelope" + }, + { + "name": "envelope-known-id-bad-param", + "transport": "f305010b10000000123e4567e89b12d3a456426614174000", + "rule": "ADR 0001 section 3: a known id with a parameter it cannot take is refused" + }, + { + "name": "envelope-uuid-wrong-length", + "transport": "f305000b03000000010203", + "rule": "ADR 0001 section 3: a Uuid is sixteen bytes" + }, + { + "name": "envelope-nested", + "transport": "f3c800f3c80000", + "rule": "ADR 0001 section 3: the envelope carries a physical scalar, not another envelope" + }, + { + "name": "envelope-unknown-over-undefined", + "transport": "f3c80001", + "rule": "ADR 0001 section 3: the envelope carries a physical scalar; Undefined has a shorthand tag and is refused" + }, + { + "name": "envelope-unknown-over-date", + "transport": "f3c8001200000000", + "rule": "ADR 0001 section 3: the envelope carries a physical scalar; Date has a shorthand tag and is refused" + }, + { + "name": "envelope-unknown-over-array", + "transport": "f3c800f000000000", + "rule": "ADR 0001 section 3: the envelope carries a physical scalar, not a container" + }, + { + "name": "leaf-0xf4", + "transport": "f4", + "rule": "ADR 0001 section 3: 0xF4 is reserved for a longer envelope and is refused" + }, + { + "name": "leaf-0xf4-with-payload", + "transport": "f405000b00000000", + "rule": "ADR 0001 section 3: 0xF4 is reserved for a longer envelope and is refused" + }, + { + "name": "envelope-timestamp-nanos", + "transport": "f30303050000000000000000", + "rule": "ADR 0001 section 3: a logical type with a shorthand tag is written with it, so Timestamp in nanoseconds (unit 3) inside the envelope is refused; units 0 to 2 have no shorthand and are accepted" + }, + { + "name": "envelope-undefined", + "transport": "f3010000", + "rule": "ADR 0001 section 3: Undefined (id 1) has the shorthand tag 0x01 and is refused inside the envelope" + }, + { + "name": "envelope-decimal", + "transport": "f304021000000000000000000000000000000000", + "rule": "ADR 0001 section 3: Decimal (id 4) has the shorthand tag 0x14 and is refused inside the envelope" + }, + { + "name": "envelope-timestamp-bad-unit", + "transport": "f30304050000000000000000", + "rule": "ADR 0001 section 3: Timestamp takes a unit of 0 to 3 as its parameter; 4 is refused" + }, + { + "name": "envelope-timestamp-not-int", + "transport": "f303010a00000000", + "rule": "ADR 0001 section 3: Timestamp admits only an int as its physical value; text is refused" + }, + { + "name": "envelope-timestamp-out-of-range", + "transport": "f30300100000000000000000000000000000ff7f", + "rule": "ADR 0001 section 3: a timestamp count outside the representable range (here an i128 of seconds far past year 9999) is refused" + }, + { + "name": "envelope-uuid-over-text", + "transport": "f305000a1000000030313233343536373839616263646566", + "rule": "ADR 0001 section 3: Uuid admits only sixteen bytes as its physical value; text of that length is refused" + }, + { + "name": "envelope-truncated", + "transport": "f3c8", + "rule": "ADR 0001 section 3: the envelope is id, parameter and a physical scalar; a parameter and payload cut off are refused" + } +, + { + "name": "typed-null-truncated", + "transport": "15", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-no-padding", + "transport": "1506", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-short-padding", + "transport": "15060000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-nonzero-padding", + "transport": "1506000100", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-trailing", + "transport": "150600000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-of-null", + "transport": "1500", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-of-undefined", + "transport": "1501", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-of-bool", + "transport": "1502", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-of-text", + "transport": "150a", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-of-plain-bytes", + "transport": "150b000000000000000000000000000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-nested", + "transport": "151506000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-of-array", + "transport": "15f000000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-envelope-over-shorthand", + "transport": "15f3020004000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-envelope-timestamp-nanos", + "transport": "15f3030310000000000000000000000000000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-envelope-id-zero", + "transport": "15f3000004000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-envelope-undefined", + "transport": "15f3010004000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-envelope-decimal", + "transport": "15f3040004000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-uuid-over-int", + "transport": "15f3050004000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-uuid-with-length", + "transport": "15f305000b10000000000000000000000000000000000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-uuid-with-parameter", + "transport": "15f305010b000000000000000000000000000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-timestamp-over-float", + "transport": "15f303010900000000000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-unknown-over-bytes", + "transport": "15f3c8000b000000000000000000000000000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-unknown-over-bool", + "transport": "15f3c80002", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-inside-envelope", + "transport": "f3c800150c", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + }, + { + "name": "typed-null-0xf4", + "transport": "15f4c80004000000", + "rule": "Typed null (vitaminc#493): every absence has one encoding, so a typed null is TYPED_NULL, the header a value of a fixed-width type starts with, then zero padding to that value's length, and nothing else" + } + ], + "normalized": [ + { + "name": "decimal-negative-zero", + "kind": "decimal", + "value": "-0.00", + "transport": "1400000280000000000000000000000000", + "reencode": "1400000200000000000000000000000000", + "reencode_value": "0.00", + "rule": "ADR 0001 section 3: a decimal negative zero reads back as zero with its scale kept, and zero is always written without the sign" + } +, + { + "name": "typed-null-uint32", + "kind": "null", + "value": null, + "transport": "1506000000", + "reencode": "00", + "reencode_value": null, + "rule": "Typed null (vitaminc#493): an absent value of a fixed-width type, padded to that type's leaf length so its sealed length matches a present value's. A frame is never sealed, so it reads as null and is written back as the plain null" + }, + { + "name": "typed-null-int8", + "kind": "null", + "value": null, + "transport": "150c", + "reencode": "00", + "reencode_value": null, + "rule": "Typed null (vitaminc#493): an absent value of a fixed-width type, padded to that type's leaf length so its sealed length matches a present value's. A frame is never sealed, so it reads as null and is written back as the plain null" + }, + { + "name": "typed-null-float64", + "kind": "null", + "value": null, + "transport": "150900000000000000", + "reencode": "00", + "reencode_value": null, + "rule": "Typed null (vitaminc#493): an absent value of a fixed-width type, padded to that type's leaf length so its sealed length matches a present value's. A frame is never sealed, so it reads as null and is written back as the plain null" + }, + { + "name": "typed-null-date", + "kind": "null", + "value": null, + "transport": "1512000000", + "reencode": "00", + "reencode_value": null, + "rule": "Typed null (vitaminc#493): an absent value of a fixed-width type, padded to that type's leaf length so its sealed length matches a present value's. A frame is never sealed, so it reads as null and is written back as the plain null" + }, + { + "name": "typed-null-timestamp", + "kind": "null", + "value": null, + "transport": "15130000000000000000000000", + "reencode": "00", + "reencode_value": null, + "rule": "Typed null (vitaminc#493): an absent value of a fixed-width type, padded to that type's leaf length so its sealed length matches a present value's. A frame is never sealed, so it reads as null and is written back as the plain null" + }, + { + "name": "typed-null-decimal", + "kind": "null", + "value": null, + "transport": "1514000000000000000000000000000000", + "reencode": "00", + "reencode_value": null, + "rule": "Typed null (vitaminc#493): an absent value of a fixed-width type, padded to that type's leaf length so its sealed length matches a present value's. A frame is never sealed, so it reads as null and is written back as the plain null" + }, + { + "name": "typed-null-timestamp-millis", + "kind": "null", + "value": null, + "transport": "15f303010500000000000000", + "reencode": "00", + "reencode_value": null, + "rule": "Typed null (vitaminc#493): an absent value of a fixed-width type, padded to that type's leaf length so its sealed length matches a present value's. A frame is never sealed, so it reads as null and is written back as the plain null" + }, + { + "name": "typed-null-uuid", + "kind": "null", + "value": null, + "transport": "15f305000b000000000000000000000000000000", + "reencode": "00", + "reencode_value": null, + "rule": "Typed null (vitaminc#493): an absent value of a fixed-width type, padded to that type's leaf length so its sealed length matches a present value's. A frame is never sealed, so it reads as null and is written back as the plain null" + }, + { + "name": "typed-null-unknown-over-float32", + "kind": "null", + "value": null, + "transport": "15f3c80908000000", + "reencode": "00", + "reencode_value": null, + "rule": "Typed null (vitaminc#493): an absent value of a fixed-width type, padded to that type's leaf length so its sealed length matches a present value's. A frame is never sealed, so it reads as null and is written back as the plain null" + } + ], + "ciphertext_malformed": [ + { + "name": "ct-none", + "transport": "0204000000deadbeef", + "rule": "ADR 0001 section 3: CT_NONE (0x02) is retired because a None is a null leaf; it is never written and refused when read" + }, + { + "name": "ct-none-in-sequence", + "transport": "03010000000204000000deadbeef", + "rule": "ADR 0001 section 3: CT_NONE is refused wherever it appears" + } + ], + "leaf_type_aad": { + "rule": "LeafTypeAad (ADR 0001 section 3): the context is PAE(domain, base, kind, id) under the vitaminc-context encoding, where PAE is a u64-le count then each element as a u64-le length and its bytes, and each element is itself a typed piece: a PAE of two parts, the u64-le-prefixed label vitaminc/context/value/v1 and the u64-le-prefixed type label then the payload. The domain is bytes/v1 over vitaminc/aead/leaf-type/v2; the base is utf8/v1 over the base string; the kind is u8-le/v1 over the physical kind byte (null 0, bool 1, int 2, float 3, text 4, bytes 5; a cross-language commitment, never renumbered); the id is u8-le/v1 over the logical id byte, 0 for no logical type. The parameter is not bound: two vectors with the same base, kind and id and different parameters have the same context.", + "vectors": [ + { + "name": "int-date", + "base": "ctx", + "kind": "int", + "logical": { + "id": 2, + "param": 0 + }, + "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310300000000000000637478530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002" + }, + { + "name": "text-no-logical", + "base": "ctx", + "kind": "text", + "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310300000000000000637478530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000004530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000000" + }, + { + "name": "bytes-uuid", + "base": "schema", + "kind": "bytes", + "logical": { + "id": 5, + "param": 0 + }, + "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632570000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310600000000000000736368656d61530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000005530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000005" + }, + { + "name": "int-timestamp-millis", + "base": "events", + "kind": "int", + "logical": { + "id": 3, + "param": 1 + }, + "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632570000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763106000000000000006576656e7473530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000003" + }, + { + "name": "int-decimal-scale-2", + "base": "price", + "kind": "int", + "logical": { + "id": 4, + "param": 2 + }, + "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632560000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763105000000000000007072696365530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000004" + }, + { + "name": "null-undefined", + "base": "ctx", + "kind": "null", + "logical": { + "id": 1, + "param": 0 + }, + "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310300000000000000637478530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000000530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000001" + }, + { + "name": "bool-no-logical", + "base": "ctx", + "kind": "bool", + "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310300000000000000637478530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000001530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000000" + }, + { + "name": "float-no-logical", + "base": "ctx", + "kind": "float", + "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310300000000000000637478530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000003530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000000" + }, + { + "name": "int-decimal-scale-0", + "base": "price", + "kind": "int", + "logical": { + "id": 4, + "param": 0 + }, + "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632560000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763105000000000000007072696365530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000004" + }, + { + "name": "int-timestamp-nanos", + "base": "events", + "kind": "int", + "logical": { + "id": 3, + "param": 3 + }, + "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632570000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763106000000000000006576656e7473530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000003" + } + ] + } +} diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/value-conformance.cjs b/languages/typescript/packages/recipher-js/value-napi/tests/value-conformance.cjs new file mode 100644 index 000000000..ef223aac2 --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/tests/value-conformance.cjs @@ -0,0 +1,135 @@ +// Scalar conversions at the N-API boundary against the shared corpus: every +// vector decodes to the JavaScript value of its kind and encodes back to its +// bytes, and the BigInt width rule and the typed error codes hold. Run by +// tests/node.rs with the test addon's path. +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const addon = require(path.resolve(process.argv[2])); +const corpus = JSON.parse(fs.readFileSync(path.join(__dirname, 'testdata/value-conformance.json'))); +const { VcDate, VcTimestamp, VcDecimal, VcUuid } = addon; +function expected(row, value = row.value) { + if (/^(u?int)/.test(row.kind)) return BigInt(value); + switch (row.kind) { + case 'undefined': return undefined; + case 'bytes': return Buffer.from(value, 'hex'); + case 'date': return new VcDate(value); + case 'decimal': return new VcDecimal(value); + case 'timestamp': return row.js_date ? new Date(value) : new VcTimestamp(value); + case 'uuid': return new VcUuid(value); + default: return value; + } +} +let checked = 0; +for (const row of corpus.vectors) { + const wire = Buffer.from(row.transport, 'hex'); + assert.equal(addon.codecRoundTrip(wire).toString('hex'), row.transport, row.name); + if (row.js === 'refused') { + // A logical type this binding does not know has no JavaScript value. + assert.throws(() => addon.decode(wire), /not known to this binding/, row.name); + continue; + } + const value = addon.decode(wire); + assert.deepEqual(value, expected(row), row.name); + // Encode the decoded value and, independently, the expected one. + for (const input of [value, expected(row)]) { + assert.equal(addon.encode(input).toString('hex'), row.js_reencode ?? row.transport, row.name); + } + checked++; +} +// A normalized vector reads, and writes back as its canonical bytes, from +// the decoded value and from either spelling. +for (const row of corpus.normalized) { + const wire = Buffer.from(row.transport, 'hex'); + assert.equal(addon.codecRoundTrip(wire).toString('hex'), row.reencode, row.name); + const value = addon.decode(wire); + assert.deepEqual(value, expected(row, row.reencode_value), row.name); + for (const input of [value, expected(row), expected(row, row.reencode_value)]) { + assert.equal(addon.encode(input).toString('hex'), row.reencode, row.name); + } +} +for (const row of corpus.malformed) assert.throws(() => addon.decode(Buffer.from(row.transport, 'hex')), undefined, row.name); +const boundaries = [ + [0n,12], [127n,12], [128n,13], [255n,13], [256n,14], [32767n,14], [32768n,15], [65535n,15], [65536n,4], + [(1n<<31n)-1n,4], [1n<<31n,6], [(1n<<32n)-1n,6], [1n<<32n,5], [(1n<<63n)-1n,5], [1n<<63n,7], + [(1n<<64n)-1n,7], [1n<<64n,16], [(1n<<127n)-1n,16], [1n<<127n,17], [(1n<<128n)-1n,17], + [-128n,12], [-129n,14], [-32768n,14], [-32769n,4], [-(1n<<31n),4], [-(1n<<31n)-1n,5], [-(1n<<63n),5], [-(1n<<63n)-1n,16], [-(1n<<127n),16], +]; +for (const [value, tag] of boundaries) { + const wire = addon.encode(value); + assert.equal(wire[0], tag); + assert.equal(addon.decode(wire), value); +} +for (const value of [1n<<128n, -(1n<<127n)-1n]) assert.throws(() => addon.encode(value), {name:'TypeError',code:'ERR_INTEGER_RANGE'}); +for (const decimal of ['NaN','Infinity','-Infinity','+inf']) assert.throws(() => addon.encode(new VcDecimal(decimal)), {name:'TypeError',code:'ERR_NON_FINITE_DECIMAL'}); +assert.throws(() => addon.encode(new VcDecimal('79228162514264337593543950336')), {code:'ERR_INVALID_DECIMAL'}); +assert.throws(() => addon.encode(new VcDate('2023-02-29')), {code:'ERR_INVALID_DATE'}); +assert.throws(() => addon.encode(new VcUuid('not-a-uuid')), {code:'ERR_INVALID_UUID'}); +assert.throws(() => addon.encode(new Date(NaN)), {code:'ERR_INVALID_TIMESTAMP'}); +// A leap second has no count since the epoch and is refused (ADR 0001 section 3). +assert.throws(() => addon.encode(new VcTimestamp('2016-12-31T23:59:60Z')), {code:'ERR_INVALID_TIMESTAMP'}); +assert.deepEqual(addon.decode(addon.encode(new Date(-1))), new Date(-1)); +// A Date is stored as its millisecond count: Timestamp(Millis) over an i64, +// which has no shorthand tag and so travels in the 0xF3 envelope. +assert.equal(addon.encode(new Date(123)).toString('hex'), 'f30301057b00000000000000'); +assert.equal(addon.encode(new Date(-1)).toString('hex'), 'f3030105ffffffffffffffff'); +// A UUID is sixteen bytes under its logical type, in the envelope too. +const uuid = new VcUuid('123e4567-e89b-12d3-a456-426614174000'); +assert.equal(addon.encode(uuid).toString('hex'), 'f305000b10000000123e4567e89b12d3a456426614174000'); +assert.deepEqual(addon.decode(addon.encode(uuid)), uuid); +assert.deepEqual(addon.decode(addon.encode(new VcUuid('123E4567-E89B-12D3-A456-426614174000'))), uuid); +const nested = {items:[1n, new VcDate('2024-02-29'), new VcDecimal('1.50'), new Date(0), uuid]}; +assert.deepEqual(addon.decode(addon.encode(nested)), nested); +assert.throws(() => addon.encode(new Map([['a',1]]))); +assert.throws(() => addon.encode([,1])); +// The reported length is not trusted: the walk refuses the first hole +// without reserving room for 2^32 - 1 elements. +const maximumSparse = new Array(2 ** 32 - 1); +assert.throws(() => addon.encode(maximumSparse), /sparse arrays are not supported/); +assert.throws(() => addon.encryptValue(maximumSparse, 'aad'), /sparse arrays are not supported/); +assert.throws(() => addon.encode('\ud800')); +// A wrapper takes a string and nothing else; the text itself is checked +// when the value is encrypted, so one rule applies however it was made. +for (const Wrapper of [VcDate, VcTimestamp, VcDecimal, VcUuid]) { + for (const payload of [new Date(0), {y: 2024}, 1700000000000, null, 1n, 1.5, undefined]) { + assert.throws(() => new Wrapper(payload), {name: 'TypeError'}, Wrapper.name); + } +} +for (const [Wrapper, code] of [[VcDate, 'ERR_INVALID_DATE'], [VcTimestamp, 'ERR_INVALID_TIMESTAMP'], [VcDecimal, 'ERR_INVALID_DECIMAL'], [VcUuid, 'ERR_INVALID_UUID']]) { + // An instance made without the constructor has no text. + assert.throws(() => addon.encode(Object.create(Wrapper.prototype)), {name: 'TypeError', code}, Wrapper.name); + const forged = Object.create(Wrapper.prototype); + forged.value = 42; + assert.throws(() => addon.encode(forged), {name: 'TypeError', code}, Wrapper.name); +} +// Timestamps finer than a millisecond in a negative year (a sign and six +// digits, as JavaScript writes it) and at the end of the wire's range, +// which is jiff's, decrypt as wrappers and encrypt again unchanged. +for (const timestamp of ['-000005-03-01T12:00:00.000000001Z', '-009999-01-02T01:59:59.000000001Z', '9999-12-30T22:00:00.999999999Z']) { + assert.deepEqual(addon.decode(addon.encode(new VcTimestamp(timestamp))), new VcTimestamp(timestamp)); +} +// Past the range, a value is refused, whichever way it is given. +assert.throws(() => addon.encode(new VcTimestamp('+012000-01-01T00:00:00.000000001Z')), {code:'ERR_INVALID_TIMESTAMP'}); +assert.throws(() => addon.encode(new VcTimestamp('9999-12-30T22:00:01Z')), {code:'ERR_INVALID_TIMESTAMP'}); +assert.throws(() => addon.encode(new Date('+012000-01-01T00:00:00Z')), {code:'ERR_INVALID_TIMESTAMP'}); +assert.throws(() => addon.encode(new VcDate('+010000-01-01')), {code:'ERR_INVALID_DATE'}); +assert.deepEqual(addon.decode(addon.encode(new Date('-009999-01-02T01:59:59Z'))), new Date('-009999-01-02T01:59:59Z')); +// A whole-millisecond timestamp written by another binding is a Date here; +// a finer one is a VcTimestamp, so no precision is discarded. +assert.deepEqual(addon.decode(Buffer.from('130000000000000000c0d45407', 'hex')), new Date(123)); +assert.deepEqual(addon.decode(Buffer.from('13ffffffffffffffffffc99a3b', 'hex')), new VcTimestamp('1969-12-31T23:59:59.999999999Z')); +// A one-key object is ordinary data, whichever language wrote it (#382): +// only a wrapper instance is a wrapper. +for (const ordinary of [{date: '2024-01-01'}, {date: 'tomorrow'}, {timestamp: 1}, {decimal: '1.50'}, {date: 'not a wrapper', extra: true}]) { + assert.deepEqual(addon.decode(addon.encode(ordinary)), ordinary); +} +// The wrappers hold their text as an own, read-only, enumerable `value`, +// and serialize as that text. +const date = new VcDate('2024-02-29'); +assert.equal(date.value, '2024-02-29'); +assert.equal(JSON.stringify({date}), '{"date":"2024-02-29"}'); +assert.equal(String(date), '2024-02-29'); +assert.deepEqual(Object.keys(date), ['value']); +assert.throws(() => { 'use strict'; date.value = 'x'; }, {name: 'TypeError'}); +assert.deepEqual(structuredClone(date), {value: '2024-02-29'}); +console.log(`Node conformance: ${checked} values, ${corpus.malformed.length} refusals, BigInt boundaries passed`); diff --git a/scripts/__tests__/cargo-publish-opt-out.test.mjs b/scripts/__tests__/cargo-publish-opt-out.test.mjs index 154cb1207..adb92725b 100644 --- a/scripts/__tests__/cargo-publish-opt-out.test.mjs +++ b/scripts/__tests__/cargo-publish-opt-out.test.mjs @@ -52,6 +52,12 @@ const WORKSPACES = [ publishable: new Set(), expects: 'crates/protect-ffi', }, + { + // The Rust half of `@cipherstash/recipher`. Nothing in it is published. + root: 'languages/typescript/packages/recipher-js', + publishable: new Set(), + expects: 'value-napi', + }, { // The root workspace. The stack-* crates' release-plz step publishes // exactly these six: stack-auth and stack-profile, and stack-kms, @@ -77,6 +83,7 @@ const WORKSPACES = [ 'packages/stack-encrypt/fuzz', 'languages/golang/encrypt/guest', 'languages/golang/auth/guest', + 'languages/typescript/packages/recipher-js/value-napi/tests/addon', ].map((root) => ({ root, publishable: new Set(), expects: '.' })), ] diff --git a/scripts/__tests__/recipher-js-lock-parity.test.mjs b/scripts/__tests__/recipher-js-lock-parity.test.mjs new file mode 100644 index 000000000..ff5f53e58 --- /dev/null +++ b/scripts/__tests__/recipher-js-lock-parity.test.mjs @@ -0,0 +1,78 @@ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' +import { REPO_ROOT } from './lib/repo-root.mjs' + +/** + * The value bridge's test addon must resolve the same napi and vitaminc + * crates as the recipher-js workspace. + * + * The bridge's Node suites run against the test addon + * (`value-napi/tests/addon`), a Cargo workspace of its own with its own + * Cargo.lock. The bridge ships in the recipher-js workspace, against the + * versions that workspace's Cargo.lock resolves. If the two resolve + * different versions, the suites test a napi or a vitaminc the shipped + * addon does not run. + * + * Every napi and vitaminc crate both locks name is compared, by version, + * source and checksum, so a crate either workspace adds later is covered + * from the day it lands. + * + * Node builtins only: no cargo on `pnpm run test:scripts` (see AGENTS.md). + */ + +const RECIPHER = 'languages/typescript/packages/recipher-js' +const WORKSPACE_LOCK = `${RECIPHER}/Cargo.lock` +const ADDON_LOCK = `${RECIPHER}/value-napi/tests/addon/Cargo.lock` + +/** The crates the two workspaces must agree on. */ +const SHARED = /^(napi|vitaminc)(-|$)/ + +/** + * Every package a `Cargo.lock` records whose name matches `SHARED`, keyed by + * name, each as its sorted list of version, source and checksum. + */ +function sharedPackages(source) { + const field = (block, key) => + new RegExp(`^${key} = "([^"]*)"$`, 'm').exec(block)?.[1] ?? null + const packages = new Map() + for (const block of source.split(/^\[\[package\]\]$/m).slice(1)) { + const name = field(block, 'name') + if (!name || !SHARED.test(name)) continue + const entries = packages.get(name) ?? [] + entries.push({ + version: field(block, 'version'), + source: field(block, 'source'), + checksum: field(block, 'checksum'), + }) + entries.sort((a, b) => a.version.localeCompare(b.version)) + packages.set(name, entries) + } + return packages +} + +const read = (file) => readFileSync(join(REPO_ROOT, file), 'utf8') + +describe('napi and vitaminc parity between recipher-js and the test addon', () => { + const workspace = sharedPackages(read(WORKSPACE_LOCK)) + const addon = sharedPackages(read(ADDON_LOCK)) + const both = [...workspace.keys()].filter((name) => addon.has(name)).sort() + + it('finds the crates it means to compare', () => { + // The floor: a lock that stopped naming them would make the comparison + // below vacuous. + expect(both).toContain('napi') + expect(both).toContain('vitaminc-aead') + }) + + it.each(both)('resolves the same %s in both locks', (name) => { + expect( + addon.get(name), + `${ADDON_LOCK} resolves ${name} ${JSON.stringify(addon.get(name))}, ` + + `${WORKSPACE_LOCK} resolves ${JSON.stringify(workspace.get(name))}: ` + + 'the Node suites test a crate the shipped addon does not run. Move ' + + 'the test addon to match with `cargo update -p --precise ' + + ' --manifest-path value-napi/tests/addon/Cargo.toml`.', + ).toEqual(workspace.get(name)) + }) +})