diff --git a/AGENTS.md b/AGENTS.md index d695507f1..116fd54ef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -93,7 +93,7 @@ Every npm package except EQL lives under `languages/typescript/`: packages in `l - `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 AEAD crates and the three node binding crates below. See "Working on the Rust crates". - `packages/vitaminc-aead`, `packages/recipher-frame`, `packages/vitaminc-aead-derive`: vitaminc's AEAD crates, imported from `cipherstash/vitaminc` with their history at the code of their crates.io 0.10.0 release (`docs/plans/2026-11-14-move-vitaminc-aead-into-the-stack.md`). They define the value types Stack Encrypt seals, the transport frame and storage profile (`recipher-frame`, whose storage corpus is `testdata/storage-v1.json`), and the derive macros. `vitaminc-aead` and `vitaminc-aead-derive` keep their crates.io names, because vitaminc crates that stay on crates.io depend on `vitaminc-aead`; the frame crate was `vitaminc-aead-frame` and is now `recipher-frame`, since only crates here depend on it. All three keep the MIT licence, are members of the root workspace, and are `publish = false` with `release = false` in `release-plz.toml`: crates.io's 0.10.0 was published from vitaminc, and they publish from here only before the next `stack-encrypt` release. Every Cargo workspace that resolves `vitaminc-aead` carries a `[patch.crates-io]` table pointing at these copies (see "Working on the Rust crates"). The cross-language value conformance corpus their tests read is `conformance/vitaminc-aead/value-conformance.json`. vitaminc's checks on them run here: the storage corpus append-only check (`storage-corpus.yml`), the Kani proofs of the storage reader (`kani.yml`), `cargo deny` and `cargo vet` over their dependency graph only (`supply-chain-vitaminc-aead.yml`, config in `supply-chain/vitaminc-aead/`; the rest of the workspace is #1842), and mutation testing (`mutants.yml`). 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`: `@cipherstash/recipher`, the TypeScript SDK on the Stack Encrypt engine (design: `docs/plans/2026-11-22-recipher-typescript-sdk.md`). **Private and unpublished**: it has no platform packages and no release job yet, so it must stay `"private": true` (a public manifest would be published by `changeset publish` on merge) and takes no changeset. Its Rust is **two crates** in 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. The two crates: `crate/` (crate `recipher-js`, napi-rs 3), which defines the `Cipher`, `Keyset` and `Ciphertext` classes the package exports, runs every operation through the engine, and reads and builds JavaScript values only through the value bridge beside it, `value-napi/` (crate `recipher-value-napi`, a copy of vitaminc's `vitaminc-aead-napi` 0.10.0, unpublished, with a detached test addon workspace of its own at `value-napi/tests/addon` and vitaminc's value conformance corpus at `value-napi/tests/testdata`; Biome does not check that directory). A test fails if it links `eql-bindings` or reaches the engine's `test-support` with its default features. `@napi-rs/cli` v3 builds it (`build:debug`, `build:native`) and writes its generated TypeScript declarations to the committed `native.d.ts`; CI fails when the build changes that file. Each native method returns the package's `Result` itself, and its public signature is written in Rust (napi-rs's `ts_type`, `ts_args_type` and `ts_return_type` attributes, with `native-header.d.ts` as the generated file's header), so `native.d.ts` is the public type: never add a TypeScript wrapper or hand-written interface over a native class. The TypeScript (`src/`) holds only `Result`, `RecipherError`, the loader (`src/binding.ts`, which hands the addon the `Ok`, `Err` and `RecipherError` classes) and stand-in classes for a build that did not load. A method called without its object throws a `TypeError` (#1801); every other call returns or resolves to a `Result`. Its `build` (tsup) and `test` (the suites in `__tests__/unit` and `tsc` over `src`, the tests and `type-tests`) never run cargo; `build:debug` (the addon with the deterministic test cipher behind `@cipherstash/recipher/testing`), `build:native`, `test:addon` (the suites that load `recipher.node`) and `test:cargo` do. `.github/workflows/tests-recipher-js.yml` runs all four, and fmt and clippy over the value bridge's test addon by its manifest: `tests.yml`'s live jobs skip a change that touches only this package, so apart from that file's ungated lint and repo checks it is the only workflow such a change runs. 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/typescript/packages/recipher-js`: `@cipherstash/recipher`, the TypeScript SDK on the Stack Encrypt engine (design: `docs/plans/2026-11-22-recipher-typescript-sdk.md`). **Private and unpublished**: it has no platform packages and no release job yet, so it must stay `"private": true` (a public manifest would be published by `changeset publish` on merge) and takes no changeset. Its Rust is **two crates** in 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. The two crates: `crate/` (crate `recipher-js`, napi-rs 3), which defines the `Cipher`, `Keyset`, `Ciphertext`, and `Json` classes the package exports, runs every operation through the engine, and reads and builds JavaScript values only through the value bridge beside it, `value-napi/` (crate `recipher-value-napi`, a copy of vitaminc's `vitaminc-aead-napi` 0.10.0, unpublished, with a detached test addon workspace of its own at `value-napi/tests/addon` and vitaminc's value conformance corpus at `value-napi/tests/testdata`; Biome does not check that directory). The bridge converts JSON documents too. `JsRef::to_json` writes a JavaScript value as a document's JSON text, with the JavaScript number rules. `JsBuilder::build_json` builds a decrypted document. The addon's `json.rs` contains only the `Json` class, and passes the text to the engine's `JsonPlaintext`. A test fails if it links `eql-bindings` or reaches the engine's `test-support` with its default features. `@napi-rs/cli` v3 builds it (`build:debug`, `build:native`) and writes its generated TypeScript declarations to the committed `native.d.ts`; CI fails when the build changes that file. Each native method returns the package's `Result` itself, and its public signature is written in Rust (napi-rs's `ts_type`, `ts_args_type` and `ts_return_type` attributes, with `native-header.d.ts` as the generated file's header), so `native.d.ts` is the public type: never add a TypeScript wrapper or hand-written interface over a native class. The TypeScript (`src/`) contains only `Result`, `RecipherError`, the loader, stand-ins for a build that did not load, and the types that the generated signatures name. The loader is `src/binding.ts`. The loader gives the addon the `Ok`, `Err`, and `RecipherError` classes. The types are in `src/kinds.ts` and `src/value-types.ts`. `native.d.ts` imports those types, so a module that `native.d.ts` imports from must never load the addon. If one did, the declarations would import themselves. The declaration build of tsup would then fail. Two kinds of call throw: a method called without its object (#1801), and `new` on a class whose type has no constructor (`Cipher`, `Keyset`, `Ciphertext`, and the wrapper classes, which an application makes with `RcDate.from(text)` and the like, each returning a `Result`). Every other call returns or resolves to a `Result`. Its `build` (tsup) and `test` (the suites in `__tests__/unit` and `tsc` over `src`, the tests and `type-tests`) never run cargo; `build:debug` (the addon with the deterministic test cipher behind `@cipherstash/recipher/testing`), `build:native`, `test:addon` (the suites that load `recipher.node`) and `test:cargo` do. `.github/workflows/tests-recipher-js.yml` runs all four, and fmt and clippy over the value bridge's test addon by its manifest: `tests.yml`'s live jobs skip a change that touches only this package, so apart from that file's ungated lint and repo checks it is the only workflow such a change runs. 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, the `record` wire model, and `wasmtestrun`, the wazero runner that `wasm:auth-guest:test` runs the auth guest's wasm32 tests under). 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. diff --git a/conformance/vitaminc-aead/README.md b/conformance/vitaminc-aead/README.md index 0da8d0d3a..8733a66cf 100644 --- a/conformance/vitaminc-aead/README.md +++ b/conformance/vitaminc-aead/README.md @@ -63,11 +63,11 @@ than skipping the row: - `js_reencode`: Node has two projections. A Float32 becomes a Number and re-encodes as Float64. A timestamp that is a whole number of milliseconds - is read as a `Date` and re-encodes as the `Timestamp(Millis)` envelope; a - finer one is read as a `VcTimestamp` and re-encodes in the nanosecond - shorthand. As for Go, this is safe because `LeafTypeAad` binds the kind and - the logical id but not the unit, and the equality terms put every unit in - one timestamp domain. + is read as a `Date`, and re-encodes as the `Timestamp(Millis)` envelope. A + finer timestamp is read as an `RcTimestamp`, and re-encodes in the + nanosecond shorthand. As for Go, the timestamp projection is safe for two + reasons. `LeafTypeAad` binds the kind and the logical id, but not the + unit. The equality terms put every unit in one timestamp domain. - `go_reencode`: Go has two projections. `undefined` becomes nil and re-encodes as null. A timestamp in the envelope (seconds, milliseconds or microseconds) is read as a `time.Time` and re-encodes in the nanosecond diff --git a/languages/typescript/packages/recipher-js/Cargo.lock b/languages/typescript/packages/recipher-js/Cargo.lock index c368c643d..eb3a9efb8 100644 --- a/languages/typescript/packages/recipher-js/Cargo.lock +++ b/languages/typescript/packages/recipher-js/Cargo.lock @@ -2498,16 +2498,20 @@ dependencies = [ name = "recipher-js" version = "0.0.0" dependencies = [ + "jiff", "miette", "napi", "napi-build", "napi-derive", "recipher-value-napi", + "rust_decimal", + "serde", "serde_json", "stack-auth", "stack-encrypt", "thiserror 1.0.69", "tokio", + "uuid", "vitaminc-aead 0.10.0", "vitaminc-protected 0.10.0", ] @@ -2521,6 +2525,8 @@ dependencies = [ "mutants", "napi", "rust_decimal", + "serde", + "serde_json", "thiserror 2.0.21", "vitaminc-aead 0.10.0", "vitaminc-protected 0.10.0", diff --git a/languages/typescript/packages/recipher-js/README.md b/languages/typescript/packages/recipher-js/README.md index 441535743..0c2a0367e 100644 --- a/languages/typescript/packages/recipher-js/README.md +++ b/languages/typescript/packages/recipher-js/README.md @@ -33,6 +33,7 @@ const stored = sealed.value.toBytes() // a Uint8Array to keep const opened = await cipher.decrypt(sealed.value) ``` +- `encrypt` returns a `Ciphertext`. A ciphertext is one encrypted value. - Encrypting needs a keyset. Decrypting does not. - `cipher.decrypt` decrypts a value from any of the cipher's keysets. `keyset.decrypt` refuses a value from another keyset. @@ -43,7 +44,215 @@ const opened = await cipher.decrypt(sealed.value) This package decrypts what Rust encrypted. - You cannot make a `Cipher`, a `Keyset`, or a `Ciphertext` with a constructor. Get a cipher from `Cipher.create()`, a keyset from `cipher.defaultKeyset()`, and a ciphertext from `encrypt` or `Ciphertext.fromBytes`. -- This build encrypts a `string` only. + +## Values + +A value's type decides how it is encrypted. +The value bridge defines the mapping. +The value bridge is the `recipher-value-napi` crate, in `value-napi/`. +The value bridge converts JavaScript values in both directions: + +| Value | Encrypted as | Decrypts as | +|---|---|---| +| `string` | text | `string` | +| `boolean` | a boolean | `boolean` | +| `number` | a 64-bit float | `number` | +| `bigint` | an integer, at the narrowest width that fits it | `bigint` | +| `Uint8Array`, `Buffer` | bytes | `Uint8Array` | +| `Date` | a timestamp | `Date` | +| an `RcTimestamp`, from `RcTimestamp.from('2026-11-23T01:02:03.000000001Z')` | a timestamp, in nanoseconds | `Date` when it is whole milliseconds, else `RcTimestamp` | +| an `RcDate`, from `RcDate.from('2026-11-23')` | a calendar date | `RcDate` | +| an `RcDecimal`, from `RcDecimal.from('1.50')` | a decimal, with its scale | `RcDecimal` | +| `null` | refused: see [A declared kind](#a-declared-kind) | `null`, for a null stored another way, read with no kind or with `nullable(..)` | +| `json(value)` | a JSON document, as its JSON text | the document, from the `Ciphertext` that `encrypt` returned or one read with `kinds.json` | + +- `RcTimestamp`, `RcDate`, `RcDecimal`, and `RcUuid` are wrapper classes. + A wrapper class represents a type that JavaScript does not have. + Make an instance with the class's static `from`. + `from` takes the value as text, and returns a `Result`. + `from` checks the text with the rule that `encrypt` uses, so an instance that exists is always valid. + Text that is not a value of the class, or an argument that is not a string, is an `Err`. + The code is the value bridge's, such as `ERR_INVALID_DATE`. + + ```ts + import { RcDate } from '@cipherstash/recipher' + + const born = RcDate.from('1815-12-10') + if (born.isErr()) { + return born // ERR_INVALID_DATE for text that is not a date + } + const sealed = await keyset.encrypt(born.value) + ``` +- Integers are a `bigint`. + A `number` is a float. + The `number` `5` does not equal the integer `5n`. +- A ciphertext contains one value, and `null` is the absence of a value. + So `encrypt` refuses a `null` with no kind, and an array that contains one. + A stored null still decrypts as `null`: one in an older ciphertext, or one that Rust's `encrypt_tree` wrote. + To read one with a kind, use `nullable(..)`: see [Stored bytes](#stored-bytes). +- A plain object is refused, because an object has no single stored form. + You choose the form. + `json(..)` encrypts the object as a JSON document. + `opaque(..)`, for a whole object in the engine's own format, is not built yet. +- The package exports `RcUuid`, for a universally unique identifier (UUID). + This version of the SDK does not encrypt a UUID yet. + Encrypting an `RcUuid` is an `Err` with the code `recipher_js::uuid`. +- The value bridge refuses each of these values, with an error code for each: + - a `Map` or a `Set`; + - a class instance; + - a sparse array; + - a typed array other than a `Uint8Array`; + - a string with an unpaired surrogate; + - a property named `__proto__`, `constructor`, or `prototype`. + +If you encrypt an array, you get back an array of ciphertexts in the same order. +The whole array needs one key request to ZeroKMS, however long it is: + +```ts +const sealed = await keyset.encrypt(['first secret', 'second secret']) +const opened = await cipher.decrypt(sealed.unwrap()) +``` + +### A declared kind + +`encrypt` takes a kind in its options, as in `{ kind: kinds.uint64 }`. +The value is stored as that kind, and its ciphertext decrypts as that kind. +For an array of values, the kind applies to each value. + +```ts +import { kinds } from '@cipherstash/recipher' + +const age = (await keyset.encrypt(34, { kind: kinds.uint64 })).unwrap() +const opened = (await cipher.decrypt(age)).unwrap() +// 34n +``` + +- A value converts to the declared kind only when the conversion is exact. + A record field converts a value by the same rules. + `34` declared as `uint64` is stored as the integer `34`. + `34.5` declared as `uint64` is refused. +- A whole `number` outside the safe range, 2^53 - 1 either side of zero, is refused for an integer kind. + A `number` that large may not keep the digits you wrote: `12345678901234567890` is the `number` `12345678901234567168`. + Pass a `bigint` instead. + The refusal is an `Err` with the code `recipher_js::unsafe_integer`. + TypeScript cannot check the range, so the refusal comes when `encrypt` runs. +- A value declared as `kinds.json` must be a `json(..)` value. + A `json(..)` value declared as another kind is refused. + Each is an `Err` with the code `recipher_js::json_kind`. +- The options take only `kind`. + Any other key is an `Err` with the code `recipher_js::options`, so an option that this version does not have is never ignored. + `null` as the options is refused with the same code. +- A kind from `kinds` takes no `null`, as a Rust type that is not an `Option` takes no `None`. + `nullable(kind)` is the kind that also takes `null`, as Rust's `Option` is. + A value that is not `null` encrypts with `nullable(kind)` as it does with `kind`. +- A lone `null` is an `Err` with the code `recipher_js::null_value` today, with any kind or with none. + Store a value that is not there as a database `NULL`. + TypeScript refuses `encrypt(null)` and `encrypt(null, { kind: kinds.int64 })` before the code runs. +- Once the engine encrypts a typed null as one value, a `null` declared as `nullable(..)` of a fixed-width kind will encrypt. + A fixed-width kind is a boolean, an integer, a float, a decimal, a date, or a timestamp. + The engine will encrypt the `null` padded to the size of a value, as a record field with `"null": "sealed"` stores one. + Issue #2023 makes that engine change, and it has not merged yet. + TypeScript already takes `encrypt(null, { kind: nullable(kinds.int64) })`. + The SDK gives the engine a typed null of the kind, and the engine refuses it when the call runs. +- A `null` of a variable-width kind, such as `nullable(kinds.string)` or `nullable(kinds.bytes)`, is always refused. + A value of that kind has no fixed size, so a null cannot be padded to look like a value. + TypeScript refuses the call before the code runs. + +```ts +import { kinds, nullable } from '@cipherstash/recipher' + +const age = (await keyset.encrypt(34, { kind: nullable(kinds.uint64) })).unwrap() +// stored as the uint64 34, the same as with kinds.uint64 +``` + +### JSON documents + +`json(value)` encrypts a whole document as one ciphertext. +The document is encrypted as its JSON text, as the engine's `JsonPlaintext` type does. +Rust code that calls `keyset.decrypt::` decrypts it. + +```ts +import { json } from '@cipherstash/recipher' + +const profile = json({ name: 'Ada', visits: 3, id: 2n ** 64n - 1n }) +const sealed = (await keyset.encrypt(profile)).unwrap() + +const opened = (await cipher.decrypt(sealed)).unwrap() +// { id: 18446744073709551615n, name: 'Ada', visits: 3 } +``` + +A document is a plain object, an array, a string, a number, a `bigint`, a boolean, or `null`. +A document can nest 127 levels of arrays and objects. + +These rules decide how a number is stored and decrypted: + +| In the document | Stored as | Decrypts as | +|---|---|---| +| a whole `number` within 2^53 - 1 of zero, such as `5000000000` | the integer `5000000000` | `number` | +| a whole `number` from 2^53 up to 2^64, or from -2^53 down to -2^63 | refused: pass a `bigint` | not applicable | +| a whole `number` below -2^63 and above -2^64 | refused: no exact form | not applicable | +| any other `number`, such as `1.5` or `1e20` | a float | `number` | +| a `bigint` within 2^53 - 1 of zero, such as `5n` | the integer `5` | `number` | +| any other `bigint` from `-(2n ** 63n)` to `2n ** 64n - 1n` | an integer, with its exact digits | `bigint` | +| a `bigint` outside that range | refused | not applicable | + +- A whole `number` is stored as an integer, as `JSON.stringify` writes it. + A millisecond timestamp from `Date.now()`, such as `1764288000000`, is stored as `1764288000000`. + The timestamp is never stored as `1764288000000.0`. + Code in Rust or Go refuses that form for an integer field. +- A whole `number` from 2^53 up to 2^64, or from -2^53 down to -2^63, is refused. + A `number` that large may not keep the digits you wrote. + Use a `bigint` instead. +- A whole `number` below -2^63 and above -2^64 is refused too. + An integer in that range has no exact form in a document, because a `bigint` that size is refused as well. +- A `bigint` must be in the 64-bit range that the engine's parser reads. +- An integer decrypts as a `number` when it is within 2^53 - 1 of zero, and as a `bigint` otherwise. + So no digit is lost, and `json({ a: 5n })` decrypts as `{ a: 5 }`. +- The engine stores the members of an object sorted by key. + A decrypted object lists its members in that order, not in the order you wrote them. +- `undefined`, `NaN`, the infinities, bytes, a `Date`, and the wrapper classes have no JSON form. + Each is an `Err` with the code `recipher_js::not_json`. + The package does not call a `toJSON` method. +- A document nested deeper than 127 levels is an `Err` with the code `recipher_js::too_deep`. +- The same rules apply to a document as to any value. + A `Map`, a class instance, a sparse array, and a string with an unpaired surrogate are refused. +- A property named `__proto__`, `constructor`, or `prototype` cannot be encrypted. + Another SDK can write a document with one of these properties. + Decrypting that document here gives an `Err` with the code `recipher_js::reserved_key`. + The reason is that the value bridge does not build those properties in JavaScript. +- **Read a stored document back with `kinds.json`.** + A kind names the type that a stored ciphertext decrypts to. + The bytes do not record that a value is JSON. + `Ciphertext.fromBytes(bytes, kinds.json)` decrypts to the document. + With no kind, the document decrypts to its JSON text. + `JSON.parse` of that text loses the digits of a large integer. + +### Stored bytes + +A kind names the type a stored ciphertext decrypts to, such as `kinds.string`. + +`Ciphertext.fromBytes(bytes)` decrypts to whatever type was encrypted. +The ciphertext's TypeScript type allows any scalar: any type in the table above except a JSON document. + +`Ciphertext.fromBytes(bytes, kinds.string)` has the kind's type. +Decrypting it refuses a value that was encrypted as another type. +An integer kind accepts an integer encrypted at any width, if the value fits the kind. + +A kind from `kinds` refuses a stored null, as Rust's `decrypt::` refuses one. +The type of `Ciphertext.fromBytes(bytes, kinds.int64)` is `Ciphertext`. +Decrypting a stored null with it is an `Err` with the code `recipher_js::opened_null`. + +If the value may be absent, read it with `nullable(..)`, as Rust reads an `Option`: + +```ts +import { Ciphertext, kinds, nullable } from '@cipherstash/recipher' + +const stored = Ciphertext.fromBytes(bytes, nullable(kinds.int64)).unwrap() +const age = (await cipher.decrypt(stored)).unwrap() // bigint | null +``` + +`nullable(..)` works with every kind when you read. +A stored null can exist for a value of any type: Rust's `encrypt_tree(None::)` writes one. ## Results, not exceptions @@ -61,8 +270,11 @@ The other calls return an `Err` in these cases too: - an argument of the wrong type, or a missing argument; - a native addon that did not load. + The native addon is the compiled Rust code that Node loads. -One call throws: a method called without its object. +Two kinds of call throw. + +The first is a method called without its object. `ciphertexts.map(cipher.decrypt)` passes `decrypt` on its own, without its cipher. The JavaScript engine throws a `TypeError` when it is called, before any of the package's code runs. Call the method on its object instead: @@ -73,7 +285,14 @@ const opened = await Promise.all( ) ``` -A static method, such as `Ciphertext.fromBytes`, works on its own. +A static method, such as `Ciphertext.fromBytes` or `RcDate.from`, works on its own. + +The second is `new` on a class whose type has no constructor. +Those classes are `Cipher`, `Keyset`, `Ciphertext`, and the wrapper classes, such as `RcDate`. +TypeScript refuses `new RcDate('2026-11-23')` before the code runs. +Called from JavaScript, or past a cast, `new` throws. +For a wrapper class, it throws a `TypeError` that names the way in, such as `RcDate.from(text)`. +Make each one the way [Encrypt and decrypt one value](#encrypt-and-decrypt-one-value) and [Values](#values) describe. A `RecipherError` is an error report that a call returns as a value. Most errors come from the engine. @@ -91,9 +310,9 @@ if (opened.isErr()) { | Property | What it contains | | --- | --- | -| `code` | The code to switch on. It is stable. It is the engine's code (`stack_encrypt::aead`), vitaminc's code for a value it refused (`ERR_INTEGER_RANGE`), or the SDK's own (`recipher_js::not_a_ciphertext`). | +| `code` | The code to switch on. It is stable. It is the engine's code (`stack_encrypt::aead`), the value bridge's code for a scalar it refused (`ERR_INTEGER_RANGE`), or the SDK's own (`recipher_js::not_a_ciphertext`). | | `message` | What went wrong, in one line. | -| `help` | What to do about it, where the error knows. | +| `help` | What to do about the failure, when the error has that advice. | | `url` | A documentation page for the error, where it has one. | | `severity` | `error`, unless the engine's report states `warning` or `advice`. | | `fields` | The error's structured fields, by `snake_case` name. An example is a ZeroKMS failure's `request_kind`. | @@ -130,13 +349,22 @@ The value bridge is the `recipher-value-napi` crate in `value-napi/`. napi-rs's command-line tool builds the addon. The tool also writes the addon's TypeScript declarations to `native.d.ts`. Those declarations are the package's public types. -Each method's signature is written in Rust, in the method's `ts_type`, `ts_args_type` or `ts_return_type` attribute. -The documentation comments on the Rust code become the declarations' documentation. -`native-header.d.ts` is the start of `native.d.ts`: it imports the TypeScript types the signatures name, and gives `Ciphertext` its type parameter. `native.d.ts` is committed. +Each method's signature is written in Rust, in the method's `ts_type`, `ts_args_type`, or `ts_return_type` attribute. +The tool copies the Rust documentation comments into the declarations. + +`native-header.d.ts` is the start of `native.d.ts`. +The header does three things: + +- it imports the TypeScript types that the signatures name; +- it gives `Ciphertext` its type parameter; +- it marks `Json` so that no other object type-checks as one. + +The modules that the header imports types from never load the addon, so the declarations never import themselves. + Each native method returns a `Result` itself. -The package's TypeScript gives the addon the `Ok`, `Err` and `RecipherError` classes when it loads the addon. +The package's TypeScript gives the addon the `Ok`, `Err`, and `RecipherError` classes when it loads the addon. The package's TypeScript contains what Rust cannot provide: `Result`, `RecipherError`, the loader, and stand-in classes for when the addon did not load. The package's `build` and `test` scripts never run cargo. @@ -151,15 +379,12 @@ The package's `build` and `test` scripts never run cargo. | `test:cargo` | Runs `cargo test`, `cargo fmt --check`, and clippy over the crate. | The addon is loaded when the package is imported. -The ESM build and the CommonJS build load the same addon, so the two builds share its classes. +The ECMAScript module (ESM) build and the CommonJS build load the same addon, so the two builds share its classes. ## What is not here yet These features are not built yet: -- values other than a `string`; -- arrays; -- JSON documents; - `opaque(..)`, for a whole object; - records; - search terms; diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/builds.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/builds.test.ts index e6e0c85f1..ee918edf9 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/builds.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/builds.test.ts @@ -1,12 +1,19 @@ /** - * The ESM and the CommonJS builds in one process: an application that - * imports the package and a dependency that requires it. Both load the one - * addon, so they share its classes, and a ciphertext from either opens in - * the other. Runs the built `dist/`, in a Node process of its own; - * `test:addon` builds it first. + * Two cases: + * + * - The ECMAScript module (ESM) build and the CommonJS build in one process. + * An application imports the package, and a dependency requires it. Both + * builds load the same addon, so they share its classes. A ciphertext from + * either build decrypts in the other. + * - The package with no native build at all. + * + * Each case runs the built `dist/` in a Node process of its own. + * `test:addon` builds `dist/` first. */ import { execFileSync } from 'node:child_process' -import { existsSync } from 'node:fs' +import { cpSync, existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' @@ -48,6 +55,59 @@ const out = { console.log(JSON.stringify(out)) ` +const MISSING = ` +const recipher = await import(process.argv[1]) +const testing = await import(process.argv[2]) +const out = {} +out.date = recipher.RcDate.from('2026-11-23').err().code +out.dateFrozen = Object.isFrozen(recipher.RcDate) +out.json = String(recipher.json({ a: 1 })) +out.create = (await recipher.Cipher.create()).err().code +out.testing = (await testing.testCipher()).err().code +out.fromBytes = recipher.Ciphertext.fromBytes(new Uint8Array(4)).err().code +out.notACipher = {} instanceof recipher.Cipher +console.log(JSON.stringify(out)) +` + +describe('the package without its native build', () => { + it('imports, constructs the wrapper classes, and resolves every call to the load error', () => { + const dir = mkdtempSync(join(tmpdir(), 'recipher-missing-')) + try { + cpSync( + fileURLToPath(new URL('../../dist', import.meta.url)), + join(dir, 'dist'), + { + recursive: true, + }, + ) + writeFileSync(join(dir, 'package.json'), '{"type":"module"}') + const output = execFileSync( + process.execPath, + [ + '--input-type=module', + '--eval', + MISSING, + '--', + join(dir, 'dist', 'index.js'), + join(dir, 'dist', 'testing.js'), + ], + { encoding: 'utf8' }, + ) + expect(JSON.parse(output)).toEqual({ + date: 'recipher_js::load', + dateFrozen: true, + json: 'Json(***)', + create: 'recipher_js::load', + testing: 'recipher_js::load', + fromBytes: 'recipher_js::load', + notACipher: false, + }) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) +}) + describe('the ESM and CommonJS builds in one process', () => { it('share the native classes, so each opens what the other sealed', () => { const files = ['index.js', 'testing.js', 'index.cjs', 'testing.cjs'].map( diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/value.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/value.test.ts index 0bac781e7..715313824 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/value.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/value.test.ts @@ -116,19 +116,12 @@ describe('failures are values', () => { expect(opened.isErr()).toBe(true) }) - it('refuses a value that is not a string', async () => { - const keyset = (await cipher()).defaultKeyset() - // @ts-expect-error: this build encrypts a string. - const result = await keyset.encrypt(5) - expect(result.err()?.code).toBe('recipher_js::not_a_string') - }) - it('refuses a string with an unpaired surrogate, with a code of its own', async () => { const result = await (await cipher()).defaultKeyset().encrypt('\uD800') expect(result.err()?.code).toBe('recipher_js::unpaired_surrogate') }) - it('names the rule vitaminc refused a value by', async () => { + it('names the rule a refused value broke', async () => { const keyset = (await cipher()).defaultKeyset() const cases: [unknown, string][] = [ [new Map(), 'recipher_js::not_plain'], @@ -143,7 +136,7 @@ describe('failures are values', () => { it('refuses a decrypt of something that is not a ciphertext', async () => { const c = await cipher() - // @ts-expect-error: decrypt takes a Ciphertext. + // @ts-expect-error: decrypt accepts a Ciphertext. const result = await c.decrypt(new Uint8Array(8)) expect(result.err()?.code).toBe('recipher_js::not_a_ciphertext') }) @@ -211,13 +204,16 @@ describe('every other call returns or resolves to a Result', () => { encrypt(...args: unknown[]): ReturnType decrypt(...args: unknown[]): ReturnType } - expect((await loose.encrypt()).err()?.code).toBe( - 'recipher_js::not_a_string', - ) + expect((await loose.encrypt()).err()?.code).toBe('recipher_js::undefined') expect((await loose.decrypt()).err()?.code).toBe( 'recipher_js::not_a_ciphertext', ) - const sealed = (await loose.encrypt('a', 'extra')).unwrap() + // The second argument of `encrypt` is its options, so a stray one is + // refused. An argument after the options is ignored. + expect((await loose.encrypt('a', 'extra')).err()?.code).toBe( + 'recipher_js::options', + ) + const sealed = (await loose.encrypt('a', undefined, 'extra')).unwrap() expect((await loose.decrypt(sealed, 'extra')).unwrap()).toBe('a') const fromBytes = Ciphertext.fromBytes as (...args: unknown[]) => unknown expect((fromBytes() as { isErr(): boolean }).isErr()).toBe(true) @@ -226,19 +222,19 @@ describe('every other call returns or resolves to a Result', () => { it('arguments of every wrong type resolve to an Err', async () => { const c = await cipher() const keyset = c.defaultKeyset() - const wrong: unknown[] = [ + const notValues: unknown[] = [ undefined, - null, - 0, {}, - [], Symbol('s'), () => 1, new Map(), ] - for (const value of wrong) { + for (const value of notValues) { + expect((await keyset.encrypt(value as never)).isErr()).toBe(true) + } + const notCiphertexts: unknown[] = [...notValues, null, 0, 'text', [1]] + for (const value of notCiphertexts) { const anyValue = value as never - expect((await keyset.encrypt(anyValue)).isErr()).toBe(true) expect((await keyset.decrypt(anyValue)).isErr()).toBe(true) expect((await c.decrypt(anyValue)).isErr()).toBe(true) expect(Ciphertext.fromBytes(anyValue).isErr()).toBe(true) diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts new file mode 100644 index 000000000..124b2b646 --- /dev/null +++ b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts @@ -0,0 +1,1115 @@ +import { inspect } from 'node:util' +import { describe, expect, it } from 'vitest' +import { + Cipher, + Ciphertext, + json, + Keyset, + kinds, + nullable, + RcDate, + RcDecimal, + RcTimestamp, + RcUuid, + RecipherError, +} from '../../src/index' +import { testCipher } from '../../src/testing' +import { standInWrapper } from '../../src/values' + +async function cipher(): Promise { + return (await testCipher()).unwrap() +} + +/** Encrypt one value, read it back from its stored bytes, and decrypt it. */ +async function roundTrip(value: Parameters[1]) { + const c = await cipher() + const sealed = await encryptOne(c, value) + const stored = Ciphertext.fromBytes(sealed.toBytes()).unwrap() + return (await c.decrypt(stored)).unwrap() +} + +async function encryptOne( + c: Cipher, + value: + | string + | boolean + | number + | bigint + | Uint8Array + | Date + | RcDate + | RcTimestamp + | RcDecimal, +) { + return (await c.defaultKeyset().encrypt(value)).unwrap() +} + +describe('every value in the mapping round-trips', () => { + it('text, booleans and numbers', async () => { + expect(await roundTrip('text')).toBe('text') + expect(await roundTrip(true)).toBe(true) + expect(await roundTrip(false)).toBe(false) + expect(await roundTrip(1.5)).toBe(1.5) + expect(await roundTrip(-0.25)).toBe(-0.25) + // A number is a float: 5 stays the number 5, never the integer 5n. + expect(await roundTrip(5)).toBe(5) + }) + + it('integers, as bigints, at every width', async () => { + for (const n of [ + 0n, + -1n, + 127n, + -128n, + 2n ** 31n, + 2n ** 63n - 1n, + -(2n ** 63n), + 2n ** 64n - 1n, + 2n ** 127n - 1n, + -(2n ** 127n), + ]) { + expect(await roundTrip(n)).toBe(n) + } + }) + + it('bytes, from a Uint8Array or a Buffer', async () => { + const bytes = new Uint8Array([0, 1, 254, 255]) + expect(Buffer.from((await roundTrip(bytes)) as Uint8Array)).toEqual( + Buffer.from(bytes), + ) + const buffer = Buffer.from('a file') + expect(Buffer.from((await roundTrip(buffer)) as Uint8Array)).toEqual(buffer) + }) + + it('a Date, to the millisecond', async () => { + const date = new Date('2026-11-23T01:02:03.456Z') + const opened = await roundTrip(date) + expect(opened).toBeInstanceOf(Date) + expect((opened as Date).getTime()).toBe(date.getTime()) + }) + + it('the wrapper classes', async () => { + const day = await roundTrip(RcDate.from('2026-11-23').unwrap()) + expect(day).toBeInstanceOf(RcDate) + expect((day as RcDate).value).toBe('2026-11-23') + + const fine = await roundTrip( + RcTimestamp.from('2026-11-23T01:02:03.000000001Z').unwrap(), + ) + expect(fine).toBeInstanceOf(RcTimestamp) + expect((fine as RcTimestamp).value).toBe('2026-11-23T01:02:03.000000001Z') + + // A timestamp of whole milliseconds decrypts as a Date. + const whole = await roundTrip( + RcTimestamp.from('2026-11-23T01:02:03.000Z').unwrap(), + ) + expect(whole).toBeInstanceOf(Date) + + const price = await roundTrip(RcDecimal.from('1.50').unwrap()) + expect(price).toBeInstanceOf(RcDecimal) + expect((price as RcDecimal).value).toBe('1.50') + }) +}) + +describe('a wrapper class', () => { + const classes = { RcDate, RcTimestamp, RcDecimal, RcUuid } + const texts = { + RcDate: '2026-11-23', + RcTimestamp: '2026-11-23T01:02:03.000000001Z', + RcDecimal: '1.50', + RcUuid: '123e4567-e89b-12d3-a456-426614174000', + } + const invalid = { + RcDate: ['2023-02-29', 'ERR_INVALID_DATE'], + RcTimestamp: ['2016-12-31T23:59:60Z', 'ERR_INVALID_TIMESTAMP'], + RcDecimal: ['1e5', 'ERR_INVALID_DECIMAL'], + RcUuid: ['not-a-uuid', 'ERR_INVALID_UUID'], + } as const + const names = ['RcDate', 'RcTimestamp', 'RcDecimal', 'RcUuid'] as const + + it('makes an instance with from(text), which returns a Result', () => { + for (const name of names) { + const made = classes[name].from(texts[name]) + expect(made.isOk(), name).toBe(true) + const instance = made.unwrap() + expect(instance).toBeInstanceOf(classes[name]) + expect(Object.getOwnPropertyDescriptor(instance, 'value')).toEqual({ + value: texts[name], + writable: false, + enumerable: true, + configurable: false, + }) + expect(Object.keys(instance)).toEqual(['value']) + expect(String(instance)).toBe(texts[name]) + expect(JSON.stringify(instance)).toBe(JSON.stringify(texts[name])) + expect(inspect(instance)).toBe(`${name}(${texts[name]})`) + expect(Object.isFrozen(instance)).toBe(true) + expect(Object.isFrozen(classes[name])).toBe(true) + expect(Object.isFrozen(classes[name].prototype)).toBe(true) + } + }) + + it('refuses text that encrypt would refuse, with an Err and no throw', () => { + for (const name of names) { + const [text, code] = invalid[name] + const refused = classes[name].from(text) + expect(refused.err()?.code, name).toBe(code) + expect(refused.err()?.message).not.toContain(text) + for (const notText of [20261123, undefined, null, {}, [text], 1n]) { + // @ts-expect-error: `from` takes a string. + expect(classes[name].from(notText).err()?.code, name).toBe(code) + } + } + expect(RcDecimal.from('NaN').err()?.code).toBe('ERR_NON_FINITE_DECIMAL') + expect(RcDate.from('\uD800').err()?.code).toBe( + 'recipher_js::unpaired_surrogate', + ) + }) + + it('works taken off its class', () => { + const days = ['2026-11-23', '2026-11-24'].map(RcDate.from) + expect(days.map((day) => day.unwrap().value)).toEqual([ + '2026-11-23', + '2026-11-24', + ]) + }) + + it('throws a TypeError that names from(..) for new, for any argument', () => { + for (const name of names) { + const cls = classes[name] as unknown as new (text: unknown) => object + for (const argument of [texts[name], 20261123]) { + expect(() => new cls(argument)).toThrow( + new TypeError( + `${name} has no public constructor. Make one with ${name}.from(text), which returns a Result.`, + ), + ) + } + } + }) + + it('is like the native classes, which throw for new too', () => { + for (const cls of [Cipher, Keyset, Ciphertext]) { + const native = cls as unknown as new () => object + expect(() => new native()).toThrow() + } + }) + + it('has a stand-in whose from is the load error, and whose new throws the same', () => { + const loadError = new RecipherError({ + code: 'recipher_js::load', + message: 'the native build did not load', + }) + for (const name of names) { + const standIn = standInWrapper(name, loadError) + expect(standIn.name).toBe(name) + expect(standIn.from(texts[name]).err()).toBe(loadError) + const cls = classes[name] as unknown as new (text: unknown) => object + const stand = standIn as unknown as new (text: unknown) => object + let thrown: unknown + try { + new cls(texts[name]) + } catch (error) { + thrown = error + } + expect(() => new stand(texts[name])).toThrow(thrown as Error) + expect(Object.isFrozen(standIn)).toBe(true) + expect(Object.isFrozen(standIn.prototype)).toBe(true) + } + }) +}) + +describe('an array of values', () => { + it('is an array of ciphertexts in, an array of values out, in order', async () => { + const c = await cipher() + const keyset = c.defaultKeyset() + const sealed = (await keyset.encrypt(['first', 'second', 'third'])).unwrap() + expect(sealed).toHaveLength(3) + expect((await c.decrypt(sealed)).unwrap()).toEqual([ + 'first', + 'second', + 'third', + ]) + expect((await keyset.decrypt(sealed)).unwrap()).toEqual([ + 'first', + 'second', + 'third', + ]) + }) + + it('opens each element on its own', async () => { + const c = await cipher() + const sealed = (await c.defaultKeyset().encrypt([1n, 2n, 3n])).unwrap() + const second = sealed[1] + expect(second).toBeDefined() + if (second !== undefined) { + expect((await c.decrypt(second)).unwrap()).toBe(2n) + } + }) + + it('may mix types', async () => { + const c = await cipher() + const sealed = ( + await c.defaultKeyset().encrypt(['a', 1n, true, 1.5] as const) + ).unwrap() + expect((await c.decrypt(sealed)).unwrap()).toEqual(['a', 1n, true, 1.5]) + }) + + it('is empty in, empty out', async () => { + const c = await cipher() + const sealed = (await c.defaultKeyset().encrypt([] as string[])).unwrap() + expect(sealed).toEqual([]) + expect((await c.decrypt(sealed)).unwrap()).toEqual([]) + }) + + it('is refused when it has a hole, to encrypt or to decrypt', async () => { + const c = await cipher() + const keyset = c.defaultKeyset() + // biome-ignore lint/suspicious/noSparseArray: a hole is the case. + const holed = await keyset.encrypt(['a', , 'b'] as string[]) + expect(holed.err()?.code).toBe('recipher_js::sparse_array') + const empty = await keyset.encrypt(new Array(3)) + expect(empty.err()?.code).toBe('recipher_js::sparse_array') + + const sealed = (await keyset.encrypt('a')).unwrap() + // biome-ignore lint/suspicious/noSparseArray: a hole is the case. + const opened = await c.decrypt([sealed, , sealed] as (typeof sealed)[]) + expect(opened.err()?.code).toBe('recipher_js::sparse_array') + }) + + it('never reads a hole through a polluted Array.prototype', async () => { + const c = await cipher() + const keyset = c.defaultKeyset() + const other = (await keyset.encrypt('not passed')).unwrap() + const sealed = (await keyset.encrypt('a')).unwrap() + try { + Object.defineProperty(Array.prototype, '1', { + value: 'injected', + configurable: true, + }) + // biome-ignore lint/suspicious/noSparseArray: a hole is the case. + const holed = await keyset.encrypt(['a', , 'b'] as string[]) + expect(holed.err()?.code).toBe('recipher_js::sparse_array') + + // A ciphertext the caller never passed is not decrypted. + Object.defineProperty(Array.prototype, '1', { + value: other, + configurable: true, + }) + // biome-ignore lint/suspicious/noSparseArray: a hole is the case. + const opened = await c.decrypt([sealed, , sealed] as (typeof sealed)[]) + expect(opened.err()?.code).toBe('recipher_js::sparse_array') + } finally { + Reflect.deleteProperty(Array.prototype, '1') + } + }) + + it('is refused whole when one element is refused', async () => { + const keyset = (await cipher()).defaultKeyset() + // @ts-expect-error: an array inside an array is not a value. + const result = await keyset.encrypt(['fine', ['nested']]) + expect(result.err()?.code).toBe('recipher_js::not_a_scalar') + }) +}) + +describe('a JSON document', () => { + it('round-trips as one ciphertext', async () => { + const c = await cipher() + const card = { + number: '4111 1111 1111 1111', + expiry: { month: 4, year: 2031 }, + tags: ['a', 'b'], + active: true, + note: null, + } + const sealed = (await c.defaultKeyset().encrypt(json(card))).unwrap() + expect((await c.decrypt(sealed)).unwrap()).toEqual(card) + }) + + it('keeps an integer outside the safe range as a bigint', async () => { + const c = await cipher() + const document = { big: 18446744073709551615n, small: 5n } + const sealed = (await c.defaultKeyset().encrypt(json(document))).unwrap() + // The safe integer comes back as a number. The big one comes back as a + // bigint. + expect((await c.decrypt(sealed)).unwrap()).toEqual({ + big: 18446744073709551615n, + small: 5, + }) + }) + + /** The JSON text a document is stored as: what another SDK reads. */ + async function storedText(document: Parameters[0]) { + const c = await cipher() + const sealed = (await c.defaultKeyset().encrypt(json(document))).unwrap() + // With no kind named, the stored bytes decrypt as their text. + const untyped = Ciphertext.fromBytes(sealed.toBytes()).unwrap() + return (await c.decrypt(untyped)).unwrap() + } + + /** The code and message of the `Err` that encrypting `document` gives. */ + async function refusal(document: unknown) { + const keyset = (await cipher()).defaultKeyset() + const result = await keyset.encrypt(json(document as never)) + expect(result.isErr()).toBe(true) + return { code: result.err()?.code, message: result.err()?.message ?? '' } + } + + it('stores a whole number as an integer, at every size', async () => { + // For an integer field, a reader in Go or Rust accepts `5000000000`, and + // refuses `5000000000.0`. + expect(await storedText({ n: 5000000000 })).toBe('{"n":5000000000}') + const now = Date.now() + expect(await storedText({ t: now })).toBe(`{"t":${now}}`) + expect( + await storedText([ + 5, + -5, + 4294967296, + -5000000000, + Number.MAX_SAFE_INTEGER, + Number.MIN_SAFE_INTEGER, + -0, + ]), + ).toBe('[5,-5,4294967296,-5000000000,9007199254740991,-9007199254740991,0]') + }) + + it('stores any other number as a float', async () => { + const text = await storedText([1.5, 2 ** 64, -(2 ** 64), 1e20, -1e20]) + expect(JSON.parse(text as string)).toEqual([ + 1.5, + 2 ** 64, + -(2 ** 64), + 1e20, + -1e20, + ]) + // Each has a fraction or an exponent, so no reader reads an integer. + for (const number of (text as string).slice(1, -1).split(',')) { + expect(number).toMatch(/[.e]/) + } + }) + + it('stores a bigint as its digits, within 64 bits', async () => { + expect( + await storedText([ + 5n, + 2n ** 53n, + -(2n ** 63n), + 2n ** 63n, + 2n ** 64n - 1n, + ]), + ).toBe( + '[5,9007199254740992,-9223372036854775808,9223372036854775808,18446744073709551615]', + ) + }) + + it('stores the members of an object sorted by key', async () => { + expect(await storedText({ b: 1, a: 2, c: { z: 1, y: 2 } })).toBe( + '{"a":2,"b":1,"c":{"y":2,"z":1}}', + ) + const c = await cipher() + const sealed = ( + await c.defaultKeyset().encrypt(json({ b: 1, a: 2 })) + ).unwrap() + const opened = (await c.decrypt(sealed)).unwrap() + expect(Object.keys(opened as object)).toEqual(['a', 'b']) + }) + + it('opens an integer as a number in the safe range, and as a bigint outside it', async () => { + const c = await cipher() + const document = { + safe: 9007199254740991n, + negative: -9007199254740991n, + edge: 2n ** 53n, + least: -(2n ** 63n), + most: 2n ** 64n - 1n, + float: 1.5, + whole: 5000000000, + nested: [{ deep: 2n ** 60n, small: 7n }], + } + const sealed = (await c.defaultKeyset().encrypt(json(document))).unwrap() + expect((await c.decrypt(sealed)).unwrap()).toStrictEqual({ + edge: 9007199254740992n, + float: 1.5, + least: -9223372036854775808n, + most: 18446744073709551615n, + negative: -9007199254740991, + nested: [{ deep: 1152921504606846976n, small: 7 }], + safe: 9007199254740991, + whole: 5000000000, + }) + }) + + it('opens a document another SDK wrote, whatever its numbers', async () => { + const c = await cipher() + const keyset = c.defaultKeyset() + // Encrypted as the engine encrypts a document: as its JSON text. + const sealed = ( + await keyset.encrypt( + '{"float":5.0,"big":1e20,"id":18446744073709551615,"n":-3}', + ) + ).unwrap() + const stored = Ciphertext.fromBytes(sealed.toBytes(), kinds.json).unwrap() + expect((await c.decrypt(stored)).unwrap()).toStrictEqual({ + big: 1e20, + float: 5, + id: 18446744073709551615n, + n: -3, + }) + }) + + it('refuses a whole number from 2^53 up to 2^64, and asks for a bigint', async () => { + for (const unsafe of [ + 2 ** 53, + 2 ** 60, + 2 ** 64 - 2048, + -(2 ** 53), + -(2 ** 63), + ]) { + const refused = await refusal({ n: unsafe }) + expect(refused.code).toBe('recipher_js::not_json') + expect(refused.message).toContain('bigint') + // The message contains no part of the value. + expect(refused.message).not.toMatch(/\d{6}/) + } + }) + + it('refuses a whole number below -2^63 and above -2^64, and asks for no bigint', async () => { + // -2^63 - 1 is not a `number`: it rounds to -2^63. The first `number` + // below -2^63 is -2^63 - 2048, and the last above -2^64 is + // -2^64 + 2048. + for (const number of [-(2 ** 63) - 2048, -1e19, -(2 ** 64) + 2048]) { + const refused = await refusal({ n: number }) + expect(refused.code).toBe('recipher_js::not_json') + expect(refused.message).toContain('no exact form') + expect(refused.message).not.toContain('Pass a `bigint`') + expect(refused.message).not.toMatch(/\d{6}/) + } + // -2^63 is the least `bigint` a document can contain. + const c = await cipher() + const sealed = ( + await c.defaultKeyset().encrypt(json({ n: -(2n ** 63n) })) + ).unwrap() + expect((await c.decrypt(sealed)).unwrap()).toStrictEqual({ + n: -(2n ** 63n), + }) + }) + + it('refuses a number that is not finite', async () => { + for (const number of [Number.NaN, Infinity, -Infinity]) { + const refused = await refusal([number]) + expect(refused.code).toBe('recipher_js::not_json') + expect(refused.message).toContain('not finite') + } + }) + + it('refuses a bigint outside 64 bits, at every size', async () => { + for (const wide of [2n ** 64n, -(2n ** 63n) - 1n, 2n ** 200n]) { + const refused = await refusal({ id: wide }) + expect(refused.code).toBe('recipher_js::not_json') + expect(refused.message).toContain('64-bit') + expect(refused.message).not.toMatch(/\d{6}/) + } + }) + + it('refuses a value with no JSON form', async () => { + const keyset = (await cipher()).defaultKeyset() + // @ts-expect-error: bytes are not JSON. + const result = await keyset.encrypt(json({ b: new Uint8Array([1]) })) + expect(result.err()?.code).toBe('recipher_js::not_json') + for (const value of [ + undefined, + Buffer.from('4111 1111'), + new Uint16Array(2), + new Date('2031-04-01T00:00:00Z'), + RcDate.from('2031-04-01').unwrap(), + RcTimestamp.from('2031-04-01T00:00:00.000000001Z').unwrap(), + RcDecimal.from('4111.1111').unwrap(), + RcUuid.from('123e4567-e89b-12d3-a456-426614174000').unwrap(), + ]) { + for (const document of [value, [value], { member: value }]) { + const refused = await refusal(document) + expect(refused.code).toBe('recipher_js::not_json') + expect(refused.message).not.toMatch(/4111|2031|123e4567/) + } + } + }) + + it('refuses a function and a symbol', async () => { + for (const value of [() => 1, Symbol('s')]) { + expect((await refusal({ member: value })).code).toBe( + 'recipher_js::not_a_value', + ) + } + }) + + it('reads a document by the rules for any value', async () => { + const cases: [unknown, string][] = [ + [new Map([['k', 1]]), 'recipher_js::not_plain'], + [new (class Card {})(), 'recipher_js::not_plain'], + // biome-ignore lint/suspicious/noSparseArray: a hole is the case. + [[1, , 3], 'recipher_js::sparse_array'], + [{ text: '\uD800' }, 'recipher_js::unpaired_surrogate'], + [JSON.parse('{"__proto__":1}'), 'recipher_js::reserved_key'], + ] + for (const [document, code] of cases) { + expect((await refusal(document)).code).toBe(code) + } + const cycle: unknown[] = [] + cycle.push(cycle) + expect((await refusal(cycle)).code).toBe('recipher_js::too_deep') + }) + + it('encrypts one Json more than once', async () => { + const c = await cipher() + const keyset = c.defaultKeyset() + const wrapped = json({ id: 2n ** 64n - 1n }) + const sealed = (await keyset.encrypt([wrapped, wrapped])).unwrap() + expect((await c.decrypt(sealed)).unwrap()).toEqual([ + { id: 18446744073709551615n }, + { id: 18446744073709551615n }, + ]) + expect( + (await c.decrypt((await keyset.encrypt(wrapped)).unwrap())).unwrap(), + ).toEqual({ id: 18446744073709551615n }) + }) + + it('builds a decrypted document from own properties, past a polluted prototype', async () => { + const c = await cipher() + const sealed = ( + await c + .defaultKeyset() + .encrypt(json({ leak: 'secret', list: ['secret'] })) + ).unwrap() + let captured = 'untouched' + const capture = { + set(value: string) { + captured = value + }, + configurable: true, + } + Object.defineProperty(Object.prototype, 'leak', capture) + Object.defineProperty(Array.prototype, '0', capture) + try { + const opened = (await c.decrypt(sealed)).unwrap() as { + leak: string + list: string[] + } + expect(captured).toBe('untouched') + expect(Object.hasOwn(opened, 'leak')).toBe(true) + expect(opened.list[0]).toBe('secret') + } finally { + Reflect.deleteProperty(Object.prototype, 'leak') + Reflect.deleteProperty(Array.prototype, '0') + } + }) + + it('read back from stored bytes with kinds.json, opens as the document', async () => { + const c = await cipher() + const document = { id: 18446744073709551615n, name: 'Ada' } + const sealed = (await c.defaultKeyset().encrypt(json(document))).unwrap() + const stored = Ciphertext.fromBytes(sealed.toBytes(), kinds.json).unwrap() + expect((await c.decrypt(stored)).unwrap()).toEqual(document) + // With no kind named, the bytes say only that the value is text. + const untyped = Ciphertext.fromBytes(sealed.toBytes()).unwrap() + expect((await c.decrypt(untyped)).unwrap()).toBe( + '{"id":18446744073709551615,"name":"Ada"}', + ) + }) + + it('nests 127 levels deep and refuses 128 as a value, not as damage', async () => { + const keyset = (await cipher()).defaultKeyset() + const nested = (depth: number) => { + let value: unknown[] = [] + for (let level = 1; level < depth; level++) { + value = [value] + } + return value + } + // biome-ignore lint/suspicious/noExplicitAny: a nested array of any depth. + expect((await keyset.encrypt(json(nested(127) as any))).isOk()).toBe(true) + // biome-ignore lint/suspicious/noExplicitAny: a nested array of any depth. + const deep = await keyset.encrypt(json(nested(128) as any)) + expect(deep.err()?.code).toBe('recipher_js::too_deep') + expect(deep.err()?.message).toContain('127 levels') + }) + + it('writes a large float as a float, so a document read back encrypts again', async () => { + const c = await cipher() + for (const document of [ + { x: 1e20 }, + { x: Number.MAX_VALUE }, + JSON.parse('{"x":6.02e23}'), + ]) { + const sealed = (await c.defaultKeyset().encrypt(json(document))).unwrap() + const opened = (await c.decrypt(sealed)).unwrap() + expect(opened).toEqual(document) + expect( + (await c.defaultKeyset().encrypt(json(opened as never))).isOk(), + ).toBe(true) + } + }) + + it('refuses a reserved property name, naming the rule, both ways', async () => { + const c = await cipher() + const keyset = c.defaultKeyset() + for (const text of [ + '{"constructor":1}', + '{"prototype":1}', + '{"__proto__":{"inherited":1}}', + ]) { + const refused = await keyset.encrypt(json(JSON.parse(text))) + expect(refused.err()?.code).toBe('recipher_js::reserved_key') + // A document another SDK wrote, encrypted as the engine encrypts one: + // as its JSON text. + const sealed = (await keyset.encrypt(text)).unwrap() + const stored = Ciphertext.fromBytes(sealed.toBytes(), kinds.json).unwrap() + const opened = await c.decrypt(stored) + expect(opened.err()?.code).toBe('recipher_js::reserved_key') + } + }) + + it('reads the document when json(..) is called', async () => { + const c = await cipher() + const document = { a: 1 } + const wrapped = json(document) + document.a = 2 + const sealed = (await c.defaultKeyset().encrypt(wrapped)).unwrap() + expect((await c.decrypt(sealed)).unwrap()).toEqual({ a: 1 }) + expect(String(wrapped)).toBe('Json(***)') + }) +}) + +describe('a ciphertext read back with a kind', () => { + it('opens as the kind, at any integer width that holds the value', async () => { + const c = await cipher() + const sealed = (await c.defaultKeyset().encrypt(42n)).unwrap() + const stored = Ciphertext.fromBytes(sealed.toBytes(), kinds.int64).unwrap() + // A kind from `kinds` is not nullable, so the type allows no null. + const opened: bigint = (await c.decrypt(stored)).unwrap() + expect(opened).toBe(42n) + // `nullable(..)` of the kind reads a value the same way. + const maybe = Ciphertext.fromBytes( + sealed.toBytes(), + nullable(kinds.int64), + ).unwrap() + expect((await c.decrypt(maybe)).unwrap()).toBe(42n) + }) + + it('refuses a value sealed as another type', async () => { + const c = await cipher() + const sealed = (await c.defaultKeyset().encrypt('text')).unwrap() + const stored = Ciphertext.fromBytes(sealed.toBytes(), kinds.int64).unwrap() + const opened = await c.decrypt(stored) + expect(opened.err()?.code).toBe('recipher_js::opened_type') + }) + + it('refuses something that is not a kind', () => { + const bytes = new Uint8Array(4) + // A kind is plain data, so this compiles. The addon checks the name. + const result = Ciphertext.fromBytes(bytes, { name: 'nothing' }) + expect(result.err()?.code).toBe('recipher_js::not_a_kind') + }) + + // Rust's `encrypt_tree(None::, ())` and + // `encrypt_tree(None::, ())`, with the test cipher's default + // seed. `encrypt` makes no ciphertext of a null. + const storedNulls = { + int64: + '0100000000000000000000000000000000dc75c7b191eb522525c852ef1493f7e1200072783bd959e42d8eaeb83ab721201403719fc0dbe09abdba81844e94f13db74e02befb4a4b5a8db027a9d9fca71b4c03103795dad9c1104f0284aad4363edd919cccb147379f', + string: + '0100000000000000000000000000000000e1773ad44d8f0dbe1b2d800b2b033b4820006601100222817a44acb38f4ef4eb433c161e89354e533cac263ef2a228e1eb9d02d6843cafa43e606546e44008c19c1e48acf3fe69a1d1f249c92fa4019a', + } + + it('reads a stored null as null with nullable(..), of any width', async () => { + const c = await cipher() + for (const [bytes, kind] of [ + [storedNulls.int64, nullable(kinds.int64)], + [storedNulls.string, nullable(kinds.string)], + [storedNulls.int64, nullable(kinds.boolean)], + ] as const) { + const stored = Ciphertext.fromBytes(Buffer.from(bytes, 'hex'), kind) + const opened: bigint | string | boolean | null = ( + await c.decrypt(stored.unwrap()) + ).unwrap() + expect(opened, kind.name).toBeNull() + } + }) + + it('refuses a stored null with a kind that is not nullable', async () => { + const c = await cipher() + for (const [bytes, kind] of [ + [storedNulls.int64, kinds.int64], + [storedNulls.string, kinds.string], + ] as const) { + const stored = Ciphertext.fromBytes(Buffer.from(bytes, 'hex'), kind) + const opened = await c.decrypt(stored.unwrap()) + expect(opened.err()?.code, kind.name).toBe('recipher_js::opened_null') + expect(opened.err()?.help).toContain('nullable(kinds.int64)') + } + // With no kind, a stored null decrypts as null, as any value decrypts + // as the type it was stored as. + const untyped = Ciphertext.fromBytes(Buffer.from(storedNulls.int64, 'hex')) + expect((await c.decrypt(untyped.unwrap())).unwrap()).toBeNull() + }) + + it('is frozen from nullable(..), as each of `kinds` is', () => { + const kind = nullable(kinds.int64) + expect(kind).toEqual({ name: 'int64', nullable: true }) + expect(Object.isFrozen(kind)).toBe(true) + expect(nullable(kind)).toEqual(kind) + }) + + it('refuses a nullable kind that nullable(..) did not write', () => { + const bytes = new Uint8Array(4) + for (const kind of [ + { name: 'int64', nullable: false }, + { name: 'int64', nullable: null }, + { name: 'int64', nullable: 'yes' }, + { name: 'int64', nullable: true, extra: 1 }, + { name: 'int64', nulable: true }, + { nullable: true }, + ]) { + // @ts-expect-error: a kind is one of `kinds`, or `nullable(..)` of one. + const result = Ciphertext.fromBytes(bytes, kind) + expect(result.err()?.code, JSON.stringify(kind)).toBe( + 'recipher_js::not_a_kind', + ) + } + }) + + it('nullable(..) of something that is not a kind is refused, without a throw', async () => { + const bytes = new Uint8Array(4) + const throwing = { + get name(): string { + throw new Error('no name') + }, + } + for (const notAKind of [null, undefined, 'int64', 5, throwing]) { + // @ts-expect-error: `nullable` takes a kind. + const kind = nullable(notAKind) + expect(Ciphertext.fromBytes(bytes, kind).err()?.code).toBe( + 'recipher_js::not_a_kind', + ) + const keyset = (await cipher()).defaultKeyset() + const result = await keyset.encrypt(34, { kind }) + expect(result.err()?.code).toBe('recipher_js::not_a_kind') + } + }) + + it('takes each of `kinds`, and no other name the engine has', async () => { + const c = await cipher() + const bytes = (await c.defaultKeyset().encrypt('text')).unwrap().toBytes() + for (const kind of Object.values(kinds)) { + expect(Ciphertext.fromBytes(bytes, kind).isOk(), kind.name).toBe(true) + const maybe = Ciphertext.fromBytes(bytes, nullable(kind)) + expect(maybe.isOk(), kind.name).toBe(true) + } + // The engine has these names too. No ciphertext decrypts as one, so + // the package has no kind for it. + const named = new Set(Object.values(kinds).map((kind) => kind.name)) + for (const name of ['uuid', 'array', 'object']) { + if (named.has(name)) continue + const result = Ciphertext.fromBytes(bytes, { name }) + expect(result.err()?.code, name).toBe('recipher_js::not_a_kind') + } + expect(named.has('array') || named.has('object')).toBe(false) + }) +}) + +describe('a declared kind', () => { + it('stores a whole number as the integer kind, and decrypts as a bigint', async () => { + const c = await cipher() + const sealed = ( + await c.defaultKeyset().encrypt(34, { kind: kinds.uint64 }) + ).unwrap() + expect((await c.decrypt(sealed)).unwrap()).toBe(34n) + // The stored bytes are those of an integer, so an integer kind reads + // them back. A crate test checks that the integer is a uint64. + const stored = Ciphertext.fromBytes(sealed.toBytes(), kinds.uint64).unwrap() + expect((await c.decrypt(stored)).unwrap()).toBe(34n) + }) + + it('refuses a whole number outside the safe range for every integer kind, and asks for a bigint', async () => { + const keyset = (await cipher()).defaultKeyset() + const integers = [ + kinds.int8, + kinds.int16, + kinds.int32, + kinds.int64, + kinds.int128, + kinds.uint8, + kinds.uint16, + kinds.uint32, + kinds.uint64, + kinds.uint128, + ] + // 2^53 and the numbers past it, on both sides of zero. Such a number + // may not keep the digits that were written: 12345678901234567890 is + // stored as 12345678901234567168. + const unsafe = [ + 2 ** 53, + -(2 ** 53), + // biome-ignore lint/correctness/noPrecisionLoss: the number has lost digits, as a caller's can. + 12345678901234567890, + -1e20, + 1e30, + Number.MAX_VALUE, + ] + for (const kind of integers) { + for (const number of unsafe) { + const result = await keyset.encrypt(number, { kind }) + const error = result.err() + expect(error?.code, `${kind.name} ${number}`).toBe( + 'recipher_js::unsafe_integer', + ) + expect(error?.help).toContain('bigint') + expect(error?.message).not.toContain(String(number)) + } + } + // In an array, the whole array is refused. + const many = await keyset.encrypt([1, 2 ** 60], { kind: kinds.int64 }) + expect(many.err()?.code).toBe('recipher_js::unsafe_integer') + }) + + it('takes a whole number at the edge of the safe range, and a large float as a float', async () => { + const c = await cipher() + const edge = ( + await c + .defaultKeyset() + .encrypt([Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER], { + kind: kinds.int64, + }) + ).unwrap() + expect((await c.decrypt(edge)).unwrap()).toEqual([ + 9007199254740991n, + -9007199254740991n, + ]) + const float = ( + await c.defaultKeyset().encrypt(2 ** 60, { kind: kinds.float64 }) + ).unwrap() + expect((await c.decrypt(float)).unwrap()).toBe(2 ** 60) + }) + + it('applies to each value of an array', async () => { + const c = await cipher() + const sealed = ( + await c.defaultKeyset().encrypt([1, 2n, 3], { kind: kinds.int32 }) + ).unwrap() + expect((await c.decrypt(sealed)).unwrap()).toEqual([1n, 2n, 3n]) + }) + + it('takes a value of its own type unchanged', async () => { + const c = await cipher() + const sealed = ( + await c.defaultKeyset().encrypt('Ada', { kind: kinds.string }) + ).unwrap() + expect((await c.decrypt(sealed)).unwrap()).toBe('Ada') + const document = ( + await c.defaultKeyset().encrypt(json({ a: 1 }), { kind: kinds.json }) + ).unwrap() + expect((await c.decrypt(document)).unwrap()).toEqual({ a: 1 }) + }) + + it('refuses a value that does not convert exactly, without the value', async () => { + const keyset = (await cipher()).defaultKeyset() + const result = await keyset.encrypt(34.5, { kind: kinds.uint64 }) + expect(result.isErr()).toBe(true) + expect(result.err()?.code).toMatch(/^stack_encrypt::/) + expect(result.err()?.message).not.toContain('34.5') + // The help is about the conversion, not about what one value holds. + expect(result.err()?.help).toContain('declared kind') + expect(result.err()?.help).not.toContain('separately') + }) + + it('refuses a null of a nullable fixed-width kind until #2023', async () => { + // Issue #2023 changes the engine to encrypt a null declared as + // `nullable(..)` of a fixed-width kind as a padded typed null, as a + // record field with `"null": "sealed"` stores one. Until that change + // merges, the engine refuses it. When it merges, this test fails: + // change it to check that the null encrypts and decrypts as null. + const keyset = (await cipher()).defaultKeyset() + for (const kind of [ + nullable(kinds.int64), + nullable(kinds.boolean), + nullable(kinds.timestamp), + nullable(kinds.decimal), + ]) { + const result = await keyset.encrypt(null, { kind }) + expect(result.err()?.code, kind.name).toBe('recipher_js::null_value') + // The help does not suggest the call that was just refused. + expect(result.err()?.help).toContain('database `NULL`') + expect(result.err()?.help).toContain('once the engine') + expect(result.err()?.help).not.toContain('nullable(') + } + }) + + it('refuses a null of a plain fixed-width kind, and suggests nullable(..)', async () => { + const keyset = (await cipher()).defaultKeyset() + for (const kind of [kinds.int64, kinds.boolean, kinds.timestamp]) { + // @ts-expect-error: a plain kind takes no null. + const result = await keyset.encrypt(null, { kind }) + expect(result.err()?.code, kind.name).toBe('recipher_js::null_value') + expect(result.err()?.help).toContain('nullable(kinds.int64)') + } + }) + + it('encrypts a value with a nullable kind as the plain kind would', async () => { + const c = await cipher() + const sealed = ( + await c + .defaultKeyset() + .encrypt([34, 35n], { kind: nullable(kinds.uint64) }) + ).unwrap() + expect((await c.decrypt(sealed)).unwrap()).toEqual([34n, 35n]) + // The stored bytes are those of the plain kind. + const bytes = sealed.map((ciphertext) => ciphertext.toBytes()) + const plain = Ciphertext.fromBytes( + bytes[0] ?? new Uint8Array(), + kinds.uint64, + ) + expect((await c.decrypt(plain.unwrap())).unwrap()).toBe(34n) + const text = ( + await c.defaultKeyset().encrypt('Ada', { kind: nullable(kinds.string) }) + ).unwrap() + expect((await c.decrypt(text)).unwrap()).toBe('Ada') + }) + + it('is refused for json when the value is not a json(..)', async () => { + const keyset = (await cipher()).defaultKeyset() + // @ts-expect-error: only a `json(..)` value has the kind `json`. + const text = await keyset.encrypt('{"a":1}', { kind: kinds.json }) + expect(text.err()?.code).toBe('recipher_js::json_kind') + // @ts-expect-error: a `json(..)` value has the kind `json`. + const document = await keyset.encrypt(json({ a: 1 }), { + kind: kinds.string, + }) + expect(document.err()?.code).toBe('recipher_js::json_kind') + }) + + it('refuses options other than one kind from kinds', async () => { + const keyset = (await cipher()).defaultKeyset() + for (const options of [ + kinds.uint64, + 'uint64', + { kind: kinds.uint64, context: 'users' }, + {}, + null, + ]) { + // @ts-expect-error: the options are `{ kind }`. + const result = await keyset.encrypt(34, options) + expect(result.err()?.code).toBe('recipher_js::options') + } + // The type checker takes any `{ name }` as a kind, so this check is + // made when the call runs. + const unknown = await keyset.encrypt(34, { kind: { name: 'uuid' } }) + expect(unknown.err()?.code).toBe('recipher_js::not_a_kind') + }) +}) + +describe('refusals', () => { + it('a UUID: this version of the SDK does not encrypt one yet', async () => { + const keyset = (await cipher()).defaultKeyset() + const uuid = RcUuid.from('123e4567-e89b-12d3-a456-426614174000').unwrap() + // @ts-expect-error: a UUID is not a `Scalar` in this version of the SDK. + const result = await keyset.encrypt(uuid) + expect(result.err()?.code).toBe('recipher_js::uuid') + expect(result.err()?.message).toContain( + 'this version of the SDK does not encrypt a UUID yet', + ) + }) + + it('a bigint outside 128 bits, with the code ERR_INTEGER_RANGE', async () => { + const keyset = (await cipher()).defaultKeyset() + const result = await keyset.encrypt(2n ** 128n) + expect(result.isErr()).toBe(true) + expect(result.err()?.code).toBe('ERR_INTEGER_RANGE') + expect(result.err()?.message).not.toContain(String(2n ** 128n)) + }) + + it('a plain object, which needs json(..)', async () => { + const keyset = (await cipher()).defaultKeyset() + // @ts-expect-error: a plain object is not a value. + const result = await keyset.encrypt({ name: 'Ada' }) + expect(result.err()?.code).toBe('recipher_js::plain_object') + }) + + it('a map, a set and a class instance', async () => { + const keyset = (await cipher()).defaultKeyset() + for (const value of [new Map(), new Set(), new (class Thing {})()]) { + // @ts-expect-error: none of them is a value. + const result = await keyset.encrypt(value) + expect(result.err()?.code).toBe('recipher_js::not_plain') + } + }) + + it('a typed array other than a Uint8Array, at the top or in an array', async () => { + const keyset = (await cipher()).defaultKeyset() + // @ts-expect-error: only a Uint8Array is bytes. + const one = await keyset.encrypt(new Uint16Array(2)) + expect(one.err()?.code).toBe('recipher_js::not_bytes') + // @ts-expect-error: only a Uint8Array is bytes. + const many = await keyset.encrypt(['x', new Uint16Array(2)]) + expect(many.err()?.code).toBe('recipher_js::not_bytes') + }) + + it('undefined', async () => { + const keyset = (await cipher()).defaultKeyset() + // @ts-expect-error: undefined is not a value. + const result = await keyset.encrypt(undefined) + expect(result.err()?.code).toBe('recipher_js::undefined') + // A lone `null` is refused too, so the help does not suggest one. + expect(result.err()?.help).toContain('database `NULL`') + expect(result.err()?.help).not.toContain('`null`') + }) + + it('null with no declared kind, alone or in an array', async () => { + const keyset = (await cipher()).defaultKeyset() + for (const result of [ + // @ts-expect-error: a lone null is not a value. + await keyset.encrypt(null), + // @ts-expect-error: a lone null is not a value. + await keyset.encrypt(['fine', null]), + ]) { + expect(result.err()?.code).toBe('recipher_js::null_value') + expect(result.err()?.help).toContain('database `NULL`') + expect(result.err()?.help).toContain('nullable(kinds.int64)') + } + }) + + it('null declared as a variable-width kind', async () => { + const keyset = (await cipher()).defaultKeyset() + for (const kind of [ + kinds.string, + kinds.bytes, + nullable(kinds.string), + nullable(kinds.bytes), + nullable(kinds.json), + ]) { + // @ts-expect-error: a null of a variable-width kind is not a value. + const result = await keyset.encrypt(null, { kind }) + expect(result.err()?.code).toBe('recipher_js::null_value') + // A kind never helps a null of a variable-width type. + expect(result.err()?.help).toBe( + 'Store a value that is not there as a database `NULL`.', + ) + } + }) + + it('a string with an unpaired surrogate', async () => { + const keyset = (await cipher()).defaultKeyset() + const result = await keyset.encrypt('\uD800') + expect(result.err()?.code).toBe('recipher_js::unpaired_surrogate') + }) + + it('a getter that throws, without its message', async () => { + const keyset = (await cipher()).defaultKeyset() + const document = { + get secret(): string { + throw new Error('card 4111 is invalid') + }, + } + const result = await keyset.encrypt(json(document)) + expect(result.err()?.code).toBe('recipher_js::threw') + expect(result.err()?.message).not.toContain('4111') + }) +}) diff --git a/languages/typescript/packages/recipher-js/__tests__/unit/binding.test.ts b/languages/typescript/packages/recipher-js/__tests__/unit/binding.test.ts index 9af5e83e4..ce380c354 100644 --- a/languages/typescript/packages/recipher-js/__tests__/unit/binding.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/unit/binding.test.ts @@ -14,9 +14,15 @@ function fakeBuild(overrides: Record = {}) { Cipher: class {}, Keyset: class {}, Ciphertext: class {}, + Json: class {}, bindingInterface: () => BINDING_INTERFACE, createTesting: () => Promise.resolve('cipher'), installResult: () => true, + json: () => ({}), + RcDate: class {}, + RcTimestamp: class {}, + RcDecimal: class {}, + RcUuid: class {}, ...overrides, } } @@ -42,9 +48,15 @@ describe('load', () => { 'Cipher', 'Keyset', 'Ciphertext', + 'Json', 'bindingInterface', 'createTesting', 'installResult', + 'json', + 'RcDate', + 'RcTimestamp', + 'RcDecimal', + 'RcUuid', ]) { const loaded = load( requiring(fakeBuild({ [name]: undefined })), @@ -105,7 +117,12 @@ describe('installResult', () => { it('freezes the classes of a build that loaded', () => { const build = fakeBuild() load(requiring(build), '/x/recipher.node') - for (const cls of [build.Cipher, build.Keyset, build.Ciphertext]) { + for (const cls of [ + build.Cipher, + build.Keyset, + build.Ciphertext, + build.Json, + ]) { expect(Object.isFrozen(cls)).toBe(true) expect(Object.isFrozen(cls.prototype)).toBe(true) } diff --git a/languages/typescript/packages/recipher-js/__tests__/unit/values.test.ts b/languages/typescript/packages/recipher-js/__tests__/unit/values.test.ts new file mode 100644 index 000000000..8192b6d56 --- /dev/null +++ b/languages/typescript/packages/recipher-js/__tests__/unit/values.test.ts @@ -0,0 +1,46 @@ +/** + * The stand-in wrapper classes. The stand-ins replace the addon's classes + * when the addon did not load. None of these tests needs the addon. + */ +import { describe, expect, it } from 'vitest' +import { sdkError } from '../../src/error' +import { standInWrapper } from '../../src/values' + +const NAMES = ['RcDate', 'RcTimestamp', 'RcDecimal', 'RcUuid'] as const +const LOAD_ERROR = sdkError('recipher_js::load', 'the addon did not load') + +describe('a stand-in wrapper class', () => { + it('has the name of the class it stands in for', () => { + for (const name of NAMES) { + expect(standInWrapper(name, LOAD_ERROR).name).toBe(name) + } + }) + + it('returns the load error from from(..), for any argument', () => { + const RcDate = standInWrapper('RcDate', LOAD_ERROR) + expect(RcDate.from('2026-11-23').err()).toBe(LOAD_ERROR) + // @ts-expect-error: `from` takes a string. + expect(RcDate.from(20261123).err()).toBe(LOAD_ERROR) + }) + + it('throws a TypeError that names from(..) for new', () => { + const RcDate = standInWrapper('RcDate', LOAD_ERROR) + const cls = RcDate as unknown as new (text: unknown) => object + for (const argument of ['2026-11-23', 20261123, undefined]) { + expect(() => new cls(argument)).toThrow( + new TypeError( + 'RcDate has no public constructor. Make one with RcDate.from(text), which returns a Result.', + ), + ) + } + }) + + it('is frozen, with a frozen prototype, and has no instance', () => { + const RcUuid = standInWrapper('RcUuid', LOAD_ERROR) + expect(Object.isFrozen(RcUuid)).toBe(true) + expect(Object.isFrozen(RcUuid.prototype)).toBe(true) + expect({ + value: '123e4567-e89b-12d3-a456-426614174000', + }).not.toBeInstanceOf(RcUuid) + }) +}) diff --git a/languages/typescript/packages/recipher-js/crate/Cargo.toml b/languages/typescript/packages/recipher-js/crate/Cargo.toml index b79575a18..57a50d5b0 100644 --- a/languages/typescript/packages/recipher-js/crate/Cargo.toml +++ b/languages/typescript/packages/recipher-js/crate/Cargo.toml @@ -26,10 +26,11 @@ testing = ["stack-encrypt/test-support"] stack-encrypt = { path = "../../../../../packages/stack-encrypt", default-features = false, features = ["dynamic", "http"] } # The auth strategy the detected cipher's key source is generic over. stack-auth = { path = "../../../../../packages/stack-auth", default-features = false, features = ["http"] } -# napi-rs 3, as `recipher-value-napi` is. Its default features load Node-API -# by name at run time (`dyn-symbols`), so the crate's own tests link without -# Node. `napi6` for BigInt and property enumeration, which vitaminc's walk -# needs; `tokio_rt` runs the engine's futures on napi's runtime. +# napi-rs 3, as `recipher-value-napi` is. The default features of napi-rs +# load Node-API by name at run time (`dyn-symbols`), so the crate's own tests +# link without Node. The value bridge's walk needs `napi6`, for BigInt and +# property enumeration. `tokio_rt` runs the engine's futures on napi's +# runtime. napi = { version = "3", features = ["napi6", "tokio_rt", "serde-json"] } napi-derive = "3" # The value bridge: every JavaScript value is read and built through it. @@ -46,10 +47,19 @@ miette = "7.5.0" thiserror = "1.0.56" # For the structured fields of an engine error (`ErrorPayload::payload`). serde_json = "1" +# Deserialises the kind passed to `Ciphertext.fromBytes`. The addon reads +# the kind from its frame, through the frame's serde support. +serde = { version = "1", features = ["derive"] } [dev-dependencies] stack-encrypt = { path = "../../../../../packages/stack-encrypt", default-features = false, features = ["dynamic", "http", "test-support"] } tokio = { version = "1", features = ["rt", "macros"] } +# The values the engine-interop tests encrypt through the engine's typed API, +# and the types the counting key source names. The versions the engine +# resolves. +jiff = { version = "1.0.0", default-features = false } +rust_decimal = { version = "1", default-features = false } +uuid = "1" [build-dependencies] napi-build = "2" diff --git a/languages/typescript/packages/recipher-js/crate/src/cipher.rs b/languages/typescript/packages/recipher-js/crate/src/cipher.rs index 30cd68af6..e8e5208f1 100644 --- a/languages/typescript/packages/recipher-js/crate/src/cipher.rs +++ b/languages/typescript/packages/recipher-js/crate/src/cipher.rs @@ -13,17 +13,21 @@ use std::sync::Arc; -use napi::bindgen_prelude::{JavaScriptClassExt, JsValue, Object, PromiseRaw, Unknown}; -use napi::Env; +use napi::bindgen_prelude::{ + FromNapiValue, JavaScriptClassExt, JsValue, Object, PromiseRaw, ToNapiValue, Unknown, +}; +use napi::{Env, ValueType}; use napi_derive::napi; -use stack_encrypt::dynamic::{frame::OwnedFrame, value, ValueKind}; +use stack_encrypt::dynamic::{frame::OwnedFrame, value, Found, Reason, ValueKind}; use stack_encrypt::kms::{DataKeySource, IndexKeySource, StackKms}; use stack_encrypt::{CipherRef, DecryptFrom, KeysetCipher, Pending, StackCipher}; +use vitaminc_aead::plaintext::SealedNull; use vitaminc_protected::OpaqueDebug; -use crate::ciphertext::Ciphertext; +use crate::ciphertext::{Ciphertext, Declared}; use crate::error::{Error, RecipherErrorFields}; use crate::js; +use crate::json::Json; use crate::outcome::{not_made, refused, spawn, Outcome}; /// The engine's cipher, with the key source it was built with. A napi class @@ -119,9 +123,17 @@ impl Cipher { /// Decrypts a ciphertext made under any of this cipher's keysets. The /// value decrypts as the type it was encrypted as. /// + /// An array of ciphertexts returns an array of values, in the same + /// order. The cipher makes one key request for each keyset the + /// ciphertexts were made under. + /// /// Resolves to an `Err` with the code `recipher_js::not_a_ciphertext` - /// when the argument is not a `Ciphertext`. The promise does not reject. - #[napi(ts_type = "(ciphertext: Ciphertext): Promise>")] + /// when the argument, or an element of the array, is not a + /// `Ciphertext`. The promise does not reject. + #[napi( + ts_type = "(ciphertext: Ciphertext): Promise> +decrypt(ciphertexts: readonly Ciphertext[]): Promise>" + )] pub fn decrypt<'e>( &self, env: &'e Env, @@ -139,47 +151,111 @@ impl Cipher { #[napi] impl Keyset { - /// Encrypts a string as one ciphertext with its own data key, with no + /// Encrypts a value as one ciphertext with its own data key, with no /// context. A context is a value that a ciphertext is bound to, and /// decrypting needs the same context. /// - /// Resolves to an `Err` with the code `recipher_js::not_a_string` when - /// the value is not a string. The promise does not reject. + /// An array of values returns an array of ciphertexts, in the same + /// order. The keyset makes one key request for the whole array, however + /// long it is. A key request is one request to ZeroKMS for data keys. If + /// any value is refused, the whole array fails, before any request. + /// + /// With no options, a value's type sets how it is encrypted. The + /// package's README lists the mapping of JavaScript types. A `Json` from + /// `json(..)` is encrypted as a JSON document. + /// + /// `{ kind }` declares the kind of the value, such as + /// `{ kind: kinds.uint64 }`. The value is stored as that kind, and its + /// ciphertext decrypts as that kind. A number converts to the kind when + /// the conversion is exact, as it does for a record's field: `34` + /// declared as `uint64` decrypts as `34n`. A value that does not convert + /// exactly is refused. For an integer kind, a whole `number` outside the + /// safe range is refused with the code `recipher_js::unsafe_integer`. + /// The safe range is 2^53 - 1 either side of zero. Pass a `bigint` + /// instead. For an array of values, the kind applies to each value. + /// Options that are not `{ kind }`, `null` included, are an `Err` with + /// the code `recipher_js::options`. + /// + /// `{ kind: nullable(..) }` declares a kind that also takes `null`, such + /// as `{ kind: nullable(kinds.int64) }`. A value that is not `null` + /// encrypts as the plain kind would. A `null` of a fixed-width kind is + /// given to the engine as a typed null of that kind. The engine does + /// not encrypt a typed null as one value yet, so today that `null` is an + /// `Err` with the code `recipher_js::null_value`. + /// + /// A value that cannot be encrypted resolves to an `Err`. For example, a + /// plain object is an `Err` with the code `recipher_js::plain_object`. + /// `null` with no kind, with a kind that is not `nullable(..)`, or with + /// `nullable(..)` of a variable-width kind such as `kinds.string`, is an + /// `Err` with the code `recipher_js::null_value`. Store a value that is + /// not there as a database `NULL`. The promise does not reject. #[napi( - ts_args_type = "value: string", - ts_return_type = "Promise, RecipherError>>" + ts_type = "(value: V): Promise>, RecipherError>> +encrypt(values: readonly V[]): Promise>[], RecipherError>> +encrypt>(value: V, options: EncryptOptions): Promise>, RecipherError>> +encrypt>(values: readonly V[], options: EncryptOptions): Promise>[], RecipherError>>" )] pub fn encrypt<'e>( &self, env: &'e Env, value: Unknown<'_>, + options: Unknown<'_>, ) -> napi::Result>> { - let value = match js::read(env, value).and_then(a_string) { - Ok(value) => value, + let declared = match crate::ciphertext::declared_kind(env, options) { + Ok(declared) => declared, Err(error) => return refused(env, error), }; + let (many, values) = match js::elements(env, value) { + Some(Ok(elements)) => (true, elements), + Some(Err(error)) => return refused(env, error), + None => (false, vec![value]), + }; + let mut sealable = Vec::with_capacity(values.len()); + let mut opens_as = Vec::with_capacity(values.len()); + for value in values { + match one_value(env, value, declared) { + Ok((value, kind)) => { + sealable.push(value); + opens_as.push(kind); + } + Err(error) => return refused(env, error), + } + } let engine = Arc::clone(&self.engine); spawn( env, async move { with_engine!(&*engine, |cipher| { - seal(&cipher.default_keyset(), vec![value]).await + seal(&cipher.default_keyset(), sealable).await }) }, - |env, mut sealed| match sealed.pop() { - Some(sealed) => Ok(Ciphertext::new(sealed) - .into_instance(env) - .map_err(not_made)? - .to_unknown()), - None => Err(Error::NoResult.into()), + move |env, sealed| { + let mut instances = sealed + .into_iter() + .zip(opens_as) + .map(|(sealed, opens_as)| { + Ok(Ciphertext::new(sealed, opens_as) + .into_instance(env) + .map_err(not_made)? + .to_unknown()) + }) + .collect::>>()?; + if many { + return instances.into_unknown(env).map_err(not_made); + } + instances.pop().ok_or_else(|| Error::NoResult.into()) }, ) } - /// Decrypts a ciphertext made under this keyset. A ciphertext of another - /// keyset fails with the code `stack_encrypt::foreign_keyset`, before - /// any key is requested. The promise does not reject. - #[napi(ts_type = "(ciphertext: Ciphertext): Promise>")] + /// Decrypts a ciphertext made under this keyset, or an array of them. A + /// ciphertext of another keyset fails with the code + /// `stack_encrypt::foreign_keyset`, before any key is requested. The + /// promise does not reject. + #[napi( + ts_type = "(ciphertext: Ciphertext): Promise> +decrypt(ciphertexts: readonly Ciphertext[]): Promise>" + )] pub fn decrypt<'e>( &self, env: &'e Env, @@ -265,24 +341,50 @@ pub(crate) enum Confined { ToDefault, } -/// Decrypts a ciphertext, for `cipher.decrypt` and `keyset.decrypt`. +/// Decrypts a ciphertext, or an array of them, for `cipher.decrypt` and +/// `keyset.decrypt`. fn open<'e>( env: &'e Env, engine: &Arc, - ciphertext: Unknown<'_>, + value: Unknown<'_>, confined: Confined, ) -> napi::Result>> { - let Some(ciphertext) = Ciphertext::of(env, ciphertext) else { - return refused(env, Error::NotACiphertext.into()); + let (many, values) = match js::elements(env, value) { + Some(Ok(elements)) => (true, elements), + Some(Err(error)) => return refused(env, error), + None => (false, vec![value]), }; - let sealed = vec![ciphertext.sealed().clone()]; + let mut ciphertexts = Vec::with_capacity(values.len()); + for value in values { + match Ciphertext::of(env, value) { + Some(ciphertext) => ciphertexts.push(ciphertext), + None => return refused(env, Error::NotACiphertext.into()), + } + } + let sealed = ciphertexts + .iter() + .map(|ciphertext| ciphertext.sealed().clone()) + .collect(); let engine = Arc::clone(engine); spawn( env, - async move { open_in(&engine, sealed, confined).await }, - |env, mut opened| match opened.pop() { - Some(value) => js::build(env, value), - None => Err(Error::NoResult.into()), + async move { + let opened = open_in(&engine, sealed, confined).await?; + opened + .into_iter() + .zip(&ciphertexts) + .map(|(value, ciphertext)| ciphertext.opened(value)) + .collect::>>() + }, + move |env, opened| { + let mut values = opened + .into_iter() + .map(|value| js::build_opened(env, value)) + .collect::>>()?; + if many { + return values.into_unknown(env).map_err(not_made); + } + values.pop().ok_or_else(|| Error::NoResult.into()) }, ) } @@ -300,38 +402,133 @@ pub(crate) async fn open_in( }) } -/// Returns `value` when it is one string. This build only encrypts strings. +/// One value to encrypt, as the engine's `dynamic::value::encrypt` takes +/// it: a frame, and the kind declared for the value. +/// +/// The frame is plaintext. It wipes its bytes when it is dropped, and +/// `Debug` hides it. +#[derive(OpaqueDebug)] +pub(crate) struct Sealable { + /// The value, as the bridge read it. A `Json`'s document is its JSON + /// text. + pub(crate) value: OwnedFrame, + /// The kind declared for the value. `None` stores the value as the + /// bridge read it. Whether the kind is nullable decides only the help of + /// a refused null: the engine reads the kind alone. + pub(crate) kind: Option, +} + +/// Returns one value to encrypt, and the kind its ciphertext decrypts as. +/// +/// `declared` is the kind the caller declared, if any. A value with a +/// declared kind decrypts as that kind. A `Json`'s document is declared as +/// JSON, and decrypts as JSON. Any other value with no declared kind +/// decrypts as the type it was encrypted as. /// /// # Errors /// -/// Returns `recipher_js::not_a_string` for any other value. -pub(crate) fn a_string(value: OwnedFrame) -> Outcome { - if value.frame().kind() == Some(ValueKind::String) { - Ok(value) - } else { - Err(Error::NotAString.into()) +/// Returns `recipher_js::json_kind` for a `Json` declared as another kind, +/// and for `json` declared for a value that is not a `Json`. The engine +/// would take a string declared as `json` as the text of a document, so a +/// string could become a document without `json(..)`. +/// +/// Returns `recipher_js::null_value` for a `null`, unless the kind declared +/// is `nullable(..)` of a fixed-width kind. That `null` becomes a typed null +/// of the kind, as a record field with `"null": "sealed"` stores one, and +/// the engine decides whether to encrypt it. +/// +/// Returns `recipher_js::unsafe_integer` for a whole `number` outside the +/// safe range declared as an integer kind. The engine converts the +/// `number` exactly, but the `number` may not hold the digits that were +/// written: `12345678901234567890` is the `number` `12345678901234567168`. +/// `json(..)` refuses the same numbers. +fn one_value( + env: &Env, + value: Unknown<'_>, + declared: Option, +) -> Outcome<(Sealable, Option)> { + let kind = declared.map(|declared| declared.kind); + if let Some(text) = Json::of(env, value) { + if kind.is_some_and(|kind| kind != ValueKind::Json) { + return Err(Error::JsonKind.into()); + } + let declared = declared.unwrap_or(Declared::plain(ValueKind::Json)); + let sealable = Sealable { + value: text?, + kind: Some(declared), + }; + return Ok((sealable, Some(declared))); + } + if value.get_type().ok() == Some(ValueType::Null) { + let sealable = Sealable { + value: typed_null(declared).ok_or_else(|| Error::null_value(declared))?, + kind: declared, + }; + return Ok((sealable, declared)); + } + if kind == Some(ValueKind::Json) { + return Err(Error::JsonKind.into()); + } + if kind.is_some_and(crate::ciphertext::integer) && unsafe_number(value) { + return Err(Error::UnsafeInteger.into()); + } + let sealable = Sealable { + value: js::read(env, value)?, + kind: declared, + }; + Ok((sealable, declared)) +} + +/// Returns the null to give the engine for a `null` declared as `declared`: +/// a typed null of the kind, as long as a value of it, when the kind is +/// `nullable(..)` of a fixed-width kind. A boolean's null is the plain +/// null, which is already as long as a boolean. Returns `None` for any +/// other `null`, which is refused. +pub(crate) fn typed_null(declared: Option) -> Option { + let declared = declared.filter(|declared| declared.nullable)?; + match declared.kind.sealed_null()? { + SealedNull::Typed(ty) => Some(OwnedFrame::typed_null(ty)), + SealedNull::Plain => Some(OwnedFrame::null()), } } -/// Encrypts strings under `keyset`, with the engine's +/// 2^53 - 1, JavaScript's `Number.MAX_SAFE_INTEGER`. A `number` stores +/// every whole number up to it exactly. +const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0; + +/// Returns whether `value` is a finite `number` outside the safe range, +/// 2^53 - 1 either side of zero. Every such `number` is whole. +fn unsafe_number(value: Unknown<'_>) -> bool { + if value.get_type().ok() != Some(ValueType::Number) { + return false; + } + f64::from_unknown(value) + .is_ok_and(|number| number.is_finite() && number.abs() > MAX_SAFE_INTEGER) +} + +/// Encrypts values under `keyset`, with the engine's /// `dynamic::value::encrypt`. Each value becomes one ciphertext with its own -/// data key. Rust's `keyset.decrypt::` decrypts each ciphertext. The -/// function merges the calls, so all the values use one key request. +/// data key. Rust's typed `keyset.decrypt` decrypts each ciphertext. The +/// function merges the calls, so all the values use one key request, +/// however many there are. /// -/// The engine checks each value again. The engine refuses a value that is -/// not one string with its own error, before any key request. +/// The engine checks each value before any key request. If it refuses one +/// value, no value is encrypted. pub(crate) async fn seal( keyset: &KeysetCipher<'_, K>, - values: Vec, + values: Vec, ) -> Outcome> where K: DataKeySource + IndexKeySource + Sync + 'static, { let calls = values .iter() - .map(|value| value::encrypt(keyset, value.frame(), Some(ValueKind::String))) - .collect::, _>>() - .map_err(|error| RecipherErrorFields::engine(&error))?; + .map(|sealable| { + let kind = sealable.kind.map(|declared| declared.kind); + value::encrypt(keyset, sealable.value.frame(), kind) + .map_err(|error| refusal(&error, sealable.kind)) + }) + .collect::>>()?; // The engine has read every value. `drop` wipes the frames, so no value // stays in a frame during the key request. drop(values); @@ -340,14 +537,44 @@ where .map_err(|error| RecipherErrorFields::engine(&error)) } +/// The help of a value that does not convert exactly to its declared kind. +/// The engine's error has one help for every refusal of one value, and that +/// help is about what one ciphertext contains. +const CONVERSION_HELP: &str = "Pass a value of the declared kind, or one that converts to it exactly, such as a whole `number` for an integer kind."; + +/// Returns the failure for a value that the engine refused to encrypt as +/// one ciphertext. `declared` is the kind declared for the value, if any. +/// +/// For three values, the SDK's own error says what to do in JavaScript: +/// +/// - an array inside an array: `recipher_js::not_a_scalar`; +/// - a plain object: `recipher_js::plain_object`; +/// - `null`: `recipher_js::null_value`. +/// +/// Any other refusal keeps the engine's code and fields. A value that does +/// not convert to the declared kind gets [`CONVERSION_HELP`] in place of +/// the engine's help. +fn refusal( + error: &stack_encrypt::dynamic::Error, + declared: Option, +) -> RecipherErrorFields { + match (error.reason(), error.found()) { + (Some(Reason::NotAScalar), Some(Found::Kind(ValueKind::Array))) => Error::NotAScalar.into(), + (Some(Reason::NotAScalar), Some(Found::Kind(ValueKind::Object))) => { + Error::PlainObject.into() + } + (Some(Reason::NotAScalar), Some(Found::Null)) => Error::null_value(declared).into(), + (Some(Reason::FieldType), _) => RecipherErrorFields { + help: Some(CONVERSION_HELP.to_owned()), + ..RecipherErrorFields::engine(error) + }, + _ => RecipherErrorFields::engine(error), + } +} + /// Decrypts ciphertexts through `cipher`: a cipher, or one keyset of it. /// The function makes one key request for each keyset the ciphertexts /// were made under. -/// -/// Each value comes back in a frame, as it was encrypted. A call has no -/// kind to check at run time, because the type of a `Ciphertext` exists -/// only in TypeScript. So this function uses the engine's typed decrypt -/// into frames. That decrypt checks no kind. pub(crate) async fn unseal<'c, K>( cipher: impl Into>, sealed: Vec, @@ -364,25 +591,6 @@ where mod tests { use super::*; - #[test] - fn a_string_is_taken_and_another_value_is_not() { - assert!( - a_string(OwnedFrame::of("text").unwrap()).is_ok(), - "a string is taken" - ); - for other in [ - OwnedFrame::of(5i64).unwrap(), - OwnedFrame::of(vec!["a", "b"]).unwrap(), - OwnedFrame::null(), - ] { - let refused = a_string(other).unwrap_err(); - assert_eq!( - refused.code, "recipher_js::not_a_string", - "a value that is not a string is refused" - ); - } - } - #[test] fn a_build_without_the_test_cipher_says_how_to_get_one() { let error = RecipherErrorFields::from(Error::NoTesting); diff --git a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs index 913c72f28..c6d16dbef 100644 --- a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs +++ b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs @@ -7,32 +7,76 @@ use napi::bindgen_prelude::{ ClassInstance, FromNapiValue, JavaScriptClassExt, JsValue, Object, Uint8Array, Uint8ArraySlice, Unknown, }; -use napi::Env; +use napi::{Env, ValueType}; use napi_derive::napi; +use serde::{Deserialize, Deserializer}; +use stack_encrypt::dynamic::frame::OwnedFrame; +use stack_encrypt::dynamic::{read, ValueKind}; +use stack_encrypt::json::JsonPlaintext; use vitaminc_protected::OpaqueDebug; use crate::error::{Error, RecipherErrorFields}; -use crate::outcome::{failed, not_made, settle}; +use crate::js; +use crate::outcome::{failed, not_made, settle, Outcome}; /// One encrypted value: the engine's opaque ciphertext of the whole value, /// with its own data key. A data key is the key that encrypts one value. /// /// The ciphertext's bytes are the engine's format for an encrypted value. -/// The Rust and Go SDKs write the same bytes. `toString()` and Node's +/// Rust's `keyset.encrypt` writes the same bytes. `toString()` and Node's /// `inspect` hide the bytes, because the object has no own properties. /// -/// The SDK uses a class rather than plain bytes so that `decrypt` can tell a -/// ciphertext from any other value. +/// The SDK uses a class rather than plain bytes for two reasons. First, +/// `decrypt` can tell a ciphertext from any other value. Second, the class +/// records the type the value decrypts as. A JSON document is encrypted as +/// its JSON text, and nothing in the bytes says that it is JSON. #[napi] #[derive(Clone, OpaqueDebug)] pub struct Ciphertext { sealed: stack_encrypt::Ciphertext, + opens_as: Option, +} + +/// A kind as the package's `kinds` and `nullable(..)` write it: the +/// engine's kind, and whether a null is allowed in its place. +/// +/// A plain kind, such as `kinds.int64`, is not nullable: a stored null read +/// as it is refused, as Rust's `decrypt::` refuses one. `nullable(..)` +/// of a kind is nullable: a stored null reads as `null`, as Rust's +/// `decrypt::>` reads one as `None`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Declared { + /// The engine's kind. + pub(crate) kind: ValueKind, + /// Whether a null is allowed in place of a value of the kind. + pub(crate) nullable: bool, +} + +impl Declared { + /// Returns `kind`, not nullable. + pub(crate) fn plain(kind: ValueKind) -> Self { + Self { + kind, + nullable: false, + } + } +} + +/// A decrypted value, before the addon builds it in JavaScript. Both forms +/// are plaintext. Both are wiped when they drop. +#[derive(OpaqueDebug)] +pub(crate) enum Opened { + /// A value of the engine's value model, in a frame. + Value(OwnedFrame), + /// A JSON document. + Document(JsonPlaintext), } impl Ciphertext { - /// Wraps `sealed`. - pub(crate) fn new(sealed: stack_encrypt::Ciphertext) -> Self { - Self { sealed } + /// Wraps `sealed`. When `opens_as` is `None`, the ciphertext decrypts as + /// the type it was encrypted as. Otherwise it decrypts as that kind. + pub(crate) fn new(sealed: stack_encrypt::Ciphertext, opens_as: Option) -> Self { + Self { sealed, opens_as } } /// Returns the engine's ciphertext. @@ -50,27 +94,64 @@ impl Ciphertext { .ok() .map(|instance| Ciphertext::clone(&instance)) } + + /// Returns a decrypted value as the kind this ciphertext decrypts as. + /// A null decrypts as null when the kind is nullable, as + /// `nullable(kinds.int64)` is. + /// + /// # Errors + /// + /// Returns `recipher_js::opened_null` for a null with a kind that is not + /// nullable. Returns `recipher_js::opened_type` for a value encrypted as + /// another type. Returns `recipher_js::not_a_document` for a JSON kind + /// whose value is not a JSON document. + pub(crate) fn opened(&self, value: OwnedFrame) -> Outcome { + opened_as(self.opens_as, value) + } } #[napi] impl Ciphertext { - /// Reads a ciphertext from stored bytes, a `Uint8Array` or a `Buffer`. - /// This method checks only the shape of the bytes. Decrypting is what - /// checks that they are authentic. A failure does not quote the bytes. + /// Reads a ciphertext from stored bytes. The bytes are a `Uint8Array` + /// or a `Buffer`. This method checks only the format of the bytes. + /// Decrypting checks that the bytes are authentic. A failure does not + /// quote the bytes. + /// + /// A kind names the type that a ciphertext decrypts to. To decrypt the + /// value as one kind, pass that kind, such as `kinds.string`. `decrypt` + /// then refuses a value that was encrypted as another type. + /// `kinds.json` decrypts a JSON document. A kind from `kinds` refuses a + /// stored null, with the code `recipher_js::opened_null`. To read a + /// value that may be absent, pass `nullable(..)` of the kind, such as + /// `nullable(kinds.int64)`. A stored null then decrypts as `null`. + /// + /// With no kind, the value decrypts as the type it was encrypted as. A + /// JSON document then decrypts as its JSON text. `JSON.parse` of that + /// text loses the digits of an integer outside a `number`'s safe range. /// - /// Returns an `Err` with the code `recipher_js::not_bytes` when the - /// argument is not a `Uint8Array`. Does not throw. + /// This method does not throw. The method returns an `Err` with one of + /// two codes: + /// + /// - `recipher_js::not_bytes`, when the bytes are not a `Uint8Array`; + /// - `recipher_js::not_a_kind`, when the kind is not one of `kinds`, or + /// `nullable(..)` of one. #[napi( - ts_args_type = "bytes: Uint8Array", - ts_return_type = "Result" + ts_type = "(bytes: Uint8Array, kind: K): Result>, RecipherError> +static fromBytes(bytes: Uint8Array): Result" )] - pub fn from_bytes<'e>(env: &'e Env, bytes: Unknown<'_>) -> napi::Result> { + pub fn from_bytes<'e>( + env: &'e Env, + bytes: Unknown<'_>, + kind: Option>, + ) -> napi::Result> { let Some(bytes) = bytes_of(bytes) else { return failed(env, Error::NotBytes.into()); }; - let outcome = stack_encrypt::Ciphertext::from_bytes(&bytes) - .map(Ciphertext::new) - .map_err(|error| RecipherErrorFields::engine(&error)); + let outcome = kind_of(env, kind).and_then(|opens_as| { + stack_encrypt::Ciphertext::from_bytes(&bytes) + .map(|sealed| Ciphertext::new(sealed, opens_as)) + .map_err(|error| RecipherErrorFields::engine(&error)) + }); settle(env, outcome, |env, ciphertext| { Ok(ciphertext .into_instance(env) @@ -93,13 +174,204 @@ impl Ciphertext { } } +/// A kind, in the form the package writes it: `{ name: "string" }` from +/// `kinds`, or `{ name: "string", nullable: true }` from `nullable(..)`. +/// Any other key is refused, so a misspelt `nullable` is never read as a +/// kind that is not nullable. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct KindArgument { + name: String, + #[serde(default)] + nullable: Nullable, +} + +/// The `nullable` key of a kind: absent, or `true`. `nullable(..)` writes +/// `true`, and nothing in the package writes any other value. So `false`, +/// `null`, and any other value are refused. +#[derive(Default)] +struct Nullable(bool); + +impl<'de> Deserialize<'de> for Nullable { + fn deserialize>(deserializer: D) -> Result { + if bool::deserialize(deserializer)? { + Ok(Self(true)) + } else { + Err(serde::de::Error::custom("`nullable` is `true` or absent")) + } + } +} + +/// The shape of the options of `keyset.encrypt`: `{ kind }`. Any other key +/// is refused, so an option that this version does not have is never +/// ignored. The kind is read after the shape, so a kind that is not one is +/// refused as a kind, not as options. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct EncryptOptions { + #[serde(rename = "kind")] + _kind: serde::de::IgnoredAny, +} + +/// The kind in the options of `keyset.encrypt`, read once the options have +/// the shape [`EncryptOptions`] checks. +#[derive(Deserialize)] +struct OptionsKind { + kind: KindArgument, +} + +/// Returns `value`, or `None` when `value` is absent or `undefined`. +fn given(value: Option>) -> Option> { + value.filter(|value| value.get_type().ok() != Some(ValueType::Undefined)) +} + +/// Returns the kind that `value` names, or `None` when `value` is absent or +/// `undefined`. +fn kind_of(env: &Env, value: Option>) -> Outcome> { + let Some(value) = given(value) else { + return Ok(None); + }; + let frame = js::read(env, value).map_err(|_| Error::NotAKind)?; + let argument: KindArgument = + stack_encrypt::dynamic::frame::serde::from_slice(frame.frame().as_bytes()) + .map_err(|_| Error::NotAKind)?; + named(&argument).map(Some) +} + +/// Returns the kind that the options of `keyset.encrypt` declare, or +/// `None` when there are no options. +/// +/// # Errors +/// +/// - `recipher_js::options`, when the options are not an object whose only +/// key is `kind`, `null` included; +/// - `recipher_js::not_a_kind`, when the kind is not one of `kinds`, or +/// `nullable(..)` of one. +pub(crate) fn declared_kind(env: &Env, value: Unknown<'_>) -> Outcome> { + // A missing argument reaches the addon as `undefined`. `null` is read, + // and refused like any other value that is not `{ kind }`. + let Some(value) = given(Some(value)) else { + return Ok(None); + }; + let frame = js::read(env, value).map_err(|_| Error::Options)?; + let bytes = frame.frame().as_bytes(); + stack_encrypt::dynamic::frame::serde::from_slice::(bytes) + .map_err(|_| Error::Options)?; + let options: OptionsKind = + stack_encrypt::dynamic::frame::serde::from_slice(bytes).map_err(|_| Error::NotAKind)?; + named(&options.kind).map(Some) +} + +/// Returns the kind that `argument` names, when it is one of `kinds`, or +/// `nullable(..)` of one. +fn named(argument: &KindArgument) -> Outcome { + let kind = argument + .name + .parse::() + .ok() + .filter(|kind| readable(*kind)) + .ok_or(Error::NotAKind)?; + Ok(Declared { + kind, + nullable: argument.nullable.0, + }) +} + +/// Returns whether a stored ciphertext can be read as `kind`: whether +/// `kind` is one of the package's `kinds`. +/// +/// The engine has names for more kinds than the package exports. The list +/// here is the kinds a ciphertext decrypts as, so a kind the engine adds is +/// refused until the package has it. A suite that loads the addon checks +/// the list against `kinds`. +fn readable(kind: ValueKind) -> bool { + integer(kind) + || matches!( + kind, + ValueKind::String + | ValueKind::Bool + | ValueKind::Float32 + | ValueKind::Float64 + | ValueKind::Decimal + | ValueKind::Date + | ValueKind::Timestamp + | ValueKind::Bytes + | ValueKind::Json + ) +} + +/// Returns whether `kind` is an integer kind. +pub(crate) fn integer(kind: ValueKind) -> bool { + matches!( + kind, + ValueKind::Int8 + | ValueKind::Int16 + | ValueKind::Int32 + | ValueKind::Int64 + | ValueKind::Int128 + | ValueKind::UInt8 + | ValueKind::UInt16 + | ValueKind::UInt32 + | ValueKind::UInt64 + | ValueKind::UInt128 + ) +} + +/// Returns whether `kind` is fixed-width: whether every value of it takes +/// the same number of bytes. A null of such a kind can be padded to look +/// like a value of it. The engine says which kinds those are. Of the +/// package's kinds, they are the ones `FixedWidthName` in `src/kinds.ts` +/// names, and a test checks the two lists agree. +pub(crate) fn fixed_width(kind: ValueKind) -> bool { + kind.sealed_null().is_some() +} + +/// Returns `value` as `kind`. The value is not a null: the caller decides +/// what a null opens as. +/// +/// A value of that kind is returned unchanged. The engine's `read` converts +/// an integer to another integer width, or a float to another float width, +/// when the conversion is exact. Any other value is refused. +fn as_kind(kind: ValueKind, value: OwnedFrame) -> Outcome { + let refused = || RecipherErrorFields::from(Error::OpenedType { kind }); + let opened = value.frame().kind(); + if opened == Some(kind) { + return Ok(value); + } + let float = |kind| matches!(kind, ValueKind::Float32 | ValueKind::Float64); + let same_family = opened + .is_some_and(|opened| (integer(opened) && integer(kind)) || (float(opened) && float(kind))); + if !same_family { + return Err(refused()); + } + read(kind, &value).map_err(|_| refused()) +} + +/// Returns a decrypted value as `opens_as`, for [`Ciphertext::opened`]. +fn opened_as(opens_as: Option, value: OwnedFrame) -> Outcome { + let Some(declared) = opens_as else { + return Ok(Opened::Value(value)); + }; + if value.frame().is_null() { + return if declared.nullable { + Ok(Opened::Value(value)) + } else { + Err(Error::OpenedNull.into()) + }; + } + match declared.kind { + ValueKind::Json => crate::json::opened(&value).map(Opened::Document), + kind => as_kind(kind, value).map(Opened::Value), + } +} + /// Returns a copy of the bytes of a `Uint8Array`, or `None` for any other /// value. A `Buffer` is a `Uint8Array`. /// -/// The function reads the bytes as a borrowed slice. That is how vitaminc, -/// CipherStash's cryptography library, reads bytes. napi's owned -/// `Uint8Array` is not used. When it refuses a typed array of another -/// element type, it still keeps a reference to that array. +/// The function reads the bytes as a borrowed slice. That is how the value +/// bridge reads bytes. This function does not use napi's owned +/// `Uint8Array`. When that type refuses a typed array of another element +/// type, it still keeps a reference to that array. pub(crate) fn bytes_of(value: Unknown<'_>) -> Option> { if !value.is_typedarray().unwrap_or(false) { return None; @@ -108,3 +380,158 @@ pub(crate) fn bytes_of(value: Unknown<'_>) -> Option> { .ok() .map(|bytes| bytes.to_vec()) } + +#[cfg(test)] +mod tests { + use super::{as_kind, fixed_width, opened_as, readable, Declared, Opened}; + use stack_encrypt::dynamic::frame::OwnedFrame; + use stack_encrypt::dynamic::ValueKind; + use vitaminc_aead::plaintext::{FixedType, Width}; + + #[test] + fn a_ciphertext_is_read_as_a_kind_the_package_exports_and_no_other() { + for name in [ + "string", + "bool", + "int8", + "int16", + "int32", + "int64", + "int128", + "uint8", + "uint16", + "uint32", + "uint64", + "uint128", + "float32", + "float64", + "decimal", + "date", + "timestamp", + "bytes", + "json", + ] { + assert!(readable(name.parse::().unwrap()), "{name}"); + } + // The engine names these kinds, and no ciphertext decrypts as one. + for kind in [ValueKind::Uuid, ValueKind::Array, ValueKind::Object] { + assert!(!readable(kind), "{kind}"); + } + } + + #[test] + fn an_integer_opens_at_any_width_that_holds_it() { + let opened = as_kind(ValueKind::Int64, OwnedFrame::of(5i8).unwrap()).unwrap(); + assert_eq!(opened.frame(), OwnedFrame::of(5i64).unwrap().frame()); + assert!(as_kind(ValueKind::UInt8, OwnedFrame::of(300i16).unwrap()).is_err()); + } + + #[test] + fn a_value_of_another_type_is_refused_as_not_opened() { + let refused = as_kind(ValueKind::Int64, OwnedFrame::of(5.0f64).unwrap()).unwrap_err(); + assert_eq!(refused.code, "recipher_js::opened_type"); + assert!(as_kind(ValueKind::String, OwnedFrame::of(true).unwrap()).is_err()); + assert!(as_kind(ValueKind::String, OwnedFrame::of("x").unwrap()).is_ok()); + } + + /// Returns whether `value` opened as a null. + fn null(opened: Opened) -> bool { + matches!(opened, Opened::Value(value) if value.frame().is_null()) + } + + #[test] + fn a_null_opens_as_null_for_a_nullable_kind_of_any_width() { + let typed = || OwnedFrame::typed_null(FixedType::plain(Width::I64).unwrap()); + // A stored null can exist for any type: Rust's + // `encrypt_tree(None::)` writes one. + for kind in [ + ValueKind::Int64, + ValueKind::UInt8, + ValueKind::Bool, + ValueKind::Float64, + ValueKind::Decimal, + ValueKind::Date, + ValueKind::Timestamp, + ValueKind::String, + ValueKind::Bytes, + ValueKind::Json, + ] { + let declared = Declared { + kind, + nullable: true, + }; + for stored in [OwnedFrame::null(), typed()] { + let opened = opened_as(Some(declared), stored).unwrap(); + assert!(null(opened), "{kind}"); + } + } + } + + #[test] + fn a_null_is_refused_for_a_kind_that_is_not_nullable() { + for kind in [ + ValueKind::Int64, + ValueKind::Bool, + ValueKind::Timestamp, + ValueKind::String, + ValueKind::Json, + ] { + let Err(refused) = opened_as(Some(Declared::plain(kind)), OwnedFrame::null()) else { + panic!("{kind}: a null opened as a kind that is not nullable"); + }; + assert_eq!(refused.code, "recipher_js::opened_null", "{kind}"); + assert!(refused + .help + .is_some_and(|help| help.contains("nullable(kinds.int64)"))); + } + // With no kind, a stored null opens as null, as it always has. + assert!(null(opened_as(None, OwnedFrame::null()).unwrap())); + } + + #[test] + fn the_fixed_width_kinds_are_the_ones_that_fixed_width_name_lists() { + // `FixedWidthName` in `src/kinds.ts` lists the same names, in the + // same order. A null of one of these kinds can be padded to look + // like a value of it. + let fixed: Vec<&str> = ValueKind::ALL + .into_iter() + .filter(|kind| readable(*kind) && fixed_width(*kind)) + .map(ValueKind::name) + .collect(); + assert_eq!( + fixed, + [ + "bool", + "int8", + "int16", + "int32", + "int64", + "int128", + "uint8", + "uint16", + "uint32", + "uint64", + "uint128", + "float32", + "float64", + "decimal", + "date", + "timestamp", + ] + ); + } + + #[test] + fn a_value_opens_the_same_with_a_nullable_kind() { + let declared = Declared { + kind: ValueKind::Int64, + nullable: true, + }; + let Opened::Value(opened) = + opened_as(Some(declared), OwnedFrame::of(5i8).unwrap()).unwrap() + else { + panic!("an int64 opens as a value"); + }; + assert_eq!(opened.frame(), OwnedFrame::of(5i64).unwrap().frame()); + } +} diff --git a/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs b/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs index 5f3a39f0a..3c054472f 100644 --- a/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs +++ b/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs @@ -1,12 +1,24 @@ //! Tests of the crate's encrypt and decrypt against the engine's typed //! Rust API. Each side decrypts the other's ciphertexts. So the tests show -//! that the crate writes the engine's bytes. +//! that the crate writes the engine's bytes, for every type. + +use std::borrow::Cow; +use std::sync::atomic::{AtomicUsize, Ordering}; use stack_encrypt::dynamic::frame::OwnedFrame; -use stack_encrypt::kms::DeterministicSource; -use stack_encrypt::StackCipher; +use stack_encrypt::dynamic::ValueKind; +use stack_encrypt::json::JsonPlaintext; +use stack_encrypt::kms::{ + DataKey, DataKeySource, DataKeyWithTag, DeterministicSource, Error, GenerateKeyPayload, + IdentifiedBy, IndexKey, IndexKeySource, KeySourceKind, OwnIdentity, RetrieveKeyPayload, + UnverifiedContext, +}; +use stack_encrypt::value::{Decimal, Timestamp}; +use stack_encrypt::{Encrypt, StackCipher}; +use uuid::Uuid; -use crate::cipher::{open_in, seal, unseal, Confined, Engine}; +use crate::cipher::{open_in, seal, unseal, Confined, Engine, Sealable}; +use crate::ciphertext::{Ciphertext, Declared, Opened}; const SEED: [u8; 32] = [7; 32]; @@ -18,45 +30,145 @@ async fn engine() -> StackCipher { .unwrap() } -fn one(text: &str) -> OwnedFrame { - OwnedFrame::of(text).unwrap() +/// One value to encrypt with no declared kind, as `keyset.encrypt` reads +/// any value but a `Json`. +fn one(value: P) -> Sealable { + Sealable { + value: OwnedFrame::of(value).unwrap(), + kind: None, + } +} + +/// A document to encrypt, as `keyset.encrypt(json(..))` passes it: its JSON +/// text, declared as `json`. +fn document(text: &str) -> Sealable { + Sealable { + value: crate::json::text_frame(text.as_bytes()).unwrap(), + kind: Some(Declared::plain(ValueKind::Json)), + } } /// Encrypts `values` through the crate, with the test keys. -async fn sdk_seal(values: Vec) -> Vec { +async fn sdk_seal(values: Vec) -> Vec { seal(&engine().await.default_keyset(), values) .await .unwrap() } +/// Decrypts `sealed` through the crate, with the test keys. +async fn sdk_open(sealed: stack_encrypt::Ciphertext) -> OwnedFrame { + unseal(&engine().await, vec![sealed]) + .await + .unwrap() + .remove(0) +} + #[tokio::test] async fn the_engine_opens_what_the_sdk_sealed() { - let sealed = sdk_seal(vec![one("from the sdk")]).await.remove(0); - let stored = stack_encrypt::Ciphertext::from_bytes(&sealed.to_bytes()).unwrap(); - let opened: String = engine() + let keyset = engine().await; + let keyset = keyset.default_keyset(); + let sealed = sdk_seal(vec![one("from the sdk"), one(42i8), one(1.5f64)]).await; + let mut sealed = sealed.into_iter(); + let text: String = keyset.decrypt(sealed.next().unwrap()).await.unwrap(); + // The value bridge reads a `bigint` at its narrowest width. The engine + // decrypts it at any width that fits it. + let int: i64 = keyset.decrypt(sealed.next().unwrap()).await.unwrap(); + let float: f64 = keyset.decrypt(sealed.next().unwrap()).await.unwrap(); + assert_eq!((text.as_str(), int, float), ("from the sdk", 42, 1.5)); +} + +#[tokio::test] +async fn the_sdk_opens_what_the_engine_sealed_of_every_type() { + let cipher = engine().await; + let keyset = cipher.default_keyset(); + let timestamp = Timestamp::new( + "2026-11-23T01:02:03.000000001Z" + .parse::() + .unwrap(), + ) + .unwrap(); + let decimal = Decimal::new(rust_decimal::Decimal::new(150, 2)); + let timestamp_frame = OwnedFrame::of(×tamp).unwrap(); + let decimal_frame = OwnedFrame::of(&decimal).unwrap(); + let cases: Vec<(stack_encrypt::Ciphertext, OwnedFrame)> = vec![ + ( + keyset.encrypt("text".to_owned()).await.unwrap(), + OwnedFrame::of("text").unwrap(), + ), + ( + keyset.encrypt(-7i64).await.unwrap(), + OwnedFrame::of(-7i64).unwrap(), + ), + ( + keyset.encrypt(u64::MAX).await.unwrap(), + OwnedFrame::of(u64::MAX).unwrap(), + ), + ( + keyset.encrypt(vec![0u8, 255]).await.unwrap(), + OwnedFrame::of(vec![0u8, 255]).unwrap(), + ), + (keyset.encrypt(timestamp).await.unwrap(), timestamp_frame), + (keyset.encrypt(decimal).await.unwrap(), decimal_frame), + ]; + for (sealed, expected) in cases { + let stored = stack_encrypt::Ciphertext::from_bytes(&sealed.to_bytes()).unwrap(); + assert_eq!(sdk_open(stored).await.frame(), expected.frame()); + } +} + +#[tokio::test] +async fn a_json_document_the_engine_sealed_opens_as_that_document() { + let document = JsonPlaintext::from(serde_json::json!({"id": u64::MAX, "n": 5})); + let sealed = engine() .await .default_keyset() - .decrypt(stored) + .encrypt(document) .await .unwrap(); - assert_eq!(opened, "from the sdk"); + let ciphertext = Ciphertext::new(sealed.clone(), Some(Declared::plain(ValueKind::Json))); + let Opened::Document(opened) = ciphertext.opened(sdk_open(sealed).await).unwrap() else { + panic!("a ciphertext read as JSON opens as a document"); + }; + assert_eq!(opened.value(), &serde_json::json!({"id": u64::MAX, "n": 5})); +} + +/// Encrypts a document through the crate. `text` is the document's JSON +/// text. `keyset.encrypt(json(..))` does the same, after the bridge has +/// written the text. +async fn sdk_seal_json(text: &str) -> stack_encrypt::Ciphertext { + sdk_seal(vec![document(text)]).await.remove(0) } #[tokio::test] -async fn the_sdk_opens_what_the_engine_sealed() { - let cipher = engine().await; - let sealed = cipher +async fn a_json_document_the_sdk_sealed_is_the_engines_json_plaintext() { + let sealed = sdk_seal_json(r#"{"name":"Ada","age":36,"big":18446744073709551615}"#).await; + let opened: JsonPlaintext = engine() + .await .default_keyset() - .encrypt("from the engine".to_owned()) + .decrypt(sealed) .await .unwrap(); - let opened = unseal(&cipher, vec![sealed]).await.unwrap().remove(0); assert_eq!( - opened.frame(), - OwnedFrame::of("from the engine").unwrap().frame() + opened.value(), + &serde_json::json!({"name": "Ada", "age": 36, "big": u64::MAX}) ); } +#[tokio::test] +async fn a_json_document_is_stored_as_text_with_integers_and_sorted_members() { + // The text the bridge writes for `json({ n: 5000000000, a: 1.5 })`. + let sealed = sdk_seal_json(r#"{"n":5000000000,"a":1.5}"#).await; + // The stored text is what a Go or a Rust reader parses. The integer + // has no fraction, and the engine wrote the members in key order. + let stored: String = engine() + .await + .default_keyset() + .decrypt(sealed) + .await + .unwrap(); + assert_eq!(stored, r#"{"a":1.5,"n":5000000000}"#); +} + #[tokio::test] async fn an_altered_ciphertext_does_not_open() { let mut bytes = sdk_seal(vec![one("intact")]).await.remove(0).to_bytes(); @@ -104,3 +216,258 @@ async fn a_keyset_refuses_another_keysets_ciphertext_and_the_cipher_opens_it() { OwnedFrame::of("in another keyset").unwrap().frame() ); } + +/// A deterministic key source that counts the key requests it receives. +struct Counting { + inner: DeterministicSource, + generates: AtomicUsize, + retrieves: AtomicUsize, +} + +impl KeySourceKind for Counting { + type Kind = OwnIdentity; +} + +impl DataKeySource for Counting { + async fn generate_keys( + &self, + payloads: Vec>, + keyset_id: Option, + unverified_context: Option>, + ) -> Result, Error> { + let _ = self.generates.fetch_add(1, Ordering::SeqCst); + self.inner + .generate_keys(payloads, keyset_id, unverified_context) + .await + } + + async fn retrieve_keys( + &self, + payloads: Vec>, + keyset_id: Option, + unverified_context: Option<&UnverifiedContext>, + ) -> Result, Error> { + let _ = self.retrieves.fetch_add(1, Ordering::SeqCst); + self.inner + .retrieve_keys(payloads, keyset_id, unverified_context) + .await + } +} + +impl IndexKeySource for Counting { + async fn load_index_key( + &self, + keyset_id: Option, + ) -> Result<(Uuid, IndexKey), Error> { + self.inner.load_index_key(keyset_id).await + } +} + +async fn counting() -> StackCipher { + StackCipher::builder() + .kms(Counting { + inner: DeterministicSource::new(SEED), + generates: AtomicUsize::new(0), + retrieves: AtomicUsize::new(0), + }) + .init() + .await + .unwrap() +} + +#[tokio::test] +async fn an_array_is_one_key_request_each_way_and_opens_in_order() { + let cipher = counting().await; + let sealed = seal( + &cipher.default_keyset(), + vec![one("first"), one("second"), one("third")], + ) + .await + .unwrap(); + assert_eq!(cipher.kms().generates.load(Ordering::SeqCst), 1); + let opened = unseal(&cipher, sealed).await.unwrap(); + assert_eq!(cipher.kms().retrieves.load(Ordering::SeqCst), 1); + let opened: Vec<_> = opened.iter().map(OwnedFrame::frame).collect(); + let expected = ["first", "second", "third"].map(|text| OwnedFrame::of(text).unwrap()); + let expected: Vec<_> = expected.iter().map(OwnedFrame::frame).collect(); + assert_eq!(opened, expected); +} + +#[tokio::test] +async fn an_empty_array_makes_no_request() { + let cipher = counting().await; + let sealed = seal(&cipher.default_keyset(), vec![]).await.unwrap(); + assert!(sealed.is_empty()); + assert_eq!(cipher.kms().generates.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn text_that_is_not_a_document_is_refused_without_the_text_or_a_request() { + let cipher = counting().await; + for text in ["{not json", r#"{"a":1,"a":2}"#, "18446744073709551616"] { + let refused = seal(&cipher.default_keyset(), vec![document(text)]) + .await + .unwrap_err(); + assert!( + refused.code.starts_with("stack_encrypt::"), + "the engine refuses the text: {}", + refused.code + ); + assert!(!refused.message.contains("not json")); + } + assert_eq!(cipher.kms().generates.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn a_container_is_refused_with_the_sdks_code_before_any_request() { + let cipher = counting().await; + let cases = [ + (one(vec!["a", "b"]), "recipher_js::not_a_scalar"), + ( + one(std::collections::BTreeMap::from([("name", "Ada")])), + "recipher_js::plain_object", + ), + ]; + for (value, code) in cases { + // The refused value comes after a value that would encrypt, so no + // value of the call is encrypted. + let refused = seal(&cipher.default_keyset(), vec![one("fine"), value]) + .await + .unwrap_err(); + assert_eq!(refused.code, code); + } + assert_eq!(cipher.kms().generates.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn a_null_with_no_declared_kind_is_refused_before_any_request() { + let cipher = counting().await; + let null = Sealable { + value: OwnedFrame::null(), + kind: None, + }; + let refused = seal(&cipher.default_keyset(), vec![null]) + .await + .unwrap_err(); + assert_eq!(refused.code, "recipher_js::null_value"); + assert!(refused + .help + .is_some_and(|help| help.contains("database `NULL`"))); + assert_eq!(cipher.kms().generates.load(Ordering::SeqCst), 0); +} + +/// A null declared as `nullable(..)` of a fixed-width kind. The crate gives +/// the engine a typed null of the kind, as `keyset.encrypt` does, and the +/// engine refuses it today. Issue #2023 changes the engine to encrypt it as +/// a padded typed null, as a record field with `"null": "sealed"` stores +/// one. When that change merges, this test fails: change it to check that +/// the null encrypts and decrypts as null. +#[tokio::test] +async fn a_null_declared_nullable_of_a_fixed_width_kind_is_refused_until_2023() { + let cipher = counting().await; + for kind in [ValueKind::Int64, ValueKind::Bool, ValueKind::Timestamp] { + let declared = Declared { + kind, + nullable: true, + }; + let null = Sealable { + value: crate::cipher::typed_null(Some(declared)).unwrap(), + kind: Some(declared), + }; + let refused = seal(&cipher.default_keyset(), vec![null]) + .await + .unwrap_err(); + assert_eq!(refused.code, "recipher_js::null_value", "{kind:?}"); + // The help does not suggest the call that was just refused. + let help = refused.help.unwrap_or_default(); + assert!(help.contains("database `NULL`"), "{help}"); + assert!(help.contains("once the engine"), "{help}"); + assert!(!help.contains("nullable("), "{help}"); + } + assert_eq!(cipher.kms().generates.load(Ordering::SeqCst), 0); +} + +/// A null that Rust's `encrypt_tree` encrypted, read back with a kind. It +/// decrypts as null with `nullable(..)` of the kind, of any width, and is +/// refused with the plain kind, as Rust's `decrypt::` refuses it. +#[tokio::test] +async fn a_null_the_engine_sealed_opens_as_null_with_a_nullable_kind() { + let cipher = engine().await; + for (tree, kind) in [ + ( + cipher + .default_keyset() + .encrypt_tree(None::, ()) + .await + .unwrap(), + ValueKind::Int64, + ), + ( + cipher + .default_keyset() + .encrypt_tree(None::, ()) + .await + .unwrap(), + ValueKind::String, + ), + ] { + let stack_encrypt::CipherText::Single(leaf) = tree else { + panic!("a null seals as one leaf"); + }; + let sealed = stack_encrypt::Ciphertext::from(leaf); + let nullable = Declared { + kind, + nullable: true, + }; + let read = Ciphertext::new(sealed.clone(), Some(nullable)); + let Opened::Value(opened) = read.opened(sdk_open(sealed.clone()).await).unwrap() else { + panic!("a nullable {kind} opens as a value"); + }; + assert!(opened.frame().is_null(), "{kind}"); + let plain = Ciphertext::new(sealed.clone(), Some(Declared::plain(kind))); + let refused = plain.opened(sdk_open(sealed).await).unwrap_err(); + assert_eq!(refused.code, "recipher_js::opened_null", "{kind}"); + } +} + +/// A whole number declared as `uint64` is stored as a `uint64`. The typed +/// call decrypts it as a `u64`. +#[tokio::test] +async fn a_number_declared_as_uint64_is_stored_as_a_uint64() { + let declared = Sealable { + value: OwnedFrame::of(34.0f64).unwrap(), + kind: Some(Declared::plain(ValueKind::UInt64)), + }; + let sealed = sdk_seal(vec![declared]).await.remove(0); + let typed: u64 = engine() + .await + .default_keyset() + .decrypt(sealed.clone()) + .await + .unwrap(); + assert_eq!(typed, 34); + // With no kind, the value decrypts as it was stored: the frame of a + // `u64`, and not of another integer width. + assert_eq!( + sdk_open(sealed).await.frame(), + OwnedFrame::of(34u64).unwrap().frame() + ); +} + +/// A number that does not convert exactly to the declared kind keeps the +/// engine's code and fields. Its help is about the conversion. +#[tokio::test] +async fn a_value_that_does_not_convert_has_a_help_about_the_conversion() { + let declared = Sealable { + value: OwnedFrame::of(34.5f64).unwrap(), + kind: Some(Declared::plain(ValueKind::UInt64)), + }; + let refused = seal(&engine().await.default_keyset(), vec![declared]) + .await + .unwrap_err(); + assert_eq!(refused.code, "stack_encrypt::dynamic_value"); + assert_eq!(refused.fields["reason"], "field_type"); + let help = refused.help.unwrap_or_default(); + assert!(help.contains("declared kind"), "{help}"); + assert!(!help.contains("separately"), "{help}"); +} diff --git a/languages/typescript/packages/recipher-js/crate/src/error.rs b/languages/typescript/packages/recipher-js/crate/src/error.rs index 8e2186076..06aea623b 100644 --- a/languages/typescript/packages/recipher-js/crate/src/error.rs +++ b/languages/typescript/packages/recipher-js/crate/src/error.rs @@ -26,12 +26,27 @@ use std::error::Error as StdError; use miette::Diagnostic; use napi_derive::napi; +use stack_encrypt::dynamic::ValueKind; use stack_encrypt::ErrorPayload; +use crate::ciphertext::Declared; + /// The SDK's own errors. They cover what the addon refuses before the /// engine reads it, and what goes wrong between the engine and JavaScript. #[derive(Debug, thiserror::Error, Diagnostic)] pub(crate) enum Error { + /// `undefined` given as a value. + #[error("`undefined` cannot be encrypted")] + #[diagnostic( + code(recipher_js::undefined), + help("Check that the value is set: a misspelt property name gives `undefined`. Store a value that is not there as a database `NULL`.") + )] + Undefined, + /// An `RcUuid`. The engine accepts a UUID, but this version of the SDK + /// has no kind and no TypeScript type for one, so it refuses an `RcUuid`. + #[error("this version of the SDK does not encrypt a UUID yet")] + #[diagnostic(code(recipher_js::uuid), help("Encrypt the UUID as a string instead."))] + Uuid, /// A value outside the engine's value model, or a value that Node-API /// failed to read. #[error("the value cannot be encrypted: it is not one the engine reads")] @@ -43,12 +58,42 @@ pub(crate) enum Error { )] #[diagnostic(code(recipher_js::threw))] Threw, - /// A value other than a string, given to `encrypt`. - #[error("this build encrypts a string only")] - #[diagnostic(code(recipher_js::not_a_string))] - NotAString, + /// An array inside an array, given as one value. + #[error("an array inside an array cannot be encrypted as one value")] + #[diagnostic( + code(recipher_js::not_a_scalar), + help("To encrypt the inner array as a JSON document, wrap it in `json(..)`.") + )] + NotAScalar, + /// An object given as one value. + #[error("a plain object cannot be encrypted as one value")] + #[diagnostic( + code(recipher_js::plain_object), + help("To encrypt the object as a JSON document, wrap it in `json(..)`.") + )] + PlainObject, + /// `null` given as one value. A ciphertext contains one value, and + /// `null` is the absence of one. Make it with [`Error::null_value`]. + /// That function picks the help for the kind declared. + #[error("`null` cannot be encrypted as one value")] + #[diagnostic(code(recipher_js::null_value))] + NullValue { + /// What to do instead: [`NULL_HELP`], [`NULL_HELP_NULLABLE`], or + /// [`NULL_HELP_TYPED`]. + #[help] + help: &'static str, + }, + /// A whole `number` outside the safe range, given with an integer + /// kind. The engine would store the `number` as it is, and a `number` + /// that large may not keep the digits that were written. + #[error("a whole `number` outside the safe range may not keep the digits that were written")] + #[diagnostic( + code(recipher_js::unsafe_integer), + help("The safe range is 2^53 - 1 either side of zero. Pass the integer as a `bigint` instead.") + )] + UnsafeInteger, /// `decrypt` given something that is not a `Ciphertext`. - #[error("decrypt takes a Ciphertext")] + #[error("decrypt accepts a Ciphertext, or an array of ciphertexts")] #[diagnostic( code(recipher_js::not_a_ciphertext), help("Read stored bytes with Ciphertext.fromBytes.") @@ -58,6 +103,47 @@ pub(crate) enum Error { #[error("a ciphertext is read from a Uint8Array")] #[diagnostic(code(recipher_js::not_bytes))] NotBytes, + /// Options of `encrypt` that are not an object whose only key is + /// `kind`. + #[error("the options of `encrypt` are an object with one key, `kind`")] + #[diagnostic( + code(recipher_js::options), + help("Pass a kind from `kinds`, as in `{{ kind: kinds.int64 }}`.") + )] + Options, + /// A `Json` declared as another kind than `json`, or `json` declared + /// for a value that is not a `Json`. + #[error("only a `json(..)` value is encrypted as the kind `json`")] + #[diagnostic( + code(recipher_js::json_kind), + help("Wrap a JSON document in `json(..)`, and declare `kinds.json` or no kind.") + )] + JsonKind, + /// A kind that is not one of `kinds`. + #[error("the kind is not one of `kinds`")] + #[diagnostic( + code(recipher_js::not_a_kind), + help("Pass a kind that the package exports, such as `kinds.string`, or `nullable(..)` of one.") + )] + NotAKind, + /// A ciphertext that decrypted to a null, read with a kind that is not + /// nullable. Rust's `decrypt::` refuses a null the same way. + #[error( + "the value decrypted to a null, and the kind given for the ciphertext is not nullable" + )] + #[diagnostic( + code(recipher_js::opened_null), + help("If the value may be absent, read it with `nullable(..)`, as in `Ciphertext.fromBytes(bytes, nullable(kinds.int64))`.") + )] + OpenedNull, + /// A ciphertext that decrypted to another kind than the one named. + #[error("the value decrypted, but it was not encrypted as `{kind}`, the kind given for the ciphertext")] + #[diagnostic(code(recipher_js::opened_type))] + OpenedType { kind: ValueKind }, + /// A ciphertext named as JSON that decrypted to text that is not JSON. + #[error("the value decrypted, but it is not a JSON document")] + #[diagnostic(code(recipher_js::not_a_document))] + NotADocument, /// A test cipher's seed that is not 32 bytes. #[error("a test cipher's seed is a Uint8Array of 32 bytes")] #[diagnostic(code(recipher_js::testing_seed))] @@ -87,6 +173,35 @@ pub(crate) enum Error { BuildValue, } +/// The help of a refused `null` declared as a variable-width kind, such as +/// `string`, plain or `nullable(..)`. A value of that kind has no fixed +/// size, so no declared kind makes a `null` of it encrypt. +pub(crate) const NULL_HELP: &str = "Store a value that is not there as a database `NULL`."; + +/// The help of a refused `null` with no declared kind, or declared as a +/// fixed-width kind that is not nullable. The engine does not encrypt a +/// typed null as one value yet, so the help says the call will work later, +/// and does not suggest a call that fails today. +pub(crate) const NULL_HELP_NULLABLE: &str = "Store a value that is not there as a database `NULL`. A `null` declared as `nullable(..)` of a fixed-width kind, such as `{ kind: nullable(kinds.int64) }`, will encrypt once the engine encrypts typed nulls."; + +/// The help of a refused `null` declared as `nullable(..)` of a +/// fixed-width kind: the call that will work once the engine encrypts a +/// typed null as one value. +pub(crate) const NULL_HELP_TYPED: &str = "Store a value that is not there as a database `NULL`. This `null` will encrypt once the engine encrypts typed nulls."; + +impl Error { + /// Returns the error for a `null` given as one value, with `declared`, + /// the kind declared for it, if any. + pub(crate) fn null_value(declared: Option) -> Self { + let help = match declared { + Some(declared) if !crate::ciphertext::fixed_width(declared.kind) => NULL_HELP, + Some(declared) if declared.nullable => NULL_HELP_TYPED, + _ => NULL_HELP_NULLABLE, + }; + Self::NullValue { help } + } +} + /// How serious a failure is, as the diagnostic states it. #[napi(string_enum = "snake_case")] #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -117,8 +232,8 @@ pub struct RecipherErrorFields { /// The code is one of three kinds: /// /// - a diagnostic's code, such as the engine's `stack_encrypt::aead`; - /// - the code of vitaminc, CipherStash's cryptography library, for a - /// value it refused, such as `ERR_INTEGER_RANGE`; + /// - the value bridge's code for a scalar it refused, such as + /// `ERR_INTEGER_RANGE`; /// - the SDK's own code, such as `recipher_js::not_a_ciphertext`. pub code: String, /// What went wrong, in one line. @@ -284,7 +399,12 @@ impl From for RecipherErrorFields { #[cfg(test)] mod tests { - use super::{Error, ErrorCause, RecipherErrorFields, Severity, UNDESCRIBED_CAUSE}; + use super::{ + Error, ErrorCause, RecipherErrorFields, Severity, NULL_HELP, NULL_HELP_NULLABLE, + NULL_HELP_TYPED, UNDESCRIBED_CAUSE, + }; + use crate::ciphertext::Declared; + use stack_encrypt::dynamic::ValueKind; #[test] fn an_aead_failure_keeps_the_engine_code_message_and_help() { @@ -363,12 +483,12 @@ mod tests { #[test] fn an_error_of_the_sdks_own_has_its_code_message_and_help() { - let error = RecipherErrorFields::from(Error::NotACiphertext); - assert_eq!(error.code, "recipher_js::not_a_ciphertext"); - assert_eq!(error.message, "decrypt takes a Ciphertext"); + let error = RecipherErrorFields::from(Error::Undefined); + assert_eq!(error.code, "recipher_js::undefined"); + assert_eq!(error.message, "`undefined` cannot be encrypted"); assert_eq!( error.help.as_deref(), - Some("Read stored bytes with Ciphertext.fromBytes.") + Some("Check that the value is set: a misspelt property name gives `undefined`. Store a value that is not there as a database `NULL`.") ); assert_eq!(error.severity, Severity::Error); assert!(error.fields.is_empty() && error.causes.is_empty()); @@ -469,11 +589,24 @@ mod tests { /// so the crate does not compile when a new variant has no entry here. fn every_error() -> Vec { let all = vec![ + Error::Undefined, + Error::Uuid, Error::Value, Error::Threw, - Error::NotAString, + Error::NotAScalar, + Error::PlainObject, + Error::null_value(None), + Error::UnsafeInteger, Error::NotACiphertext, Error::NotBytes, + Error::Options, + Error::JsonKind, + Error::NotAKind, + Error::OpenedNull, + Error::OpenedType { + kind: ValueKind::String, + }, + Error::NotADocument, Error::TestingSeed, Error::NoTesting, Error::NoResult, @@ -481,11 +614,22 @@ mod tests { ]; for error in &all { match error { - Error::Value + Error::Undefined + | Error::Uuid + | Error::Value | Error::Threw - | Error::NotAString + | Error::NotAScalar + | Error::PlainObject + | Error::NullValue { .. } + | Error::UnsafeInteger | Error::NotACiphertext | Error::NotBytes + | Error::Options + | Error::JsonKind + | Error::NotAKind + | Error::OpenedNull + | Error::OpenedType { .. } + | Error::NotADocument | Error::TestingSeed | Error::NoTesting | Error::NoResult @@ -495,6 +639,87 @@ mod tests { all } + /// Returns the help that `error` states, or `None` for an error that + /// leaves nothing for the caller to do. The match has no wildcard, so a + /// new variant needs an entry here. + fn help_of(error: &Error) -> Option<&'static str> { + match error { + Error::Undefined => Some("Check that the value is set: a misspelt property name gives `undefined`. Store a value that is not there as a database `NULL`."), + Error::Uuid => Some("Encrypt the UUID as a string instead."), + Error::NotAScalar => { + Some("To encrypt the inner array as a JSON document, wrap it in `json(..)`.") + } + Error::PlainObject => { + Some("To encrypt the object as a JSON document, wrap it in `json(..)`.") + } + Error::NullValue { .. } => Some(NULL_HELP_NULLABLE), + Error::UnsafeInteger => Some( + "The safe range is 2^53 - 1 either side of zero. Pass the integer as a `bigint` instead.", + ), + Error::Options => Some("Pass a kind from `kinds`, as in `{ kind: kinds.int64 }`."), + Error::JsonKind => { + Some("Wrap a JSON document in `json(..)`, and declare `kinds.json` or no kind.") + } + Error::NotACiphertext => Some("Read stored bytes with Ciphertext.fromBytes."), + Error::NotAKind => { + Some("Pass a kind that the package exports, such as `kinds.string`, or `nullable(..)` of one.") + } + Error::OpenedNull => Some("If the value may be absent, read it with `nullable(..)`, as in `Ciphertext.fromBytes(bytes, nullable(kinds.int64))`."), + Error::NoTesting => { + Some("Build it with `pnpm --filter @cipherstash/recipher build:debug`.") + } + Error::NoResult | Error::BuildValue => { + Some("Report this as a bug in @cipherstash/recipher.") + } + Error::Value + | Error::Threw + | Error::NotBytes + | Error::OpenedType { .. } + | Error::NotADocument + | Error::TestingSeed => None, + } + } + + #[test] + fn a_null_has_the_help_for_its_declared_kind() { + let help = |declared| RecipherErrorFields::from(Error::null_value(declared)).help; + let nullable = |kind| Declared { + kind, + nullable: true, + }; + // No kind, or a fixed-width kind that is not nullable: declare it + // `nullable(..)`. + for declared in [ + None, + Some(Declared::plain(ValueKind::Int64)), + Some(Declared::plain(ValueKind::Timestamp)), + ] { + assert_eq!(help(declared).as_deref(), Some(NULL_HELP_NULLABLE)); + } + // `nullable(..)` of a fixed-width kind: the call is the one to use, + // once the engine encrypts typed nulls. + for kind in [ValueKind::Int64, ValueKind::Bool, ValueKind::Timestamp] { + assert_eq!(help(Some(nullable(kind))).as_deref(), Some(NULL_HELP_TYPED)); + } + // A variable-width kind, plain or nullable: no kind helps. + for kind in [ValueKind::String, ValueKind::Bytes, ValueKind::Json] { + assert_eq!( + help(Some(Declared::plain(kind))).as_deref(), + Some(NULL_HELP) + ); + assert_eq!(help(Some(nullable(kind))).as_deref(), Some(NULL_HELP)); + } + } + + #[test] + fn every_error_states_its_help_and_no_other() { + for error in every_error() { + let help = help_of(&error); + let fields = RecipherErrorFields::from(error); + assert_eq!(fields.help.as_deref(), help, "{}", fields.code); + } + } + #[test] fn every_error_has_a_recipher_code_of_its_own() { let mut codes = std::collections::BTreeSet::new(); diff --git a/languages/typescript/packages/recipher-js/crate/src/js.rs b/languages/typescript/packages/recipher-js/crate/src/js.rs index c2fe20f66..9ce4770ed 100644 --- a/languages/typescript/packages/recipher-js/crate/src/js.rs +++ b/languages/typescript/packages/recipher-js/crate/src/js.rs @@ -4,12 +4,17 @@ //! The engine is the Stack Encrypt engine, the `stack-encrypt` crate. The //! engine's value model is the set of value types it reads. //! -//! `JsRef::to_frame` reads a JavaScript value, on the JavaScript thread, -//! into a buffer, which becomes the engine's [`OwnedFrame`] without a copy. -//! A frame is a byte buffer that contains one value. The buffer is wiped -//! when it drops. A worker thread then -//! encrypts the frame, with no access to JavaScript. `JsBuilder::build` -//! builds a decrypted frame back into a JavaScript value. This module does +//! `JsRef::to_frame` reads a JavaScript value into a buffer, on the +//! JavaScript thread. The buffer becomes the engine's [`OwnedFrame`] without +//! a copy. A frame is a byte buffer that contains one value. The buffer is +//! wiped when it drops. +//! +//! A worker thread then encrypts the frame, with no access to JavaScript. +//! `JsBuilder::build` builds a decrypted frame back into a JavaScript value. +//! +//! The bridge converts a JSON document too. `JsRef::to_json` reads a +//! JavaScript value as the document's JSON text. `JsBuilder::build_json` +//! builds the JavaScript value of a decrypted document. This module does //! not convert any value itself. //! //! When the bridge refuses a value, it says which rule the value broke. A @@ -22,12 +27,16 @@ //! and drops it without copying it. The exception's message may contain //! the value. -use napi::bindgen_prelude::Unknown; -use napi::{Env, Status}; -use recipher_value_napi::{JsBuilder, JsFault, JsRef}; +use napi::bindgen_prelude::{FnArgs, FromNapiValue, JsObjectValue, JsValue, Object, Unknown}; +use napi::sys::napi_value; +use napi::{Env, Status, ValueType}; +use recipher_value_napi::{JsBuilder, JsFault, JsRef, Refusal, Wrapper, Wrappers}; use stack_encrypt::dynamic::frame::OwnedFrame; +use vitaminc_protected::Buffer; +use crate::ciphertext::Opened; use crate::error::{Error, RecipherErrorFields}; +use crate::outcome::settle; /// Reads a JavaScript value into a frame of the engine's value model. /// @@ -35,11 +44,19 @@ use crate::error::{Error, RecipherErrorFields}; /// /// Returns one of these errors: /// +/// - `recipher_js::undefined` for `undefined`; +/// - `recipher_js::uuid` for an `RcUuid`; /// - `recipher_js::value` when the bridge's bytes are not one well-formed /// frame the engine reads (`FrameError`); /// - `recipher_js::threw` when reading the value threw; /// - the bridge's code, for a value the bridge refused. pub fn read(env: &Env, value: Unknown<'_>) -> Result { + if value.get_type().ok() == Some(ValueType::Undefined) { + return Err(Error::Undefined.into()); + } + if is_uuid(env, &value) { + return Err(Error::Uuid.into()); + } let frame = JsRef::new(value) .to_frame() .map_err(|error| refused(env, &error))?; @@ -47,21 +64,156 @@ pub fn read(env: &Env, value: Unknown<'_>) -> Result, + max_depth: usize, +) -> Result { + JsRef::new(value) + .to_json(max_depth) + .map_err(|error| refused(env, &error)) +} + +/// Returns the elements of `value` when it is an array, or `None` when it +/// is not. +/// +/// # Errors +/// +/// Returns one of these errors: +/// +/// - `recipher_js::sparse_array` for an array with a hole; +/// - `recipher_js::threw` when reading an element threw, as a getter can; +/// - `recipher_js::value` when Node-API failed to read the array. +pub fn elements<'e>( + env: &Env, + value: Unknown<'e>, +) -> Option>, RecipherErrorFields>> { + if !value.is_array().unwrap_or(false) { + return None; + } + let array = Object::from_unknown(value).ok()?; + Some(own_elements(env, &array)) +} + +/// Returns the elements of `array`, each read as an own property. +/// +/// A hole is an index with no own property. Reading one would read the +/// prototype chain, so a polluted `Array.prototype` could supply a value +/// that the caller never passed. The bridge refuses a hole inside a value +/// for the same reason, and this function refuses one in the array given +/// to `encrypt` or `decrypt`. +/// +/// The array's length comes from JavaScript, and `new Array(2 ** 32 - 1)` +/// costs nothing to make. So nothing is allocated for the length: the +/// result grows as elements are read, and the first hole stops the read. +fn own_elements<'e>( + env: &Env, + array: &Object<'e>, +) -> Result>, RecipherErrorFields> { + let failed = |error: napi::Error| refused(env, &error.into()); + let len = array.get_array_length().map_err(failed)?; + let mut elements = Vec::new(); + for at in 0..len { + if !array.has_own_property(&at.to_string()).map_err(failed)? { + return Err(RecipherErrorFields::diagnostic(&Refusal::SparseArray, None)); + } + elements.push(array.get_element::>(at).map_err(failed)?); + } + Ok(elements) +} + /// Builds the JavaScript value of a decrypted frame. /// /// # Errors /// -/// Returns `recipher_js::build_value` when the value cannot be built. +/// Returns `recipher_js::reserved_key` for a value that JavaScript cannot +/// represent in the form it was encrypted. That is a value with a map key +/// that the value bridge does not build. +/// Returns `recipher_js::build_value` for any other failure. pub fn build(env: &Env, value: OwnedFrame) -> Result, RecipherErrorFields> { JsBuilder::build(env, value.frame()).map_err(|error| not_built(env, &error)) } +/// Builds the JavaScript value of a decrypted value: a frame, or a JSON +/// document. +/// +/// # Errors +/// +/// Returns the errors of [`build`]. A document with a member named +/// `__proto__`, `constructor`, or `prototype` is +/// `recipher_js::reserved_key`. +pub fn build_opened(env: &Env, opened: Opened) -> Result, RecipherErrorFields> { + match opened { + Opened::Value(value) => build(env, value), + // The document is wiped when it drops, at the end of this arm. + Opened::Document(document) => { + JsBuilder::build_json(env, document.value()).map_err(|error| not_built(env, &error)) + } + } +} + /// Returns the failure for a value that `JsBuilder` did not build. fn not_built(env: &Env, fault: &JsFault) -> RecipherErrorFields { if fault.status() == Status::PendingException { clear_exception(env); } - Error::BuildValue.into() + match fault.refusal() { + Some(refusal @ Refusal::ReservedKey) => RecipherErrorFields::diagnostic(&refusal, None), + _ => Error::BuildValue.into(), + } +} + +/// Gives the wrapper classes of `env` the factory that their static +/// `from(text)` calls. The factory returns a `Result`: an `Ok` of a new +/// instance, or an `Err` with the code the value bridge gives an instance +/// holding that text when it is encrypted, such as `ERR_INVALID_DATE`. So +/// `RcDate.from(text)` refuses what `encrypt` would refuse, and never +/// throws. +pub fn install_wrapper_from(env: &Env) -> napi::Result { + let from = env.create_function_from_closure::)>, napi_value, _>( + "from", + |call| { + let env = &*call.env; + let name: String = call.get(0)?; + let text: Unknown<'_> = call.get(1)?; + wrapper_from(env, &name, text).map(|result| result.raw()) + }, + )?; + Wrappers::get(env)?.install_from(from.to_unknown()) +} + +/// Returns the `Result` of `from(text)` on the wrapper class `name`. +fn wrapper_from<'e>(env: &'e Env, name: &str, text: Unknown<'e>) -> napi::Result> { + // Only the classes' own `from` calls the factory, with its class's name. + let wrapper = Wrapper::from_class_name(name) + .ok_or_else(|| napi::Error::new(Status::InvalidArg, "not a wrapper class"))?; + let made = match Wrappers::get(env).and_then(|wrappers| wrappers.from_text(wrapper, text)) { + Ok(Ok(instance)) => Ok(instance), + Ok(Err(refusal)) => Err(RecipherErrorFields::diagnostic(&refusal, None)), + Err(_) => Err(Error::BuildValue.into()), + }; + settle(env, made, |_, instance| Ok(instance)) +} + +/// Returns whether `value` is an `RcUuid`. +fn is_uuid(env: &Env, value: &Unknown<'_>) -> bool { + Wrappers::get(env) + .and_then(|wrappers| wrappers.classify(value)) + .is_ok_and(|wrapper| wrapper == Some(Wrapper::Uuid)) } /// Returns the failure for a value the bridge refused. The bridge says diff --git a/languages/typescript/packages/recipher-js/crate/src/json.rs b/languages/typescript/packages/recipher-js/crate/src/json.rs new file mode 100644 index 000000000..6c70bc1f5 --- /dev/null +++ b/languages/typescript/packages/recipher-js/crate/src/json.rs @@ -0,0 +1,237 @@ +//! JSON documents: the [`Json`] class that `json(..)` makes. +//! +//! The engine is the Stack Encrypt engine, the `stack-encrypt` crate. The +//! engine encrypts a JSON document as the document's JSON text, through its +//! [`JsonPlaintext`] type. Rust's `keyset.encrypt` of a `JsonPlaintext` +//! writes the same ciphertext, so each side decrypts the other's documents. +//! +//! The value bridge, the `recipher-value-napi` crate, converts between a +//! JavaScript value and a JSON document. This module converts nothing. This +//! module passes the document between the bridge and the engine: +//! +//! - To encrypt, `json(..)` asks the bridge for the document's JSON text, +//! and keeps the text in a [`Json`]. `encrypt` gives the text to the +//! engine's `dynamic::value::encrypt`, with the declared kind `json`. The +//! engine parses the text into the [`JsonPlaintext`] it encrypts. +//! - To decrypt, [`opened`] gives the decrypted text to the engine's +//! parser. The bridge then builds the JavaScript value of the document. +//! +//! The text and the document are plaintext. Each is wiped when it is +//! dropped, and nothing prints either. + +use napi::bindgen_prelude::{ClassInstance, FromNapiValue, JavaScriptClassExt, Unknown}; +use napi::Env; +use napi_derive::napi; +use stack_encrypt::dynamic::frame::OwnedFrame; +use stack_encrypt::dynamic::read_json; +use stack_encrypt::json::JsonPlaintext; +use vitaminc_protected::{Buffer, Controlled, OpaqueDebug}; + +use crate::error::{Error, RecipherErrorFields}; +use crate::js; + +/// The deepest a document can nest. The engine's JSON parser reads 127 +/// levels of arrays and objects, and `[1]` is one level. +/// +/// The bridge checks this depth when `json(..)` reads the document, so the +/// refusal says the document is too deep. The engine's parser would refuse +/// the same text without a reason. +const MAX_DEPTH: usize = 127; + +/// A JSON document to encrypt as one ciphertext, as its JSON text. Nothing +/// inside the document can be searched. Make one with `json(..)`. +/// +/// `json(..)` reads the document when it makes the `Json`. So a later +/// change to the object does not change what is encrypted. If the document +/// cannot be encrypted, the `Json` keeps the failure, and `encrypt` returns +/// that failure. `toString()` and Node's `inspect` hide the document. +/// +/// The class has no constructor. +#[napi] +#[derive(OpaqueDebug)] +pub struct Json { + /// The document's JSON text, or the reason `json(..)` refused it. + text: Result, +} + +#[napi] +impl Json { + /// Returns the type's name, and hides the document. + #[napi(js_name = "toString")] + pub fn describe(&self) -> &'static str { + "Json(***)" + } +} + +impl Json { + /// Returns the document in `value`, when `value` is a `Json`. + /// + /// The result records two facts, so it has three cases: + /// + /// - `None`: `value` is not a `Json`. That is not a failure. The caller + /// reads `value` as any other value. + /// - `Some(Err(..))`: `value` is a `Json`, and `json(..)` refused its + /// document. `json(..)` never throws, so it kept the refusal for + /// `encrypt` to return. + /// - `Some(Ok(..))`: `value` is a `Json`. The result contains its + /// document's JSON text, as a bytes value in a frame. + /// + /// The `Option` is `Some` when `value` is a `Json`. The `Result` is `Ok` + /// when that `Json`'s document can be encrypted. A single `Result` + /// could not tell "not a `Json`" from "a `Json` that was refused". + /// + /// `encrypt` calls this function to choose how to read each value: + /// + /// ```ignore + /// let leaf = match Json::of(env, value) { + /// // `keyset.encrypt(json({ name: 'Ada' }))`: the document's + /// // text, or the refusal that `json(..)` kept. + /// Some(text) => Sealable { value: text?, kind: Some(Declared::plain(ValueKind::Json)) }, + /// // `keyset.encrypt('Ada')`: any other value. + /// None => Sealable { value: js::read(env, value)?, kind: None }, + /// }; + /// ``` + pub(crate) fn of( + env: &Env, + value: Unknown<'_>, + ) -> Option> { + if !Self::instance_of(env, &value).unwrap_or(false) { + return None; + } + ClassInstance::::from_unknown(value) + .ok() + .map(|json| json.text()) + } + + /// Returns the document's JSON text in a frame, or the refusal that + /// `json(..)` kept. Each call copies the text, so each `encrypt` of one + /// `Json` gets a frame of its own to wipe. + fn text(&self) -> Result { + match &self.text { + Ok(text) => text_frame(text.risky_ref()), + Err(refusal) => Err(refusal.clone()), + } + } +} + +/// Makes a JSON document to encrypt as one ciphertext. +/// +/// ```ts +/// const profile = json({ name: 'Ada', visits: 3, id: 2n ** 64n - 1n }) +/// const sealed = (await keyset.encrypt(profile)).unwrap() +/// const opened = (await cipher.decrypt(sealed)).unwrap() +/// // { id: 18446744073709551615n, name: 'Ada', visits: 3 } +/// ``` +/// +/// The document is a plain object, an array, text, a number, a `bigint`, a +/// boolean, or `null`. A document nests at most 127 levels of arrays and +/// objects. +/// +/// These rules decide how a number is stored: +/// +/// - A whole `number` within 2^53 - 1 of zero is an integer, as +/// `JSON.stringify` writes it. `5000000000` is stored as `5000000000`. +/// - A whole `number` from 2^53 up to 2^64, or from -2^53 down to -2^63, +/// is refused. A `number` that large may not keep the digits you wrote. +/// Pass a `bigint` instead. +/// - A whole `number` below -2^63 and above -2^64 is refused too. An +/// integer in that range has no exact form in a document, because a +/// `bigint` that size is refused as well. +/// - Any other `number` is a float. `NaN` and the infinities are refused. +/// - A `bigint` is its exact digits, from `-(2n ** 63n)` to +/// `2n ** 64n - 1n`. A `bigint` outside that range is refused. +/// +/// Decrypting gives an integer back as a `number` when it is within +/// 2^53 - 1 of zero, and as a `bigint` otherwise. So `json({ a: 5n })` +/// decrypts as `{ a: 5 }`. +/// +/// The engine stores an object's members sorted by key. A decrypted object +/// lists its members in that order, not in the order you wrote them. +/// +/// `undefined`, bytes, a `Date`, and the wrapper classes have no JSON form. +/// Each one is refused. +/// +/// `json(..)` reads the document when you call it. `json(..)` never throws. +/// For a document that cannot be encrypted, `encrypt` returns an `Err`. +#[napi(js_name = "json", ts_args_type = "document: JsonValue")] +pub fn json_document(env: &Env, document: Unknown<'_>) -> Json { + Json { + text: js::read_json(env, document, MAX_DEPTH), + } +} + +/// Returns `text`, the JSON text of a document, as a bytes value in a +/// frame. The engine's `dynamic::value::encrypt` takes a document in this +/// form, and checks the text. +/// +/// # Errors +/// +/// Returns `recipher_js::value` when the frame cannot be written. +pub(crate) fn text_frame(text: &[u8]) -> Result { + OwnedFrame::of(text).map_err(|_| Error::Value.into()) +} + +/// Returns the document in a decrypted value. The value is the document's +/// JSON text. +/// +/// # Errors +/// +/// Returns `recipher_js::not_a_document` for a value that is not the text +/// of a JSON document. The failure quotes none of the text. +pub(crate) fn opened(value: &OwnedFrame) -> Result { + read_json(value.frame()).map_err(|_| Error::NotADocument.into()) +} + +#[cfg(test)] +mod tests { + use super::{opened, text_frame, MAX_DEPTH}; + use serde_json::json; + use stack_encrypt::dynamic::frame::OwnedFrame; + use stack_encrypt::dynamic::read_json; + + /// The text of `levels` arrays, each inside the one before. + fn nested(levels: usize) -> String { + format!("{}{}", "[".repeat(levels), "]".repeat(levels)) + } + + // `dynamic::value::encrypt` reads a document declared as `json` with + // `read_json`. So these tests call `read_json` on the frame that + // `text_frame` makes, and need no key. + + #[test] + fn the_text_of_a_document_is_the_document_the_engine_encrypts() { + let text = text_frame(br#"{"n":5000000000,"big":18446744073709551615,"f":1.5}"#).unwrap(); + assert_eq!( + read_json(text.frame()).unwrap().value(), + &json!({"n": 5_000_000_000u64, "big": u64::MAX, "f": 1.5}) + ); + } + + #[test] + fn the_depth_limit_is_the_depth_the_engine_reads() { + let deepest = text_frame(nested(MAX_DEPTH).as_bytes()).unwrap(); + assert!(read_json(deepest.frame()).is_ok()); + let too_deep = text_frame(nested(MAX_DEPTH + 1).as_bytes()).unwrap(); + assert!(read_json(too_deep.frame()).is_err()); + } + + #[test] + fn decrypted_text_opens_as_its_document() { + let text = + OwnedFrame::of(r#"{"small": 5, "big": 18446744073709551615, "f": 1e20}"#).unwrap(); + assert_eq!( + opened(&text).unwrap().value(), + &json!({"small": 5, "big": u64::MAX, "f": 1e20}) + ); + } + + #[test] + fn text_that_is_not_a_document_does_not_open() { + let error = opened(&OwnedFrame::of("{not json").unwrap()).unwrap_err(); + assert_eq!(error.code, "recipher_js::not_a_document"); + assert!(!error.message.contains("not json")); + // A value that is not text is not a document. + let error = opened(&OwnedFrame::of(5i64).unwrap()).unwrap_err(); + assert_eq!(error.code, "recipher_js::not_a_document"); + } +} diff --git a/languages/typescript/packages/recipher-js/crate/src/lib.rs b/languages/typescript/packages/recipher-js/crate/src/lib.rs index 53356392c..e14909dc8 100644 --- a/languages/typescript/packages/recipher-js/crate/src/lib.rs +++ b/languages/typescript/packages/recipher-js/crate/src/lib.rs @@ -1,13 +1,13 @@ //! The Node addon of `@cipherstash/recipher`. //! //! The addon defines the classes the package exports: [`Cipher`], -//! [`Keyset`] and [`Ciphertext`]. Every operation runs through the +//! [`Keyset`], [`Ciphertext`], and [`Json`]. Every operation runs through the //! Stack Encrypt engine, the `stack-encrypt` crate. The engine encrypts and //! decrypts values with keys from ZeroKMS, CipherStash's key service. //! //! napi-rs generates the classes' TypeScript declarations (`native.d.ts`) //! from this crate. The crate reads and builds JavaScript values only -//! through the `recipher-value-napi` crate (see [`js`]). +//! through the `recipher-value-napi` crate. The `js` module does that. //! //! # Results //! @@ -21,23 +21,35 @@ //! checks it. So a value of the wrong type gives an `Err`, not an //! exception. //! -//! The one call that throws is a method called without its object, as in -//! `stored.map(cipher.decrypt)`. The JavaScript engine checks the object +//! One call of the addon's throws: a method called without its object, as +//! in `stored.map(cipher.decrypt)`. The JavaScript engine checks the object //! and throws a `TypeError` before any of the addon's code runs. //! -//! The `ts_type`, `ts_args_type` and `ts_return_type` attributes give each -//! method the signature the package exports. napi-rs writes them to -//! `native.d.ts`, with the header in `native-header.d.ts`, and that file is -//! the package's public type. +//! The wrapper classes are `RcDate`, `RcTimestamp`, `RcDecimal`, and +//! `RcUuid`. The value bridge defines them in JavaScript. An application +//! makes an instance with the class's static `from(text)`, which returns a +//! `Result` that the addon builds. A class that has no constructor in its +//! type throws when `new` is called on it anyway: `Cipher`, `Keyset`, +//! `Ciphertext`, and the wrapper classes. A wrapper class throws a +//! `TypeError` that names `from`. +//! +//! The `ts_type`, `ts_args_type`, and `ts_return_type` attributes give each +//! method the signature that the package exports. The build writes the +//! signatures to `native.d.ts`, after the header in `native-header.d.ts`. +//! `native.d.ts` is the package's public type. //! //! # The interface number //! //! [`binding_interface`] returns [`BINDING_INTERFACE`]. That number is the //! version of the interface that the package's TypeScript calls. The -//! TypeScript refuses an addon build that returns another number. No build -//! has been released, so the number is 1. After the first release, the -//! number changes whenever a class, a method or a returned value changes -//! shape. +//! TypeScript states the same number, as `BINDING_INTERFACE` in +//! `src/binding.ts`, and refuses an addon build that returns another one. +//! So an addon built from older or newer code fails when it loads, with the +//! code `recipher_js::binding_interface`. The build does not fail later, on +//! a call whose arguments or result changed shape. +//! +//! Add 1 to the number in both places whenever a class, a method, or a +//! returned value changes shape. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic)] #![warn(clippy::mem_forget)] #![warn(clippy::print_stdout)] @@ -54,6 +66,7 @@ mod cipher; mod ciphertext; mod error; mod js; +mod json; mod outcome; #[cfg(all(test, feature = "testing"))] @@ -62,13 +75,16 @@ mod engine_tests; pub use cipher::{create_testing, Cipher, Keyset}; pub use ciphertext::Ciphertext; pub use error::RecipherErrorFields; +pub use json::{json_document, Json}; pub use outcome::install_result; +use napi::bindgen_prelude::{JsObjectValue, Object, Unknown}; +use napi::Env; use napi_derive::napi; /// The version of the interface between the package's TypeScript and this /// addon build. -pub const BINDING_INTERFACE: u32 = 1; +pub const BINDING_INTERFACE: u32 = 2; /// Returns the version of the interface between the package's TypeScript /// and this addon build. The TypeScript refuses a build that returns @@ -77,3 +93,21 @@ pub const BINDING_INTERFACE: u32 = 1; pub fn binding_interface() -> u32 { BINDING_INTERFACE } + +/// Exports the value bridge's wrapper classes: `RcDate`, `RcTimestamp`, +/// `RcDecimal`, and `RcUuid`. Each class represents a type that JavaScript +/// does not have. The addon exports the classes so that JavaScript can make +/// instances with their static `from(text)`. A decrypted value is then an +/// instance of the same classes. +// napi's module registration calls this function. `clippy --all-targets` +// also builds the crate as a test, where nothing calls it. +#[cfg_attr(test, allow(dead_code))] +#[napi(module_exports)] +fn wrappers(mut exports: Object<'_>, env: Env) -> napi::Result<()> { + let classes = recipher_value_napi::Wrappers::exports(&env)?; + for wrapper in recipher_value_napi::Wrapper::ALL { + let name = wrapper.class_name(); + exports.set_named_property(name, classes.get_named_property::>(name)?)?; + } + Ok(()) +} diff --git a/languages/typescript/packages/recipher-js/crate/src/outcome.rs b/languages/typescript/packages/recipher-js/crate/src/outcome.rs index 8139f17ad..4ba014383 100644 --- a/languages/typescript/packages/recipher-js/crate/src/outcome.rs +++ b/languages/typescript/packages/recipher-js/crate/src/outcome.rs @@ -49,6 +49,10 @@ fn construct<'e>( /// The package calls this once, when it loads the addon, so an /// application never needs to. /// +/// The call also gives the wrapper classes the factory that their static +/// `from(text)` calls. `from` returns a `Result`, so it can work only once +/// the classes are here. +/// /// Returns `true` when the classes were installed. Returns `false` when /// this JavaScript environment already has them, and keeps the ones it has. /// That happens when both the ESM and the CommonJS builds of the package @@ -71,6 +75,7 @@ pub fn install_result(env: Env, classes: Object<'_>) -> napi::Result { error: class("RecipherError")?, }; env.set_instance_data(installed, (), |_| {})?; + crate::js::install_wrapper_from(&env)?; Ok(true) } diff --git a/languages/typescript/packages/recipher-js/native-header.d.ts b/languages/typescript/packages/recipher-js/native-header.d.ts index e7f4c4600..ba59797ff 100644 --- a/languages/typescript/packages/recipher-js/native-header.d.ts +++ b/languages/typescript/packages/recipher-js/native-header.d.ts @@ -3,18 +3,41 @@ The header is `native-header.d.ts`: the types the generated signatures take from the package's TypeScript. */ -// biome-ignore lint/correctness/noUnusedImports: the generated signatures after this header use it. +// biome-ignore-start lint/correctness/noUnusedImports: the generated signatures after this header use these imports. import type { RecipherError } from './src/error' -// biome-ignore lint/correctness/noUnusedImports: the generated signatures after this header use them. +import type { + Declared, + EncryptOptions, + Kind, + OpenedAs, + ReadAs, +} from './src/kinds' import type { Err, Ok, Result } from './src/result' +import type { + JsonMarker, + JsonValue, + Opened, + OpenedScalar, + Value, +} from './src/value-types' + +// biome-ignore-end lint/correctness/noUnusedImports: the generated signatures after this header use these imports. declare const opens: unique symbol /** * `T` is the type the ciphertext decrypts to. For example, * `keyset.encrypt('..')` returns a `Ciphertext`. + * + * A kind names the type that a stored ciphertext decrypts to, such as + * `kinds.string`. A ciphertext read from stored bytes with no kind decrypts + * to whatever type was encrypted. So its type allows any scalar, or `null`. + * A scalar is a single value, not a JSON document. */ -export interface Ciphertext { +export interface Ciphertext { /** Stores `T` for the type checker. The property never exists at run time. */ readonly [opens]?: T } + +/** The marker stops any other object type-checking as a `Json`. */ +export interface Json extends JsonMarker {} diff --git a/languages/typescript/packages/recipher-js/native.d.ts b/languages/typescript/packages/recipher-js/native.d.ts index fc34559f7..d0235a006 100644 --- a/languages/typescript/packages/recipher-js/native.d.ts +++ b/languages/typescript/packages/recipher-js/native.d.ts @@ -3,22 +3,45 @@ The header is `native-header.d.ts`: the types the generated signatures take from the package's TypeScript. */ -// biome-ignore lint/correctness/noUnusedImports: the generated signatures after this header use it. +// biome-ignore-start lint/correctness/noUnusedImports: the generated signatures after this header use these imports. import type { RecipherError } from './src/error' -// biome-ignore lint/correctness/noUnusedImports: the generated signatures after this header use them. +import type { + Declared, + EncryptOptions, + Kind, + OpenedAs, + ReadAs, +} from './src/kinds' import type { Err, Ok, Result } from './src/result' +import type { + JsonMarker, + JsonValue, + Opened, + OpenedScalar, + Value, +} from './src/value-types' + +// biome-ignore-end lint/correctness/noUnusedImports: the generated signatures after this header use these imports. declare const opens: unique symbol /** * `T` is the type the ciphertext decrypts to. For example, * `keyset.encrypt('..')` returns a `Ciphertext`. + * + * A kind names the type that a stored ciphertext decrypts to, such as + * `kinds.string`. A ciphertext read from stored bytes with no kind decrypts + * to whatever type was encrypted. So its type allows any scalar, or `null`. + * A scalar is a single value, not a JSON document. */ -export interface Ciphertext { +export interface Ciphertext { /** Stores `T` for the type checker. The property never exists at run time. */ readonly [opens]?: T } +/** The marker stops any other object type-checking as a `Json`. */ +export interface Json extends JsonMarker {} + /** * A cipher: the engine, and the keysets it can use. A keyset is a group * of keys in ZeroKMS, CipherStash's key service. @@ -55,10 +78,16 @@ export declare class Cipher { * Decrypts a ciphertext made under any of this cipher's keysets. The * value decrypts as the type it was encrypted as. * + * An array of ciphertexts returns an array of values, in the same + * order. The cipher makes one key request for each keyset the + * ciphertexts were made under. + * * Resolves to an `Err` with the code `recipher_js::not_a_ciphertext` - * when the argument is not a `Ciphertext`. The promise does not reject. + * when the argument, or an element of the array, is not a + * `Ciphertext`. The promise does not reject. */ decrypt(ciphertext: Ciphertext): Promise> + decrypt(ciphertexts: readonly Ciphertext[]): Promise> /** Returns the type's name. */ toString(): string } @@ -68,21 +97,41 @@ export declare class Cipher { * with its own data key. A data key is the key that encrypts one value. * * The ciphertext's bytes are the engine's format for an encrypted value. - * The Rust and Go SDKs write the same bytes. `toString()` and Node's + * Rust's `keyset.encrypt` writes the same bytes. `toString()` and Node's * `inspect` hide the bytes, because the object has no own properties. * - * The SDK uses a class rather than plain bytes so that `decrypt` can tell a - * ciphertext from any other value. + * The SDK uses a class rather than plain bytes for two reasons. First, + * `decrypt` can tell a ciphertext from any other value. Second, the class + * records the type the value decrypts as. A JSON document is encrypted as + * its JSON text, and nothing in the bytes says that it is JSON. */ export declare class Ciphertext { /** - * Reads a ciphertext from stored bytes, a `Uint8Array` or a `Buffer`. - * This method checks only the shape of the bytes. Decrypting is what - * checks that they are authentic. A failure does not quote the bytes. + * Reads a ciphertext from stored bytes. The bytes are a `Uint8Array` + * or a `Buffer`. This method checks only the format of the bytes. + * Decrypting checks that the bytes are authentic. A failure does not + * quote the bytes. * - * Returns an `Err` with the code `recipher_js::not_bytes` when the - * argument is not a `Uint8Array`. Does not throw. + * A kind names the type that a ciphertext decrypts to. To decrypt the + * value as one kind, pass that kind, such as `kinds.string`. `decrypt` + * then refuses a value that was encrypted as another type. + * `kinds.json` decrypts a JSON document. A kind from `kinds` refuses a + * stored null, with the code `recipher_js::opened_null`. To read a + * value that may be absent, pass `nullable(..)` of the kind, such as + * `nullable(kinds.int64)`. A stored null then decrypts as `null`. + * + * With no kind, the value decrypts as the type it was encrypted as. A + * JSON document then decrypts as its JSON text. `JSON.parse` of that + * text loses the digits of an integer outside a `number`'s safe range. + * + * This method does not throw. The method returns an `Err` with one of + * two codes: + * + * - `recipher_js::not_bytes`, when the bytes are not a `Uint8Array`; + * - `recipher_js::not_a_kind`, when the kind is not one of `kinds`, or + * `nullable(..)` of one. */ + static fromBytes(bytes: Uint8Array, kind: K): Result>, RecipherError> static fromBytes(bytes: Uint8Array): Result /** * Returns the bytes to store. They are a copy, so changing them does @@ -93,6 +142,22 @@ export declare class Ciphertext { toString(): string } +/** + * A JSON document to encrypt as one ciphertext, as its JSON text. Nothing + * inside the document can be searched. Make one with `json(..)`. + * + * `json(..)` reads the document when it makes the `Json`. So a later + * change to the object does not change what is encrypted. If the document + * cannot be encrypted, the `Json` keeps the failure, and `encrypt` returns + * that failure. `toString()` and Node's `inspect` hide the document. + * + * The class has no constructor. + */ +export declare class Json { + /** Returns the type's name, and hides the document. */ + toString(): string +} + /** * One keyset of a cipher. A data key is the key that encrypts one value. * Each data key is made under one keyset. A ciphertext names the keyset it @@ -106,20 +171,57 @@ export declare class Ciphertext { */ export declare class Keyset { /** - * Encrypts a string as one ciphertext with its own data key, with no + * Encrypts a value as one ciphertext with its own data key, with no * context. A context is a value that a ciphertext is bound to, and * decrypting needs the same context. * - * Resolves to an `Err` with the code `recipher_js::not_a_string` when - * the value is not a string. The promise does not reject. + * An array of values returns an array of ciphertexts, in the same + * order. The keyset makes one key request for the whole array, however + * long it is. A key request is one request to ZeroKMS for data keys. If + * any value is refused, the whole array fails, before any request. + * + * With no options, a value's type sets how it is encrypted. The + * package's README lists the mapping of JavaScript types. A `Json` from + * `json(..)` is encrypted as a JSON document. + * + * `{ kind }` declares the kind of the value, such as + * `{ kind: kinds.uint64 }`. The value is stored as that kind, and its + * ciphertext decrypts as that kind. A number converts to the kind when + * the conversion is exact, as it does for a record's field: `34` + * declared as `uint64` decrypts as `34n`. A value that does not convert + * exactly is refused. For an integer kind, a whole `number` outside the + * safe range is refused with the code `recipher_js::unsafe_integer`. + * The safe range is 2^53 - 1 either side of zero. Pass a `bigint` + * instead. For an array of values, the kind applies to each value. + * Options that are not `{ kind }`, `null` included, are an `Err` with + * the code `recipher_js::options`. + * + * `{ kind: nullable(..) }` declares a kind that also takes `null`, such + * as `{ kind: nullable(kinds.int64) }`. A value that is not `null` + * encrypts as the plain kind would. A `null` of a fixed-width kind is + * given to the engine as a typed null of that kind. The engine does + * not encrypt a typed null as one value yet, so today that `null` is an + * `Err` with the code `recipher_js::null_value`. + * + * A value that cannot be encrypted resolves to an `Err`. For example, a + * plain object is an `Err` with the code `recipher_js::plain_object`. + * `null` with no kind, with a kind that is not `nullable(..)`, or with + * `nullable(..)` of a variable-width kind such as `kinds.string`, is an + * `Err` with the code `recipher_js::null_value`. Store a value that is + * not there as a database `NULL`. The promise does not reject. */ - encrypt(value: string): Promise, RecipherError>> + encrypt(value: V): Promise>, RecipherError>> + encrypt(values: readonly V[]): Promise>[], RecipherError>> + encrypt>(value: V, options: EncryptOptions): Promise>, RecipherError>> + encrypt>(values: readonly V[], options: EncryptOptions): Promise>[], RecipherError>> /** - * Decrypts a ciphertext made under this keyset. A ciphertext of another - * keyset fails with the code `stack_encrypt::foreign_keyset`, before - * any key is requested. The promise does not reject. + * Decrypts a ciphertext made under this keyset, or an array of them. A + * ciphertext of another keyset fails with the code + * `stack_encrypt::foreign_keyset`, before any key is requested. The + * promise does not reject. */ decrypt(ciphertext: Ciphertext): Promise> + decrypt(ciphertexts: readonly Ciphertext[]): Promise> /** Returns the type's name. */ toString(): string } @@ -167,6 +269,10 @@ export interface ErrorCause { * The package calls this once, when it loads the addon, so an * application never needs to. * + * The call also gives the wrapper classes the factory that their static + * `from(text)` calls. `from` returns a `Result`, so it can work only once + * the classes are here. + * * Returns `true` when the classes were installed. Returns `false` when * this JavaScript environment already has them, and keeps the ones it has. * That happens when both the ESM and the CommonJS builds of the package @@ -174,6 +280,49 @@ export interface ErrorCause { */ export declare function installResult(classes: { Ok: typeof Ok; Err: typeof Err; RecipherError: typeof RecipherError }): boolean +/** + * Makes a JSON document to encrypt as one ciphertext. + * + * ```ts + * const profile = json({ name: 'Ada', visits: 3, id: 2n ** 64n - 1n }) + * const sealed = (await keyset.encrypt(profile)).unwrap() + * const opened = (await cipher.decrypt(sealed)).unwrap() + * // { id: 18446744073709551615n, name: 'Ada', visits: 3 } + * ``` + * + * The document is a plain object, an array, text, a number, a `bigint`, a + * boolean, or `null`. A document nests at most 127 levels of arrays and + * objects. + * + * These rules decide how a number is stored: + * + * - A whole `number` within 2^53 - 1 of zero is an integer, as + * `JSON.stringify` writes it. `5000000000` is stored as `5000000000`. + * - A whole `number` from 2^53 up to 2^64, or from -2^53 down to -2^63, + * is refused. A `number` that large may not keep the digits you wrote. + * Pass a `bigint` instead. + * - A whole `number` below -2^63 and above -2^64 is refused too. An + * integer in that range has no exact form in a document, because a + * `bigint` that size is refused as well. + * - Any other `number` is a float. `NaN` and the infinities are refused. + * - A `bigint` is its exact digits, from `-(2n ** 63n)` to + * `2n ** 64n - 1n`. A `bigint` outside that range is refused. + * + * Decrypting gives an integer back as a `number` when it is within + * 2^53 - 1 of zero, and as a `bigint` otherwise. So `json({ a: 5n })` + * decrypts as `{ a: 5 }`. + * + * The engine stores an object's members sorted by key. A decrypted object + * lists its members in that order, not in the order you wrote them. + * + * `undefined`, bytes, a `Date`, and the wrapper classes have no JSON form. + * Each one is refused. + * + * `json(..)` reads the document when you call it. `json(..)` never throws. + * For a document that cannot be encrypted, `encrypt` returns an `Err`. + */ +export declare function json(document: JsonValue): Json + /** A failure, as JavaScript receives it. */ export interface RecipherErrorFields { /** @@ -181,8 +330,8 @@ export interface RecipherErrorFields { * The code is one of three kinds: * * - a diagnostic's code, such as the engine's `stack_encrypt::aead`; - * - the code of vitaminc, CipherStash's cryptography library, for a - * value it refused, such as `ERR_INTEGER_RANGE`; + * - the value bridge's code for a scalar it refused, such as + * `ERR_INTEGER_RANGE`; * - the SDK's own code, such as `recipher_js::not_a_ciphertext`. */ code: string diff --git a/languages/typescript/packages/recipher-js/src/binding.ts b/languages/typescript/packages/recipher-js/src/binding.ts index b5e60f4a2..f57f505a7 100644 --- a/languages/typescript/packages/recipher-js/src/binding.ts +++ b/languages/typescript/packages/recipher-js/src/binding.ts @@ -31,9 +31,13 @@ import { Err, err, Ok, ok, type Result } from './result' /** * The binding interface version of this TypeScript. The addon must report - * the same number. + * the same number, `BINDING_INTERFACE` in `crate/src/lib.rs`. So `load` + * refuses an addon built from older or newer code, instead of calling a + * method whose arguments or result changed shape. Add 1 to the number here + * and in the crate whenever a class, a method, or a returned value of the + * addon changes shape. */ -export const BINDING_INTERFACE = 1 +export const BINDING_INTERFACE = 2 /** The native addon's exports, as `native.d.ts` declares them. */ export type Binding = typeof Native @@ -43,9 +47,15 @@ const EXPORTS = [ 'Cipher', 'Keyset', 'Ciphertext', + 'Json', 'bindingInterface', 'createTesting', 'installResult', + 'json', + 'RcDate', + 'RcTimestamp', + 'RcDecimal', + 'RcUuid', ] as const /** @@ -112,7 +122,12 @@ export function load( ), ) } - for (const cls of [binding.Cipher, binding.Keyset, binding.Ciphertext]) { + for (const cls of [ + binding.Cipher, + binding.Keyset, + binding.Ciphertext, + binding.Json, + ]) { Object.freeze(cls.prototype) Object.freeze(cls) } diff --git a/languages/typescript/packages/recipher-js/src/cipher.ts b/languages/typescript/packages/recipher-js/src/cipher.ts index 3a042bba1..53c1d7c44 100644 --- a/languages/typescript/packages/recipher-js/src/cipher.ts +++ b/languages/typescript/packages/recipher-js/src/cipher.ts @@ -16,14 +16,20 @@ import type * as Native from '../native' import { type Binding, binding } from './binding' import type { RecipherError } from './error' import { err, type Result } from './result' +import type { OpenedScalar } from './value-types' /** * One encrypted value: opaque bytes, encrypted with a data key of its own. * * `T` is the type the ciphertext decrypts to. For example, * `keyset.encrypt('..')` returns a `Ciphertext`. + * + * A kind names the type that a stored ciphertext decrypts to, such as + * `kinds.string`. A ciphertext read from stored bytes with no kind decrypts + * to whatever type was encrypted. So its type allows any scalar. A scalar is + * a single value, not a JSON document. */ -export type Ciphertext = Native.Ciphertext +export type Ciphertext = Native.Ciphertext /** A cipher: the Stack Encrypt engine, and the keysets it can use. */ export type Cipher = Native.Cipher /** One keyset of a cipher. A keyset is a group of keys in ZeroKMS. */ diff --git a/languages/typescript/packages/recipher-js/src/error.ts b/languages/typescript/packages/recipher-js/src/error.ts index 4ba76d069..9e2bff839 100644 --- a/languages/typescript/packages/recipher-js/src/error.ts +++ b/languages/typescript/packages/recipher-js/src/error.ts @@ -17,25 +17,28 @@ export type { ErrorCause, RecipherErrorFields, Severity } * A failure, as a value. Every call that fails returns, or resolves to, an * `Err` that contains a `RecipherError`. * - * - `code` is the code to switch on. It is stable. It is one of these: - * - the engine's error code, such as `stack_encrypt::aead`; - * - vitaminc's code for a value it refused, such as `ERR_INTEGER_RANGE`. - * vitaminc is the CipherStash Rust library that the engine's plaintext - * types come from; + * - `code` is the code to switch on. A code is stable. A code is one of + * these: + * - the engine's error code, such as `stack_encrypt::aead`. The engine is + * Stack Encrypt, CipherStash's encryption engine; + * - the value bridge's code for a scalar it refused, such as + * `ERR_INTEGER_RANGE`. The value bridge is the part of the addon that + * converts JavaScript values; * - the SDK's own code, such as `recipher_js::not_a_ciphertext`. * - `message` says what went wrong, in one line. - * - `help` says what to do about it, where the error knows. + * - `help` says what to do about the failure, when the error has that + * advice. * - `url` is a documentation page for the error, where it has one. - * - `severity` is `error`, unless the engine's error report states - * `warning` or `advice`. + * - `severity` is `error`, unless the engine's error report states `warning` + * or `advice`. * - `fields` contains the error's structured fields, by `snake_case` name. - * An example is a ZeroKMS failure's `request_kind`. `fields` is empty - * when the error has no structured fields. + * An example is a ZeroKMS failure's `request_kind`. `fields` is empty when + * the error has no structured fields. * - `field` names the field at fault, where one is known. * - `record` names the record that the failed declaration, row, or stored * row belongs to. - * - `causes` lists the errors behind this one, outermost first. A cause - * from another library has no code, and a fixed message. + * - `causes` lists the errors behind this one, outermost first. A cause from + * another library has no code, and a fixed message. * * No property, and no text that the error gives, contains a plaintext, a * key, a token, or a ciphertext. diff --git a/languages/typescript/packages/recipher-js/src/index.ts b/languages/typescript/packages/recipher-js/src/index.ts index b7f032637..a9d50cad1 100644 --- a/languages/typescript/packages/recipher-js/src/index.ts +++ b/languages/typescript/packages/recipher-js/src/index.ts @@ -16,13 +16,20 @@ * const opened = await cipher.decrypt(sealed.value) * ``` * - * Every call returns, or resolves to, a `Result`, and no promise rejects. A - * call with an argument of the wrong type is an `Err`, not an exception. + * Every call returns, or resolves to, a `Result`. No promise rejects. A call + * with an argument of the wrong type is an `Err`, not an exception. * - * The one exception is a method called without its object, as in + * One exception is a method called without its object, as in * `stored.map(cipher.decrypt)`. The JavaScript engine throws a `TypeError` * for it, before any of the package's code runs. Call each method on its * object: `stored.map((ciphertext) => cipher.decrypt(ciphertext))`. + * + * A class whose type has no constructor throws when `new` is called on it + * anyway, from JavaScript or past a cast. Those classes are `Cipher`, + * `Keyset`, `Ciphertext`, and the wrapper classes, such as `RcDate`. + * TypeScript refuses the call before it runs. A wrapper class throws a + * `TypeError` that names `from`. Make a wrapper with its static `from`, + * which returns a `Result`: `RcDate.from('2026-11-23')`. */ export { Cipher, @@ -38,4 +45,33 @@ export { type RecipherErrorFields, type Severity, } from './error' +export { + type Declared, + type EncryptOptions, + type FixedWidthName, + type Kind, + kinds, + type Nullable, + type NullableKind, + nullable, + type OpenedAs, + type ReadAs, + type ValueOf, +} from './kinds' export { Err, err, Ok, ok, type Result } from './result' +export { + type Json, + type JsonFunction, + type JsonValue, + json, + type Opened, + type OpenedJson, + type OpenedScalar, + RcDate, + RcDecimal, + RcTimestamp, + RcUuid, + type Scalar, + type Value, + type WrapperClass, +} from './values' diff --git a/languages/typescript/packages/recipher-js/src/kinds.ts b/languages/typescript/packages/recipher-js/src/kinds.ts new file mode 100644 index 000000000..5bfc81b0e --- /dev/null +++ b/languages/typescript/packages/recipher-js/src/kinds.ts @@ -0,0 +1,200 @@ +/** + * Kinds. A kind names the type that a stored ciphertext decrypts to, as in + * `Ciphertext.fromBytes(bytes, kinds.string)`. Each kind has the name that + * the engine uses for the type. The engine is Stack Encrypt, CipherStash's + * encryption engine. + * + * A kind is plain data: `{ name }`. `name` is the engine's name for the + * type. The kind's TypeScript type records the type of the kind's values. An + * integer kind's values are a `bigint` at every width. + * + * A kind from `kinds` does not take `null`, as a Rust type that is not an + * `Option` does not. `nullable(kind)` is the kind that also takes `null`, + * as Rust's `Option` is: `{ name, nullable: true }`. + */ +import type { + JsonMarker, + OpenedJson, + RcDate, + RcDecimal, + RcTimestamp, +} from './value-types' + +/** A kind: the type of a value, by the engine's name for it. */ +export interface Kind { + /** The engine's name for the kind, such as `int32`. */ + readonly name: Name + /** Stores `T` for the type checker. The property never exists at run time. */ + readonly __value?: T +} + +function kind(name: Name): Kind { + return Object.freeze({ name }) +} + +/** + * A kind that also takes `null`, from `nullable(kind)`. It is the kind's + * `Option`: a stored null decrypts as `null`. + */ +export interface NullableKind + extends Kind { + /** Marks the kind as one that takes `null`. */ + readonly nullable: true +} + +/** The kind `K` that also takes `null`: the type of `nullable(kind)`. */ +export type Nullable = + K extends Kind ? NullableKind : never + +/** + * The kind `kind` that also takes `null`, as Rust's `Option` is the type + * `T` that also takes `None`. The result is frozen, as each of `kinds` is. + * + * ```ts + * const stored = Ciphertext.fromBytes(bytes, nullable(kinds.int64)) + * // Result, RecipherError> + * ``` + * + * A stored null read with `nullable(kind)` decrypts as `null`. Read with + * the plain kind, it is an `Err` with the code `recipher_js::opened_null`. + * + * `nullable` never throws. A `kind` that is not a kind gives a value that + * `encrypt` and `Ciphertext.fromBytes` refuse with the code + * `recipher_js::not_a_kind`. + */ +export function nullable(kind: K): Nullable { + // biome-ignore lint/plugin: the object is `{ name, nullable: true }`, the shape `Nullable` gives the type checker. + return Object.freeze({ + name: nameOf(kind), + nullable: true, + }) as unknown as Nullable +} + +/** + * The name of a kind, read without throwing. A value that is not an object, + * and an object whose `name` getter throws, have no name. The addon refuses + * a kind with no name. + */ +function nameOf(kind: unknown): unknown { + if (typeof kind !== 'object' || kind === null) { + return undefined + } + try { + return Reflect.get(kind, 'name') + } catch { + return undefined + } +} + +/** Whether a kind is `nullable(..)`, by its type. */ +type IsNullable = K extends { readonly nullable: true } ? true : false + +/** The TypeScript type of a value of kind `K`. */ +export type ValueOf = K extends Kind ? T : never + +/** + * The type that a stored ciphertext read as kind `K` decrypts to. A kind + * from `kinds` decrypts to its values only: a stored null is an `Err`. A + * `nullable(..)` kind also decrypts a stored null as `null`, for a kind of + * any width. For a union of kinds, a value of any kind in the union. + */ +export type ReadAs = K extends Kind + ? ValueOf | (IsNullable extends true ? null : never) + : never + +/** + * The names of the fixed-width kinds. A value of a fixed-width kind always + * takes the same number of bytes, so a ciphertext of a `null` declared as + * that kind can look like the ciphertext of a value. + */ +export type FixedWidthName = + | 'bool' + | 'int8' + | 'int16' + | 'int32' + | 'int64' + | 'int128' + | 'uint8' + | 'uint16' + | 'uint32' + | 'uint64' + | 'uint128' + | 'float32' + | 'float64' + | 'decimal' + | 'date' + | 'timestamp' + +/** + * The values that `encrypt` takes with the declared kind `K`. A value of an + * integer kind is a `bigint`, or a whole `number` in the safe range. The + * safe range is 2^53 - 1 either side of zero. The type cannot check the + * range, so `encrypt` refuses a larger `number` when it runs. A `json` + * value is a `Json` from `json(..)`. For a union of kinds, a value of any + * kind in the union. + * + * `nullable(..)` of a fixed-width kind also takes `null`, as the type of a + * value that will encrypt as a typed null. The engine does not encrypt a + * typed null as one value yet. So `encrypt` refuses the `null` when it + * runs, with the code `recipher_js::null_value`. A kind from `kinds` takes + * no `null`. Nor does `nullable(..)` of a variable-width kind, such as + * `nullable(kinds.string)`: a value of that kind has no fixed size, so a + * null cannot be padded to look like one. + */ +export type Declared = K extends Kind + ? + | (K['name'] extends 'json' + ? JsonMarker + : ValueOf extends bigint + ? number | bigint + : ValueOf) + | (IsNullable extends true + ? K['name'] extends FixedWidthName + ? null + : never + : never) + : never + +/** + * The type that a value of type `V`, encrypted with the declared kind `K`, + * decrypts to. A `null` decrypts as `null`. Until the engine encrypts a + * typed null as one value, `encrypt` refuses a `null` when it runs, so no + * such ciphertext is made. + */ +export type OpenedAs = V extends null ? null : ValueOf + +/** The options of `encrypt`: the kind declared for the value. */ +export interface EncryptOptions { + /** + * The kind of the value, from `kinds`, such as `kinds.uint64`, or + * `nullable(..)` of one. + */ + readonly kind: K +} + +/** + * The kinds, by the engine's names for them. An integer kind's values are a + * `bigint` at every width. `json` is a JSON document, encrypted as its JSON + * text. + */ +export const kinds = Object.freeze({ + string: kind<'string', string>('string'), + boolean: kind<'bool', boolean>('bool'), + int8: kind<'int8', bigint>('int8'), + int16: kind<'int16', bigint>('int16'), + int32: kind<'int32', bigint>('int32'), + int64: kind<'int64', bigint>('int64'), + int128: kind<'int128', bigint>('int128'), + uint8: kind<'uint8', bigint>('uint8'), + uint16: kind<'uint16', bigint>('uint16'), + uint32: kind<'uint32', bigint>('uint32'), + uint64: kind<'uint64', bigint>('uint64'), + uint128: kind<'uint128', bigint>('uint128'), + float32: kind<'float32', number>('float32'), + float64: kind<'float64', number>('float64'), + decimal: kind<'decimal', RcDecimal>('decimal'), + date: kind<'date', RcDate>('date'), + timestamp: kind<'timestamp', Date | RcTimestamp>('timestamp'), + bytes: kind<'bytes', Uint8Array>('bytes'), + json: kind<'json', OpenedJson>('json'), +}) diff --git a/languages/typescript/packages/recipher-js/src/value-types.ts b/languages/typescript/packages/recipher-js/src/value-types.ts new file mode 100644 index 000000000..dbadb0e45 --- /dev/null +++ b/languages/typescript/packages/recipher-js/src/value-types.ts @@ -0,0 +1,153 @@ +/** + * The types of the values the SDK encrypts, and of what they decrypt to. + * + * This module contains types only, and imports nothing. The addon's + * generated declarations (`native.d.ts`) name these types in their + * signatures. If a module here loaded the addon, the declarations would + * import themselves. + */ + +declare const wrapper: unique symbol + +/** A calendar date, such as `RcDate.from('2026-11-23')`. */ +export interface RcDate { + /** The date as `YYYY-MM-DD`. */ + readonly value: string + toJSON(): string + readonly [wrapper]: 'RcDate' +} + +/** A UTC instant, to the nanosecond. */ +export interface RcTimestamp { + /** The instant as RFC 3339 text, with nanoseconds. */ + readonly value: string + toJSON(): string + readonly [wrapper]: 'RcTimestamp' +} + +/** A decimal with its scale, such as `RcDecimal.from('1.50')`. */ +export interface RcDecimal { + /** The decimal as text, with its scale. */ + readonly value: string + toJSON(): string + readonly [wrapper]: 'RcDecimal' +} + +/** + * A universally unique identifier (UUID). + * This version of the SDK does not encrypt a UUID yet. Encrypting an `RcUuid` + * is an `Err` with the code `recipher_js::uuid`. `RcUuid` is not a `Scalar`. + */ +export interface RcUuid { + /** The UUID as hyphenated hex. */ + readonly value: string + toJSON(): string + readonly [wrapper]: 'RcUuid' +} + +/** + * A value that is one scalar: a single value, not a JSON document. + * + * `null` is not a scalar. A ciphertext contains one value, and `null` is + * the absence of one. `encrypt` takes `null` only with `nullable(..)` of a + * fixed-width kind declared, such as `nullable(kinds.int64)`. Until the + * engine encrypts a typed null as one value, `encrypt` refuses that `null` + * when it runs. + */ +export type Scalar = + | string + | boolean + | number + | bigint + | Uint8Array + | Date + | RcTimestamp + | RcDate + | RcDecimal + +/** + * A JSON value. + * + * The safe range of a `number` is 2^53 - 1 either side of zero. Write an + * integer outside the safe range as a `bigint`. The `bigint` must be in the + * 64-bit range, from `-(2n ** 63n)` to `2n ** 64n - 1n`. + * + * `encrypt` stores a whole `number` in the safe range as an integer, and any + * other `number` as a float. `encrypt` refuses a whole `number` from 2^53 up + * to 2^64, either side of zero. A `number` that large may not keep the + * digits that were written. Below -2^63, no `bigint` can take its place, so + * an integer below -2^63 and above -2^64 has no exact form in a document. + * `encrypt` also refuses `NaN` and the infinities. + */ +export type JsonValue = + | null + | boolean + | number + | bigint + | string + | readonly JsonValue[] + | { readonly [key: string]: JsonValue } + +/** + * A JSON document as it decrypts. An integer is a `number` when it is in the + * safe range of a `number`, and a `bigint` otherwise. The safe range is 2^53 + * - 1 either side of zero. A decrypted object lists its members sorted by + * key. + */ +export type OpenedJson = + | null + | boolean + | number + | bigint + | string + | OpenedJson[] + | { [key: string]: OpenedJson } + +declare const document: unique symbol + +/** + * The marker of a `Json`. `Json` is the native addon's class for a JSON + * document. The marker stops any other object type-checking as a `Json`. The + * marker never exists at run time. + */ +export interface JsonMarker { + readonly [document]: true +} + +/** + * A value that `encrypt` accepts with no kind declared: a scalar, or a + * `Json` from `json(..)`. With a kind declared, `encrypt` takes the values + * that `Declared` names. + */ +export type Value = Scalar | JsonMarker + +/** The type that a value of type `V` decrypts to. */ +export type Opened = V extends string + ? string + : V extends boolean + ? boolean + : V extends number + ? number + : V extends bigint + ? bigint + : V extends Uint8Array + ? Uint8Array + : V extends Date + ? Date + : V extends RcTimestamp + ? Date | RcTimestamp + : V extends RcDate + ? RcDate + : V extends RcDecimal + ? RcDecimal + : V extends JsonMarker + ? OpenedJson + : never + +/** + * Any type that a stored ciphertext read with no kind can decrypt to: any + * scalar, or `null`. A stored null decrypts as `null`. `encrypt` does not + * make one. An older ciphertext can contain one. So can a ciphertext that + * Rust's `encrypt_tree` wrote. + */ +export type OpenedScalar = Opened | null diff --git a/languages/typescript/packages/recipher-js/src/values.ts b/languages/typescript/packages/recipher-js/src/values.ts new file mode 100644 index 000000000..111ef4fb5 --- /dev/null +++ b/languages/typescript/packages/recipher-js/src/values.ts @@ -0,0 +1,208 @@ +/** + * The values the SDK encrypts, and the types they decrypt to. + * + * A value's type decides how it is encrypted. The value bridge defines the + * mapping. The value bridge is the part of the native addon that converts + * JavaScript values. + * + * | Value | Encrypted as | Decrypts as | + * |---|---|---| + * | `string` | text | `string` | + * | `boolean` | a boolean | `boolean` | + * | `number` | a 64-bit float | `number` | + * | `bigint` | an integer, at the narrowest width that fits it | `bigint` | + * | `Uint8Array`, `Buffer` | bytes | `Uint8Array` | + * | `Date` | a timestamp | `Date` | + * | `RcTimestamp` | a timestamp, in nanoseconds | `Date` when it is whole milliseconds, else `RcTimestamp` | + * | `RcDate` | a calendar date | `RcDate` | + * | `RcDecimal` | a decimal, with its scale | `RcDecimal` | + * | `null` | refused: see below | `null`, for a stored null | + * | `json(value)` | a JSON document, as its text | the document | + * + * Integers are a `bigint`. A `number` is a float. The `number` `5` does not + * equal the integer `5n`. + * + * A ciphertext contains one value, and `null` is the absence of one. So + * `encrypt` refuses a lone `null`. A `null` declared as `nullable(..)` of a + * fixed-width kind, such as `nullable(kinds.int64)`, will encrypt once the + * engine encrypts a typed null as one value. A stored null decrypts as + * `null` when it is read with no kind, or with `nullable(..)` of a kind. + * Read with a kind from `kinds`, it is an `Err` with the code + * `recipher_js::opened_null`. A stored null can be one in an older + * ciphertext, or one that Rust's `encrypt_tree` wrote. + * + * A plain object is refused, because an object has no single stored form. + * `json(..)` encrypts it as a JSON document. `opaque(..)`, for a whole + * object in the engine's own format, is not built yet. The engine is Stack + * Encrypt, CipherStash's encryption engine. + * + * The native addon defines `json` and the wrapper classes: `RcDate`, + * `RcTimestamp`, `RcDecimal`, and `RcUuid`. A wrapper class represents a + * type that JavaScript does not have. Make an instance with the class's + * static `from(text)`, which returns a `Result`: `RcDate.from('2026-11-23')`. + * `from` checks the text with the rule `encrypt` uses, so an instance that + * exists is valid. `from` returns an `Err` for text that is not a value of + * the class, and for a value that is not a string. The code is the value + * bridge's, such as `ERR_INVALID_DATE`. + * + * A wrapper class has no constructor in its type. When `new` is called on + * one anyway, from JavaScript or past a cast, it throws a `TypeError` that + * names `from`. A decrypted value is an instance of the same classes. + * + * When the addon did not load, this module exports stand-ins instead. A + * stand-in's `from` returns the `Err` that says why the addon did not load, + * and its `new` throws as the class's does. + */ +import type * as Native from '../native' +import { type Binding, binding } from './binding' +import type { RecipherError } from './error' +import { err, type Result } from './result' +import type * as Types from './value-types' + +export type { + JsonValue, + Opened, + OpenedJson, + OpenedScalar, + Scalar, + Value, +} from './value-types' + +/** + * A wrapper class, without a constructor: its static `from`, its + * prototype, and `instanceof`. + */ +export interface WrapperClass { + /** The class's name, such as `RcDate`. */ + readonly name: string + /** + * Makes an instance holding `text`, when `text` is a value of the class. + * Returns an `Err` otherwise, with the value bridge's code for the class, + * such as `ERR_INVALID_DATE`. The `Err` contains no part of the text. + * `from` never throws. It reads no `this`, so it works taken off its + * class: `texts.map(RcDate.from)`. + */ + from(text: string): Result + readonly prototype: W + /** Whether `value` is an instance of the class, for `instanceof`. */ + [Symbol.hasInstance](value: unknown): value is W +} + +type WrapperName = 'RcDate' | 'RcTimestamp' | 'RcDecimal' | 'RcUuid' + +/** + * A stand-in for the wrapper class `name`, for when the native addon did not + * load. `from` returns an `Err` of `error`, the reason the addon did not + * load. `new` throws the `TypeError` that the class's `new` throws. The + * class and its prototype are frozen, and no value is an instance of it. + */ +export function standInWrapper( + name: WrapperName, + error: RecipherError, +): WrapperClass { + const StandIn = class { + constructor() { + throw new TypeError( + `${name} has no public constructor. Make one with ${name}.from(text), which returns a Result.`, + ) + } + static from(): Result { + return err(error) + } + } + Object.defineProperty(StandIn, 'name', { value: name }) + Object.freeze(StandIn.prototype) + // biome-ignore lint/plugin: a stand-in for the class. Its `instanceof` narrows to the class's instances, which a function's `boolean` `Symbol.hasInstance` cannot say. + return Object.freeze(StandIn) as unknown as WrapperClass +} + +/** + * The class that the native addon defines. When the addon did not load, a + * stand-in class instead. + */ +function wrapperClass(name: WrapperName): WrapperClass { + if (binding.isOk()) { + // The addon exports each class under its name (`crate/src/lib.rs`). + // napi-rs does not declare these classes, so this code gives them types. + return Reflect.get(binding.value, name) as WrapperClass + } + return standInWrapper(name, binding.error) +} + +// A class is a constant and a type of one name. The addon's declarations +// name the types, so `./value-types` declares them. A module cannot export a +// type from another module and a constant under the same name. So each +// constant here has its type beside it. + +/** A calendar date, such as `RcDate.from('2026-11-23')`. */ +export const RcDate: WrapperClass = wrapperClass('RcDate') +export type RcDate = Types.RcDate + +/** + * A UTC instant, to the nanosecond, such as + * `RcTimestamp.from('2026-11-23T01:02:03.000000001Z')`. + */ +export const RcTimestamp: WrapperClass = + wrapperClass('RcTimestamp') +export type RcTimestamp = Types.RcTimestamp + +/** A decimal with its scale, such as `RcDecimal.from('1.50')`. */ +export const RcDecimal: WrapperClass = wrapperClass('RcDecimal') +export type RcDecimal = Types.RcDecimal + +/** + * A universally unique identifier (UUID). This version of the SDK does not + * encrypt a UUID yet. Encrypting an `RcUuid` is an `Err` with the code + * `recipher_js::uuid`. `RcUuid` is not a `Scalar`. + */ +export const RcUuid: WrapperClass = wrapperClass('RcUuid') +export type RcUuid = Types.RcUuid + +/** + * A JSON document to encrypt as one ciphertext, as its JSON text. Make one + * with `json(..)`. `toString()` and Node's `inspect` hide the document. + * + * The type is the native addon's `Json` class. + */ +export type Json = Native.Json + +/** + * The type of `json`. `json` makes a JSON document to encrypt as one + * ciphertext. + */ +export type JsonFunction = Binding['json'] + +/** + * Makes a JSON document, to encrypt as one ciphertext. `json` reads the + * document immediately, so a later change to the object does not change what + * is encrypted. + * + * ```ts + * const sealed = await keyset.encrypt(json({ name: 'Ada', visits: 3 })) + * ``` + * + * A whole `number` within 2^53 - 1 of zero is stored as an integer, and any + * other `number` as a float. A whole `number` from 2^53 up to 2^64, or from + * -2^53 down to -2^63, is refused. Pass a `bigint` instead. A whole `number` + * below -2^63 and above -2^64 is refused too. An integer in that range has + * no exact form in a document, because a `bigint` that size is refused as + * well. A `bigint` is stored as its exact digits, from `-(2n ** 63n)` to + * `2n ** 64n - 1n`. A `bigint` outside that range is refused. + * + * A decrypted integer is a `number` when it is within 2^53 - 1 of zero, and + * a `bigint` otherwise. So `json({ a: 5n })` decrypts as `{ a: 5 }`. A + * decrypted object lists its members sorted by key. + * + * `json` never throws. A document that cannot be encrypted is an `Err` from + * `encrypt`. Examples are a document that contains `undefined`, bytes, or a + * `Date`, and a document nested deeper than 127 levels. + */ +export const json: JsonFunction = binding.isOk() + ? binding.value.json + : standInJson + +/** The stand-in for `json` when the native addon did not load. */ +function standInJson(): Json { + // biome-ignore lint/plugin: a stand-in `Json`. `encrypt` refuses it with the load error. + return Object.freeze({ toString: () => 'Json(***)' }) as unknown as Json +} diff --git a/languages/typescript/packages/recipher-js/type-tests/native.ts b/languages/typescript/packages/recipher-js/type-tests/native.ts index 972f35b44..3facf9a5f 100644 --- a/languages/typescript/packages/recipher-js/type-tests/native.ts +++ b/languages/typescript/packages/recipher-js/type-tests/native.ts @@ -8,7 +8,10 @@ import { Cipher, Ciphertext, type CiphertextClass, + type Json, + type json, Keyset, + type OpenedScalar, type RecipherError, type Result, } from '../src/index' @@ -24,9 +27,11 @@ type Equal = check>() check>() check, Native.Ciphertext>>() -// A ciphertext with no type named decrypts to a string, as this build -// encrypts strings only. -check>>() +check>() +check>() +// A ciphertext with no type named, as one read from stored bytes with no +// kind, decrypts to any scalar. +check>>() // The static methods are the generated ones. check>() diff --git a/languages/typescript/packages/recipher-js/type-tests/result.ts b/languages/typescript/packages/recipher-js/type-tests/result.ts index 255c6db63..b9deaed02 100644 --- a/languages/typescript/packages/recipher-js/type-tests/result.ts +++ b/languages/typescript/packages/recipher-js/type-tests/result.ts @@ -61,7 +61,5 @@ function describe(error: RecipherError): string { void describe declare const keyset: Keyset -// @ts-expect-error: this build encrypts a string only. -void keyset.encrypt(42n) // @ts-expect-error: a plain object is not a value. void keyset.encrypt({ name: 'Ada' }) diff --git a/languages/typescript/packages/recipher-js/type-tests/values.ts b/languages/typescript/packages/recipher-js/type-tests/values.ts new file mode 100644 index 000000000..398e7b009 --- /dev/null +++ b/languages/typescript/packages/recipher-js/type-tests/values.ts @@ -0,0 +1,243 @@ +// Compile-time tests: `pnpm run typecheck` compiles this file and nothing +// runs it. Each `@ts-expect-error` is a line that must not compile. +import type { + Cipher, + Keyset, + Nullable, + OpenedJson, + OpenedScalar, + RcDate, + RcDecimal, + RcTimestamp, + RcUuid, + RecipherError, + Result, +} from '../src/index' +import { + Ciphertext, + json, + kinds, + nullable, + RcDate as RcDateClass, + RcDecimal as RcDecimalClass, + RcTimestamp as RcTimestampClass, + RcUuid as RcUuidClass, +} from '../src/index' + +declare const keyset: Keyset +declare const cipher: Cipher + +type Exact = [A] extends [B] ? ([B] extends [A] ? true : false) : false +function expectType(_: T): void {} +function check<_ extends true>(): void {} + +// One value gives one ciphertext. The type of the ciphertext is the type the +// value decrypts to. A literal widens. +const text = await keyset.encrypt('a secret') +check, RecipherError>>>() +const count = await keyset.encrypt(5n) +check, RecipherError>>>() +const flag = await keyset.encrypt(true) +check, RecipherError>>>() +const bytes = await keyset.encrypt(new Uint8Array(1)) +check, RecipherError>>>() +const when = await keyset.encrypt(new Date()) +check, RecipherError>>>() +declare const instant: RcTimestamp +const fine = await keyset.encrypt(instant) +check< + Exact, RecipherError>> +>() +declare const day: RcDate +const dated = await keyset.encrypt(day) +check, RecipherError>>>() +declare const price: RcDecimal +const priced = await keyset.encrypt(price) +check, RecipherError>>>() +const document = await keyset.encrypt(json({ a: [1, 2n, null] })) +check, RecipherError>>>() + +// An array is an array. +const many = await keyset.encrypt(['a', 'b']) +check[], RecipherError>>>() + +// Decrypting gives the type back, for one ciphertext or for an array. +if (text.isOk()) { + const opened = await cipher.decrypt(text.value) + check>>() +} +if (many.isOk()) { + const opened = await keyset.decrypt(many.value) + check>>() +} + +// A plain object needs json(..). +// @ts-expect-error: a plain object is not a value. +void keyset.encrypt({ name: 'Ada' }) +// This version of the SDK does not encrypt a UUID yet. +declare const uuid: RcUuid +// @ts-expect-error: a UUID is not a value. +void keyset.encrypt(uuid) +// @ts-expect-error: undefined is not a value. +void keyset.encrypt(undefined) +// With no kind, a null is refused. So is an array that contains one. +// @ts-expect-error: a lone null is not a value. +void keyset.encrypt(null) +// @ts-expect-error: a lone null is not a value. +void keyset.encrypt(['x', null]) +// @ts-expect-error: a Map is not a value. +void keyset.encrypt(new Map()) +// @ts-expect-error: bytes have no JSON form. +void json({ b: new Uint8Array(1) }) +// @ts-expect-error: a date has no JSON form. +void json({ d: new Date() }) +// The wrapper types are distinct. +// @ts-expect-error: an RcDate is not an RcDecimal. +expectType(day) + +// A ciphertext read from stored bytes has the type of the kind named. A +// kind from `kinds` is not nullable, as a Rust type that is not an `Option` +// is not: a stored null read as it is an `Err`. With no kind, its type is +// any scalar, or null. +declare const stored: Uint8Array +const typed = Ciphertext.fromBytes(stored, kinds.int64) +check, RecipherError>>>() +const typedText = Ciphertext.fromBytes(stored, kinds.string) +check, RecipherError>>>() +const typedJson = Ciphertext.fromBytes(stored, kinds.json) +check, RecipherError>>>() +const untyped = Ciphertext.fromBytes(stored) +check, RecipherError>>>() +// @ts-expect-error: a kind is one of `kinds`. +void Ciphertext.fromBytes(stored, 'string') + +// `nullable(..)` of a kind reads a stored null as null, for a kind of any +// width: a stored null can exist for any type. +const maybe = Ciphertext.fromBytes(stored, nullable(kinds.int64)) +check, RecipherError>>>() +const maybeText = Ciphertext.fromBytes(stored, nullable(kinds.string)) +check< + Exact, RecipherError>> +>() +const maybeJson = Ciphertext.fromBytes(stored, nullable(kinds.json)) +check< + Exact, RecipherError>> +>() +// `nullable` of a nullable kind is the same nullable kind. +const twice = Ciphertext.fromBytes(stored, nullable(nullable(kinds.date))) +check, RecipherError>>>() +// A union of kinds reads each kind as it would alone. +declare const intOrMaybeText: typeof kinds.int64 | Nullable +const mixed = Ciphertext.fromBytes(stored, intOrMaybeText) +check< + Exact, RecipherError>> +>() +// @ts-expect-error: `nullable` takes a kind. +void nullable('int64') + +// A declared kind sets the type the ciphertext decrypts to. A whole +// `number` declared as an integer kind decrypts as a `bigint`. +const age = await keyset.encrypt(34, { kind: kinds.uint64 }) +check, RecipherError>>>() +const ages = await keyset.encrypt([34, 35n], { kind: kinds.int32 }) +check[], RecipherError>>>() +const named = await keyset.encrypt('Ada', { kind: kinds.string }) +check, RecipherError>>>() +const declaredDocument = await keyset.encrypt(json({ a: 1 }), { + kind: kinds.json, +}) +check< + Exact, RecipherError>> +>() +// A null declared as `nullable(..)` of a fixed-width kind decrypts as null. +// Until the engine change in #2023 merges, encrypting it is an `Err` at run +// time. +const absent = await keyset.encrypt(null, { kind: nullable(kinds.int64) }) +check, RecipherError>>>() +for (const kind of [ + nullable(kinds.boolean), + nullable(kinds.uint8), + nullable(kinds.float32), + nullable(kinds.decimal), + nullable(kinds.date), + nullable(kinds.timestamp), +]) { + void keyset.encrypt(null, { kind }) +} +// A value that is not null, declared as a nullable kind, encrypts as the +// plain kind would. +const present = await keyset.encrypt(34, { kind: nullable(kinds.int64) }) +check, RecipherError>>>() +// Each value of an array of a nullable kind decrypts as its own type. +const someAbsent = await keyset.encrypt([34, null], { + kind: nullable(kinds.int64), +}) +check< + Exact[], RecipherError>> +>() +// @ts-expect-error: a plain kind takes no null. +void keyset.encrypt(null, { kind: kinds.int64 }) +// @ts-expect-error: a plain kind takes no null. +void keyset.encrypt(null, { kind: kinds.boolean }) +// @ts-expect-error: a plain kind takes no null, in an array either. +void keyset.encrypt([34, null], { kind: kinds.int64 }) +// @ts-expect-error: a null of a variable-width kind is not a value. +void keyset.encrypt(null, { kind: nullable(kinds.string) }) +// @ts-expect-error: a null of a variable-width kind is not a value. +void keyset.encrypt(null, { kind: nullable(kinds.bytes) }) +// @ts-expect-error: a null of a variable-width kind is not a value. +void keyset.encrypt(null, { kind: nullable(kinds.json) }) +// @ts-expect-error: a null of a variable-width kind is not a value. +void keyset.encrypt(null, { kind: kinds.string }) +// A value of a variable-width nullable kind encrypts as the plain kind. +const nullableText = await keyset.encrypt('Ada', { + kind: nullable(kinds.string), +}) +check, RecipherError>>>() +// @ts-expect-error: a value of another type than the kind is refused. +void keyset.encrypt('34', { kind: kinds.uint64 }) +// @ts-expect-error: a number is not a string. +void keyset.encrypt(34, { kind: kinds.string }) +// @ts-expect-error: only a `json(..)` value has the kind `json`. +void keyset.encrypt('{"a":1}', { kind: kinds.json }) +// @ts-expect-error: the kind is one of `kinds`, inside `{ kind }`. +void keyset.encrypt(34, kinds.uint64) +// @ts-expect-error: the options take only `kind`. +void keyset.encrypt(34, { kind: kinds.uint64, context: 'users' }) + +// A union of kinds takes a value of each kind in it, and no other. +declare const intOrJson: typeof kinds.int64 | typeof kinds.json +// @ts-expect-error: a plain object is neither an int64 nor a `json(..)`. +void keyset.encrypt({ a: 1 }, { kind: intOrJson }) +void keyset.encrypt(json({ a: 1 }), { kind: intOrJson }) +void keyset.encrypt(34, { kind: intOrJson }) +declare const intOrText: typeof kinds.int64 | typeof kinds.string +const either = await keyset.encrypt(34, { kind: intOrText }) +check< + Exact, RecipherError>> +>() +void keyset.encrypt('Ada', { kind: intOrText }) +// @ts-expect-error: a boolean is neither an int64 nor a string. +void keyset.encrypt(true, { kind: intOrText }) + +// A wrapper is made with its static `from`, which returns a `Result`. The +// classes have no constructor. +const madeDay = RcDateClass.from('2026-11-23') +check>>() +const madeInstant = RcTimestampClass.from('2026-11-23T01:02:03.000000001Z') +check>>() +const madePrice = RcDecimalClass.from('1.50') +check>>() +const madeUuid = RcUuidClass.from('123e4567-e89b-12d3-a456-426614174000') +check>>() +// @ts-expect-error: a wrapper class has no constructor. +void new RcDateClass('2026-11-23') +// @ts-expect-error: a wrapper class has no constructor. +void new RcDecimalClass('1.50') +// @ts-expect-error: `from` takes a string. +void RcDateClass.from(20261123) +// `instanceof` narrows to the class's instances. +declare const something: unknown +if (something instanceof RcDateClass) { + expectType(something) +} diff --git a/languages/typescript/packages/recipher-js/value-napi/Cargo.toml b/languages/typescript/packages/recipher-js/value-napi/Cargo.toml index 8250bffe2..2fc4ad5fa 100644 --- a/languages/typescript/packages/recipher-js/value-napi/Cargo.toml +++ b/languages/typescript/packages/recipher-js/value-napi/Cargo.toml @@ -19,11 +19,19 @@ jiff = { version = "1.0.0", default-features = false } 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"] } +# Date detection needs napi5, and Node 12 and later provide napi5. BigInt +# needs napi6, and napi6 implies napi5. `napi_get_all_property_names` needs +# napi6 too, and is the only own-property enumeration that Node-API offers. +# Every supported Node release is far beyond both levels. +# +# `serde-json` converts a `serde_json::Number` to a JavaScript `number` or +# `bigint`, for a decrypted JSON document. +napi = { version = "3", default-features = false, features = ["napi6", "serde-json"] } +# For a JSON document. `serde_json` writes each scalar of the document's text. +# A decrypted document arrives as a `serde_json::Value`. `serde` is listed for +# the `Serialize` bound of the function that writes a scalar. +serde = "1" +serde_json = "1" zeroize = { version = "1", features = ["derive"] } # Only for `#[cfg_attr(test, mutants::skip)]`; consumers never see it. mutants = "0.0.4" diff --git a/languages/typescript/packages/recipher-js/value-napi/README.md b/languages/typescript/packages/recipher-js/value-napi/README.md index 6ae681334..bebed27a9 100644 --- a/languages/typescript/packages/recipher-js/value-napi/README.md +++ b/languages/typescript/packages/recipher-js/value-napi/README.md @@ -1,63 +1,100 @@ # 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 the JavaScript value bridge of `@cipherstash/recipher`. The +value bridge converts values between JavaScript and Rust: + +- The bridge reads a Node-API value as a value of the plaintext model of + `vitaminc-aead`. +- The bridge builds a JavaScript value from a value of that model. + +The plaintext model describes a value as scalars, sequences, and maps. The +`recipher-js` addon reads and builds every value through this crate. + +This crate is a library that a Node addon links. Node cannot load this crate +itself. + +## Where this crate comes from + +This crate is a renamed copy of `vitaminc-aead-napi` 0.10.0. The copy comes +from [`cipherstash/vitaminc`](https://github.com/cipherstash/vitaminc) at +commit `b3f69b12c1fde38faff2becec04f9e633dbd4f1c`. This crate is not +published. + +The wrapper classes of this crate are `RcDate`, `RcTimestamp`, `RcDecimal`, +and `RcUuid`. vitaminc names the same classes with the prefix `Vc`, such as +`VcDate`. -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 a copy of -`conformance/vitaminc-aead/value-conformance.json`: the vectors the Rust, -Node and Go bindings all check. The bridge's tests read the copy, so a run -scoped to this package finds it. -`scripts/__tests__/recipher-js-value-corpus-parity.test.mjs` fails when the -two parse to different JSON, so change both together, then run -`pnpm run code:fix`. - -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 +`conformance/vitaminc-aead/value-conformance.json`. That file contains the +test vectors that the Rust, Node, and Go bindings all check. The tests of +this crate read the copy, so a test run that covers only this package finds +the file. `scripts/__tests__/recipher-js-value-corpus-parity.test.mjs` fails +when the two files parse to different JSON. So change both files together, +then run `pnpm run code:fix`. + +## What this crate provides + +[`Encrypt`] and [`Sink`] are traits of `vitaminc-aead`. A JavaScript value +that comes in implements `Encrypt`. A `Sink` builds the JavaScript value +that goes out. This crate provides both sides of that conversion: + +- **`JsRef<'e>`** is a live JavaScript value as an `Encrypt`. `JsRef` reads + the value in a walk. A walk is one pass over a value and every value + nested in it. The walk runs on the JavaScript thread, and reads each value + when it reaches that value. The walk builds no tree of values. The walk + copies a scalar out of the JavaScript engine only to pass it straight to + the sink. + + `encrypt(JsRef::new(value), &cipher, aad)` encrypts a value in place. To + encrypt off the JavaScript thread, call `JsRef::to_frame` on the + JavaScript thread first. `to_frame` copies the value into a frame. A frame + is a byte buffer that contains one value. A worker thread then encrypts + the frame, with no access to JavaScript. +- **`JsBuilder<'e>`** is a `Sink` that builds JavaScript values. Pass it to + `decrypt_into(&cipher, ct, aad, JsBuilder::new(&env))`. For a frame, call + `JsBuilder::build(&env, frame)`. +- **`JsRef::to_json`** and **`JsBuilder::build_json`** convert a JSON + document. `to_json` writes a JavaScript value as the text of a document. + `build_json` builds the JavaScript value of a `serde_json::Value`. See + [JSON documents](#json-documents). +- **`JsCipherText`** converts the generic `CipherText` container to + plain JavaScript values, and back. The JavaScript form is `{ t, v }` nodes + with `Buffer` leaves. That form is for the application to use in memory. + Durable database storage that every language reads is the job of the EQL + layer, not of this type. + + The passthrough payload `P` converts through `NapiPassthrough`. + `NapiPassthrough` is implemented for `PassthroughFrame` and for `()`. + `PassthroughFrame` is the payload of the sink-based tree. The conversion 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. +- **`Wrappers`** contains the wrapper classes: `RcDate`, `RcTimestamp`, + `RcDecimal`, and `RcUuid`. The classes are defined once for each + environment. An addon exports the classes with `Wrappers::exports`, and + installs the factory that each class's static `from(text)` calls with + `Wrappers::install_from`. This crate keeps the classes in its own + registry, keyed by the environment. An environment cleanup hook releases + them. This crate never reads or changes the addon's instance data. ## 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 +This crate provides Rust building blocks for a Node addon. The [test +addon](tests/addon/src/lib.rs) exports `encryptValue` and `decryptValue`. +The two functions use `JsRef`, `JsCipherText`, and `JsBuilder` with +AES-256-GCM. The test addon uses a fixed, public test key, so use it only with sample data. -From `languages/typescript/packages/recipher-js`, with Rust and Node.js -installed, run: +You need Rust and Node.js. From `languages/typescript/packages/recipher-js`, +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`. +The command builds the addon. The command then runs the example below, and +the other Node tests of this crate. To run the example on its own: + +1. Save the example as `example.cjs` in that directory. +2. Run `node example.cjs target/napi-test-addon/addon.node`. ```javascript const assert = require('node:assert/strict'); @@ -73,13 +110,16 @@ 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 associated data (`aad`) must be the same for encryption and for +decryption. You can use the associated data to bind a ciphertext to a +tenant, or to another application context. Use a `bigint` for an integer, +such as `42n`. A JavaScript `number` is a float. + +## How JavaScript values map to the plaintext model -## The mapping +The walk reads each JavaScript value as the value in this table: -| JavaScript | Scalar | +| JavaScript | Read as | | ----------------------------------- | ---------------------------------------- | | `null` | null | | `undefined` | null, logical type `Undefined` | @@ -89,145 +129,351 @@ for integer values, as shown by `42n`; JavaScript `number` values are floats. | `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 | +| `RcDate("YYYY-MM-DD")` | `Date` over the day count | +| `RcTimestamp("RFC 3339, ns")` | `Timestamp(Nanos)` over the count | +| `RcDecimal("1.50")` | `Decimal { scale }` over the mantissa | +| `RcUuid("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. A record field that declares a type is the exception: the -engine reads each value written to it, or queried against it, as that -type when the conversion is exact, so `5` and `5n` are both the `int64` 5 -on an `int64` field. +A logical type says what a stored scalar means, such as `Timestamp(Millis)` +for an `i64` count. + +`JsBuilder` builds each stored value as the JavaScript value in this table: + +| Stored value | Built as | +| ---------------------------------------------- | ------------------------------------------- | +| an int of any width | `BigInt` | +| a float of either width | `number`; an `f32` widens exactly | +| a timestamp in any unit, in whole milliseconds | `Date` | +| any other timestamp | `RcTimestamp`, so no precision is discarded | +| a calendar date | `RcDate` | +| a decimal | `RcDecimal` | +| a UUID | `RcUuid` | + +A `Date` is stored as its millisecond count. `JsBuilder` reads the same +count back. The count is never converted through seconds and nanoseconds. + +A stored value can have a logical type that this build does not define. That +value has no JavaScript value. `JsBuilder` refuses it, and does not build it +with its type dropped. + +### Equality across widths and types + +An equality term is a value derived from a plaintext. A database compares +equality terms to find equal values without decrypting them. Two terms can +match only when they are in the same domain. + +- Every integer width is in one domain. So a `BigInt` written as `int8` + matches the same number written as `int64` from Go. +- Both float widths are in one domain too. +- Integers and floats are in different domains. So a JavaScript `number` 5 + does not match an `int64` 5. Use a `BigInt` for integer data. + +A record field that declares a type is the exception. The engine reads each +value written to that field, or queried against it, as the declared type, +when the conversion is exact. So `5` and `5n` are both the `int64` 5 on an +`int64` field. ### 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`. +than a millisecond, a decimal, or a universally unique identifier (UUID). So +each one is an instance of a small class that stores the value's text. An +application makes one with the class's static `from`, such as +`RcDecimal.from("1.50")`. + +Some rules below mention a polluted prototype. A polluted prototype is a +built-in prototype, such as `Object.prototype`, that other code has added +properties to. + +- **`from(text)` is the only way in.** `from` returns what the addon's + factory returns. A factory that calls `Wrappers::from_text` checks the + text with the rule that applies when the value is encrypted. So an + instance that `from` made is valid. `from_text` refuses these with the + class's code, such as `ERR_INVALID_DATE`: + - a value that is not a string; + - text that is not a value of the class. + + `from_text` throws nothing. +- **`new` throws.** The constructor takes a token that only the classes' + script contains. `new RcDate("2024-02-29")` throws a `TypeError` that names + `RcDate.from`. `JsBuilder` makes a decrypted value's instance with the + token. +- **The text is checked again when the value is encrypted.** + `Object.create(RcDate.prototype)` makes an object that `instanceof` + accepts without the constructor. This crate reads the text as an own + string property, and checks it with the same rule. So one rule applies + however the object was made. +- **`value` is an own, read-only, enumerable property.** So + `JSON.stringify`, `structuredClone`, and a deep equality check all read + it. `JSON.stringify` gets the bare text through `toJSON`. +- **A clone is not a wrapper.** A clone, or a wrapper posted to a Worker, is + a plain `{ value }` object, and encrypts as a map. Rebuild the wrapper + with `from` on the other side. +- **The classes, their prototypes, and every instance are frozen.** + 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. Neither can break a decrypt, or turn a plain `{ value }` + object back into a wrapper. +- **An instance is not a plain object.** So no code confuses an instance + with a plain one-key object that another language wrote. For example, Go's + `{"date": "2024-01-01"}` decrypts in JavaScript as that object, and + encrypts again unchanged. + +These rules apply to the text: + +- Decimal text is exact fixed-point. Decimal text is not a JavaScript + number, or an instance of a decimal library. A negative zero reads back as + zero, with its scale kept. +- A leap second has no count since the epoch, so it is refused. +- Dates and timestamps cover the range of the jiff library, years -9999 to + 9999, as in every binding. +- A negative year is a sign and six digits, as JavaScript writes it: + `-000005-03-01T12:00:00.000000001Z`. + +A scalar that cannot be converted throws a `TypeError` with one of these +stable codes: + +- `ERR_INTEGER_RANGE`; +- `ERR_INVALID_DATE`; +- `ERR_INVALID_TIMESTAMP`; +- `ERR_INVALID_DECIMAL`; +- `ERR_NON_FINITE_DECIMAL`; +- `ERR_INVALID_UUID`. + +## JSON documents + +A JSON document is encrypted as its JSON text, so that Rust, Go, and +JavaScript all read the same document. Two functions convert a document: + +- `JsRef::to_json(max_depth)` writes the text of a JavaScript value, for + encrypting. +- `JsBuilder::build_json(&env, &document)` builds the JavaScript value of a + decrypted document. + +### Writing a document + +`to_json` uses the same walk as every other value, with every rule in +[Safety notes](#safety-notes). For a document, the walk reads only the +values that a JSON document can contain: + +| JavaScript | In the document | +| --------------------------------------- | ---------------------------- | +| `null`, `boolean`, `string` | the same | +| `Array`, plain object | an array, an object | +| whole `number` within 2^53 - 1 of zero | an integer | +| whole `number` from 2^53 up to 2^64 | refused | +| whole `number` from -2^53 down to -2^64 | refused | +| any other finite `number` | a float | +| `bigint` within 64 bits | an integer, with its digits | +| anything else | refused | + +- **A whole number is an integer.** `to_json` writes `5000000000` as + `5000000000`, as `JSON.stringify` does, and never as `5000000000.0`. + Rust's `serde_json` and Go's `encoding/json` refuse a number with a + fraction for an integer field. `to_json` writes `-0` as `0`. +- **A whole number from 2^53 up to 2^64 is refused**, either side of zero. A + `number` that large may not have the digits that were written. An integer + was probably meant, and a `bigint` stores an integer exactly. A number of + 2^64 or more, either side of zero, is not an integer that any reader + accepts, so it is a float. +- **A whole number below -2^63 and above -2^64 has no exact form.** A + `bigint` that size is refused too, so the refusal has its own message, + which does not ask for a `bigint`. From -2^53 down to -2^63, the message + asks for a `bigint`. +- **A `bigint` is written as its exact digits**, from -2^63 to 2^64 - 1. + That is the range that a JSON parser in Rust or Go reads. A `bigint` + outside that range is refused, whatever its size. +- **Everything else is refused.** Each of these values has the code + `recipher_js::not_json`: + - `undefined`; + - `NaN` and the infinities; + - bytes: a `Buffer`, a typed array, or a `DataView`; + - a `Date`; + - a wrapper class instance. + + The message names the kind of value, and contains no part of the value. A + function and a symbol have the code `recipher_js::not_a_value`, as for any + value. No code calls a `toJSON` method. +- **`max_depth` is the limit of the code that reads the text.** The limit + counts levels of arrays and objects, so `[1]` is one level. A document + nested deeper has the code `recipher_js::too_deep`. The walk's own limit + of 128 levels applies too. +- **`to_json` writes the text straight into a protected buffer.** The buffer + wipes each allocation it outgrows, and wipes itself when it is dropped. + `to_json` builds no tree of the document. `to_json` writes an object's + members in the order JavaScript lists them. + +### Building a document + +`build_json` builds each number by these rules: + +| In the document | JavaScript | +| ---------------------------------------- | ----------- | +| an integer within 2^53 - 1 of zero | `number` | +| any other integer | `bigint` | +| a float | `number` | + +So an integer never loses a digit. The safe range is 2^53 - 1 either side of +zero. A `bigint` in the safe range comes back as a `number`. For example, +`to_json` writes `5n` as `5`. `build_json` reads `5` as the `number` `5`. + +napi-rs has its own `serde_json` conversion, and `build_json` uses it for +each scalar. That conversion has the number rules above. This crate builds +each array and object itself, from own data properties. This crate refuses a +member named `__proto__`, `constructor`, or `prototype`. + +This crate does not use napi-rs's conversion of a whole document. That +conversion assigns each member (`object[key] = value`), and an assignment +has two unsafe effects: + +- An assignment to a member named `__proto__` sets the object's prototype. +- An assignment runs a setter that a polluted prototype defines. The setter + then receives the decrypted value. + +`build_json` copies nothing out of the document. The document belongs to the +caller, and the caller wipes it. + +This crate does not use napi-rs's conversion in the other direction either, +from a JavaScript value to a `serde_json::Value`. That conversion: + +- writes a whole number above 2^32 as a float; +- writes a `bigint` outside 64 bits as a string; +- drops a member that is `undefined`; +- reads a `Date` as `{}`; +- reads inherited properties; +- replaces an unpaired surrogate. + +`tests/json.cjs` pins each of these. ## 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_js::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. +Four faults in a value stop the walk: -## Safety notes +- a getter that throws; +- a string with an unpaired surrogate; +- a `BigInt` out of range; +- a `Date` outside the range of the wire format. That range is jiff's, about + years -9999 to 9999. + +The walk reports each fault through the sink's `Error::source`, as a +[`JsFault`]. A `JsFault` contains the napi status and the reason. At the +boundary with JavaScript, `JsFault::from_source` turns the fault back into +the napi error. A pending JavaScript exception passes through unchanged, so +the application receives the error that its getter threw. -- 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, except as the value - of a record field that declares a type, which refuses it with the reason - `undefined`. -- 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). +When the fault is this crate's refusal of a value, `JsFault::refusal()` +returns a `Refusal`. A `Refusal` names the rule that the value broke. A +caller reports the refusal from the `Refusal`, and never reads the text of +the reason. + +A `Refusal` is a diagnostic with a stable code and a message. Examples of +the code are `recipher_js::sparse_array` and `ERR_INTEGER_RANGE`. A +`Refusal` also has help, when the caller can do something about the refusal. + +`JsFault::refusal()` returns `None` in two cases: + +- a failure of Node-API's own; +- an exception that the application threw. + +`JsRef::to_frame`, `JsRef::to_json`, `JsBuilder::build`, and +`JsBuilder::build_json` return the `JsFault` itself. + +## Safety notes +### Copies of plaintext in memory + +- V8 is Node's JavaScript engine. The original of each value to encrypt is + in the V8 heap. V8 owns those originals, and Rust cannot wipe them. +- When this crate reads a value, every copy that Rust makes of a string is + wiped on drop. Those copies are the UTF-16 code units and the UTF-8 text + of each value, each key, and each wrapper class's text. This crate builds + the UTF-8 text in a buffer of its final size, so no smaller buffer + remains. This crate parses a wrapper's text in place, and makes no further + copies. +- An error message names no property of the value, with one exception. The + exception is one of the three refused property names in the next section. + An error message contains no other part of the value. +- A frame that `to_frame` makes is `Protected`. The frame is wiped on drop. +- When this crate builds a value, it gives the decrypted text and bytes to + JavaScript. V8 then owns them. The Rust copies made during the build are + not wiped. Those copies are: + - the text of each wrapper class, formatted by this crate or by + `rust_decimal`; + - each map key; + - the bytes copied into a `Buffer`. + +### Property names and nesting depth + +- Three property names would reach the prototype chain: `__proto__`, + `constructor`, and `prototype`. This crate rejects them in both + directions. +- Nesting is limited to 128 levels in both directions. The count is the + frame's count, and includes the levels inside a ciphertext's passthrough + payload. +- The walk and the build each check the depth before they recurse. So Node + does not abort for a tree that is far too deep for the stack. The walk or + the build returns an error instead. A debug build can also walk a document + at the limit. + +### Objects that the walk accepts + +- The walk accepts only plain objects and the wrapper classes for + encryption. A plain object has the prototype `Object.prototype` or `null`. +- A `Map`, a `Set`, a `RegExp`, a `DataView`, a class instance, and other + exotic objects keep their state in internal slots. Each one would silently + encrypt as `{}`, so the walk rejects it with an error. +- The walk gets the prototype through `Object.getPrototypeOf`. That call + runs a `Proxy`'s trap. So a proxied `Map` or `Date` reports its target's + prototype, and is refused. The walk reads a proxy over a plain object + through the proxy's traps. +- A typed array other than a `Uint8Array` is refused. A `DataView` is + refused too. Neither is encrypted as its raw bytes. A `Buffer` is a + `Uint8Array`. + +### Properties and arrays + +- The walk reads only the own, enumerable, string-keyed properties of an + object. So a polluted `Object.prototype`, or an inherited enumerable + getter, can never add a key to the encrypted value. Neither can run code + during encryption. +- An own property explicitly set to `undefined` round-trips. The exception + is the value of a record field that declares a type. That field refuses + `undefined`, with the reason `undefined`. +- A sparse array is rejected, such as `[, , "x"]` or `new Array(n)`. + `[undefined]` is not sparse, and round-trips. The walk detects a hole at + each index with the semantics of `Object.hasOwn`. So a polluted + `Array.prototype` cannot fill a hole with an inherited element. +- No code allocates memory in advance for an array length that JavaScript + reports. `new Array(2**32 - 1)` is one line of code for an attacker, and + creates no elements. This rule applies in the walk, in the build, and + where a ciphertext is rebuilt. + +### Strings + +- A string or an object key with an unpaired UTF-16 surrogate is rejected. + This crate does not silently normalise it. The conversion to UTF-8 would + replace a lone surrogate with U+FFFD. This crate would then encrypt a + plaintext that no longer equals the value the caller passed, or a key that + no longer names its property. +- The walk reads each property back through its original JavaScript key. + +### Values that this crate builds in JavaScript + +- This crate writes everything it builds in JavaScript with own-property + defines, and not with `[[Set]]` assignment. This crate calls + `napi_define_properties` once for each object. The rule covers decrypted + object properties and array elements. The rule also covers every + ciphertext node's `t`, `v`, sequence elements, and map entries. So a + setter that a polluted `Object.prototype` or `Array.prototype` defines can + never receive decrypted plaintext or ciphertext. Such a setter can never + discard a property either. +- A ciphertext node passed back for decryption must be an object. Node-API + reads the properties of a primitive through its wrapper object. Without + this check, a bare string would get `t` and `v` from `String.prototype`. +- Errors contain no cryptographic detail. At the trait layer, the error is + `Unspecified`. ## Cargo features @@ -235,8 +481,8 @@ 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. +This crate requires the Rust standard library (`std`). This crate targets +native Node.js addons. This crate is not a WebAssembly binding. [`Encrypt`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/trait.Encrypt.html diff --git a/languages/typescript/packages/recipher-js/value-napi/src/error.rs b/languages/typescript/packages/recipher-js/value-napi/src/error.rs index da1a2f147..37be3ff7a 100644 --- a/languages/typescript/packages/recipher-js/value-napi/src/error.rs +++ b/languages/typescript/packages/recipher-js/value-napi/src/error.rs @@ -24,10 +24,15 @@ pub enum Refusal { #[error("an object has a property named `__proto__`, `constructor` or `prototype`, which is refused in both directions")] #[diagnostic(code(recipher_js::reserved_key))] ReservedKey, - /// A value nested past [`MAX_DEPTH`](crate::MAX_DEPTH). - #[error("the value is nested deeper than 128 levels")] + /// A value nested past the limit: [`MAX_DEPTH`](crate::MAX_DEPTH), or + /// the limit given for a JSON document. + #[error("the value is nested deeper than {limit} levels")] #[diagnostic(code(recipher_js::too_deep))] - TooDeep, + TooDeep { + /// The largest number of levels of arrays and objects that the value + /// may nest. + limit: usize, + }, /// An array with a hole. #[error("an array has a hole")] #[diagnostic( @@ -55,6 +60,10 @@ pub enum Refusal { )] #[diagnostic(code(recipher_js::unpaired_surrogate))] UnpairedSurrogate, + /// A value that a JSON document cannot contain. + #[error("a JSON document cannot contain {0}")] + #[diagnostic(code(recipher_js::not_json))] + NotJson(NoJsonForm), /// A scalar outside what its type holds. A `TypeError` with the same /// code is pending in JavaScript. #[error(transparent)] @@ -62,6 +71,43 @@ pub enum Refusal { Scalar(#[from] ConversionError), } +/// A value that has no form in a JSON document. Each variant's display text +/// names the kind of value, and never the value. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +#[non_exhaustive] +pub enum NoJsonForm { + /// `undefined`. + #[error("`undefined`")] + Undefined, + /// `NaN`, `Infinity`, or `-Infinity`. + #[error("a number that is not finite")] + NonFinite, + /// A whole `number` from 2^53 up to 2^64, or from -2^53 down to -2^63. + /// A `number` that large may not have the digits that were written. A + /// `bigint` stores the integer exactly. + #[error( + "a whole `number` from 2^53 up to 2^64, or from -2^53 down to -2^63. A `number` that \ + large may not keep the digits that were written. Pass a `bigint` instead." + )] + UnsafeInteger, + /// A whole `number` below -2^63 and above -2^64. A `bigint` that size is + /// refused too, so the integer has no exact form in a document. + #[error( + "a whole `number` below -2^63 and above -2^64. An integer in that range has no exact \ + form in a JSON document, because a `bigint` that size is refused too." + )] + NoExactForm, + /// A `bigint` below -2^63 or above 2^64 - 1. + #[error("a `bigint` outside the 64-bit range. The range is from -2^63 to 2^64 - 1.")] + BigIntRange, + /// A `Buffer`, a typed array, or a `DataView`. + #[error("bytes")] + Bytes, + /// A `Date` or a wrapper class instance. + #[error("a date, a timestamp, a decimal, or a UUID. Write the value as a string instead.")] + Typed, +} + /// 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. @@ -222,12 +268,13 @@ mod tests { let all = vec![ Refusal::NotPlain, Refusal::ReservedKey, - Refusal::TooDeep, + Refusal::TooDeep { limit: 128 }, Refusal::SparseArray, Refusal::NotBytes, Refusal::NotAValue, Refusal::ChangedWhileRead, Refusal::UnpairedSurrogate, + Refusal::NotJson(NoJsonForm::Undefined), Refusal::Scalar(C::IntegerRange), Refusal::Scalar(C::InvalidDate), Refusal::Scalar(C::InvalidTimestamp), @@ -239,12 +286,13 @@ mod tests { match refusal { Refusal::NotPlain | Refusal::ReservedKey - | Refusal::TooDeep + | Refusal::TooDeep { .. } | Refusal::SparseArray | Refusal::NotBytes | Refusal::NotAValue | Refusal::ChangedWhileRead - | Refusal::UnpairedSurrogate => {} + | Refusal::UnpairedSurrogate + | Refusal::NotJson(_) => {} Refusal::Scalar(scalar) => match scalar { C::IntegerRange | C::InvalidDate diff --git a/languages/typescript/packages/recipher-js/value-napi/src/js.rs b/languages/typescript/packages/recipher-js/value-napi/src/js.rs index ac61a7234..35edbe724 100644 --- a/languages/typescript/packages/recipher-js/value-napi/src/js.rs +++ b/languages/typescript/packages/recipher-js/value-napi/src/js.rs @@ -10,7 +10,7 @@ use napi::bindgen_prelude::{ use napi::{check_status, sys, Env, Error, Property, Result, Status, ValueType}; use zeroize::Zeroizing; -use crate::error::{JsFault, Refusal}; +use crate::error::{JsFault, NoJsonForm, Refusal}; /// Maximum nesting depth, in both directions: walking a JavaScript value /// and building one. Bounds recursion so a deeply nested input cannot @@ -27,7 +27,18 @@ pub(crate) fn forbidden_key(key: &str) -> bool { } pub(crate) fn depth_error() -> JsFault { - JsFault::refused(Refusal::TooDeep, "value is nested too deeply") + too_deep(MAX_DEPTH) +} + +/// The refusal of a value that a JSON document cannot contain. +pub(crate) fn not_json_error(form: NoJsonForm) -> JsFault { + let refusal = Refusal::NotJson(form); + JsFault::refused(refusal, refusal.to_string()) +} + +/// The refusal of a value nested past `limit` levels. +pub(crate) fn too_deep(limit: usize) -> JsFault { + JsFault::refused(Refusal::TooDeep { limit }, "value is nested too deeply") } pub(crate) fn forbidden_key_error(key: &str) -> JsFault { 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 index 5bb183def..9e2f9e623 100644 --- a/languages/typescript/packages/recipher-js/value-napi/src/js_ref.rs +++ b/languages/typescript/packages/recipher-js/value-napi/src/js_ref.rs @@ -1,8 +1,10 @@ //! [`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: +//! A walk is one pass over a value and every value nested in it. The walk +//! runs on the JavaScript thread, and reads each value when it reaches that +//! value. The walk builds no tree. The walk copies a scalar out of the +//! JavaScript engine only to pass it straight to the sink. The walk makes one +//! sink call for each value: //! //! | JavaScript | `Sink` call | //! | ---------------------- | ----------------------------------------------- | @@ -17,15 +19,42 @@ //! | `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. +//! The wrapper classes represent the scalars that JavaScript has no type for: //! -//! 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`]. +//! | Class | Scalar | +//! | ------------- | -------------------------------------------- | +//! | `RcDate` | `Date` over the day count | +//! | `RcTimestamp` | `Timestamp(Nanos)` over the nanosecond count | +//! | `RcDecimal` | `Decimal` over the mantissa | +//! | `RcUuid` | `Uuid` over sixteen bytes | +//! +//! Four faults stop the walk: +//! +//! - a getter that throws; +//! - a string with an unpaired surrogate; +//! - a BigInt out of range; +//! - a `Date` outside the range of the wire format. +//! +//! The walk reports each fault through +//! [`Error::source`](vitaminc_aead::plaintext::Error::source). JavaScript +//! receives the fault as that error: see [`JsFault`]. +//! +//! # A JSON document +//! +//! [`JsRef::to_json`] walks a value as a JSON document. `to_json` uses the +//! same walk, with the same safety rules. For a document, the walk reads only +//! the values a JSON document can contain: +//! +//! | JavaScript | In the document | +//! | ----------------------------------------- | --------------------------- | +//! | `null`, `boolean`, `string` | the same | +//! | `Array`, plain object | an array, an object | +//! | whole `number` within 2^53 - 1 of zero | an integer | +//! | whole `number` from 2^53 up to 2^64 | refused | +//! | whole `number` from -2^53 down to -2^64 | refused | +//! | any other finite `number` | a float | +//! | `bigint` within 64 bits | an integer, with its digits | +//! | anything else | refused | use napi::bindgen_prelude::{ Array, BigInt, FromNapiValue, JsObjectValue, JsValue, Object, Uint8ArraySlice, Unknown, @@ -38,10 +67,10 @@ use vitaminc_aead::{ }; use vitaminc_protected::Buffer; -use crate::error::{JsFault, Refusal}; +use crate::error::{JsFault, NoJsonForm, Refusal}; use crate::js::{ - depth_error, forbidden_key, forbidden_key_error, get_own, lossless_string, not_plain_error, - own_enumerable_keys, MAX_DEPTH, + depth_error, forbidden_key, forbidden_key_error, get_own, lossless_string, not_json_error, + not_plain_error, own_enumerable_keys, MAX_DEPTH, }; use crate::scalar::{self, ConversionError}; use crate::wrappers::{Wrapper, Wrappers}; @@ -52,6 +81,16 @@ pub struct JsRef<'e> { depth: usize, } +/// Which values a walk reads. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum Model { + /// Every value in the module's first table. + Value, + /// Only the values a JSON document can contain: the module's second + /// table. + Json, +} + impl<'e> JsRef<'e> { /// The value to walk, as the root of the structure. pub fn new(value: Unknown<'e>) -> Self { @@ -64,6 +103,13 @@ impl<'e> JsRef<'e> { Self { value, depth } } + /// Walk the value into `sink` as a JSON document. The sink receives only + /// nulls, booleans, 64-bit integers, finite floats, text, sequences, and + /// maps. + pub(crate) fn visit_json(self, sink: S) -> Result { + js_walk(self.value, self.depth, Model::Json, sink) + } + /// 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. @@ -79,7 +125,7 @@ impl<'e> JsRef<'e> { impl Encrypt for JsRef<'_> { fn visit(self, sink: S) -> Result { - js_walk(self.value, self.depth, sink) + js_walk(self.value, self.depth, Model::Value, sink) } } @@ -106,26 +152,71 @@ fn js_conversion(env: &Env, error: ConversionError) -> S::Error { } } -fn js_walk(value: Unknown<'_>, depth: usize, sink: S) -> Result { +/// The refusal of a value with no form in a JSON document, as the sink's +/// error. +fn no_json_form(form: NoJsonForm) -> S::Error { + js_fault::(not_json_error(form)) +} + +/// Walk one value. +/// +/// This function, [`js_object`], [`js_array`], and [`js_map`] call each other +/// recursively. Each nested level uses one stack frame of each function. So +/// these functions keep as little on the stack as they can. +/// +/// The code that reads a scalar or builds a refusal is in helper functions. A +/// helper's stack frame is gone before the walk enters a nested container. As +/// a result, a debug build can also walk a document at the depth limit. +fn js_walk( + value: Unknown<'_>, + depth: usize, + model: Model, + sink: S, +) -> Result { if depth > MAX_DEPTH { return Err(js_fault::(depth_error())); } match value.get_type().map_err(js_fault::)? { + ValueType::Object => js_object(value, depth, model, sink), + ty => js_primitive(value, ty, model, sink), + } +} + +/// A value of type `ty`. The value is not an object. +fn js_primitive( + value: Unknown<'_>, + ty: ValueType, + model: Model, + sink: S, +) -> Result { + match ty { ValueType::Null => sink.scalar(None, Physical::Null), - ValueType::Undefined => sink.scalar(Some(Logical::Undefined), Physical::Null), + ValueType::Undefined => match model { + Model::Value => sink.scalar(Some(Logical::Undefined), Physical::Null), + Model::Json => Err(no_json_form::(NoJsonForm::Undefined)), + }, 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))) + let number = match model { + Model::Value => Physical::Float(Float::F64(n)), + Model::Json => scalar::json_number(n).map_err(no_json_form::)?, + }; + sink.scalar(None, number) } 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))?; + let int = match model { + Model::Value => scalar::bigint(big.sign_bit, &big.words) + .map_err(|e| js_conversion::(&env, e))?, + Model::Json => { + scalar::json_bigint(big.sign_bit, &big.words).map_err(no_json_form::)? + } + }; sink.scalar(None, Physical::Int(int)) } ValueType::String => { @@ -134,7 +225,6 @@ fn js_walk(value: Unknown<'_>, depth: usize, sink: S) -> Result)?; 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}"), @@ -142,29 +232,71 @@ fn js_walk(value: Unknown<'_>, depth: usize, sink: S) -> Result(value: Unknown<'_>, depth: usize, sink: S) -> Result { +/// The kind of object, as the walk classifies it. +enum Shape { + /// A `Buffer` or a typed array. + Bytes, + /// An array. + Array, + /// A `Date`. + Date, + /// An instance of a wrapper class. + Wrapped(Wrapper), + /// A plain object. + Map, +} + +/// The shape of `value`, or the refusal of an object the walk does not read. +/// +/// A JSON document cannot contain the scalar shapes: bytes, a `Date`, and a +/// wrapper class instance. This function refuses each one by its shape, +/// before the walk reads it. +fn js_shape(value: Unknown<'_>, model: Model) -> Result { + let json = model == Model::Json; // 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_typedarray()? { + if json { + return Err(not_json_error(NoJsonForm::Bytes)); + } + return Ok(Shape::Bytes); + } + if value.is_dataview()? { + if json { + return Err(not_json_error(NoJsonForm::Bytes)); + } + return Err(not_bytes_error("DataView")); } - if value.is_dataview().map_err(js_fault::)? { - return Err(js_fault::(not_bytes_error("DataView"))); + if value.is_array()? { + return Ok(Shape::Array); } - if value.is_array().map_err(js_fault::)? { - return js_array(value, depth, sink); + if value.is_date()? { + if json { + return Err(not_json_error(NoJsonForm::Typed)); + } + return Ok(Shape::Date); } - if value.is_date().map_err(js_fault::)? { - return js_date(value, sink); + match js_classify(value)? { + Some(_) if json => Err(not_json_error(NoJsonForm::Typed)), + Some(wrapper) => Ok(Shape::Wrapped(wrapper)), + None => Ok(Shape::Map), } - match js_classify(value).map_err(js_fault::)? { - Some(wrapper) => js_wrapped(value, wrapper, sink), - None => js_map(value, depth, sink), +} + +/// Dispatch an object by its shape. +fn js_object( + value: Unknown<'_>, + depth: usize, + model: Model, + sink: S, +) -> Result { + match js_shape(value, model).map_err(js_fault::)? { + Shape::Bytes => js_bytes(value, sink), + Shape::Array => js_array(value, depth, model, sink), + Shape::Date => js_date(value, sink), + Shape::Wrapped(wrapper) => js_wrapped(value, wrapper, sink), + Shape::Map => js_map(value, depth, model, sink), } } @@ -218,7 +350,12 @@ fn js_classify(value: Unknown<'_>) -> Result, JsFault> { } } -fn js_map(value: Unknown<'_>, depth: usize, sink: S) -> Result { +fn js_map( + value: Unknown<'_>, + depth: usize, + model: Model, + 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()))?; @@ -229,12 +366,17 @@ fn js_map(value: Unknown<'_>, depth: usize, sink: S) -> Result)?; - js_walk(value, depth + 1, map.entry(&key.name)?)?; + js_walk(value, depth + 1, model, map.entry(&key.name)?)?; } map.end() } -fn js_array(value: Unknown<'_>, depth: usize, sink: S) -> Result { +fn js_array( + value: Unknown<'_>, + depth: usize, + model: Model, + 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)`, @@ -258,7 +400,7 @@ fn js_array(value: Unknown<'_>, depth: usize, sink: S) -> Result)? .ok_or_else(|| js_fault::(sparse()))?; - js_walk(element, depth + 1, seq.element()?)?; + js_walk(element, depth + 1, model, seq.element()?)?; } seq.end() } @@ -270,12 +412,7 @@ 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 invalid = wrapper.invalid(); 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)), @@ -316,7 +453,10 @@ mod tests { too_deep.reason().contains("nested too deeply"), "{too_deep}" ); - assert_eq!(too_deep.refusal(), Some(Refusal::TooDeep)); + assert_eq!( + too_deep.refusal(), + Some(Refusal::TooDeep { limit: MAX_DEPTH }) + ); let too_long = frame_error(FrameWriteError::TooLong); assert_eq!(too_long.status(), Status::InvalidArg); diff --git a/languages/typescript/packages/recipher-js/value-napi/src/json.rs b/languages/typescript/packages/recipher-js/value-napi/src/json.rs new file mode 100644 index 000000000..016647318 --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/src/json.rs @@ -0,0 +1,602 @@ +//! JSON documents: a JavaScript value written as the text of a document, and +//! a document built as a JavaScript value. +//! +//! # Encrypting: a JavaScript value to JSON text +//! +//! [`JsRef::to_json`] reads a JavaScript value and writes the text of a JSON +//! document. A walk is one pass over a value and every value nested in it. +//! `to_json` uses the same walk as every other value, so the same safety +//! rules apply: +//! +//! - The walk reads only plain objects, by their own enumerable string keys. +//! - The walk refuses a hole in an array, a getter that throws, an unpaired +//! surrogate, and a reserved property name. +//! +//! The [`js_ref`](crate::js_ref) module lists the values a document can +//! contain. +//! +//! `to_json` writes the text straight into a [`Buffer`]. A `Buffer` wipes +//! each allocation it outgrows. A `Buffer` also wipes itself when it is +//! dropped. `to_json` builds no tree of the document, so no other copy of the +//! document stays in memory. +//! +//! # Decrypting: a document to a JavaScript value +//! +//! [`JsBuilder::build_json`] builds the JavaScript value of a +//! `serde_json::Value`. napi-rs has a conversion for each scalar type, and +//! `build_json` uses it. That conversion turns a number into: +//! +//! - a `number`, for an integer within 2^53 - 1 of zero; +//! - a `bigint`, for any other integer, so no digit is lost; +//! - a `number`, for a float. +//! +//! This module writes each array and object itself. napi-rs's conversion of +//! an array or an object assigns each element and member +//! (`object[key] = value`). An assignment has two effects that this module +//! must prevent: +//! +//! - An assignment runs a setter that a polluted prototype defines. The +//! setter would receive the decrypted value. +//! - An assignment to a member named `__proto__` sets the object's prototype. +//! +//! So this module defines each element and member as an own data property. +//! This module also refuses the three reserved property names, as +//! [`JsBuilder`] does for every other value. + +use std::io; + +use napi::bindgen_prelude::{JsValue, Null, ToNapiValue, Unknown}; +use napi::{Env, Status}; +use serde_json::Value; +use vitaminc_aead::{EncryptRef, FixedType, Float, Logical, MapSink, Physical, SeqSink, Sink}; +use vitaminc_protected::Buffer; + +use crate::error::{JsFault, NoJsonForm}; +use crate::js::{ + define_own_properties, depth_error, forbidden_key, forbidden_key_error, new_array, + not_json_error, own_property, too_deep, MAX_DEPTH, +}; +use crate::{JsBuilder, JsRef}; + +impl JsRef<'_> { + /// Write the value as the text of a JSON document. Call this method on + /// the JavaScript thread. The text is plaintext. The method returns the + /// text in a buffer that is wiped when it is dropped. + /// + /// `max_depth` is the largest number of levels of arrays and objects that + /// the document may nest. Pass the limit of the code that will read the + /// text. `[1]` is one level. The walk's own limit, [`MAX_DEPTH`], applies + /// too. + /// + /// The method writes an object's members in the order JavaScript lists + /// them. + /// + /// # Errors + /// + /// Returns a [`JsFault`]. For a value the walk refused, + /// [`JsFault::refusal`] names the rule that the value broke: + /// + /// - [`Refusal::NotJson`], for a value with no JSON form; + /// - [`Refusal::TooDeep`], for a document nested past `max_depth`. + /// + /// No error contains any part of the value. + /// + /// [`Refusal::NotJson`]: crate::Refusal::NotJson + /// [`Refusal::TooDeep`]: crate::Refusal::TooDeep + pub fn to_json(self, max_depth: usize) -> Result { + let mut text = Buffer::new(); + self.visit_json(JsonText::new(&mut text, max_depth))?; + Ok(text) + } +} + +impl<'e> JsBuilder<'e> { + /// The JavaScript value of a JSON document. + /// + /// The function builds each part of the document by these rules: + /// + /// - An integer within 2^53 - 1 of zero becomes a `number`. + /// - Any other integer becomes a `bigint`. + /// - A float becomes a `number`. + /// - An array or an object is built from own data properties. + /// + /// This function copies nothing out of `document`. `document` still + /// belongs to the caller, and the caller wipes it. + /// + /// # Errors + /// + /// Returns a [`JsFault`]. Two refusals apply to a document: + /// + /// - [`Refusal::ReservedKey`], for an object with a member named + /// `__proto__`, `constructor`, or `prototype`; + /// - [`Refusal::TooDeep`], for a document nested past [`MAX_DEPTH`]. + /// + /// [`Refusal::ReservedKey`]: crate::Refusal::ReservedKey + /// [`Refusal::TooDeep`]: crate::Refusal::TooDeep + pub fn build_json(env: &'e Env, document: &Value) -> Result, JsFault> { + json_to_js(env, document, 0) + } +} + +/// The JavaScript value of `value`. `value` is `depth` levels down in its +/// document. +fn json_to_js<'e>(env: &'e Env, value: &Value, depth: usize) -> Result, JsFault> { + if depth > MAX_DEPTH { + return Err(depth_error()); + } + match value { + Value::Null => Ok(Null.into_unknown(env)?), + Value::Bool(flag) => Ok((*flag).into_unknown(env)?), + // napi-rs converts a `serde_json::Number`. The module docs say which + // numbers become a `bigint`. + Value::Number(number) => Ok(number.into_unknown(env)?), + Value::String(text) => Ok(text.as_str().into_unknown(env)?), + Value::Array(items) => { + let mut built = Vec::with_capacity(items.len()); + for item in items { + built.push(json_to_js(env, item, depth + 1)?); + } + let mut array = new_array(env, built.len())?; + let mut elements = Vec::with_capacity(built.len()); + for (index, item) in built.iter().enumerate() { + elements.push(own_property(env, &index.to_string(), item)?); + } + define_own_properties(&mut array, &elements)?; + Ok(array.to_unknown()) + } + Value::Object(members) => { + let mut built = Vec::with_capacity(members.len()); + for (key, member) in members { + if forbidden_key(key) { + return Err(forbidden_key_error(key)); + } + built.push((key, json_to_js(env, member, depth + 1)?)); + } + let mut object = napi::bindgen_prelude::Object::new(env)?; + let mut properties = Vec::with_capacity(built.len()); + for (key, member) in &built { + properties.push(own_property(env, key, member)?); + } + define_own_properties(&mut object, &properties)?; + Ok(object.to_unknown()) + } + } +} + +/// A sink that writes one value as JSON text. +/// +/// The sink writes the values a JSON document can contain: a null, a boolean, +/// an integer, a finite float, text, a sequence, and a map. The sink refuses +/// anything else. The sink writes an integer of any width with its digits. +/// The code that reads the text decides which integers it accepts. +/// +/// If a walk fails part way, the buffer keeps the text written so far. The +/// buffer belongs to the caller, and is wiped when it is dropped. +pub(crate) struct JsonText<'b> { + out: &'b mut Buffer, + /// How many more levels of sequences and maps may open here. + levels: usize, + /// The limit the document was given, for the refusal's message. + limit: usize, +} + +impl<'b> JsonText<'b> { + /// A sink that writes one document into `out`, nested at most + /// `max_depth` levels of sequences and maps. + pub(crate) fn new(out: &'b mut Buffer, max_depth: usize) -> Self { + Self { + out, + levels: max_depth, + limit: max_depth, + } + } + + /// The levels left for the children of a sequence or map that opens + /// here, or the refusal of one that opens past the limit. + fn open(&self) -> Result { + self.levels + .checked_sub(1) + .ok_or_else(|| too_deep(self.limit)) + } +} + +/// Appends to a [`Buffer`], so `serde_json` can write into one. +struct Append<'a>(&'a mut Buffer); + +impl io::Write for Append<'_> { + fn write(&mut self, bytes: &[u8]) -> io::Result { + self.0.extend_from_slice(bytes); + Ok(bytes.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +/// Writes one scalar as `serde_json` writes it: +/// +/// - text with its escapes; +/// - an integer as its digits; +/// - a float in the shortest form that reads back as the same float. +/// +/// `serde_json` writes each one straight into `out`. +fn write_scalar(out: &mut Buffer, value: &T) -> Result<(), JsFault> { + // Only the writer can fail here, and this writer never fails. This code + // drops the error's text, so the error contains no part of the value. + serde_json::to_writer(Append(out), value) + .map_err(|_| JsFault::new(Status::GenericFailure, "JSON text could not be written")) +} + +impl<'b> Sink for JsonText<'b> { + type Ok = (); + type Error = JsFault; + type Seq = JsonSeq<'b>; + type Map = JsonMap<'b>; + + fn scalar(self, ty: Option, value: Physical<'_>) -> Result<(), JsFault> { + match (ty, value) { + (None, Physical::Null) => { + self.out.extend_from_slice(b"null"); + Ok(()) + } + (None, Physical::Bool(flag)) => write_scalar(self.out, &flag), + (None, Physical::Int(int)) => match int.to_i128() { + Some(signed) => write_scalar(self.out, &signed), + // Only a `u128` above `i128::MAX` does not fit an `i128`. + None => write_scalar(self.out, &int.to_u128().unwrap_or(u128::MAX)), + }, + (None, Physical::Float(float)) => { + let float = match float { + Float::F32(narrow) => f64::from(narrow), + Float::F64(wide) => wide, + }; + // `serde_json` writes a float that is not finite as `null`. + if !float.is_finite() { + return Err(not_json_error(NoJsonForm::NonFinite)); + } + write_scalar(self.out, &float) + } + (None, Physical::Text(text)) => write_scalar(self.out, text), + (None, Physical::Bytes(_)) => Err(not_json_error(NoJsonForm::Bytes)), + (Some(Logical::Undefined), _) => Err(not_json_error(NoJsonForm::Undefined)), + (Some(_), _) => Err(not_json_error(NoJsonForm::Typed)), + } + } + + /// An absent value is JSON's `null`, whatever its type. + fn typed_null(self, _: FixedType) -> Result<(), JsFault> { + self.scalar(None, Physical::Null) + } + + fn seq(self, _: Option) -> Result, JsFault> { + let levels = self.open()?; + self.out.push(b'['); + Ok(JsonSeq(Container { + out: self.out, + levels, + limit: self.limit, + empty: true, + })) + } + + fn map(self, _: Option) -> Result, JsFault> { + let levels = self.open()?; + self.out.push(b'{'); + Ok(JsonMap(Container { + out: self.out, + levels, + limit: self.limit, + empty: true, + })) + } + + fn passthrough(self, _: &P) -> Result<(), JsFault> { + Err(JsFault::new( + Status::InvalidArg, + "a passthrough has no JSON form", + )) + } +} + +/// An array or an object that is being written. +struct Container<'b> { + out: &'b mut Buffer, + levels: usize, + limit: usize, + /// Whether no element or member has been written yet. + empty: bool, +} + +impl Container<'_> { + /// The sink for the next element or member's value, after the comma + /// that separates it from the one before. + fn next(&mut self) -> JsonText<'_> { + if !self.empty { + self.out.push(b','); + } + self.empty = false; + JsonText { + out: self.out, + levels: self.levels, + limit: self.limit, + } + } +} + +/// The sequence side of [`JsonText`]: a JSON array. +pub(crate) struct JsonSeq<'b>(Container<'b>); + +impl SeqSink for JsonSeq<'_> { + type Ok = (); + type Error = JsFault; + type Element<'s> + = JsonText<'s> + where + Self: 's; + + fn element(&mut self) -> Result, JsFault> { + Ok(self.0.next()) + } + + fn end(self) -> Result<(), JsFault> { + self.0.out.push(b']'); + Ok(()) + } +} + +/// The map side of [`JsonText`]: a JSON object. +pub(crate) struct JsonMap<'b>(Container<'b>); + +impl MapSink for JsonMap<'_> { + type Ok = (); + type Error = JsFault; + type Entry<'s> + = JsonText<'s> + where + Self: 's; + + fn entry(&mut self, key: &str) -> Result, JsFault> { + let value = self.0.next(); + write_scalar(value.out, key)?; + value.out.push(b':'); + Ok(value) + } + + fn end(self) -> Result<(), JsFault> { + self.0.out.push(b'}'); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use vitaminc_aead::{Encrypt, Int}; + use vitaminc_protected::Controlled; + + use super::*; + use crate::Refusal; + + /// The JSON text of `value`, nested at most `max_depth` levels. + fn text_within(value: impl Encrypt, max_depth: usize) -> Result { + let mut out = Buffer::new(); + value.visit(JsonText::new(&mut out, max_depth))?; + Ok(String::from_utf8(out.risky_ref().clone()).expect("JSON text is UTF-8")) + } + + fn text(value: impl Encrypt) -> String { + text_within(value, 127).expect("a JSON value") + } + + fn refused(value: impl Encrypt) -> Refusal { + text_within(value, 127) + .expect_err("no JSON form") + .refusal() + .expect("a refusal") + } + + /// One scalar, sent to the sink as it is. + struct Scalar<'a>(Option, Physical<'a>); + + impl Encrypt for Scalar<'_> { + fn visit(self, sink: S) -> Result { + sink.scalar(self.0, self.1) + } + } + + /// `.0` arrays, each inside the one before. The innermost is empty. + struct Nested(usize); + + impl Encrypt for Nested { + fn visit(self, sink: S) -> Result { + let mut seq = sink.seq(None)?; + if self.0 > 1 { + Nested(self.0 - 1).visit(seq.element()?)?; + } + seq.end() + } + } + + #[test] + fn scalars_are_written_as_json() { + assert_eq!(text(Scalar(None, Physical::Null)), "null"); + assert_eq!(text(true), "true"); + assert_eq!(text(false), "false"); + assert_eq!(text("plain"), r#""plain""#); + assert_eq!(text(-7i64), "-7"); + assert_eq!(text(1.5f64), "1.5"); + assert_eq!(text(1.5f32), "1.5"); + } + + #[test] + fn an_integer_is_written_with_its_digits_and_no_fraction() { + // The number a Go or a Rust reader must read into an integer field. + assert_eq!(text(5_000_000_000i64), "5000000000"); + assert_eq!(text(i64::MIN), "-9223372036854775808"); + assert_eq!(text(u64::MAX), "18446744073709551615"); + // The sink writes every width. The reader decides which widths it + // accepts. + assert_eq!( + text(Scalar(None, Physical::Int(Int::U128(u128::MAX)))), + u128::MAX.to_string() + ); + assert_eq!( + text(Scalar(None, Physical::Int(Int::I128(i128::MIN)))), + i128::MIN.to_string() + ); + } + + #[test] + fn a_float_is_written_as_a_float_that_reads_back_the_same() { + assert_eq!(text(5.0f64), "5.0"); + assert_eq!(text(0.1f64), "0.1"); + assert_eq!(text(-0.0f64), "-0.0"); + for float in [ + 5.0f64, + 0.1, + 1e20, + -6.02e23, + f64::MAX, + f64::MIN, + 5e-324, + -0.0, + ] { + let written = text(float); + // A fraction or an exponent: a reader reads it as a float, never + // as an integer out of range. + assert!(written.contains(['.', 'e']), "{written}"); + let read: f64 = serde_json::from_str(&written).unwrap(); + assert_eq!(read.to_bits(), float.to_bits(), "{written}"); + } + } + + #[test] + fn a_float_that_is_not_finite_is_refused_not_written_as_null() { + for float in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert_eq!(refused(float), Refusal::NotJson(NoJsonForm::NonFinite)); + } + assert_eq!(refused(f32::NAN), Refusal::NotJson(NoJsonForm::NonFinite)); + } + + #[test] + fn text_is_escaped_and_reads_back_as_itself() { + for plain in [ + "", + "quote \" and backslash \\", + "line\nfeed, tab\t, nul\0, and \u{1f}", + "José, 日本, 😀, \u{2028} and \u{10FFFF}", + ] { + let written = text(plain); + let read: String = serde_json::from_str(&written).unwrap(); + assert_eq!(read, plain, "{written}"); + } + assert_eq!(text("a\"b\n"), r#""a\"b\n""#); + } + + #[test] + fn arrays_and_objects_are_written_with_their_separators() { + assert_eq!(text(Vec::::new()), "[]"); + assert_eq!(text(vec![1i64]), "[1]"); + assert_eq!(text(vec![vec![1i64, 2], vec![]]), "[[1,2],[]]"); + assert_eq!(text(BTreeMap::::new()), "{}"); + let object: BTreeMap>> = [ + ("a \"key\"".to_owned(), vec![Some(true), None]), + ("b".to_owned(), vec![]), + ] + .into(); + assert_eq!(text(object), r#"{"a \"key\"":[true,null],"b":[]}"#); + } + + #[test] + fn a_typed_null_is_null() { + assert_eq!(text(None::), "null"); + } + + #[test] + fn a_value_with_no_json_form_is_refused_by_what_it_is() { + assert_eq!( + refused(Scalar(None, Physical::Bytes(&[1, 2, 3]))), + Refusal::NotJson(NoJsonForm::Bytes) + ); + assert_eq!( + refused(Scalar(Some(Logical::Undefined), Physical::Null)), + Refusal::NotJson(NoJsonForm::Undefined) + ); + assert_eq!( + refused(Scalar(Some(Logical::Date), Physical::Int(Int::I32(1)))), + Refusal::NotJson(NoJsonForm::Typed) + ); + assert_eq!( + refused(Scalar(Some(Logical::Uuid), Physical::Bytes(&[0; 16]))), + Refusal::NotJson(NoJsonForm::Typed) + ); + } + + #[test] + fn a_refusal_names_the_kind_of_value_and_never_the_value() { + let fault = text_within(vec!["a secret".to_owned()], 0).expect_err("too deep"); + assert_eq!(fault.refusal(), Some(Refusal::TooDeep { limit: 0 })); + assert!(!fault.reason().contains("secret")); + let fault = text_within(Scalar(None, Physical::Bytes(b"a secret")), 1).expect_err("bytes"); + assert_eq!(fault.reason(), "a JSON document cannot contain bytes"); + assert_eq!(fault.status(), Status::InvalidArg); + } + + #[test] + fn a_document_nests_as_deep_as_the_limit_and_no_deeper() { + for limit in [1usize, 2, 127] { + let deepest = text_within(Nested(limit), limit).expect("at the limit"); + assert_eq!( + deepest, + format!("{}{}", "[".repeat(limit), "]".repeat(limit)) + ); + let fault = text_within(Nested(limit + 1), limit).expect_err("past the limit"); + assert_eq!(fault.refusal(), Some(Refusal::TooDeep { limit })); + } + // A scalar adds no level, so a scalar is a document at any limit. + assert_eq!(text_within(5i64, 0).unwrap(), "5"); + assert!(text_within(Nested(1), 0).is_err()); + // A map is a level, as an array is. + let object: BTreeMap> = [("k".to_owned(), vec![])].into(); + assert_eq!(text_within(object.clone(), 2).unwrap(), r#"{"k":[]}"#); + assert!(text_within(object, 1).is_err()); + } + + #[test] + fn the_refusal_of_a_deep_document_states_the_limit_it_was_given() { + let fault = text_within(Nested(128), 127).expect_err("past the limit"); + assert_eq!( + fault.refusal().map(|refusal| refusal.to_string()), + Some("the value is nested deeper than 127 levels".to_owned()) + ); + } + + #[test] + fn a_passthrough_has_not_json_error() { + struct Clear; + impl Encrypt for Clear { + fn visit(self, sink: S) -> Result { + sink.passthrough("in the clear") + } + } + let fault = text_within(Clear, 127).expect_err("a passthrough"); + assert_eq!(fault.refusal(), None); + assert!(!fault.reason().contains("in the clear")); + } + + #[test] + fn the_text_of_a_document_parses_as_that_document() { + let object: BTreeMap>> = [ + ("floats".to_owned(), vec![Some(1.5), None, Some(-2.25e-7)]), + ("none".to_owned(), vec![]), + ] + .into(); + let read: serde_json::Value = serde_json::from_str(&text(object)).unwrap(); + assert_eq!( + read, + serde_json::json!({"floats": [1.5, null, -2.25e-7], "none": []}) + ); + } +} diff --git a/languages/typescript/packages/recipher-js/value-napi/src/lib.rs b/languages/typescript/packages/recipher-js/value-napi/src/lib.rs index 4288bb659..256eebea8 100644 --- a/languages/typescript/packages/recipher-js/value-napi/src/lib.rs +++ b/languages/typescript/packages/recipher-js/value-napi/src/lib.rs @@ -29,11 +29,12 @@ mod error; mod js; mod js_builder; mod js_ref; +mod json; mod scalar; mod wrappers; pub use ciphertext::{JsCipherText, NapiPassthrough}; -pub use error::{JsFault, Refusal}; +pub use error::{JsFault, NoJsonForm, Refusal}; pub use js::MAX_DEPTH; pub use js_builder::JsBuilder; pub use js_ref::JsRef; diff --git a/languages/typescript/packages/recipher-js/value-napi/src/scalar.rs b/languages/typescript/packages/recipher-js/value-napi/src/scalar.rs index d4efb9a37..f4d6b2ffd 100644 --- a/languages/typescript/packages/recipher-js/value-napi/src/scalar.rs +++ b/languages/typescript/packages/recipher-js/value-napi/src/scalar.rs @@ -9,7 +9,9 @@ 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}; +use vitaminc_aead::{Float, Int, Logical, Physical, TimeUnit}; + +use crate::error::NoJsonForm; /// Host scalar conversion errors. Node receives a TypeError with the same /// stable code; errors contain no user plaintext. @@ -116,6 +118,75 @@ fn unsigned(value: u128) -> Int { } } +/// The largest whole number that a JavaScript `number` stores exactly: 2^53 - +/// 1, `Number.MAX_SAFE_INTEGER`. +const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0; + +/// 2^64: the least magnitude above every 64-bit integer. +const TWO_TO_64: f64 = 18_446_744_073_709_551_616.0; + +/// -2^63: the least `i64`, and the least integer a `bigint` in a document +/// can be. +const MINUS_TWO_TO_63: f64 = -9_223_372_036_854_775_808.0; + +/// A JavaScript `number` as a JSON document stores it. +/// +/// The safe range is 2^53 - 1 either side of zero. A whole number within the +/// safe range is an integer, as `JSON.stringify` writes it: `5`, not `5.0`. +/// So a reader in another language can read it into an integer field. `-0` is +/// the integer `0`. +/// +/// A whole number from 2^53 up to 2^64, or from -2^53 down to -2^63, is +/// refused. A `number` that large may not have the digits that were written. +/// An integer was probably meant, and a `bigint` stores an integer exactly. +/// +/// A whole number below -2^63 and above -2^64 is refused with its own error. +/// A `bigint` that size is refused too, so the refusal does not ask for one. +/// +/// Any other finite number is a float: a number with a fraction, or a number +/// of 2^64 or more either side of zero. +pub(crate) fn json_number(value: f64) -> Result, NoJsonForm> { + if !value.is_finite() { + return Err(NoJsonForm::NonFinite); + } + let magnitude = value.abs(); + if value.fract() == 0.0 && magnitude < TWO_TO_64 { + if value < MINUS_TWO_TO_63 { + return Err(NoJsonForm::NoExactForm); + } + if magnitude > MAX_SAFE_INTEGER { + return Err(NoJsonForm::UnsafeInteger); + } + // A whole number in the safe range is an `i64` exactly. + return Ok(Physical::Int(Int::I64(value as i64))); + } + Ok(Physical::Float(Float::F64(value))) +} + +/// A JavaScript `bigint` as a JSON document stores it: a signed or an +/// unsigned 64-bit integer. A JSON parser in Rust or Go reads no wider +/// integer. So a `bigint` outside that range is refused, whatever its size. +pub(crate) fn json_bigint(negative: bool, words: &[u64]) -> Result { + if words + .get(1..) + .is_some_and(|tail| tail.iter().any(|&word| word != 0)) + { + return Err(NoJsonForm::BigIntRange); + } + let magnitude = words.first().copied().unwrap_or(0); + if negative && magnitude != 0 { + // -2^63 is the least `i64`. 2^63 does not fit an `i64`, so negate as + // an `i128`. + return i64::try_from(-i128::from(magnitude)) + .map(Int::I64) + .map_err(|_| NoJsonForm::BigIntRange); + } + Ok(match i64::try_from(magnitude) { + Ok(value) => Int::I64(value), + Err(_) => Int::U64(magnitude), + }) +} + /// 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) { @@ -262,7 +333,7 @@ pub(crate) fn timestamp_js_millis(unit: TimeUnit, count: Int) -> Option { } /// A stored timestamp as RFC 3339 text with nanoseconds, for the -/// `VcTimestamp` wrapper. +/// `RcTimestamp` wrapper. pub(crate) fn timestamp_text(unit: TimeUnit, count: Int) -> Option { kinds_jiff::timestamp(unit, count).map(|instant| format!("{instant:.9}")) } @@ -296,7 +367,7 @@ pub(crate) fn decimal(text: &str) -> Result<(u8, Int), ConversionError> { Ok((scale, Int::I128(mantissa))) } -/// A stored decimal as fixed-point text with its scale, for the `VcDecimal` +/// A stored decimal as fixed-point text with its scale, for the `RcDecimal` /// wrapper. pub(crate) fn decimal_text(scale: u8, mantissa: Int) -> Option { kinds_decimal::decimal(scale, mantissa).map(|value| value.to_string()) @@ -341,6 +412,152 @@ mod tests { use super::*; use vitaminc_aead::plaintext::kinds::{MAX_TIMESTAMP_NANOS, MIN_TIMESTAMP_NANOS}; + #[test] + fn a_whole_number_in_the_safe_range_is_a_json_integer() { + for (number, integer) in [ + (0.0, 0i64), + (5.0, 5), + (-5.0, -5), + // Above 2^32, where a float would be written `5000000000.0`. + (5_000_000_000.0, 5_000_000_000), + (-5_000_000_000.0, -5_000_000_000), + // A millisecond timestamp. + (1_764_288_000_000.0, 1_764_288_000_000), + (MAX_SAFE_INTEGER, 9_007_199_254_740_991), + (-MAX_SAFE_INTEGER, -9_007_199_254_740_991), + ] { + assert_eq!( + json_number(number), + Ok(Physical::Int(Int::I64(integer))), + "{number}" + ); + } + // `JSON.stringify(-0)` is `0`. + assert_eq!(json_number(-0.0), Ok(Physical::Int(Int::I64(0)))); + } + + #[test] + fn a_whole_number_from_2_53_up_to_2_64_is_refused() { + // 2^53, the next number a `number` can store, and the largest + // `number` below 2^64. Below zero: -2^53, the next number, and -2^63. + // A `bigint` can be -2^63. + for number in [ + 9_007_199_254_740_992.0, + 9_007_199_254_740_994.0, + 1e17, + 18_446_744_073_709_549_568.0, + -9_007_199_254_740_992.0, + -9_007_199_254_740_994.0, + MINUS_TWO_TO_63, + ] { + assert_eq!( + json_number(number), + Err(NoJsonForm::UnsafeInteger), + "{number}" + ); + } + } + + #[test] + fn a_whole_number_below_minus_2_63_and_above_minus_2_64_has_no_exact_form() { + // The first `number` below -2^63 is -2^63 - 2048, because -2^63 - 1 + // rounds to -2^63. Then -1e19, and the last `number` above -2^64. + for number in [ + -9_223_372_036_854_777_856.0, + -1e19, + -18_446_744_073_709_549_568.0, + ] { + assert_eq!( + json_number(number), + Err(NoJsonForm::NoExactForm), + "{number}" + ); + } + // -2^64 itself is a float, and -2^63 as a `bigint` is an integer. + assert_eq!( + json_number(-TWO_TO_64), + Ok(Physical::Float(Float::F64(-TWO_TO_64))) + ); + assert_eq!(json_bigint(true, &[1 << 63]), Ok(Int::I64(i64::MIN))); + } + + #[test] + fn any_other_finite_number_is_a_json_float() { + for number in [ + 0.5, + -1.5, + 5e-324, + // The largest `number` below 2^53 that is not whole. + 4_503_599_627_370_495.5, + // 2^64 and above: not an integer that the document's readers + // accept. + TWO_TO_64, + -TWO_TO_64, + 1e20, + f64::MAX, + f64::MIN, + ] { + assert_eq!( + json_number(number), + Ok(Physical::Float(Float::F64(number))), + "{number}" + ); + } + } + + #[test] + fn a_number_that_is_not_finite_is_refused() { + for number in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert_eq!(json_number(number), Err(NoJsonForm::NonFinite)); + } + } + + #[test] + fn a_bigint_within_64_bits_is_a_json_integer() { + assert_eq!(json_bigint(false, &[]), Ok(Int::I64(0))); + assert_eq!(json_bigint(false, &[0]), Ok(Int::I64(0))); + // `-0n` is `0n`, whatever its sign bit. + assert_eq!(json_bigint(true, &[0]), Ok(Int::I64(0))); + assert_eq!(json_bigint(false, &[5]), Ok(Int::I64(5))); + assert_eq!(json_bigint(true, &[5]), Ok(Int::I64(-5))); + assert_eq!(json_bigint(false, &[5, 0, 0]), Ok(Int::I64(5))); + assert_eq!( + json_bigint(false, &[i64::MAX as u64]), + Ok(Int::I64(i64::MAX)) + ); + assert_eq!( + json_bigint(false, &[1 << 63]), + Ok(Int::U64(1 << 63)), + "2^63 is no i64" + ); + assert_eq!(json_bigint(false, &[u64::MAX]), Ok(Int::U64(u64::MAX))); + assert_eq!(json_bigint(true, &[1 << 63]), Ok(Int::I64(i64::MIN))); + assert_eq!( + json_bigint(true, &[(1 << 63) - 1]), + Ok(Int::I64(i64::MIN + 1)) + ); + } + + #[test] + fn a_bigint_outside_64_bits_is_refused_whatever_its_size() { + for (negative, words) in [ + // 2^64, and -(2^63) - 1. + (false, &[0, 1][..]), + (true, &[(1 << 63) + 1][..]), + (true, &[u64::MAX][..]), + (true, &[0, 1][..]), + // Past 128 bits, where `bigint` refuses with another error. + (false, &[0, 0, 1][..]), + (true, &[0, 0, 0, 1][..]), + ] { + assert_eq!( + json_bigint(negative, words), + Err(NoJsonForm::BigIntRange), + "{negative} {words:?}" + ); + } + } + fn width(int: Int) -> &'static str { match int { Int::I8(_) => "i8", diff --git a/languages/typescript/packages/recipher-js/value-napi/src/wrappers.js b/languages/typescript/packages/recipher-js/value-napi/src/wrappers.js index de914d704..f50376156 100644 --- a/languages/typescript/packages/recipher-js/value-napi/src/wrappers.js +++ b/languages/typescript/packages/recipher-js/value-napi/src/wrappers.js @@ -2,12 +2,20 @@ // 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, +// A wrapper holds its text and nothing else. `value` is an own, enumerable, // read-only property, so `JSON.stringify`, `structuredClone` and a deep // equality see it. // +// An application makes an instance with the static `from(text)`, which +// returns what the factory installed from Rust returns: for the SDK, a +// `Result`. The factory checks the text with the rule `encrypt` uses, so +// an instance that `from` made is valid. The constructor takes a token that +// only this script holds, so `new RcDate(..)` is not a way to make one: it +// throws a `TypeError` that names `from`. Rust makes an instance with +// `make`, for a decrypted value. The text is still checked when the value +// is encrypted, because `Object.create` makes an object that `instanceof` +// accepts without the constructor. +// // 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 @@ -36,6 +44,11 @@ getter(SharedArrayBuffer.prototype, 'byteLength'), ]) const brandCount = brands.length + // The token the constructor takes. Only this script holds it. + const token = freeze({ __proto__: null }) + // The function `from` calls, installed once from Rust. Until then, `from` + // throws, as every call of an addon loaded without its package does. + let factory = null const isSlotted = (value) => { for (let i = 0; i < brandCount; i++) { try { @@ -50,9 +63,11 @@ const define = (name) => { const cls = { [name]: class { - constructor(value) { - if (typeof value !== 'string') { - throw new TypeError(`${name} takes a string`) + constructor(key, value) { + if (key !== token) { + throw new TypeError( + `${name} has no public constructor. Make one with ${name}.from(text), which returns a Result.`, + ) } defineProperty(this, 'value', { __proto__: null, @@ -61,6 +76,14 @@ }) freeze(this) } + static from(text) { + if (factory === null) { + throw new TypeError( + `${name}.from needs the factory that @cipherstash/recipher installs when it loads the addon`, + ) + } + return factory(name, text) + } toJSON() { return this.value } @@ -75,12 +98,31 @@ freeze(cls.prototype) return freeze(cls) } + const classes = freeze({ + __proto__: null, + RcDate: define('RcDate'), + RcTimestamp: define('RcTimestamp'), + RcDecimal: define('RcDecimal'), + RcUuid: define('RcUuid'), + }) return freeze({ __proto__: null, - VcDate: define('VcDate'), - VcTimestamp: define('VcTimestamp'), - VcDecimal: define('VcDecimal'), - VcUuid: define('VcUuid'), + RcDate: classes.RcDate, + RcTimestamp: classes.RcTimestamp, + RcDecimal: classes.RcDecimal, + RcUuid: classes.RcUuid, + // A new instance of the class `name` holding `value`, for Rust only. The + // text is not checked here: Rust passes text it built or checked. + make: (name, value) => new classes[name](token, value), + // Sets the function `from` calls, once. Returns whether it was set: a + // second call keeps the first function. + install: (fn) => { + if (factory !== null || typeof fn !== 'function') { + return false + } + factory = fn + return true + }, // 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 diff --git a/languages/typescript/packages/recipher-js/value-napi/src/wrappers.rs b/languages/typescript/packages/recipher-js/value-napi/src/wrappers.rs index 060de89b0..c973975a3 100644 --- a/languages/typescript/packages/recipher-js/value-napi/src/wrappers.rs +++ b/languages/typescript/packages/recipher-js/value-napi/src/wrappers.rs @@ -1,25 +1,46 @@ -//! The wrapper classes: `VcDate`, `VcTimestamp`, `VcDecimal` and `VcUuid`. +//! The wrapper classes: `RcDate`, `RcTimestamp`, `RcDecimal`, and `RcUuid`. //! -//! 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). +//! JavaScript has no type of its own for four kinds of value: //! -//! 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. +//! - a calendar date; +//! - a timestamp finer than a millisecond; +//! - a decimal; +//! - a universally unique identifier (UUID). +//! +//! This crate represents each one as an instance of a small class. The +//! instance stores the value's text. A class instance is not a plain object. +//! So no code can confuse an instance with a plain one-key object that +//! another language wrote. +//! +//! The JavaScript in `wrappers.js` defines the classes. This crate evaluates +//! that JavaScript once for each environment. The JavaScript returns a frozen +//! object that contains the classes and the plain-object check. +//! +//! This crate keeps the object in a registry keyed by the environment. An +//! environment cleanup hook releases the object. So this crate never reads +//! or changes the addon's own instance data (`napi_set_instance_data`). +//! +//! An addon exports the classes with [`Wrappers::exports`]. An application +//! makes an instance with the class's static `from(text)`. `from` calls the +//! factory that the addon installs with [`Wrappers::install_from`], and +//! returns what the factory returns. A factory that calls +//! [`Wrappers::from_text`] checks the text with the rule that the walk +//! applies when the value is encrypted. So an instance that `from` made is +//! valid. +//! +//! The constructor takes a token that only the script holds, so +//! `new RcDate(..)` throws a `TypeError` that names `from`. The walk in the +//! `js_ref` module recognises an instance with `instanceof`. `JsBuilder` +//! makes instances through the script, with the token. 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}; +use napi::bindgen_prelude::{FnArgs, Function, JsObjectValue, JsValue, Object, ObjectRef, Unknown}; +use napi::{Env, Error, Result, Status, ValueType}; + +use crate::error::Refusal; +use crate::scalar::{self, ConversionError}; /// Which wrapper class a value is an instance of. /// @@ -28,13 +49,13 @@ use napi::{Env, Error, Result, Status}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[non_exhaustive] pub enum Wrapper { - /// `VcDate`: a calendar date as `YYYY-MM-DD`. + /// `RcDate`: a calendar date as `YYYY-MM-DD`. Date, - /// `VcTimestamp`: an instant as RFC 3339 text, to the nanosecond. + /// `RcTimestamp`: an instant as RFC 3339 text, to the nanosecond. Timestamp, - /// `VcDecimal`: a fixed-point decimal as text. + /// `RcDecimal`: a fixed-point decimal as text. Decimal, - /// `VcUuid`: a UUID as hyphenated hexadecimal. + /// `RcUuid`: a UUID as hyphenated hexadecimal. Uuid, } @@ -50,10 +71,39 @@ impl Wrapper { /// 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", + Wrapper::Date => "RcDate", + Wrapper::Timestamp => "RcTimestamp", + Wrapper::Decimal => "RcDecimal", + Wrapper::Uuid => "RcUuid", + } + } + + /// The wrapper class named `name`, as JavaScript sees it, if any. + pub fn from_class_name(name: &str) -> Option { + Self::ALL + .iter() + .copied() + .find(|wrapper| wrapper.class_name() == name) + } + + /// The error for text that is not a value of this class. + pub(crate) fn invalid(self) -> ConversionError { + match self { + Wrapper::Date => ConversionError::InvalidDate, + Wrapper::Timestamp => ConversionError::InvalidTimestamp, + Wrapper::Decimal => ConversionError::InvalidDecimal, + Wrapper::Uuid => ConversionError::InvalidUuid, + } + } + + /// Checks `text` with the rule the walk applies when it encrypts an + /// instance of this class. + pub(crate) fn check(self, text: &str) -> std::result::Result<(), ConversionError> { + match self { + Wrapper::Date => scalar::date(text).map(drop), + Wrapper::Timestamp => scalar::timestamp(text).map(drop), + Wrapper::Decimal => scalar::decimal(text).map(drop), + Wrapper::Uuid => scalar::uuid(text).map(drop), } } } @@ -66,6 +116,13 @@ const VALUE: &str = "value"; /// The property of the script's result that answers the plain-object check. const IS_PLAIN: &str = "isPlain"; +/// The property of the script's result that makes an instance, with the +/// token the constructor takes. +const MAKE: &str = "make"; + +/// The property of the script's result that sets the factory `from` calls. +const INSTALL: &str = "install"; + /// 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. @@ -113,8 +170,8 @@ impl<'e> Wrappers<'e> { Ok(Self { classes }) } - /// An object holding every class under its name, for an addon to - /// re-export: `VcDate`, `VcTimestamp`, `VcDecimal` and `VcUuid`. + /// An object with every class under its name, for an addon to re-export: + /// `RcDate`, `RcTimestamp`, `RcDecimal`, and `RcUuid`. pub fn exports(env: &'e Env) -> Result> { let wrappers = Self::get(env)?; let mut exports = Object::new(env)?; @@ -183,9 +240,71 @@ impl<'e> Wrappers<'e> { Ok((text.get_type()? == napi::ValueType::String).then_some(text)) } - /// A new instance of `wrapper` holding `text`. + /// A new instance of `wrapper` holding `text`. The text is not + /// checked: pass text built from a stored value, or checked with + /// [`Wrappers::from_text`]. pub fn construct(&self, wrapper: Wrapper, text: &str) -> Result> { - self.constructor(wrapper)?.new_instance(text.to_owned()) + self.make(wrapper, text.to_owned()) + } + + fn make( + &self, + wrapper: Wrapper, + text: T, + ) -> Result> { + let make: Function<'e, FnArgs<(&str, T)>, Unknown<'e>> = + self.classes.get_named_property(MAKE)?; + make.call((wrapper.class_name(), text).into()) + } + + /// Sets the function every class's static `from(text)` calls, as + /// `factory(className, text)`. `from` returns what the factory returns. + /// The factory is set once for each environment. Returns whether it was + /// set: `false` when the environment already has one, which it keeps. + /// + /// Until a factory is set, `from` throws a `TypeError`. A `factory` + /// that is not a function is not set. + pub fn install_from(&self, factory: Unknown<'_>) -> Result { + let install: Function<'e, Unknown<'_>, bool> = self.classes.get_named_property(INSTALL)?; + install.call(factory) + } + + /// A new instance of `wrapper` holding `text`, when `text` is a string + /// that the walk would encrypt. This is the check a factory for `from` + /// makes. + /// + /// The outer `Result` is an error only when Node-API fails. The inner + /// one refuses the text with the refusal the walk gives for an + /// instance holding it: + /// + /// - a value that is not a string, or text that is not a value of the + /// class, is the class's [`ConversionError`], such as + /// `ERR_INVALID_DATE`; + /// - text with an unpaired surrogate is [`Refusal::UnpairedSurrogate`]. + /// + /// Nothing is thrown in JavaScript, and no refusal holds the text. + pub fn from_text( + &self, + wrapper: Wrapper, + text: Unknown<'e>, + ) -> Result, Refusal>> { + if text.get_type()? != ValueType::String { + return Ok(Err(Refusal::Scalar(wrapper.invalid()))); + } + let checked = match crate::js::lossless_string(text, wrapper.class_name()) { + Ok(checked) => checked, + Err(fault) => { + return match fault.refusal() { + Some(refusal) => Ok(Err(refusal)), + None => Err(fault.into()), + } + } + }; + if let Err(error) = wrapper.check(&checked) { + return Ok(Err(Refusal::Scalar(error))); + } + // The instance holds the string it was given, not a copy of it. + self.make(wrapper, text).map(Ok) } } @@ -214,9 +333,53 @@ mod tests { #[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"]); + assert_eq!(names, ["RcDate", "RcTimestamp", "RcDecimal", "RcUuid"]); for &wrapper in Wrapper::ALL { - assert_eq!(wrapper.class_name(), format!("Vc{wrapper:?}")); + assert_eq!(wrapper.class_name(), format!("Rc{wrapper:?}")); + assert_eq!( + Wrapper::from_class_name(wrapper.class_name()), + Some(wrapper) + ); + } + assert_eq!(Wrapper::from_class_name("Date"), None); + } + + #[test] + fn a_wrapper_checks_its_text_with_the_rule_encrypt_uses() { + let cases = [ + ( + Wrapper::Date, + "2026-11-23", + "20261123", + ConversionError::InvalidDate, + ), + ( + Wrapper::Timestamp, + "2026-11-23T01:02:03.000000001Z", + "2026-11-23", + ConversionError::InvalidTimestamp, + ), + ( + Wrapper::Decimal, + "1.50", + "1e5", + ConversionError::InvalidDecimal, + ), + ( + Wrapper::Uuid, + "123e4567-e89b-12d3-a456-426614174000", + "{123e4567-e89b-12d3-a456-426614174000}", + ConversionError::InvalidUuid, + ), + ]; + for (wrapper, valid, invalid, error) in cases { + assert_eq!(wrapper.check(valid), Ok(()), "{wrapper:?}"); + assert_eq!(wrapper.check(invalid), Err(error), "{wrapper:?}"); + assert_eq!(wrapper.invalid(), error, "{wrapper:?}"); } + assert_eq!( + Wrapper::Decimal.check("NaN"), + Err(ConversionError::NonFiniteDecimal) + ); } } 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 index 86d29fe77..fdd0c938b 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.lock +++ b/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.lock @@ -620,6 +620,8 @@ dependencies = [ "napi-sys", "nohash-hasher", "rustc-hash", + "serde", + "serde_json", ] [[package]] @@ -869,6 +871,8 @@ dependencies = [ "mutants", "napi", "rust_decimal", + "serde", + "serde_json", "thiserror", "vitaminc-aead", "vitaminc-protected", @@ -879,10 +883,12 @@ dependencies = [ name = "recipher-value-napi-test-addon" version = "0.0.0" dependencies = [ + "miette", "napi", "napi-build", "napi-derive", "recipher-value-napi", + "serde_json", "vitaminc-aead", "vitaminc-encrypt", "vitaminc-protected", 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 index 0e71e685b..eb1609c99 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.toml +++ b/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.toml @@ -10,8 +10,14 @@ publish = false crate-type = ["cdylib"] [dependencies] -napi = { version = "3", default-features = false, features = ["napi6"] } +# `serde-json` is napi-rs's own conversion between a JavaScript value and a +# `serde_json::Value`. `tests/json.cjs` pins what it does, beside what the +# bridge does. +napi = { version = "3", default-features = false, features = ["napi6", "serde-json"] } napi-derive = "3" +serde_json = "1" +# For a refusal's code. The code is the refusal's diagnostic code. +miette = "7.5.0" vitaminc-aead = { version = "0.10.0", features = ["rust_decimal"] } recipher-value-napi = { path = "../.." } vitaminc-encrypt = "0.10.0" 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 index fa8340db1..9221257f4 100644 --- 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 @@ -3,10 +3,10 @@ //! `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::bindgen_prelude::{AsyncTask, Buffer, FnArgs, JsObjectValue, JsValue, Object, Unknown}; use napi::{Env, Error, Result, Status, Task}; use napi_derive::napi; -use recipher_value_napi::{JsBuilder, JsCipherText, JsFault, JsRef, Wrappers}; +use recipher_value_napi::{JsBuilder, JsCipherText, JsFault, JsRef, Refusal, Wrapper, Wrappers}; use vitaminc_aead::seal::Cipher; use vitaminc_aead::{ decrypt, decrypt_into, encrypt, to_frame, CipherText, Context, DecryptError, Encrypt, @@ -16,16 +16,61 @@ use vitaminc_aead::{ use vitaminc_encrypt::{Aes256Cipher, Key, LocalCipherText}; use vitaminc_protected::{Controlled, Protected}; -/// The wrapper classes, exported so JavaScript can construct them. +/// The wrapper classes, exported so JavaScript can make instances with +/// their static `from(text)`. The factory `from` calls returns +/// `{ value: instance }`, or `{ code, message }` for a refusal, since this +/// addon has no `Result` class. #[napi(module_exports)] fn init(mut exports: Object<'_>, env: Env) -> Result<()> { let wrappers = Wrappers::exports(&env)?; - for name in ["VcDate", "VcTimestamp", "VcDecimal", "VcUuid"] { + for name in ["RcDate", "RcTimestamp", "RcDecimal", "RcUuid"] { exports.set_named_property(name, wrappers.get_named_property::(name)?)?; } + let from = env + .create_function_from_closure::)>, napi::sys::napi_value, _>( + "from", + |call| { + let env = &*call.env; + let name: String = call.get(0)?; + let text: Unknown<'_> = call.get(1)?; + let wrapper = Wrapper::from_class_name(&name) + .ok_or_else(|| Error::new(Status::InvalidArg, "not a wrapper class"))?; + let mut out = Object::new(env)?; + match Wrappers::get(env)?.from_text(wrapper, text)? { + Ok(instance) => out.set_named_property("value", instance)?, + Err(refusal) => { + out.set_named_property("code", refusal_code(&refusal))?; + out.set_named_property("message", refusal.to_string())?; + } + } + Ok(out.raw()) + }, + )?; + Wrappers::get(&env)?.install_from(from.to_unknown())?; Ok(()) } +/// Tries to install a second factory, one that returns `"replaced"`. +/// Returns whether it was installed: the first factory must be kept. +#[napi] +pub fn install_second_factory(env: Env) -> Result { + let other = env + .create_function_from_closure::)>, &str, _>("from", |_| { + Ok("replaced") + })?; + Wrappers::get(&env)?.install_from(other.to_unknown()) +} + +/// A new instance of the wrapper class `name` holding `text`, with no check +/// of the text, as a decrypt builds one. The suites use it to make +/// instances whose text `encode` must refuse. +#[napi] +pub fn make_wrapper<'e>(env: &'e Env, name: String, text: String) -> Result> { + let wrapper = Wrapper::from_class_name(&name) + .ok_or_else(|| Error::new(Status::InvalidArg, "not a wrapper class"))?; + Wrappers::get(env)?.construct(wrapper, &text) +} + /// Take the environment's instance data for the addon itself, as an addon /// author may: the binding must not depend on that slot. #[napi] @@ -73,6 +118,92 @@ pub fn encode(value: Unknown<'_>) -> Result { Ok(Buffer::from(frame.risky_ref().to_vec())) } +/// Write a JavaScript value as the text of a JSON document, nested at most +/// `max_depth` levels. A refused value comes back as `{ code, message }`, +/// the refusal's diagnostic code and message. Any other failure throws. +#[napi(ts_return_type = "{ text: string } | { code: string; message: string }")] +pub fn json_text<'e>(env: &'e Env, value: Unknown<'_>, max_depth: u32) -> Result> { + let mut out = Object::new(env)?; + match JsRef::new(value).to_json(max_depth as usize) { + Ok(text) => { + let text = std::str::from_utf8(text.risky_ref()) + .map_err(|_| Error::from_reason("JSON text is not UTF-8"))?; + out.set_named_property("text", text)?; + } + Err(fault) => match fault.refusal() { + Some(refusal) => { + out.set_named_property("code", refusal_code(&refusal))?; + out.set_named_property("message", refusal.to_string())?; + } + None => return Err(fault.into()), + }, + } + Ok(out) +} + +fn refusal_code(refusal: &Refusal) -> String { + use miette::Diagnostic; + refusal + .code() + .map_or_else(String::new, |code| code.to_string()) +} + +/// Build the JavaScript value of the JSON document `text`. A refused +/// document comes back as `{ code, message }`. Any other failure throws. +#[napi(ts_return_type = "{ value: unknown } | { code: string; message: string }")] +pub fn json_value<'e>(env: &'e Env, text: String) -> Result> { + let document: serde_json::Value = + serde_json::from_str(&text).map_err(|_| Error::from_reason("not JSON text"))?; + json_built(env, &document) +} + +/// Nest `true` inside `levels` JSON containers, then build the document as a +/// JavaScript value. `wrap` names the kind of container: "array" or "object". +/// A parser would refuse the deepest of these documents, so the build's own +/// depth limit applies. +#[napi(ts_return_type = "{ value: unknown } | { code: string; message: string }")] +pub fn json_nested_value<'e>(env: &'e Env, levels: u32, wrap: String) -> Result> { + let mut document = serde_json::Value::Bool(true); + for _ in 0..levels { + document = match wrap.as_str() { + "array" => serde_json::Value::Array(vec![document]), + _ => serde_json::Value::Object([("k".to_owned(), document)].into_iter().collect()), + }; + } + json_built(env, &document) +} + +/// The JavaScript value of `document` as `{ value }`, or its refusal as +/// `{ code, message }`. +fn json_built<'e>(env: &'e Env, document: &serde_json::Value) -> Result> { + let mut out = Object::new(env)?; + match JsBuilder::build_json(env, document) { + Ok(value) => out.set_named_property("value", value)?, + Err(fault) => match fault.refusal() { + Some(refusal) => { + out.set_named_property("code", refusal_code(&refusal))?; + out.set_named_property("message", refusal.to_string())?; + } + None => return Err(fault.into()), + }, + } + Ok(out) +} + +/// napi-rs's own conversion of a JavaScript value to a `serde_json::Value`, +/// as the JSON text of what it read. The bridge does not use it. +#[napi] +pub fn napi_json_text(value: serde_json::Value) -> String { + value.to_string() +} + +/// napi-rs's own conversion of a `serde_json::Value` to a JavaScript value. +/// The bridge uses it for scalars only. +#[napi] +pub fn napi_json_value(text: String) -> Result { + serde_json::from_str(&text).map_err(|_| Error::from_reason("not JSON text")) +} + /// Walk a JavaScript value and drop the frame, to test the walk alone. #[napi] pub fn convert(value: Unknown<'_>) -> Result<()> { diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/encrypt.cjs b/languages/typescript/packages/recipher-js/value-napi/tests/encrypt.cjs index 6558811f7..92bd86f63 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/encrypt.cjs +++ b/languages/typescript/packages/recipher-js/value-napi/tests/encrypt.cjs @@ -5,7 +5,6 @@ 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 = { @@ -25,14 +24,17 @@ const rows = { 'plain object': { name: 'Ada', tags: ['math'], - born: new VcDate('1815-12-10'), + born: addon.makeWrapper('RcDate', '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'), + RcDate: addon.makeWrapper('RcDate', '2024-02-29'), + RcTimestamp: addon.makeWrapper( + 'RcTimestamp', + '1969-12-31T23:59:59.999999999Z', + ), + RcDecimal: addon.makeWrapper('RcDecimal', '-1.50'), + RcUuid: addon.makeWrapper('RcUuid', '123e4567-e89b-12d3-a456-426614174000'), 'empty array': [], 'empty object': {}, } diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/frames.cjs b/languages/typescript/packages/recipher-js/value-napi/tests/frames.cjs index afe874bd3..d83a90415 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/frames.cjs +++ b/languages/typescript/packages/recipher-js/value-napi/tests/frames.cjs @@ -21,7 +21,6 @@ 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 { VcDate, VcTimestamp, VcDecimal, VcUuid } = addon const golden = path.join(__dirname, 'testdata/js-frames.json') const vendored = path.join(__dirname, 'testdata/corpus-frames.json') @@ -151,72 +150,75 @@ const inputs = [ ['Date 123', () => new Date(123)], ['Date -1', () => new Date(-1)], [ - 'VcDate 1970-01-01', - () => new VcDate('1970-01-01'), + 'RcDate 1970-01-01', + () => addon.makeWrapper('RcDate', '1970-01-01'), 'record-values-v1/date-epoch', ], [ - 'VcDate 1969-12-31', - () => new VcDate('1969-12-31'), + 'RcDate 1969-12-31', + () => addon.makeWrapper('RcDate', '1969-12-31'), 'record-values-v1/date-before-epoch', ], [ - 'VcDate 0001-01-01', - () => new VcDate('0001-01-01'), + 'RcDate 0001-01-01', + () => addon.makeWrapper('RcDate', '0001-01-01'), 'record-values-v1/date-year-one', ], [ - 'VcDate 9999-12-31', - () => new VcDate('9999-12-31'), + 'RcDate 9999-12-31', + () => addon.makeWrapper('RcDate', '9999-12-31'), 'record-values-v1/date-year-9999', ], [ - 'VcTimestamp epoch', - () => new VcTimestamp('1970-01-01T00:00:00Z'), + 'RcTimestamp epoch', + () => addon.makeWrapper('RcTimestamp', '1970-01-01T00:00:00Z'), 'record-values-v1/timestamp-epoch', ], [ - 'VcTimestamp one nanosecond', - () => new VcTimestamp('2026-10-17T01:02:03.000000001Z'), + 'RcTimestamp one nanosecond', + () => addon.makeWrapper('RcTimestamp', '2026-10-17T01:02:03.000000001Z'), 'record-values-v1/timestamp-nanosecond', ], [ - 'VcTimestamp before epoch', - () => new VcTimestamp('1969-12-31T23:59:59.999999999Z'), + 'RcTimestamp before epoch', + () => addon.makeWrapper('RcTimestamp', '1969-12-31T23:59:59.999999999Z'), 'record-values-v1/timestamp-before-epoch', ], [ - 'VcTimestamp nanoseconds', - () => new VcTimestamp('2026-10-17T01:02:03.123456789Z'), + 'RcTimestamp nanoseconds', + () => addon.makeWrapper('RcTimestamp', '2026-10-17T01:02:03.123456789Z'), 'record-values-v1/timestamp-microsecond-query', ], [ - 'VcTimestamp year 9999', - () => new VcTimestamp('9999-12-30T22:00:00.999999999Z'), + 'RcTimestamp year 9999', + () => addon.makeWrapper('RcTimestamp', '9999-12-30T22:00:00.999999999Z'), 'record-values-v1/timestamp-year-9999', ], [ - 'VcDecimal 42', - () => new VcDecimal('42'), + 'RcDecimal 42', + () => addon.makeWrapper('RcDecimal', '42'), 'record-values-v1/decimal-scale-0', ], [ - 'VcDecimal scale 28', - () => new VcDecimal('0.0000000000000000000000000001'), + 'RcDecimal scale 28', + () => addon.makeWrapper('RcDecimal', '0.0000000000000000000000000001'), 'record-values-v1/decimal-scale-28', ], [ - 'VcDecimal -1234.5600', - () => new VcDecimal('-1234.5600'), + 'RcDecimal -1234.5600', + () => addon.makeWrapper('RcDecimal', '-1234.5600'), 'record-values-v1/decimal-trailing-zeros', ], [ - 'VcDecimal max mantissa', - () => new VcDecimal('79228162514264337593543950335'), + 'RcDecimal max mantissa', + () => addon.makeWrapper('RcDecimal', '79228162514264337593543950335'), 'record-values-v1/decimal-max-mantissa', ], - ['VcDecimal -0.00', () => new VcDecimal('-0.00')], - ['VcUuid', () => new VcUuid('123e4567-e89b-12d3-a456-426614174000')], + ['RcDecimal -0.00', () => addon.makeWrapper('RcDecimal', '-0.00')], + [ + 'RcUuid', + () => addon.makeWrapper('RcUuid', '123e4567-e89b-12d3-a456-426614174000'), + ], ['array empty', () => []], ['array of bigint and string', () => [1n, 'x']], ['array of null', () => [null]], diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/json.cjs b/languages/typescript/packages/recipher-js/value-napi/tests/json.cjs new file mode 100644 index 000000000..98887ae0f --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/tests/json.cjs @@ -0,0 +1,536 @@ +// JSON documents at the N-API boundary. `JsRef::to_json` writes a JavaScript +// value as the text of a document. `JsBuilder::build_json` builds a document +// as a JavaScript value. +// +// The last section pins what napi-rs's own `serde_json` conversion does. +// That conversion is the reason the bridge reads a value itself, and writes +// arrays and objects itself. `tests/node.rs` runs this file 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])) + +// The depth the engine's JSON parser reads. +const DEPTH = 127 + +const NOT_JSON = 'recipher_js::not_json' + +/** The JSON text of `value`. */ +const text = (value, depth = DEPTH) => { + const out = addon.jsonText(value, depth) + assert.equal(out.code, undefined, out.message) + return out.text +} + +/** The refusal of `value`: its code and its message. */ +const refusal = (value, depth = DEPTH) => { + const out = addon.jsonText(value, depth) + assert.equal(out.text, undefined, 'the value was written') + return out +} + +/** The JavaScript value of the document `json`. */ +const built = (json) => { + const out = addon.jsonValue(json) + assert.equal(out.code, undefined, out.message) + return out.value +} + +// --- Writing a value as JSON text --- + +// An object, an array, a string, a boolean, and null stay as they are. The +// members keep the order JavaScript lists them in. +assert.equal( + text({ b: 'text', a: [true, false, null], nested: { deep: [] } }), + '{"b":"text","a":[true,false,null],"nested":{"deep":[]}}', +) +assert.equal(text(null), 'null') +assert.equal(text('alone'), '"alone"') +assert.equal(text([]), '[]') +assert.equal(text({}), '{}') +assert.equal(text(Object.create(null)), '{}') + +// A whole number in the safe range is an integer, as JSON.stringify writes +// it, at every size. napi-rs writes one above 2^32 as a float. +for (const whole of [ + 0, + 5, + -5, + 4294967296, + 5000000000, + -5000000000, + // A millisecond timestamp, as Date.now() gives one. + 1764288000000, + Number.MAX_SAFE_INTEGER, + Number.MIN_SAFE_INTEGER, +]) { + assert.equal(text(whole), JSON.stringify(whole), String(whole)) + assert.equal(text({ n: whole }), `{"n":${whole}}`) +} +assert.equal(text(5000000000), '5000000000') +const now = Date.now() +assert.equal(text({ t: now }), `{"t":${now}}`) +// JSON.stringify(-0) is "0". +assert.equal(text(-0), '0') + +// Any other finite number is a float that reads back as the same number. +for (const float of [ + 1.5, + -0.25, + 0.1, + 5e-324, + // 2^64 and above. + 2 ** 64, + -(2 ** 64), + 1e20, + -1e20, + -6.02e23, + Number.MAX_VALUE, + -Number.MAX_VALUE, +]) { + const written = text(float) + assert.equal(JSON.parse(written), float, written) + // A fraction or an exponent, so no reader reads it as an integer. + assert.match(written, /[.e]/, written) +} + +// A whole number from 2^53 up to 2^64 is refused: its digits may not be +// the ones written. +for (const unsafe of [ + 2 ** 53, + 2 ** 53 + 2, + 2 ** 60, + // The largest number below 2^64. + 2 ** 64 - 2048, + -(2 ** 53), + -(2 ** 63), +]) { + const refused = refusal({ n: unsafe }) + assert.equal(refused.code, NOT_JSON, String(unsafe)) + assert.match(refused.message, /bigint/) + // No message contains any part of the value. + assert.ok(!/\d{6}/.test(refused.message), refused.message) +} + +// A whole number below -2^63 and above -2^64 is refused. The message does +// not ask for a bigint, because a bigint that size is refused too. -2^63 - 1 +// rounds to -2^63, so the first number below -2^63 is -2^63 - 2048. +for (const number of [-(2 ** 63) - 2048, -1e19, -(2 ** 64) + 2048]) { + const refused = refusal({ n: number }) + assert.equal(refused.code, NOT_JSON, String(number)) + assert.match(refused.message, /no exact form/) + assert.doesNotMatch(refused.message, /Pass a `bigint`/) + assert.ok(!/\d{6}/.test(refused.message), refused.message) +} + +// NaN and the infinities have no JSON form. JSON.stringify writes each one as +// null. A null would decrypt as a different value. +for (const number of [ + Number.NaN, + Number.POSITIVE_INFINITY, + Number.NEGATIVE_INFINITY, +]) { + const refused = refusal([number]) + assert.equal(refused.code, NOT_JSON, String(number)) + assert.match(refused.message, /not finite/) +} + +// A bigint is its exact digits, within 64 bits, signed or unsigned. +assert.equal(text(0n), '0') +assert.equal(text(-0n), '0') +assert.equal(text(5n), '5') +assert.equal(text(-5n), '-5') +assert.equal(text(2n ** 53n), '9007199254740992') +assert.equal(text(2n ** 63n - 1n), '9223372036854775807') +assert.equal(text(2n ** 63n), '9223372036854775808') +assert.equal(text(2n ** 64n - 1n), '18446744073709551615') +assert.equal(text(-(2n ** 63n)), '-9223372036854775808') +// Outside 64 bits a bigint is refused, with one refusal at every size. +for (const wide of [ + 2n ** 64n, + -(2n ** 63n) - 1n, + 2n ** 127n, + -(2n ** 127n), + 2n ** 128n, + 2n ** 200n, + -(2n ** 200n), +]) { + const refused = refusal({ id: wide }) + assert.equal(refused.code, NOT_JSON, String(wide)) + assert.match(refused.message, /64-bit/) + assert.ok(!/\d{6}/.test(refused.message), refused.message) +} + +// A value with no JSON form is refused, at the top, in an array, and as a +// member. JSON.stringify would drop it, or write something else. +const noJsonForm = [ + [undefined, /undefined/], + [new Date(0), /a date/], + [new Date(Number.NaN), /a date/], + [Buffer.from('bytes'), /bytes/], + [new Uint8Array(2), /bytes/], + [new Uint16Array(2), /bytes/], + [new Float64Array(2), /bytes/], + [new DataView(new ArrayBuffer(2)), /bytes/], + [addon.makeWrapper('RcDate', '2026-11-23'), /a date/], + [ + addon.makeWrapper('RcTimestamp', '2026-11-23T01:02:03.000000001Z'), + /a date/, + ], + [addon.makeWrapper('RcDecimal', '1.50'), /a decimal/], + [ + addon.makeWrapper('RcUuid', '123e4567-e89b-12d3-a456-426614174000'), + /a UUID/, + ], + // A wrapper is refused before its text is read, so a malformed one is + // refused the same way. + [addon.makeWrapper('RcDate', 'not a date'), /a date/], +] +for (const [value, message] of noJsonForm) { + for (const document of [ + value, + [value], + { member: value }, + [[{ deep: value }]], + ]) { + const refused = refusal(document) + assert.equal(refused.code, NOT_JSON) + assert.match(refused.message, message) + } +} + +// A function and a symbol are not values at all. +for (const value of [() => 1, function named() {}, Symbol('s'), class {}]) { + assert.equal(refusal(value).code, 'recipher_js::not_a_value') + assert.equal(refusal({ member: value }).code, 'recipher_js::not_a_value') +} +// So an object with a toJSON method is refused: nothing calls the method. +assert.equal( + refusal({ toJSON: () => 'replaced' }).code, + 'recipher_js::not_a_value', +) + +// The walk's safety rules apply to a document as to any value. +assert.equal(refusal(new Map([['k', 1]])).code, 'recipher_js::not_plain') +assert.equal(refusal(new Set([1])).code, 'recipher_js::not_plain') +assert.equal(refusal(new (class Thing {})()).code, 'recipher_js::not_plain') +assert.equal(refusal(new ArrayBuffer(2)).code, 'recipher_js::not_plain') +assert.equal( + refusal(Object.create({ inherited: 1 })).code, + 'recipher_js::not_plain', +) +// biome-ignore lint/suspicious/noSparseArray: a hole is the case. +assert.equal(refusal([1, , 3]).code, 'recipher_js::sparse_array') +assert.equal(refusal(new Array(3)).code, 'recipher_js::sparse_array') +assert.equal(refusal('\uD800').code, 'recipher_js::unpaired_surrogate') +assert.equal(refusal({ '\uDC00': 1 }).code, 'recipher_js::unpaired_surrogate') +for (const reserved of ['__proto__', 'constructor', 'prototype']) { + assert.equal( + refusal(JSON.parse(`{"${reserved}":1}`)).code, + 'recipher_js::reserved_key', + ) +} +// Only own, enumerable, string keys are members. +const mixed = { own: 1 } +Object.defineProperty(mixed, 'hidden', { value: 2, enumerable: false }) +mixed[Symbol('s')] = 3 +assert.equal(text(mixed), '{"own":1}') +Object.prototype.polluted = 'x' +try { + assert.equal(text({ a: 1 }), '{"a":1}') +} finally { + delete Object.prototype.polluted +} +// A hole is not read through a polluted Array.prototype. +Array.prototype[1] = 'injected' +try { + // biome-ignore lint/suspicious/noSparseArray: a hole is the case. + assert.equal(refusal(['a', , 'b']).code, 'recipher_js::sparse_array') +} finally { + delete Array.prototype[1] +} +// When a getter throws, the caller receives the error the getter threw. That +// error is not a refusal. +const thrown = new Error('the getter threw') +assert.throws( + () => + addon.jsonText( + { + get member() { + throw thrown + }, + }, + DEPTH, + ), + (error) => error === thrown, +) + +// Text is written with JSON's escapes, and reads back as itself. +for (const plain of [ + '', + 'quote " and backslash \\', + 'line\nfeed, tab\t, nul\0 and \u001f', + 'José, 日本, 😀, 
 and \u{10FFFF}', +]) { + assert.equal(JSON.parse(text(plain)), plain) + assert.deepEqual(JSON.parse(text({ [plain]: [plain] })), { [plain]: [plain] }) +} +assert.equal(text('a"b\n'), '"a\\"b\\n"') + +// The text of a document is the document. +const document = { + number: '4111 1111 1111 1111', + expiry: { month: 4, year: 2031 }, + tags: ['a', 'b'], + active: true, + note: null, + ratio: 0.75, + big: 1e21, +} +assert.deepEqual(JSON.parse(text(document)), document) + +// A document nests as deep as the limit it is given, and no deeper. The +// innermost array is empty, so `nested(n)` is n levels. +const nested = (levels) => { + let value = [] + for (let level = 1; level < levels; level++) value = [value] + return value +} +const nestedObject = (levels) => { + let value = {} + for (let level = 1; level < levels; level++) value = { k: value } + return value +} +for (const limit of [1, 2, DEPTH]) { + assert.equal( + text(nested(limit), limit), + '['.repeat(limit) + ']'.repeat(limit), + ) + assert.ok(text(nestedObject(limit), limit).startsWith('{')) + for (const tooDeep of [nested(limit + 1), nestedObject(limit + 1)]) { + const refused = refusal(tooDeep, limit) + assert.equal(refused.code, 'recipher_js::too_deep') + assert.equal( + refused.message, + `the value is nested deeper than ${limit} levels`, + ) + } +} +// A scalar is no level. +assert.equal(text(5, 0), '5') +assert.equal(refusal([], 0).code, 'recipher_js::too_deep') +// A cycle is refused as too deep, at the limit given or at the walk's own. +const cycle = [] +cycle.push(cycle) +assert.equal(refusal(cycle).code, 'recipher_js::too_deep') +assert.equal(refusal(cycle, 100000).code, 'recipher_js::too_deep') +const loop = {} +loop.self = loop +assert.equal(refusal(loop).code, 'recipher_js::too_deep') + +// A long array is written whole. +const long = Array.from({ length: 5000 }, (_, index) => index) +assert.deepEqual(JSON.parse(text(long)), long) + +// --- Building a document as a JavaScript value --- + +// An integer in the safe range is a number, at both ends of the range. +assert.strictEqual(built('5'), 5) +assert.strictEqual(built('-5'), -5) +assert.strictEqual(built('5000000000'), 5000000000) +assert.strictEqual(built('9007199254740991'), Number.MAX_SAFE_INTEGER) +assert.strictEqual(built('-9007199254740991'), Number.MIN_SAFE_INTEGER) +// Any other integer is a bigint, so no digit is lost. +assert.strictEqual(built('9007199254740992'), 2n ** 53n) +assert.strictEqual(built('-9007199254740992'), -(2n ** 53n)) +assert.strictEqual(built('9223372036854775807'), 2n ** 63n - 1n) +assert.strictEqual(built('9223372036854775808'), 2n ** 63n) +assert.strictEqual(built('-9223372036854775808'), -(2n ** 63n)) +assert.strictEqual(built('18446744073709551615'), 2n ** 64n - 1n) +// A float is a number, even when the float is whole. +assert.strictEqual(built('1.5'), 1.5) +assert.strictEqual(built('5.0'), 5) +assert.strictEqual(built('1e20'), 1e20) +assert.strictEqual(built('1.7976931348623157e308'), Number.MAX_VALUE) +assert.ok(Object.is(built('-0.0'), -0)) +// The rest stay as they are. +assert.strictEqual(built('null'), null) +assert.strictEqual(built('true'), true) +assert.strictEqual(built('"text 😀"'), 'text 😀') +assert.deepEqual( + built('{"a":[1,{"b":null,"big":18446744073709551615}],"c":"d","e":{}}'), + { a: [1, { b: null, big: 18446744073709551615n }], c: 'd', e: {} }, +) + +// What is written reads back, with a safe bigint as a number. +assert.deepEqual(built(text(document)), document) +assert.deepEqual( + built(text({ small: 5n, big: 2n ** 64n - 1n, t: 1764288000000 })), + { + small: 5, + big: 2n ** 64n - 1n, + t: 1764288000000, + }, +) + +// An array and an object are ordinary ones, of own data properties that are +// writable, enumerable, and configurable. +const made = built('{"k":[7]}') +assert.equal(Object.getPrototypeOf(made), Object.prototype) +assert.ok(Array.isArray(made.k)) +assert.ok(Object.hasOwn(made, 'k')) +assert.deepEqual(Object.getOwnPropertyDescriptor(made.k, '0'), { + value: 7, + writable: true, + enumerable: true, + configurable: true, +}) +assert.deepEqual(built('[]'), []) +assert.equal(built('[1,2,3]').length, 3) +// A key keeps its exact text. +assert.deepEqual(Object.keys(built('{"a\\u0000b":1,"7":2,"":3}')).sort(), [ + '', + '7', + 'a\0b', +]) + +// A setter on a polluted prototype never receives a decrypted value, from +// an object or from an array. +let captured = 'untouched' +Object.defineProperty(Object.prototype, 'leak', { + set(value) { + captured = value + }, + configurable: true, +}) +Object.defineProperty(Array.prototype, '0', { + set(value) { + captured = value + }, + configurable: true, +}) +try { + const out = built('{"leak":"secret","list":["secret"]}') + assert.equal(captured, 'untouched') + assert.ok(Object.hasOwn(out, 'leak')) + assert.equal(out.leak, 'secret') + assert.ok(Object.hasOwn(out.list, '0')) + assert.equal(out.list[0], 'secret') +} finally { + delete Object.prototype.leak + delete Array.prototype[0] +} + +// A member with a reserved name is refused, at any depth. The member is never +// assigned, so it never becomes the object's prototype. +for (const reserved of ['__proto__', 'constructor', 'prototype']) { + for (const json of [ + `{"${reserved}":{"polluted":true}}`, + `[{"deep":{"${reserved}":1}}]`, + ]) { + const out = addon.jsonValue(json) + assert.equal(out.value, undefined, json) + assert.equal(out.code, 'recipher_js::reserved_key', json) + } +} +assert.equal({}.polluted, undefined) + +// A document nested as deep as the engine reads is built. +assert.ok(Array.isArray(built('['.repeat(DEPTH) + ']'.repeat(DEPTH)))) +// The build has a limit of its own, 128 levels as for any value, for a +// document that no parser has bounded. Arrays and objects both count. +for (const wrap of ['array', 'object']) { + let deepest = addon.jsonNestedValue(128, wrap).value + assert.notEqual(deepest, undefined, wrap) + for (let level = 0; level < 128; level++) { + deepest = wrap === 'array' ? deepest[0] : deepest.k + } + assert.strictEqual(deepest, true) + const tooDeep = addon.jsonNestedValue(129, wrap) + assert.equal(tooDeep.value, undefined, wrap) + assert.equal(tooDeep.code, 'recipher_js::too_deep', wrap) + assert.equal(tooDeep.message, 'the value is nested deeper than 128 levels') +} + +// --- What napi-rs's own conversion does --- +// +// The bridge uses napi-rs's conversion for a document's scalars only. These +// cases pin the behaviour that is the reason. If one of them fails after a +// napi-rs update, read the change and decide again. + +// Reading a value. A whole number above 2^32, or below -2^31, becomes a +// float. Rust's `serde_json` and Go's `encoding/json` refuse `5000000000.0` +// for an integer field. +assert.equal(addon.napiJsonText(4294967295), '4294967295') +assert.equal(addon.napiJsonText(5000000000), '5000000000.0') +assert.equal(addon.napiJsonText(-5000000000), '-5000000000.0') +assert.equal(addon.napiJsonText(2 ** 53), '9007199254740992.0') +// A bigint outside 64 bits becomes a string of its digits. +assert.equal(addon.napiJsonText(2n ** 64n), '"18446744073709551616"') +// A member that is undefined is dropped. A Date, a Map, and a wrapper class +// instance are read as objects. +assert.equal(addon.napiJsonText({ a: undefined, b: 1 }), '{"b":1}') +assert.equal(addon.napiJsonText(new Date(0)), '{}') +assert.equal(addon.napiJsonText(new Map([[1, 2]])), '{}') +assert.equal( + addon.napiJsonText(addon.makeWrapper('RcDate', '2026-11-23')), + '{"value":"2026-11-23"}', +) +// An inherited property is read. An unpaired surrogate is replaced. +assert.equal( + addon.napiJsonText(Object.create({ inherited: 1 })), + '{"inherited":1}', +) +assert.equal(addon.napiJsonText('\uD800'), '"�"') + +// Building a value. The number rule is the rule that the bridge documents and +// uses. +assert.deepEqual( + addon.napiJsonValue( + '[5,9007199254740991,9007199254740992,-9223372036854775808,18446744073709551615,1.5,1e20,5.0]', + ), + [ + 5, + Number.MAX_SAFE_INTEGER, + 2n ** 53n, + -(2n ** 63n), + 2n ** 64n - 1n, + 1.5, + 1e20, + 5, + ], +) +// A member named `__proto__` becomes the object's prototype. +const assigned = addon.napiJsonValue('{"__proto__":{"inherited":1},"own":2}') +assert.deepEqual(Object.keys(assigned), ['own']) +assert.equal(assigned.inherited, 1) +// Members and elements are assigned. So a setter on a polluted prototype +// receives the value. The result has no such property of its own. +captured = 'untouched' +Object.defineProperty(Object.prototype, 'leak', { + set(value) { + captured = value + }, + configurable: true, +}) +try { + const out = addon.napiJsonValue('{"leak":"secret"}') + assert.equal(captured, 'secret') + assert.ok(!Object.hasOwn(out, 'leak')) +} finally { + delete Object.prototype.leak +} +captured = 'untouched' +Object.defineProperty(Array.prototype, '0', { + set(value) { + captured = value + }, + configurable: true, +}) +try { + const out = addon.napiJsonValue('["secret"]') + assert.equal(captured, 'secret') + assert.ok(!Object.hasOwn(out, '0')) +} finally { + delete Array.prototype[0] +} 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 index ea7342f68..ba74328aa 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/kind_inventory.cjs +++ b/languages/typescript/packages/recipher-js/value-napi/tests/kind_inventory.cjs @@ -5,7 +5,6 @@ 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, @@ -24,13 +23,19 @@ assert.deepStrictEqual(addon.kindInventory(), { float64: 2.5, string: 'hello', bytes: Buffer.from([0, 255]), - date: new VcDate('2024-02-29'), + date: addon.makeWrapper('RcDate', '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'), + timestampMicros: addon.makeWrapper( + 'RcTimestamp', + '1970-01-01T00:00:00.000001000Z', + ), + timestampNanos: addon.makeWrapper( + 'RcTimestamp', + '1969-12-31T23:59:59.999999999Z', + ), + decimal: addon.makeWrapper('RcDecimal', '1.50'), + uuid: addon.makeWrapper('RcUuid', '123e4567-e89b-12d3-a456-426614174000'), array: [true], object: { k: true }, passthrough: true, diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/node.rs b/languages/typescript/packages/recipher-js/value-napi/tests/node.rs index 98143c53a..ee5f1b084 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/node.rs +++ b/languages/typescript/packages/recipher-js/value-napi/tests/node.rs @@ -66,6 +66,7 @@ fn node_value_conformance() { "tests/kind_inventory.cjs", "tests/encrypt.cjs", "tests/frames.cjs", + "tests/json.cjs", ] .map(|suite| package.join(suite)) .into_iter() 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 index 32d51380f..ddf1fe076 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/object-safety.cjs +++ b/languages/typescript/packages/recipher-js/value-napi/tests/object-safety.cjs @@ -142,12 +142,22 @@ for (const view of [ // 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.equal(roundTrip(addon.makeWrapper('RcDecimal', '2.50')).value, '2.50') assert.deepEqual(roundTrip({ k: 'v' }), { k: 'v' }) +// The addon exports the classes, and not the script's `make` and `install`, +// which take the constructor's token and set the factory `from` calls. +for (const name of ['make', 'install', 'isPlain']) { + assert.equal(addon[name], undefined, name) +} +// The factory is set once: a second one is not installed, and `from` keeps +// the first. +assert.equal(addon.installSecondFactory(), false) +assert.equal(addon.RcDate.from('2026-10-09').value.value, '2026-10-09') + // 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) +const date = roundTrip(addon.makeWrapper('RcDate', '2026-10-09')) +assert.ok(date instanceof addon.RcDate) 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 @@ -155,14 +165,14 @@ assert.equal(date.value, '2026-10-09') // `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(addon.RcUuid) && + Object.isFrozen(addon.RcUuid.prototype) && Object.isFrozen(date), ) Object.prototype.writable = true Object.prototype.get = () => 'polluted' try { - const decimal = new addon.VcDecimal('1.50') + const decimal = addon.makeWrapper('RcDecimal', '1.50') assert.throws(() => { 'use strict' decimal.value = '999.99' @@ -175,7 +185,7 @@ try { } assert.throws( () => - Object.defineProperty(addon.VcUuid, Symbol.hasInstance, { + Object.defineProperty(addon.RcUuid, Symbol.hasInstance, { value: () => true, }), TypeError, @@ -200,7 +210,7 @@ const ct = { v: [ { t: 'eseq', v: leaf }, { t: 'pt', v: 5n }, - { t: 'pt', v: { a: [new addon.VcDecimal('1.50')] } }, + { t: 'pt', v: { a: [addon.makeWrapper('RcDecimal', '1.50')] } }, ], }, e: { t: 'eseq', v: leaf }, @@ -280,7 +290,7 @@ for (const wrap of [ // 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')), + () => addon.encode(addon.makeWrapper('RcTimestamp', '2016-12-31T23:59:60Z')), { code: 'ERR_INVALID_TIMESTAMP' }, ) @@ -562,8 +572,8 @@ assert.throws(() => addon.ciphertextWithPayload(60, HUGE), /nested too deeply/) 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 date = addon.decode(addon.encode(addon.makeWrapper('RcDate', '2024-02-29'))); + require('node:worker_threads').parentPort.postMessage(date instanceof addon.RcDate ? date.value : 'not a wrapper'); ` const reply = await new Promise((resolve, reject) => { const worker = new Worker(script, { eval: true }) @@ -575,7 +585,10 @@ assert.throws(() => addon.ciphertextWithPayload(60, HUGE), /nested too deeply/) ) }) assert.equal(reply, '2024-02-29') - assert.equal(roundTrip(new addon.VcDate('2024-02-29')).value, '2024-02-29') + assert.equal( + roundTrip(addon.makeWrapper('RcDate', '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. diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/testdata/js-frames.json b/languages/typescript/packages/recipher-js/value-napi/tests/testdata/js-frames.json index 1dd7138e0..ae7997876 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/testdata/js-frames.json +++ b/languages/typescript/packages/recipher-js/value-napi/tests/testdata/js-frames.json @@ -252,75 +252,75 @@ "Date -1": { "frame": "f3030105ffffffffffffffff" }, - "VcDate 1970-01-01": { + "RcDate 1970-01-01": { "frame": "123bf90a00", "corpus_case": "record-values-v1/date-epoch", "same_as_corpus": true }, - "VcDate 1969-12-31": { + "RcDate 1969-12-31": { "frame": "123af90a00", "corpus_case": "record-values-v1/date-before-epoch", "same_as_corpus": true }, - "VcDate 0001-01-01": { + "RcDate 0001-01-01": { "frame": "1201000000", "corpus_case": "record-values-v1/date-year-one", "same_as_corpus": true }, - "VcDate 9999-12-31": { + "RcDate 9999-12-31": { "frame": "12dbb93700", "corpus_case": "record-values-v1/date-year-9999", "same_as_corpus": true }, - "VcTimestamp epoch": { + "RcTimestamp epoch": { "frame": "13000000000000000000000000", "corpus_case": "record-values-v1/timestamp-epoch", "same_as_corpus": true }, - "VcTimestamp one nanosecond": { + "RcTimestamp one nanosecond": { "frame": "130bc9d26a0000000001000000", "corpus_case": "record-values-v1/timestamp-nanosecond", "same_as_corpus": true }, - "VcTimestamp before epoch": { + "RcTimestamp before epoch": { "frame": "13ffffffffffffffffffc99a3b", "corpus_case": "record-values-v1/timestamp-before-epoch", "same_as_corpus": true }, - "VcTimestamp nanoseconds": { + "RcTimestamp nanoseconds": { "frame": "130bc9d26a0000000015cd5b07", "corpus_case": "record-values-v1/timestamp-microsecond-query", "same_as_corpus": true }, - "VcTimestamp year 9999": { + "RcTimestamp year 9999": { "frame": "13e0d3f2ff3a000000ffc99a3b", "corpus_case": "record-values-v1/timestamp-year-9999", "same_as_corpus": true }, - "VcDecimal 42": { + "RcDecimal 42": { "frame": "14000000002a0000000000000000000000", "corpus_case": "record-values-v1/decimal-scale-0", "same_as_corpus": true }, - "VcDecimal scale 28": { + "RcDecimal scale 28": { "frame": "1400001c00010000000000000000000000", "corpus_case": "record-values-v1/decimal-scale-28", "same_as_corpus": true }, - "VcDecimal -1234.5600": { + "RcDecimal -1234.5600": { "frame": "14000004800061bc000000000000000000", "corpus_case": "record-values-v1/decimal-trailing-zeros", "same_as_corpus": true }, - "VcDecimal max mantissa": { + "RcDecimal max mantissa": { "frame": "1400000000ffffffffffffffffffffffff", "corpus_case": "record-values-v1/decimal-max-mantissa", "same_as_corpus": true }, - "VcDecimal -0.00": { + "RcDecimal -0.00": { "frame": "1400000200000000000000000000000000" }, - "VcUuid": { + "RcUuid": { "frame": "f305000b10000000123e4567e89b12d3a456426614174000" }, "array empty": { 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 index 4f8f35bd3..59810d959 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/value-conformance.cjs +++ b/languages/typescript/packages/recipher-js/value-napi/tests/value-conformance.cjs @@ -9,7 +9,7 @@ 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 +const { RcDate, RcTimestamp, RcDecimal, RcUuid } = addon function expected(row, value = row.value) { if (/^(u?int)/.test(row.kind)) return BigInt(value) switch (row.kind) { @@ -18,13 +18,15 @@ function expected(row, value = row.value) { case 'bytes': return Buffer.from(value, 'hex') case 'date': - return new VcDate(value) + return addon.makeWrapper('RcDate', value) case 'decimal': - return new VcDecimal(value) + return addon.makeWrapper('RcDecimal', value) case 'timestamp': - return row.js_date ? new Date(value) : new VcTimestamp(value) + return row.js_date + ? new Date(value) + : addon.makeWrapper('RcTimestamp', value) case 'uuid': - return new VcUuid(value) + return addon.makeWrapper('RcUuid', value) default: return value } @@ -125,27 +127,33 @@ for (const value of [1n << 128n, -(1n << 127n) - 1n]) code: 'ERR_INTEGER_RANGE', }) for (const decimal of ['NaN', 'Infinity', '-Infinity', '+inf']) - assert.throws(() => addon.encode(new VcDecimal(decimal)), { + assert.throws(() => addon.encode(addon.makeWrapper('RcDecimal', decimal)), { name: 'TypeError', code: 'ERR_NON_FINITE_DECIMAL', }) assert.throws( - () => addon.encode(new VcDecimal('79228162514264337593543950336')), + () => + addon.encode( + addon.makeWrapper('RcDecimal', '79228162514264337593543950336'), + ), { code: 'ERR_INVALID_DECIMAL' }, ) -assert.throws(() => addon.encode(new VcDate('2023-02-29')), { +assert.throws(() => addon.encode(addon.makeWrapper('RcDate', '2023-02-29')), { code: 'ERR_INVALID_DATE', }) -assert.throws(() => addon.encode(new VcUuid('not-a-uuid')), { +assert.throws(() => addon.encode(addon.makeWrapper('RcUuid', '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.throws( + () => addon.encode(addon.makeWrapper('RcTimestamp', '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. @@ -158,7 +166,7 @@ assert.equal( 'f3030105ffffffffffffffff', ) // A UUID is sixteen bytes under its logical type, in the envelope too. -const uuid = new VcUuid('123e4567-e89b-12d3-a456-426614174000') +const uuid = addon.makeWrapper('RcUuid', '123e4567-e89b-12d3-a456-426614174000') assert.equal( addon.encode(uuid).toString('hex'), 'f305000b10000000123e4567e89b12d3a456426614174000', @@ -166,15 +174,17 @@ assert.equal( assert.deepEqual(addon.decode(addon.encode(uuid)), uuid) assert.deepEqual( addon.decode( - addon.encode(new VcUuid('123E4567-E89B-12D3-A456-426614174000')), + addon.encode( + addon.makeWrapper('RcUuid', '123E4567-E89B-12D3-A456-426614174000'), + ), ), uuid, ) const nested = { items: [ 1n, - new VcDate('2024-02-29'), - new VcDecimal('1.50'), + addon.makeWrapper('RcDate', '2024-02-29'), + addon.makeWrapper('RcDecimal', '1.50'), new Date(0), uuid, ], @@ -195,9 +205,49 @@ assert.throws( /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]) { +// A wrapper has no public constructor: `new` throws a TypeError that names +// `from`, for a string as for anything else. +for (const Wrapper of [RcDate, RcTimestamp, RcDecimal, RcUuid]) { + for (const payload of ['2024-02-29', new Date(0), 1n, undefined]) { + assert.throws( + () => new Wrapper(payload), + { + name: 'TypeError', + message: `${Wrapper.name} has no public constructor. Make one with ${Wrapper.name}.from(text), which returns a Result.`, + }, + Wrapper.name, + ) + } + // Nor does a subclass get around it. + assert.throws(() => new (class extends Wrapper {})('x'), TypeError) +} +// `from(text)` checks the text with the rule `encode` applies, and returns +// what the installed factory returns. It never throws. +for (const [Wrapper, valid, invalid, code] of [ + [RcDate, '2024-02-29', '2023-02-29', 'ERR_INVALID_DATE'], + [ + RcTimestamp, + '1969-12-31T23:59:59.999999999Z', + '2016-12-31T23:59:60Z', + 'ERR_INVALID_TIMESTAMP', + ], + [RcDecimal, '-1.50', '1e5', 'ERR_INVALID_DECIMAL'], + [ + RcUuid, + '123e4567-e89b-12d3-a456-426614174000', + 'not-a-uuid', + 'ERR_INVALID_UUID', + ], +]) { + const made = Wrapper.from(valid) + assert.ok(made.value instanceof Wrapper, Wrapper.name) + assert.equal(made.value.value, valid) + assert.ok(Object.isFrozen(made.value)) + assert.equal(addon.decode(addon.encode(made.value)).value, valid) + // A refusal has the code `encode` gives, and no part of the text. + const refused = Wrapper.from(invalid) + assert.equal(refused.code, code, Wrapper.name) + assert.ok(!refused.message.includes(invalid), refused.message) for (const payload of [ new Date(0), { y: 2024 }, @@ -207,18 +257,20 @@ for (const Wrapper of [VcDate, VcTimestamp, VcDecimal, VcUuid]) { 1.5, undefined, ]) { - assert.throws( - () => new Wrapper(payload), - { name: 'TypeError' }, - Wrapper.name, - ) + assert.equal(Wrapper.from(payload).code, code, `${Wrapper.name} ${payload}`) } + assert.equal(Wrapper.from().code, code) + // A method taken off its class works, since it reads no `this`. + const { from } = Wrapper + assert.ok(from(valid).value instanceof Wrapper) } +assert.equal(RcDecimal.from('NaN').code, 'ERR_NON_FINITE_DECIMAL') +assert.equal(RcDate.from('\ud800').code, 'recipher_js::unpaired_surrogate') for (const [Wrapper, code] of [ - [VcDate, 'ERR_INVALID_DATE'], - [VcTimestamp, 'ERR_INVALID_TIMESTAMP'], - [VcDecimal, 'ERR_INVALID_DECIMAL'], - [VcUuid, 'ERR_INVALID_UUID'], + [RcDate, 'ERR_INVALID_DATE'], + [RcTimestamp, 'ERR_INVALID_TIMESTAMP'], + [RcDecimal, 'ERR_INVALID_DECIMAL'], + [RcUuid, 'ERR_INVALID_UUID'], ]) { // An instance made without the constructor has no text. assert.throws( @@ -243,37 +295,46 @@ for (const timestamp of [ '9999-12-30T22:00:00.999999999Z', ]) { assert.deepEqual( - addon.decode(addon.encode(new VcTimestamp(timestamp))), - new VcTimestamp(timestamp), + addon.decode(addon.encode(addon.makeWrapper('RcTimestamp', timestamp))), + addon.makeWrapper('RcTimestamp', 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')), + () => + addon.encode( + addon.makeWrapper('RcTimestamp', '+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(addon.makeWrapper('RcTimestamp', '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.throws( + () => addon.encode(addon.makeWrapper('RcDate', '+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. +// A whole-millisecond timestamp written by another binding is a Date here. A +// finer timestamp is an RcTimestamp, 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'), + addon.makeWrapper('RcTimestamp', '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. @@ -288,7 +349,7 @@ for (const ordinary of [ } // The wrappers hold their text as an own, read-only, enumerable `value`, // and serialize as that text. -const date = new VcDate('2024-02-29') +const date = addon.makeWrapper('RcDate', '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')