From fc5c851dd05682303466e2b5c2c0f609de900837 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Wed, 25 Nov 2026 23:16:47 +1100 Subject: [PATCH 01/25] feat(recipher-js): every value type, arrays and JSON documents The skeleton encrypts one string. An application needs every value JavaScript has, arrays of them, and JSON documents. keyset.encrypt now takes every value in the value bridge's mapping: a string, a boolean, a number, a bigint at the narrowest width that holds it, bytes, a Date, the wrapper classes for a date, a fine timestamp and a decimal, and null. An array in gives an array out, in one key request each way, and one refused element fails the whole array before any request. json(..) is a native function that reads a document when it is called and holds the engine's JsonPlaintext, so a document is encrypted as the engine encrypts one. A Ciphertext records the kind it decrypts as, and Ciphertext.fromBytes(bytes, kind) reads stored bytes as a kind, so a JSON document read back with kinds.json decrypts to the document, not to its text. Each refusal is a variant of the SDK's error enum with a recipher_js:: code of its own, and the bridge's refusals keep the bridge's codes. Every new signature is written on the Rust method, as the skeleton's are: the array overloads of encrypt and decrypt, and the kind overload of fromBytes, are ts_type strings, one overload per line, so the generated native.d.ts stays the public type. The value types those signatures name live in src/value-types.ts, which imports nothing: the declarations import it, and a module that loaded the addon would make them import themselves. A Json is the native class, marked in the header so no other object type-checks as one. A ciphertext with no type named now allows any scalar, since one read from stored bytes with no kind can decrypt to any. Nothing is released, so the binding interface stays 1. Closes #1812 --- AGENTS.md | 2 +- .../packages/recipher-js/Cargo.lock | 4 + .../typescript/packages/recipher-js/README.md | 89 ++- .../__tests__/addon/builds.test.ts | 62 +- .../recipher-js/__tests__/addon/value.test.ts | 23 +- .../__tests__/addon/values.test.ts | 365 +++++++++++ .../__tests__/unit/binding.test.ts | 19 +- .../packages/recipher-js/crate/Cargo.toml | 9 + .../packages/recipher-js/crate/src/cipher.rs | 153 ++++- .../recipher-js/crate/src/ciphertext.rs | 151 ++++- .../recipher-js/crate/src/engine_tests.rs | 256 +++++++- .../packages/recipher-js/crate/src/error.rs | 88 ++- .../packages/recipher-js/crate/src/js.rs | 59 +- .../packages/recipher-js/crate/src/json.rs | 581 ++++++++++++++++++ .../packages/recipher-js/crate/src/lib.rs | 24 +- .../packages/recipher-js/crate/src/value.rs | 64 +- .../packages/recipher-js/native-header.d.ts | 22 +- .../packages/recipher-js/native.d.ts | 106 +++- .../packages/recipher-js/src/binding.ts | 13 +- .../packages/recipher-js/src/cipher.ts | 7 +- .../packages/recipher-js/src/index.ts | 17 + .../packages/recipher-js/src/kinds.ts | 52 ++ .../packages/recipher-js/src/value-types.ts | 127 ++++ .../packages/recipher-js/src/values.ts | 134 ++++ .../packages/recipher-js/type-tests/native.ts | 11 +- .../packages/recipher-js/type-tests/result.ts | 2 - .../packages/recipher-js/type-tests/values.ts | 92 +++ 27 files changed, 2374 insertions(+), 158 deletions(-) create mode 100644 languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts create mode 100644 languages/typescript/packages/recipher-js/crate/src/json.rs create mode 100644 languages/typescript/packages/recipher-js/src/kinds.ts create mode 100644 languages/typescript/packages/recipher-js/src/value-types.ts create mode 100644 languages/typescript/packages/recipher-js/src/values.ts create mode 100644 languages/typescript/packages/recipher-js/type-tests/values.ts diff --git a/AGENTS.md b/AGENTS.md index bd0367d58..7ddf00563 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -92,7 +92,7 @@ Every npm package except EQL lives under `languages/typescript/`: packages in `l links are provenance only. - `packages/stack-auth`, `packages/stack-profile`, `packages/stack-kms`, `packages/stack-encrypt`, `packages/stack-encrypt-derive`, `packages/stack-encrypt-jsonpath`, `packages/stack-guest-abi`: The Rust crates imported from `cipherstash/cipherstash-suite` with their history, and one added here — `stack-auth` and `stack-profile` (published to crates.io, one version group), `stack-kms` (published to crates.io from 0.1.0, its own version group, re-exported by `stack-encrypt` as `stack_encrypt::kms`), `stack-encrypt` and `stack-encrypt-derive` (published to crates.io from 0.1.0, one version group; `eql-bindings`' `stack-encrypt` feature depends on them from the registry), `stack-encrypt-jsonpath` (the JSONPath grammar of the JSON index and the SQL/JSON path predicate grammar its `match` operator reads, moved out of `stack-encrypt` so the derive can check a field's declared paths, and `predicate!` a predicate's text, at compile time; in the `stack-encrypt` version group, re-exported at `stack_encrypt::json`; its first version is published by hand, as the others' were, before Trusted Publishing can take it), and `stack-guest-abi` (`publish = false`). They are the members of the **root Cargo workspace**, with the three node binding crates below. See "Working on the Rust crates". - `languages/typescript/packages/auth`, `languages/typescript/packages/profile`, `languages/typescript/packages/stack-auth-wasm`: The node bindings of those crates. `@cipherstash/auth` (napi-rs v2) and its six `platforms/*` packages are published to npm from this repository by `release.yml` (`auth-artifacts`, `publish-auth`); a change to what it ships, the `stack-auth` crate included, needs an `@cipherstash/auth` changeset (`require-auth-npm-changeset.yml`). `@cipherstash/profile` and its platforms are private and never published; `@cipherstash/stack-auth-wasm` is private and builds the wasm that `@cipherstash/auth` ships. Their `build` and `test` scripts never invoke cargo; `build:native`, `build:debug` and `test:cargo` do. `@cipherstash/auth` also ships two pure-JS framework adapters over the wasm `OidcFederationStrategy`: `./next` (Next.js App Router, hands the token to the render on a request header) and `./start` (TanStack Start: `csFederateCurrent` is called inside a function middleware the app declares itself, which hands the token to the server function through `next({ context })`; `@tanstack/react-start` is an optional peer loaded only by that entry). -- `languages/typescript/packages/recipher-js`: `@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). 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), stand-ins for a build that did not load, and the types the generated signatures name (`src/kinds.ts`, `src/value-types.ts`). `native.d.ts` imports those types, so a module it imports from must never load the addon: the declarations would import themselves and tsup's declaration build fails. 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/golang`: The Go module — the SDK `encrypt` with its generated-code support `encrypt/gensupport`, its test package `encrypt/encrypttest` (context assertions, and `NewClient`: an offline client over the deterministic test builds, for an application's tests; a **nested Go module** of its own, so only a program that imports it downloads those builds, requiring the SDK at the zero pseudo-version with `replace ../..` in the tree, and `NewClient` fails when the two are at different versions) and the policy packages `encrypt/policy` and `encrypt/policy/protosource`; the credential package `auth`; the generator `stashgen` and its command `cmd/stashgen`; and `internal` (the shared guest plumbing and the `record` wire model). A wazero host with no cgo. Its two WASI guests (`encrypt/guest`, `auth/guest`) are detached Cargo workspaces built by `mise run wasm:guest:build` and `mise run wasm:auth-guest:build`; `mise run wasm:guest:build:deterministic` and `wasm:guest:build:eql:deterministic` build the seeded TEST builds into `encrypt/encrypttest/wasm`, which `encrypttest` embeds and the hermetic Go tests read; the `.wasm` files are gitignored. The stack-encrypt guest has a second build with the EQL types (`mise run wasm:guest:build:eql`, cargo feature `eql`, linking `eql-bindings` by path; `wasm:guest:build:eql:deterministic` is its test build), embedded by `encrypt/eql` and registered on import, so a program whose generated code names an EQL type runs it (ADR-0007, amended). `encrypt/eql`'s types and `Types` table are generated from the EQL catalog by `eql-codegen` (`eql_gen.go`, written by `mise run types:generate` in `packages/eql` and drift-gated by `types:check` and `cargo test -p eql-codegen`). Generated `*_stash.go` files are committed and CI fails when `go generate ./...` changes one. Releases are cut by hand with `.github/workflows/release-golang.yml` (`gh workflow run release-golang.yml -f version=X.Y.Z[-pre] --ref `): because the guests are gitignored on main and Go fetches a version as the files committed at its tag, the workflow builds them, commits them on a release-only commit no branch points at, with `encrypt/encrypttest/go.mod` pinned to the SDK version by `scripts/go-release-pin-encrypttest.sh` (run in `build` and in `publish`), tags it `languages/golang/vX.Y.Z` and `languages/golang/encrypt/encrypttest/vX.Y.Z` (the workflow's `MODULES`) and pushes the tags alone, then attaches the EQL v4 SQL bundle to the GitHub release. The ref must carry the EQL v4 bundle, or the build stops at "Build the EQL SQL bundles". `scripts/go-release-version.mjs` refuses, before anything is built, every version Go would refuse (non-canonical semver, `+build` metadata, a v2+ major on a module path with no `/vN` suffix, a version shaped like a pseudo-version), a final version dispatched from anywhere but `main`, and a final version while `languages/golang/go.mod` pins a `github.com/cipherstash/vitaminc/…` module at a pseudo-version (vitaminc's Go bindings have no tags, and a TEMPORARY pin on an unreleased commit must be gone before the module is tagged); a pre-release may come from a branch and may carry such a pin. The build job also refuses a version the Go proxy already lists in `@v/list`, which catches a tag deleted after the proxy fetched it; it never asks the proxy for the version itself before the tag exists, because the proxy would cache "not found" for up to 30 minutes and `verify` would fail after the push. The build checks the `Cargo.lock` of the EQL workspace and both guest workspaces with `--locked` first, since none of those builds passes it. It runs in a job with no write token and hands the guests to a `publish` job that holds `contents: write` and runs only git and gh. `publish` fetches the commit with plain unauthenticated git rather than `actions/checkout`, whose `token` input defaults to the job's writable token, and refuses a release commit whose tree is not the one the build tested. `publish` takes the paths it commits from the workflow's fixed `GUESTS` list, never from the artifact, and refuses a `guests.sha256` that is not exactly one SHA-256 line for each of those five guests (the three production guests and the two test builds `encrypttest` embeds): the build job runs third-party code after writing that manifest, so a path read from it could put any file on the tag (`scripts/__tests__/go-release-artifact.test.mjs`). The release page's notes are the version's `## [X.Y.Z]` section of `languages/golang/CHANGELOG.md`, taken by `scripts/go-release-notes.mjs` in a `notes` job that runs no third-party code and that `build` waits for: a version with no section, or an empty one, is refused before anything is built, so write the section before dispatching. A version is immutable once the Go proxy has fetched it, so a tag is never moved or deleted: if `publish` or `verify` fails after the tag is pushed, use "Re-run failed jobs" on the same run, which keeps a tag that run pushed and creates or completes the release; a new dispatch of the same version is refused. Never tag a main commit by hand: `go get` would fetch a module with no guests. `encrypt/example` is a third nested module, never tagged: it requires both modules as an application does. `./...` stops at a nested module, so `scripts/go-binding-test.sh`, `go:lint` and the generated-code check find each `go.mod` and run in its directory. - `e2e/*`: Cross-package end-to-end tests (package managers, supply chain, Prisma example README) - `e2e/migration-guide`: Unpublished, separately installed npm examples for the Protect/EQL v2 to Stack/EQL v3 guide. See its README before running; Postgres requires a disposable database and DynamoDB persistence is in memory. diff --git a/languages/typescript/packages/recipher-js/Cargo.lock b/languages/typescript/packages/recipher-js/Cargo.lock index 58fd3bd90..25b247046 100644 --- a/languages/typescript/packages/recipher-js/Cargo.lock +++ b/languages/typescript/packages/recipher-js/Cargo.lock @@ -2489,16 +2489,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", "zeroize", diff --git a/languages/typescript/packages/recipher-js/README.md b/languages/typescript/packages/recipher-js/README.md index 441535743..5f73b7b00 100644 --- a/languages/typescript/packages/recipher-js/README.md +++ b/languages/typescript/packages/recipher-js/README.md @@ -43,7 +43,88 @@ 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. +vitaminc defines the mapping. +vitaminc is the CipherStash Rust library that the engine's plaintext types come from. +The `recipher-value-napi` crate, in `value-napi/`, converts JavaScript values by that mapping, 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 holds it | `bigint` | +| `Uint8Array`, `Buffer` | bytes | `Uint8Array` | +| `Date` | a timestamp | `Date` | +| `new VcTimestamp('2026-11-23T01:02:03.000000001Z')` | a timestamp, in nanoseconds | `Date` when it is whole milliseconds, else `VcTimestamp` | +| `new VcDate('2026-11-23')` | a calendar date | `VcDate` | +| `new VcDecimal('1.50')` | a decimal, with its scale | `VcDecimal` | +| `null` | null | `null` | +| `json(value)` | a JSON document, as its JSON text | the document, from the `Ciphertext` that `encrypt` returned or one read with `kinds.json` | + +- Integers are a `bigint`. + A `number` is a float. + The `number` `5` does not equal the integer `5n`. +- A plain object is refused. + Wrap it in `json(..)`. +- The package exports `VcUuid`, for a universally unique identifier (UUID). + The engine has no plaintext type for a UUID yet. + Encrypting a `VcUuid` is an `Err` with the code `recipher_js::uuid`. +- vitaminc's rules refuse 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()) +``` + +### 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. + +- An integer outside a `number`'s safe range is a `bigint`. + The `bigint` must be in the 64-bit range that the engine's parser reads: `-(2n ** 63n)` to `2n ** 64n - 1n`. + A `bigint` outside that range is refused. +- A whole `number` is refused when its absolute value is at least 2^53 but less than 2^64. + An integer was likely meant. + The `number` does not keep the digits that were written. + Use a `bigint` instead. + Any other finite `number`, such as `1e20`, is a float. +- Bytes, a `Date`, the wrapper classes, and `undefined` have no JSON form. + The package refuses them. + The package also refuses a document nested deeper than 127 levels. +- 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 vitaminc does not build those properties in JavaScript. +- **Read a stored document back with `kinds.json`.** + 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. ## Results, not exceptions @@ -132,7 +213,8 @@ 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-header.d.ts` is the start of `native.d.ts`: it imports the TypeScript types the signatures name, gives `Ciphertext` its type parameter, and marks `Json` so that no other object type-checks as one. +The modules it imports types from never load the addon, so the declarations never import themselves. `native.d.ts` is committed. Each native method returns a `Result` itself. @@ -157,9 +239,6 @@ The ESM build and the CommonJS build load the same addon, so the two builds shar 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..c2f36f36b 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/builds.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/builds.test.ts @@ -2,11 +2,14 @@ * 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. + * the other. And the package with no native build at all. Each runs the + * built `dist/`, in a Node process of its own; `test:addon` builds it + * 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 +51,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 = new recipher.VcDate('2026-11-23').value +out.dateFrozen = Object.isFrozen(new recipher.VcDate('2026-11-23')) +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: '2026-11-23', + 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..dae8b9873 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/value.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/value.test.ts @@ -116,13 +116,6 @@ 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') @@ -211,9 +204,7 @@ 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', ) @@ -226,19 +217,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..1b23051ac --- /dev/null +++ b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts @@ -0,0 +1,365 @@ +import { describe, expect, it } from 'vitest' +import { + type Cipher, + Ciphertext, + json, + kinds, + VcDate, + VcDecimal, + VcTimestamp, + VcUuid, +} from '../../src/index' +import { testCipher } from '../../src/testing' + +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 + | VcDate + | VcTimestamp + | VcDecimal + | null, +) { + 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("vitaminc's wrapper classes", async () => { + const day = await roundTrip(new VcDate('2026-11-23')) + expect(day).toBeInstanceOf(VcDate) + expect((day as VcDate).value).toBe('2026-11-23') + + const fine = await roundTrip( + new VcTimestamp('2026-11-23T01:02:03.000000001Z'), + ) + expect(fine).toBeInstanceOf(VcTimestamp) + expect((fine as VcTimestamp).value).toBe('2026-11-23T01:02:03.000000001Z') + + // A timestamp of whole milliseconds opens as a Date. + const whole = await roundTrip(new VcTimestamp('2026-11-23T01:02:03.000Z')) + expect(whole).toBeInstanceOf(Date) + + const price = await roundTrip(new VcDecimal('1.50')) + expect(price).toBeInstanceOf(VcDecimal) + expect((price as VcDecimal).value).toBe('1.50') + }) + + it('null', async () => { + expect(await roundTrip(null)).toBeNull() + }) +}) + +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, null] as const) + ).unwrap() + expect((await c.decrypt(sealed)).unwrap()).toEqual(['a', 1n, true, null]) + }) + + 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 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 as a bigint. + expect((await c.decrypt(sealed)).unwrap()).toEqual({ + big: 18446744073709551615n, + small: 5, + }) + }) + + it('refuses a number that is an integer outside the safe range', async () => { + const keyset = (await cipher()).defaultKeyset() + const result = await keyset.encrypt(json({ n: 2 ** 60 })) + expect(result.err()?.code).toBe('recipher_js::not_json') + }) + + 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') + }) + + 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') + }) + + 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 property vitaminc reserves, naming the rule, both ways', async () => { + const c = await cipher() + const keyset = c.defaultKeyset() + for (const text of ['{"constructor":1}', '{"prototype":1}']) { + const refused = await keyset.encrypt(json(JSON.parse(text))) + expect(refused.err()?.code).toBe('recipher_js::reserved_key') + // A document another SDK wrote, sealed as the engine seals 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() + const opened: bigint = (await c.decrypt(stored)).unwrap() + expect(opened).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 build checks the name. + const result = Ciphertext.fromBytes(bytes, { name: 'nothing' }) + expect(result.err()?.code).toBe('recipher_js::not_a_kind') + }) +}) + +describe('refusals', () => { + it('a UUID, which the engine does not hold yet', async () => { + const keyset = (await cipher()).defaultKeyset() + const uuid = new VcUuid('123e4567-e89b-12d3-a456-426614174000') + // @ts-expect-error: a UUID is not a scalar of the engine's value model. + const result = await keyset.encrypt(uuid) + expect(result.err()?.code).toBe('recipher_js::uuid') + expect(result.err()?.message).toContain('UUID') + }) + + it("an integer vitaminc cannot hold, with vitaminc's code", 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') + }) + + 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..97f52590a 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: () => ({}), + VcDate: class {}, + VcTimestamp: class {}, + VcDecimal: class {}, + VcUuid: class {}, ...overrides, } } @@ -42,9 +48,15 @@ describe('load', () => { 'Cipher', 'Keyset', 'Ciphertext', + 'Json', 'bindingInterface', 'createTesting', 'installResult', + 'json', + 'VcDate', + 'VcTimestamp', + 'VcDecimal', + 'VcUuid', ]) { 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/crate/Cargo.toml b/languages/typescript/packages/recipher-js/crate/Cargo.toml index 3d6fa1191..b7ea0bf79 100644 --- a/languages/typescript/packages/recipher-js/crate/Cargo.toml +++ b/languages/typescript/packages/recipher-js/crate/Cargo.toml @@ -49,10 +49,19 @@ serde_json = "1" # The engine's opaque path wipes a value it did not seal. The version the # engine resolves. zeroize = "1" +# A kind named to `Ciphertext.fromBytes`, read from its frame through +# vitaminc's frame serde. +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 seal 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 0229f3caf..aeed977ea 100644 --- a/languages/typescript/packages/recipher-js/crate/src/cipher.rs +++ b/languages/typescript/packages/recipher-js/crate/src/cipher.rs @@ -13,10 +13,12 @@ use std::sync::Arc; -use napi::bindgen_prelude::{JavaScriptClassExt, JsValue, Object, PromiseRaw, Unknown}; +use napi::bindgen_prelude::{ + JavaScriptClassExt, JsValue, Object, PromiseRaw, ToNapiValue, Unknown, +}; use napi::Env; use napi_derive::napi; -use stack_encrypt::dynamic::ValueFrame; +use stack_encrypt::dynamic::{ValueFrame, ValueKind}; use stack_encrypt::kms::{DataKeySource, IndexKeySource, StackKms}; use stack_encrypt::{CipherRef, DecryptFrom, EncryptInto, KeysetCipher, StackCipher}; use vitaminc_protected::OpaqueDebug; @@ -24,6 +26,7 @@ use vitaminc_protected::OpaqueDebug; use crate::ciphertext::Ciphertext; use crate::error::{Error, RecipherErrorFields}; use crate::js; +use crate::json::Json; use crate::outcome::{not_made, refused, spawn, Outcome}; use crate::value::OneValue; @@ -120,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, @@ -140,47 +151,82 @@ 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. + /// + /// A value's type sets how it is encrypted. The mapping of JavaScript + /// types comes from vitaminc, CipherStash's cryptography library. A + /// `Json` from `json(..)` is encrypted as a JSON document. + /// + /// 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`. + /// 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>>" )] pub fn encrypt<'e>( &self, env: &'e Env, value: Unknown<'_>, ) -> napi::Result>> { - let value = match js::read(env, value).and_then(OneValue::new) { - Ok(value) => value, - 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) { + 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, @@ -266,24 +312,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(env, value)) + .collect::>>()?; + if many { + return values.into_unknown(env).map_err(not_made); + } + values.pop().ok_or_else(|| Error::NoResult.into()) }, ) } @@ -301,6 +373,16 @@ pub(crate) async fn open_in( }) } +/// Returns one value to encrypt, and the kind its ciphertext decrypts as. A +/// `Json`'s document decrypts as JSON. Any other value decrypts as the type +/// it was encrypted as. +fn one_value(env: &Env, value: Unknown<'_>) -> Outcome<(OneValue, Option)> { + if let Some(document) = Json::of(env, value) { + return Ok((OneValue::json(document?), Some(ValueKind::Json))); + } + Ok((OneValue::scalar(js::read(env, value)?)?, None)) +} + /// Encrypts values under `keyset`. Each value becomes one ciphertext with /// its own data key. All the values use one key request, however many /// there are. @@ -314,7 +396,12 @@ where values .encrypt_into::, K>(keyset) .await - .map_err(|error| RecipherErrorFields::engine(&error)) + .map_err(|error| match error { + // No ciphertext exists yet, so the value caused this failure, + // not a damaged ciphertext. + stack_encrypt::Error::Aead => Error::NotSealed.into(), + error => RecipherErrorFields::engine(&error), + }) } /// Decrypts ciphertexts through `cipher`: a cipher, or one keyset of it. diff --git a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs index 913c72f28..6005fc68e 100644 --- a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs +++ b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs @@ -7,12 +7,16 @@ 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; +use stack_encrypt::dynamic::{read, ValueFrame, ValueKind}; +use stack_encrypt::AsProtectedRef; 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. @@ -21,18 +25,22 @@ use crate::outcome::{failed, not_made, settle}; /// The Rust and Go SDKs write 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, } 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,6 +58,21 @@ impl Ciphertext { .ok() .map(|instance| Ciphertext::clone(&instance)) } + + /// Returns a decrypted value as the kind this ciphertext decrypts as. + /// + /// # Errors + /// + /// Returns `recipher_js::opened_type` for a value encrypted as another + /// type. Returns `recipher_js::not_a_document` when the kind is JSON but + /// the value is not a JSON document. + pub(crate) fn opened(&self, value: ValueFrame) -> Outcome { + match self.opens_as { + None => Ok(value), + Some(ValueKind::Json) => crate::json::opened(&value), + Some(kind) => as_kind(kind, value), + } + } } #[napi] @@ -58,19 +81,34 @@ impl Ciphertext { /// This method checks only the shape of the bytes. Decrypting is what /// checks that they are authentic. A failure does not quote the bytes. /// + /// Give a kind, such as `kinds.string`, to decrypt the value as that + /// kind. Decrypting then refuses a value encrypted as another type. + /// `kinds.json` decrypts a JSON document. + /// + /// 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. + /// bytes are not a `Uint8Array`, and `recipher_js::not_a_kind` when the + /// kind is not one of `kinds`. Does not throw. #[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,6 +131,70 @@ impl Ciphertext { } } +/// A kind, in the form the package's `kinds` object writes it: +/// `{ name: "string" }`. +#[derive(Deserialize)] +struct KindArgument { + name: String, +} + +/// 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) = value.filter(|value| value.get_type().ok() != Some(ValueType::Undefined)) + 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.as_protected_ref().risky_ref()) + .map_err(|_| Error::NotAKind)?; + let kind = argument + .name + .parse::() + .ok() + .filter(|kind| !matches!(kind, ValueKind::Array | ValueKind::Object)) + .ok_or(Error::NotAKind)?; + Ok(Some(kind)) +} + +/// Returns whether `kind` is an integer kind. +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 `value` as `kind`. +/// +/// 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: ValueFrame) -> Outcome { + let refused = || RecipherErrorFields::from(Error::OpenedType { kind }); + let opened = value.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 copy of the bytes of a `Uint8Array`, or `None` for any other /// value. A `Buffer` is a `Uint8Array`. /// @@ -108,3 +210,24 @@ pub(crate) fn bytes_of(value: Unknown<'_>) -> Option> { .ok() .map(|bytes| bytes.to_vec()) } + +#[cfg(test)] +mod tests { + use super::as_kind; + use stack_encrypt::dynamic::{ValueFrame, ValueKind}; + + #[test] + fn an_integer_opens_at_any_width_that_holds_it() { + let opened = as_kind(ValueKind::Int64, ValueFrame::of(5i8).unwrap()).unwrap(); + assert_eq!(opened, ValueFrame::of(5i64).unwrap()); + assert!(as_kind(ValueKind::UInt8, ValueFrame::of(300i16).unwrap()).is_err()); + } + + #[test] + fn a_value_of_another_type_is_refused_as_not_opened() { + let refused = as_kind(ValueKind::Int64, ValueFrame::of(5.0f64).unwrap()).unwrap_err(); + assert_eq!(refused.code, "recipher_js::opened_type"); + assert!(as_kind(ValueKind::String, ValueFrame::of(true).unwrap()).is_err()); + assert!(as_kind(ValueKind::String, ValueFrame::of("x").unwrap()).is_ok()); + } +} 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 7eb3d6f34..2b378b624 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,23 @@ //! 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 stack_encrypt::dynamic::ValueFrame; -use stack_encrypt::kms::DeterministicSource; -use stack_encrypt::StackCipher; +use std::borrow::Cow; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use stack_encrypt::dynamic::{ValueFrame, 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::ciphertext::Ciphertext; use crate::value::OneValue; const SEED: [u8; 32] = [7; 32]; @@ -19,8 +30,8 @@ async fn engine() -> StackCipher { .unwrap() } -fn one(text: &str) -> OneValue { - OneValue::new(ValueFrame::of(text).unwrap()).unwrap() +fn one(value: P) -> OneValue { + OneValue::scalar(ValueFrame::of(value).unwrap()).unwrap() } /// Encrypts `values` through the crate, with the test keys. @@ -30,29 +41,137 @@ async fn sdk_seal(values: Vec) -> Vec { .unwrap() } +/// Decrypts `sealed` through the crate, with the test keys. +async fn sdk_open(sealed: stack_encrypt::Ciphertext) -> ValueFrame { + 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(); + // vitaminc 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 = ValueFrame::of(×tamp).unwrap(); + let decimal_frame = ValueFrame::of(&decimal).unwrap(); + let cases: Vec<(stack_encrypt::Ciphertext, ValueFrame)> = vec![ + ( + keyset.encrypt("text".to_owned()).await.unwrap(), + ValueFrame::of("text").unwrap(), + ), + ( + keyset.encrypt(-7i64).await.unwrap(), + ValueFrame::of(-7i64).unwrap(), + ), + ( + keyset.encrypt(u64::MAX).await.unwrap(), + ValueFrame::of(u64::MAX).unwrap(), + ), + ( + keyset.encrypt(vec![0u8, 255]).await.unwrap(), + ValueFrame::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, expected); + } +} + +#[tokio::test] +async fn a_json_document_the_engine_sealed_opens_as_json_with_its_big_integer() { + 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(ValueKind::Json)); + let opened = ciphertext.opened(sdk_open(sealed).await).unwrap(); + // A safe integer decrypts as a float, for a JavaScript `number`. An + // integer outside the safe range decrypts as an integer, for a + // JavaScript `bigint`. + let expected = crate::json::document(&opened).unwrap(); + assert_eq!( + expected.value(), + &serde_json::json!({"id": u64::MAX, "n": 5}) + ); + assert_eq!( + opened, + ValueFrame::of(&OpenedDocument).unwrap(), + "the opened frame holds `n` as a float and `id` as an integer" + ); +} + +/// `{"id": u64::MAX, "n": 5.0}`, as the crate decrypts the document above. +struct OpenedDocument; + +impl Encrypt for &OpenedDocument { + fn visit(self, sink: S) -> Result { + use stack_encrypt::dynamic::plaintext::MapSink; + let mut map = sink.map(Some(2))?; + let _ = u64::MAX.visit(map.entry("id")?)?; + let _ = 5.0f64.visit(map.entry("n")?)?; + map.end() + } } #[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 frame = ValueFrame::of(&Document).unwrap(); + let document = crate::json::document(&frame).unwrap(); + let sealed = sdk_seal(vec![OneValue::json(document)]).await.remove(0); + 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, ValueFrame::of("from the engine").unwrap()); + assert_eq!( + opened.value(), + &serde_json::json!({"name": "Ada", "age": 36, "big": u64::MAX}) + ); +} + +/// `{"name": "Ada", "age": 36.0, "big": u64::MAX}`, in the form a +/// JavaScript caller passes it: a number is a float, and a `bigint` is an +/// integer. +struct Document; + +impl Encrypt for &Document { + fn visit(self, sink: S) -> Result { + use stack_encrypt::dynamic::plaintext::MapSink; + let mut map = sink.map(Some(3))?; + let _ = "Ada".visit(map.entry("name")?)?; + let _ = 36.0f64.visit(map.entry("age")?)?; + let _ = u64::MAX.visit(map.entry("big")?)?; + map.end() + } } #[tokio::test] @@ -99,3 +218,106 @@ async fn a_keyset_refuses_another_keysets_ciphertext_and_the_cipher_opens_it() { .remove(0); assert_eq!(opened, ValueFrame::of("in another keyset").unwrap()); } + +/// 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); + assert_eq!( + opened, + vec![ + ValueFrame::of("first").unwrap(), + ValueFrame::of("second").unwrap(), + ValueFrame::of("third").unwrap(), + ] + ); +} + +#[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); +} + +#[test] +fn a_uuid_is_outside_the_engines_value_model() { + struct AUuid; + impl Encrypt for &AUuid { + fn visit( + self, + sink: S, + ) -> Result { + use stack_encrypt::dynamic::plaintext::{Logical, Physical}; + sink.scalar(Some(Logical::Uuid), Physical::Bytes(&[7; 16])) + } + } + assert!(ValueFrame::of(&AUuid).is_err()); +} diff --git a/languages/typescript/packages/recipher-js/crate/src/error.rs b/languages/typescript/packages/recipher-js/crate/src/error.rs index 8e2186076..4d1b30720 100644 --- a/languages/typescript/packages/recipher-js/crate/src/error.rs +++ b/languages/typescript/packages/recipher-js/crate/src/error.rs @@ -26,12 +26,25 @@ use std::error::Error as StdError; use miette::Diagnostic; use napi_derive::napi; +use stack_encrypt::dynamic::ValueKind; use stack_encrypt::ErrorPayload; /// 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` is not a value")] + #[diagnostic( + code(recipher_js::undefined), + help("Use `null` for a value that is not there.") + )] + Undefined, + /// A `VcUuid`. The engine's value model, the set of value types the + /// engine reads, has no UUID type. + #[error("a UUID cannot be encrypted yet: the engine's value model does not hold one")] + #[diagnostic(code(recipher_js::uuid), help("Encrypt its text 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 +56,30 @@ 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 is not a value")] + #[diagnostic(code(recipher_js::not_a_scalar), help("Wrap it in json(..)."))] + NotAScalar, + /// An object given as one value. + #[error("an object is not a value")] + #[diagnostic(code(recipher_js::plain_object), help("Wrap it in json(..)."))] + PlainObject, + /// A value that the engine cannot encrypt as a JSON document. + #[error("the value is not a JSON document the engine seals: {what}")] + #[diagnostic(code(recipher_js::not_json))] + NotJson { what: &'static str }, + /// A JSON document nested deeper than the engine's JSON parser reads. + #[error( + "the value is not a JSON document the engine seals: it is nested deeper than 127 levels of arrays and objects" + )] + #[diagnostic(code(recipher_js::too_deep))] + JsonTooDeep, + /// The engine refused to encrypt a value in the form it was given. + #[error("the engine could not seal the value as given")] + #[diagnostic(code(recipher_js::not_sealed))] + NotSealed, /// `decrypt` given something that is not a `Ciphertext`. - #[error("decrypt takes a Ciphertext")] + #[error("decrypt takes a Ciphertext, or an array of them")] #[diagnostic( code(recipher_js::not_a_ciphertext), help("Read stored bytes with Ciphertext.fromBytes.") @@ -58,6 +89,18 @@ pub(crate) enum Error { #[error("a ciphertext is read from a Uint8Array")] #[diagnostic(code(recipher_js::not_bytes))] NotBytes, + /// A kind that is not one of `kinds`. + #[error("a ciphertext opens as one of `kinds`, such as `kinds.string`")] + #[diagnostic(code(recipher_js::not_a_kind))] + NotAKind, + /// A ciphertext that decrypted to another kind than the one named. + #[error("the value opened, but it was not sealed as the kind named, {kind}")] + #[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 opened, 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))] @@ -285,6 +328,7 @@ impl From for RecipherErrorFields { #[cfg(test)] mod tests { use super::{Error, ErrorCause, RecipherErrorFields, Severity, UNDESCRIBED_CAUSE}; + use stack_encrypt::dynamic::ValueKind; #[test] fn an_aead_failure_keeps_the_engine_code_message_and_help() { @@ -363,12 +407,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` is not a value"); assert_eq!( error.help.as_deref(), - Some("Read stored bytes with Ciphertext.fromBytes.") + Some("Use `null` for a value that is not there.") ); assert_eq!(error.severity, Severity::Error); assert!(error.fields.is_empty() && error.causes.is_empty()); @@ -469,11 +513,22 @@ 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::NotJson { what: "bytes" }, + Error::JsonTooDeep, + Error::NotSealed, Error::NotACiphertext, Error::NotBytes, + Error::NotAKind, + Error::OpenedType { + kind: ValueKind::String, + }, + Error::NotADocument, Error::TestingSeed, Error::NoTesting, Error::NoResult, @@ -481,11 +536,20 @@ 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::NotJson { .. } + | Error::JsonTooDeep + | Error::NotSealed | Error::NotACiphertext | Error::NotBytes + | Error::NotAKind + | Error::OpenedType { .. } + | Error::NotADocument | Error::TestingSeed | Error::NoTesting | Error::NoResult diff --git a/languages/typescript/packages/recipher-js/crate/src/js.rs b/languages/typescript/packages/recipher-js/crate/src/js.rs index b43befdfd..82b042743 100644 --- a/languages/typescript/packages/recipher-js/crate/src/js.rs +++ b/languages/typescript/packages/recipher-js/crate/src/js.rs @@ -21,9 +21,9 @@ //! 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::{FromNapiValue, JsObjectValue, JsValue, Object, Unknown}; +use napi::{Env, Status, ValueType}; +use recipher_value_napi::{JsBuilder, JsFault, JsRef, Refusal, Wrapper, Wrappers}; use stack_encrypt::dynamic::ValueFrame; use stack_encrypt::AsProtectedRef; use vitaminc_aead::Frame; @@ -37,21 +37,56 @@ use crate::error::{Error, RecipherErrorFields}; /// /// Returns one of these errors: /// -/// - `recipher_js::value` for a value outside the engine's value model; +/// - `recipher_js::undefined` for `undefined`; +/// - `recipher_js::uuid` for a `VcUuid`; +/// - `recipher_js::value` for another value outside the engine's value model; /// - `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()); + } + let uuid = is_uuid(env, &value); let frame = JsRef::new(value) .to_frame() .map_err(|error| refused(env, &error))?; - ValueFrame::from_bytes(frame.as_protected_ref()).map_err(|_| Error::Value.into()) + ValueFrame::from_bytes(frame.as_protected_ref()) + .map_err(|_| RecipherErrorFields::from(if uuid { Error::Uuid } else { Error::Value })) +} + +/// Returns the elements of `value` when it is an array, or `None` when it +/// is not. +/// +/// # Errors +/// +/// Returns the bridge's refusal, or `recipher_js::threw`, when an element +/// cannot be read. For example, an element behind a getter that throws +/// cannot be read. +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()?; + let read = || -> napi::Result>> { + let len = array.get_array_length()?; + (0..len) + .map(|at| array.get_element::>(at)) + .collect() + }; + Some(read().map_err(|error| refused(env, &error.into()))) } /// 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 vitaminc, CipherStash's cryptography library, does not build. +/// Returns `recipher_js::build_value` for any other failure. pub fn build(env: &Env, value: ValueFrame) -> Result, RecipherErrorFields> { let bytes = value.into_inner(); let frame = Frame::parse(bytes.risky_ref()).map_err(|_| Error::BuildValue)?; @@ -63,7 +98,17 @@ 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(), + } +} + +/// Returns whether `value` is a vitaminc `VcUuid`. +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..18ddc02ac --- /dev/null +++ b/languages/typescript/packages/recipher-js/crate/src/json.rs @@ -0,0 +1,581 @@ +//! JSON documents: the [`Json`] class that `json(..)` makes, and the +//! conversion between a frame and the engine's [`JsonPlaintext`]. +//! +//! The engine is the Stack Encrypt engine, the `stack-encrypt` crate. The +//! engine's value model is the set of value types it reads. A frame is a +//! byte buffer that contains one value of the model. A sink receives a +//! value from a frame one part at a time: one scalar, array or map. +//! +//! # Encrypting +//! +//! JavaScript has one number type, and a `number` cannot represent every +//! integer that a JSON document can. So a document's values become JSON +//! values by these rules: +//! +//! - An object, an array, text, a boolean and null stay as they are. +//! - A `number` that is a safe integer is written as that integer, as +//! `JSON.stringify` writes it. A safe integer is at most 2^53 - 1 from +//! zero. +//! - A whole `number` between 2^53 and 2^64 from zero is refused. The +//! caller probably meant an integer, and the `number`'s digits are not the +//! ones the caller wrote. +//! - Any other finite `number` is written as a float. +//! - A `bigint` is written as its digits. A `bigint` outside the 64-bit +//! range that the engine's parser reads is refused. +//! - Any other value is refused, because it has no JSON form. Examples are +//! bytes, a date, a timestamp, a decimal, a UUID and `undefined`. +//! - A document nested deeper than 127 levels is refused, because the +//! engine's parser would refuse it when the document is decrypted. +//! +//! # Decrypting +//! +//! An integer in the safe range becomes a `number`, and an integer outside +//! it becomes a `bigint`, so no digit is lost. A float becomes a `number`. +//! +//! The engine encrypts the document as its JSON text, through +//! [`JsonPlaintext`], and reads it back with the engine's JSON parser. +//! Everything built along the way, including map keys, is wiped when it is +//! dropped. + +use napi::bindgen_prelude::{ClassInstance, FromNapiValue, JavaScriptClassExt, Unknown}; +use napi::Env; +use napi_derive::napi; +use serde_json::{Map, Number, Value}; +use stack_encrypt::dynamic::plaintext::{ + Error as SinkError, FixedType, Float, Int, Logical, MapSink, Physical, SeqSink, Sink, + SourceError, +}; +use stack_encrypt::dynamic::{read_json, ValueFrame}; +use stack_encrypt::json::{wipe_value, JsonPlaintext}; +use stack_encrypt::{Encrypt, EncryptRef}; +use vitaminc_protected::OpaqueDebug; +use zeroize::Zeroizing; + +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. +const MAX_DEPTH: usize = 127; + +/// The largest integer that a JavaScript `number` represents exactly: +/// 2^53 - 1. +const MAX_SAFE: u64 = (1 << 53) - 1; + +/// 2^64: the smallest magnitude larger than every 64-bit integer. +const TWO_TO_64: f64 = 18_446_744_073_709_551_616.0; + +/// 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 { + document: 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 of `value` as a value to encrypt, when `value` + /// is a `Json`. Returns the failure instead when the document cannot be + /// encrypted. Returns `None` when `value` is not a `Json`. + 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.document()) + } + + /// Returns the document as a value to encrypt, or the failure that + /// stops it being encrypted. + pub(crate) fn document(&self) -> Result { + match &self.document { + // The copy is wiped when the `JsonPlaintext` that contains it + // drops. + Ok(document) => Ok(JsonPlaintext::from(document.value().clone())), + Err(error) => Err(error.clone()), + } + } +} + +/// Makes a JSON document to encrypt as one ciphertext. The document is a +/// plain object, an array, text, a number, a `bigint`, a boolean or `null`, +/// nested at most 127 levels. +/// +/// Give an integer outside a `number`'s safe range as a `bigint`, within 64 +/// bits. The safe range is at most 2^53 - 1 from zero. A whole `number` +/// between 2^53 and 2^64 from zero is refused, because the caller probably +/// meant an integer. +/// +/// `json(..)` reads the document now. `json(..)` never throws: `encrypt` +/// returns an `Err` for a document that cannot be encrypted. +#[napi(js_name = "json", ts_args_type = "document: JsonValue")] +pub fn json_document(env: &Env, document: Unknown<'_>) -> Json { + Json { + document: js::read(env, document).and_then(|frame| self::document(&frame)), + } +} + +/// The JSON sink returns the SDK's own errors: [`Error::NotJson`] or +/// [`Error::JsonTooDeep`]. Each has fixed text that includes no part of the +/// value. +impl SinkError for Error { + fn source(_: SourceError) -> Self { + Self::NotJson { + what: "it could not be read", + } + } +} + +/// Returns the document in a frame, as the engine's [`JsonPlaintext`]. +pub(crate) fn document(frame: &ValueFrame) -> Result { + frame + .visit(ToJson { + out: Root, + depth: 0, + }) + .map(JsonPlaintext::from) + .map_err(RecipherErrorFields::from) +} + +/// Returns the value of a decrypted document's text, as a frame. The +/// conversion follows the rules in the module docs. +pub(crate) fn opened(frame: &ValueFrame) -> Result { + let document = read_json(frame).map_err(|_| Error::NotADocument)?; + ValueFrame::of(&FromJson(document.value())).map_err(|_| Error::BuildValue.into()) +} + +/// The place a built JSON value goes. +trait Out { + type Ok; + fn put(self, value: Value) -> Result; +} + +/// The built value is the result. +struct Root; + +impl Out for Root { + type Ok = Value; + fn put(self, value: Value) -> Result { + Ok(value) + } +} + +/// The built value is the next element of an array. +struct Element<'s>(&'s mut Vec); + +impl Out for Element<'_> { + type Ok = (); + fn put(self, value: Value) -> Result<(), Error> { + self.0.push(value); + Ok(()) + } +} + +/// The built value is the member `key` of an object. Until the key is in +/// the object, it is kept in a buffer that is wiped when dropped. So a +/// member that is refused, or dropped unfinished, leaves no copy of its key. +struct Member<'s> { + object: &'s mut Map, + key: Zeroizing, +} + +impl Out for Member<'_> { + type Ok = (); + fn put(mut self, value: Value) -> Result<(), Error> { + let key = std::mem::take(&mut *self.key); + let _ = self.object.insert(key, value); + Ok(()) + } +} + +/// A sink that builds a JSON value at `depth` levels of nesting, and passes +/// it to `O`. +struct ToJson { + out: O, + depth: usize, +} + +/// Returns the JSON number for a float, by the rules in the module docs. +fn float(value: f64) -> Result { + if !value.is_finite() { + return Err(Error::NotJson { + what: "a number that is not finite", + }); + } + let magnitude = value.abs(); + if value.fract() == 0.0 && magnitude <= MAX_SAFE as f64 { + // The value is a safe integer, so the conversion is exact. + #[allow(clippy::cast_possible_truncation)] + return Ok(Value::Number(Number::from(value as i64))); + } + if value.fract() == 0.0 && magnitude < TWO_TO_64 { + return Err(Error::NotJson { + what: "a whole number between 2^53 and 2^64 held as a number, whose digits may not be \ + the ones meant; use a bigint", + }); + } + Number::from_f64(value) + .map(Value::Number) + .ok_or(Error::NotJson { + what: "a number that is not finite", + }) +} + +/// Returns the JSON number for an integer. An integer outside the 64-bit +/// range is refused. +fn integer(value: Int) -> Result { + let wide = match value { + Int::I8(n) => i128::from(n), + Int::I16(n) => i128::from(n), + Int::I32(n) => i128::from(n), + Int::I64(n) => i128::from(n), + Int::I128(n) => n, + Int::U8(n) => i128::from(n), + Int::U16(n) => i128::from(n), + Int::U32(n) => i128::from(n), + Int::U64(n) => i128::from(n), + Int::U128(n) => i128::try_from(n).unwrap_or(i128::MAX), + }; + if let Ok(n) = i64::try_from(wide) { + return Ok(Value::Number(Number::from(n))); + } + if let Ok(n) = u64::try_from(wide) { + return Ok(Value::Number(Number::from(n))); + } + Err(Error::NotJson { + what: "a bigint outside the 64-bit range (below -2^63 or above 2^64 - 1)", + }) +} + +impl ToJson { + /// Returns the depth of an array or object that starts here. A depth + /// past the limit is refused. + fn nested(&self) -> Result { + let depth = self.depth + 1; + if depth > MAX_DEPTH { + return Err(Error::JsonTooDeep); + } + Ok(depth) + } +} + +impl Sink for ToJson { + type Ok = O::Ok; + type Error = Error; + type Seq = JsonArray; + type Map = JsonObject; + + fn scalar(self, ty: Option, value: Physical<'_>) -> Result { + let value = match (ty, value) { + (None, Physical::Null) => Value::Null, + (None, Physical::Bool(b)) => Value::Bool(b), + (None, Physical::Text(text)) => Value::String(text.to_owned()), + (None, Physical::Float(Float::F64(n))) => float(n)?, + (None, Physical::Float(Float::F32(n))) => float(f64::from(n))?, + (None, Physical::Int(n)) => integer(n)?, + (None, Physical::Bytes(_)) => return Err(Error::NotJson { what: "bytes" }), + (Some(Logical::Undefined), _) => return Err(Error::NotJson { what: "undefined" }), + (Some(_), _) => { + return Err(Error::NotJson { + what: "a date, a timestamp, a decimal or a UUID; write it as text", + }) + } + }; + self.out.put(value) + } + + fn typed_null(self, _: FixedType) -> Result { + self.out.put(Value::Null) + } + + fn seq(self, len: Option) -> Result, Error> { + let depth = self.nested()?; + Ok(JsonArray { + out: Some(self.out), + depth, + items: Vec::with_capacity(len.unwrap_or(0).min(1024)), + }) + } + + fn map(self, _: Option) -> Result, Error> { + let depth = self.nested()?; + Ok(JsonObject { + out: Some(self.out), + depth, + members: Map::new(), + }) + } + + fn passthrough(self, _: &P) -> Result { + Err(Error::NotJson { + what: "a passthrough", + }) + } +} + +/// An array being built. Its items are wiped if it is dropped unfinished. +struct JsonArray { + out: Option, + depth: usize, + items: Vec, +} + +impl Drop for JsonArray { + fn drop(&mut self) { + for item in &mut self.items { + wipe_value(item); + } + } +} + +impl SeqSink for JsonArray { + type Ok = O::Ok; + type Error = Error; + type Element<'s> + = ToJson> + where + Self: 's; + + fn element(&mut self) -> Result>, Error> { + Ok(ToJson { + out: Element(&mut self.items), + depth: self.depth, + }) + } + + fn end(mut self) -> Result { + let items = std::mem::take(&mut self.items); + match self.out.take() { + Some(out) => out.put(Value::Array(items)), + None => Err(Error::NotJson { + what: "it could not be read", + }), + } + } +} + +/// An object being built. Its members are wiped if it is dropped +/// unfinished. +struct JsonObject { + out: Option, + depth: usize, + members: Map, +} + +impl Drop for JsonObject { + fn drop(&mut self) { + let mut members = Value::Object(std::mem::take(&mut self.members)); + wipe_value(&mut members); + } +} + +impl MapSink for JsonObject { + type Ok = O::Ok; + type Error = Error; + type Entry<'s> + = ToJson> + where + Self: 's; + + fn entry(&mut self, key: &str) -> Result>, Error> { + Ok(ToJson { + out: Member { + object: &mut self.members, + key: Zeroizing::new(key.to_owned()), + }, + depth: self.depth, + }) + } + + fn end(mut self) -> Result { + let members = std::mem::take(&mut self.members); + match self.out.take() { + Some(out) => out.put(Value::Object(members)), + None => Err(Error::NotJson { + what: "it could not be read", + }), + } + } +} + +/// A JSON value, written into a sink by the rules in the module docs. +struct FromJson<'v>(&'v Value); + +impl Encrypt for &FromJson<'_> { + fn visit(self, sink: S) -> Result { + walk(self.0, sink) + } +} + +fn walk(value: &Value, sink: S) -> Result { + match value { + Value::Null => sink.scalar(None, Physical::Null), + Value::Bool(b) => sink.scalar(None, Physical::Bool(*b)), + Value::String(text) => sink.scalar(None, Physical::Text(text)), + Value::Number(number) => sink.scalar(None, number_of(number)), + Value::Array(items) => { + let mut seq = sink.seq(Some(items.len()))?; + for item in items { + walk(item, seq.element()?)?; + } + seq.end() + } + Value::Object(members) => { + let mut map = sink.map(Some(members.len()))?; + for (key, member) in members { + walk(member, map.entry(key)?)?; + } + map.end() + } + } +} + +/// Returns a number in the form JavaScript reads it: a `number` for a float +/// or a safe integer, and a `bigint` for any other integer. +fn number_of(number: &Number) -> Physical<'static> { + if let Some(n) = number.as_i64() { + if n.unsigned_abs() <= MAX_SAFE { + // The integer is in the safe range, so the conversion is exact. + #[allow(clippy::cast_precision_loss)] + return Physical::Float(Float::F64(n as f64)); + } + return Physical::Int(Int::I64(n)); + } + if let Some(n) = number.as_u64() { + return Physical::Int(Int::U64(n)); + } + Physical::Float(Float::F64(number.as_f64().unwrap_or(f64::NAN))) +} + +#[cfg(test)] +mod tests { + use super::{document, opened, MAX_DEPTH}; + use serde_json::json; + use stack_encrypt::dynamic::ValueFrame; + use stack_encrypt::json::JsonPlaintext; + + fn frame_of_text(text: &str) -> ValueFrame { + ValueFrame::of(text).unwrap() + } + + /// Arrays nested `.0` levels deep. The innermost array is empty. + struct Nested(usize); + + impl stack_encrypt::Encrypt for &Nested { + fn visit( + self, + sink: S, + ) -> Result { + use stack_encrypt::dynamic::plaintext::SeqSink; + let mut seq = sink.seq(Some(usize::from(self.0 > 1)))?; + if self.0 > 1 { + let _ = (&Nested(self.0 - 1)).visit(seq.element()?)?; + } + seq.end() + } + } + + /// Returns a frame of `depth` nested arrays, each inside the one before. + fn nested(depth: usize) -> ValueFrame { + ValueFrame::of(&Nested(depth)).unwrap() + } + + #[test] + fn a_safe_integer_float_is_written_as_an_integer() { + let frame = ValueFrame::of(vec![5.0f64, 1.5]).unwrap(); + assert_eq!(document(&frame).unwrap().value(), &json!([5, 1.5])); + } + + #[test] + fn a_whole_number_between_2_53_and_2_64_is_refused() { + let frame = ValueFrame::of(9_007_199_254_740_993.0f64).unwrap(); + let error = document(&frame).unwrap_err(); + assert_eq!(error.code, "recipher_js::not_json"); + assert!(error.message.contains("bigint")); + } + + #[test] + fn a_large_float_is_written_as_a_float_and_reads_back_the_same() { + for value in [1e20f64, f64::MAX, -6.02e23] { + let written = document(&ValueFrame::of(value).unwrap()).unwrap(); + assert_eq!(written.value().as_f64(), Some(value)); + // The engine's parser reads the text back as the same float. + let text = stack_encrypt::json::to_text(written.value()).unwrap(); + let read = JsonPlaintext::parse(std::str::from_utf8(&text).unwrap()).unwrap(); + assert_eq!(read.value().as_f64(), Some(value)); + } + } + + #[test] + fn a_bigint_is_written_as_its_digits_within_64_bits() { + let frame = ValueFrame::of(u64::MAX).unwrap(); + assert_eq!( + document(&frame).unwrap().value(), + &json!(18_446_744_073_709_551_615u64) + ); + assert!(document(&ValueFrame::of(u128::MAX).unwrap()).is_err()); + assert!(document(&ValueFrame::of(i128::MIN).unwrap()).is_err()); + } + + #[test] + fn bytes_have_no_json_form() { + let frame = ValueFrame::of(vec![1u8, 2, 3]).unwrap(); + assert_eq!(document(&frame).unwrap_err().code, "recipher_js::not_json"); + } + + #[test] + fn a_document_nests_as_deep_as_the_engine_reads_and_no_deeper() { + assert!(document(&nested(MAX_DEPTH)).is_ok()); + let refused = document(&nested(MAX_DEPTH + 1)).unwrap_err(); + assert_eq!(refused.code, "recipher_js::too_deep"); + } + + #[test] + fn an_opened_integer_is_a_number_when_safe_and_an_integer_when_not() { + let opened = opened(&frame_of_text( + r#"{"small": 5, "big": 18446744073709551615, "f": 1.5}"#, + )) + .unwrap(); + // In the decrypted frame, the small integer is now a float, and the + // big one is still an integer. The frame reads back as the same + // document. + let read = document(&opened).unwrap(); + assert_eq!( + read.value(), + &json!({"small": 5, "big": 18_446_744_073_709_551_615u64, "f": 1.5}) + ); + } + + #[test] + fn a_document_another_sdk_wrote_with_a_large_float_encrypts_again() { + let opened = opened(&frame_of_text(r#"{"x": 1e20}"#)).unwrap(); + assert_eq!(document(&opened).unwrap().value(), &json!({"x": 1e20})); + } + + #[test] + fn text_that_is_not_a_document_does_not_open() { + let error = opened(&frame_of_text("{not json")).unwrap_err(); + assert_eq!(error.code, "recipher_js::not_a_document"); + assert!(!error.message.contains("not json")); + } +} diff --git a/languages/typescript/packages/recipher-js/crate/src/lib.rs b/languages/typescript/packages/recipher-js/crate/src/lib.rs index 858ed99b1..a5c918bb5 100644 --- a/languages/typescript/packages/recipher-js/crate/src/lib.rs +++ b/languages/typescript/packages/recipher-js/crate/src/lib.rs @@ -1,7 +1,7 @@ //! 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. //! @@ -54,6 +54,7 @@ mod cipher; mod ciphertext; mod error; mod js; +mod json; mod outcome; mod value; @@ -63,8 +64,11 @@ 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 @@ -78,3 +82,21 @@ pub const BINDING_INTERFACE: u32 = 1; pub fn binding_interface() -> u32 { BINDING_INTERFACE } + +/// Exports the wrapper classes of vitaminc, CipherStash's cryptography +/// library: `VcDate`, `VcTimestamp`, `VcDecimal` and `VcUuid`. Each class +/// stands for a type that JavaScript does not have. The addon exports them +/// so JavaScript can construct them, and so decrypted values are instances +/// of them. +// 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/value.rs b/languages/typescript/packages/recipher-js/crate/src/value.rs index 0aba706b6..29bb10ace 100644 --- a/languages/typescript/packages/recipher-js/crate/src/value.rs +++ b/languages/typescript/packages/recipher-js/crate/src/value.rs @@ -5,12 +5,18 @@ use stack_encrypt::dynamic::plaintext::{depth, Error as _, Scalar, Sink, SourceError}; use stack_encrypt::dynamic::{ValueFrame, ValueKind}; +use stack_encrypt::json::JsonPlaintext; use stack_encrypt::Encrypt; use vitaminc_protected::OpaqueDebug; use crate::error::{Error, RecipherErrorFields}; -/// A value checked to be one string. +/// A value checked to be one leaf: one scalar of the engine's value model, +/// or one JSON document. +/// +/// The value model is the set of value types the engine reads. A scalar is +/// a value of the model that is not an array or a map, such as text, a +/// number or bytes. /// /// The engine encrypts the value through its opaque scalar path. That path /// encrypts a whole value as one leaf. Rust's `keyset.encrypt(value)` uses @@ -19,35 +25,49 @@ use crate::error::{Error, RecipherErrorFields}; /// /// The engine encrypts a value as one opaque leaf only when its type /// implements `Scalar`, a trait of vitaminc, CipherStash's cryptography -/// library. A [`ValueFrame`] can contain any value of the engine's value -/// model, the set of value types the engine reads. So a [`ValueFrame`] is -/// not a `Scalar`. This type checks that the frame contains one string. The -/// check runs once, before the engine reads the value. +/// library. A [`ValueFrame`] can contain any value of the model, including +/// an array or a map. So a [`ValueFrame`] is not a `Scalar`. This type +/// checks that the frame contains one scalar. The check runs once, before +/// the engine reads the value. /// /// The opaque path also needs a value it can wipe (`Zeroize`). Wiping drops -/// the frame, and the frame wipes its own buffer when it drops. `Debug` +/// the value, and the value wipes its own buffer when it drops. `Debug` /// hides the value. #[derive(OpaqueDebug)] -pub(crate) struct OneValue(Option); +pub(crate) struct OneValue(Option); + +/// The value inside a [`OneValue`]: a scalar, or a JSON document. +#[derive(OpaqueDebug)] +enum Leaf { + Scalar(ValueFrame), + Json(JsonPlaintext), +} impl OneValue { - /// Returns `value` as a [`OneValue`], if it is one string. + /// Returns `value` as a [`OneValue`], if it is one scalar. /// /// # Errors /// - /// Returns `recipher_js::not_a_string` for any other value. - pub(crate) fn new(value: ValueFrame) -> Result { - if value.kind() == Some(ValueKind::String) { - Ok(Self(Some(value))) - } else { - Err(Error::NotAString.into()) + /// Returns `recipher_js::not_a_scalar` for an array, and + /// `recipher_js::plain_object` for an object. + pub(crate) fn scalar(value: ValueFrame) -> Result { + match value.kind() { + Some(ValueKind::Array) => Err(Error::NotAScalar.into()), + Some(ValueKind::Object) => Err(Error::PlainObject.into()), + _ => Ok(Self(Some(Leaf::Scalar(value)))), } } + + /// Returns a JSON document as a [`OneValue`]. The engine encrypts it as + /// it encrypts any `JsonPlaintext`: as its JSON text. + pub(crate) fn json(document: JsonPlaintext) -> Self { + Self(Some(Leaf::Json(document))) + } } impl zeroize::Zeroize for OneValue { fn zeroize(&mut self) { - // Dropping the frame wipes its buffer. + // Dropping the leaf wipes its buffer. self.0 = None; } } @@ -56,7 +76,8 @@ impl Encrypt for &OneValue { const DEPTH: Option = depth::SCALAR; fn visit(self, sink: S) -> Result { match &self.0 { - Some(frame) => frame.visit(sink), + Some(Leaf::Scalar(frame)) => frame.visit(sink), + Some(Leaf::Json(document)) => document.visit(sink), None => Err(S::Error::source(SourceError::msg("a wiped value"))), } } @@ -70,15 +91,16 @@ mod tests { use stack_encrypt::dynamic::ValueFrame; #[test] - fn a_string_is_one_value_and_another_value_is_not() { - assert!(OneValue::new(ValueFrame::of("text").unwrap()).is_ok()); - let refused = OneValue::new(ValueFrame::of(5i64).unwrap()).unwrap_err(); - assert_eq!(refused.code, "recipher_js::not_a_string"); + fn a_scalar_is_one_value_and_a_container_is_not() { + assert!(OneValue::scalar(ValueFrame::of("text").unwrap()).is_ok()); + assert!(OneValue::scalar(ValueFrame::of(vec![1u8, 2]).unwrap()).is_ok()); + let refused = OneValue::scalar(ValueFrame::of(vec!["a", "b"]).unwrap()).unwrap_err(); + assert_eq!(refused.code, "recipher_js::not_a_scalar"); } #[test] fn debug_hides_the_value() { - let value = OneValue::new(ValueFrame::of("secret").unwrap()).unwrap(); + let value = OneValue::scalar(ValueFrame::of("secret").unwrap()).unwrap(); assert!(!format!("{value:?}").contains("secret")); } } diff --git a/languages/typescript/packages/recipher-js/native-header.d.ts b/languages/typescript/packages/recipher-js/native-header.d.ts index e7f4c4600..f46b05b92 100644 --- a/languages/typescript/packages/recipher-js/native-header.d.ts +++ b/languages/typescript/packages/recipher-js/native-header.d.ts @@ -3,18 +3,32 @@ 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 { Kind, ValueOf } 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`. + * `keyset.encrypt('..')` returns a `Ciphertext`. A ciphertext read + * from stored bytes with no kind named decrypts to whatever type was + * encrypted, so its type allows any scalar. */ -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..134f254a6 100644 --- a/languages/typescript/packages/recipher-js/native.d.ts +++ b/languages/typescript/packages/recipher-js/native.d.ts @@ -3,22 +3,36 @@ 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 { Kind, ValueOf } 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`. + * `keyset.encrypt('..')` returns a `Ciphertext`. A ciphertext read + * from stored bytes with no kind named decrypts to whatever type was + * encrypted, so its type allows any scalar. */ -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 +69,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 } @@ -71,8 +91,10 @@ export declare class Cipher { * The Rust and Go SDKs write 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 { /** @@ -80,9 +102,19 @@ export declare class Ciphertext { * This method checks only the shape of the bytes. Decrypting is what * checks that they are authentic. A failure does not quote the bytes. * + * Give a kind, such as `kinds.string`, to decrypt the value as that + * kind. Decrypting then refuses a value encrypted as another type. + * `kinds.json` decrypts a JSON document. + * + * 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. + * bytes are not a `Uint8Array`, and `recipher_js::not_a_kind` when the + * kind is not one of `kinds`. Does not throw. */ + 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 +125,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 +154,33 @@ 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. + * + * A value's type sets how it is encrypted. The mapping of JavaScript + * types comes from vitaminc, CipherStash's cryptography library. A + * `Json` from `json(..)` is encrypted as a JSON document. + * + * 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`. + * The promise does not reject. */ - encrypt(value: string): Promise, RecipherError>> + encrypt(value: V): Promise>, RecipherError>> + encrypt(values: readonly V[]): 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 } @@ -174,6 +235,21 @@ 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. The document is a + * plain object, an array, text, a number, a `bigint`, a boolean or `null`, + * nested at most 127 levels. + * + * Give an integer outside a `number`'s safe range as a `bigint`, within 64 + * bits. The safe range is at most 2^53 - 1 from zero. A whole `number` + * between 2^53 and 2^64 from zero is refused, because the caller probably + * meant an integer. + * + * `json(..)` reads the document now. `json(..)` never throws: `encrypt` + * returns an `Err` for a document that cannot be encrypted. + */ +export declare function json(document: JsonValue): Json + /** A failure, as JavaScript receives it. */ export interface RecipherErrorFields { /** diff --git a/languages/typescript/packages/recipher-js/src/binding.ts b/languages/typescript/packages/recipher-js/src/binding.ts index b5e60f4a2..d885b4f17 100644 --- a/languages/typescript/packages/recipher-js/src/binding.ts +++ b/languages/typescript/packages/recipher-js/src/binding.ts @@ -43,9 +43,15 @@ const EXPORTS = [ 'Cipher', 'Keyset', 'Ciphertext', + 'Json', 'bindingInterface', 'createTesting', 'installResult', + 'json', + 'VcDate', + 'VcTimestamp', + 'VcDecimal', + 'VcUuid', ] as const /** @@ -112,7 +118,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..559fe9449 100644 --- a/languages/typescript/packages/recipher-js/src/cipher.ts +++ b/languages/typescript/packages/recipher-js/src/cipher.ts @@ -16,14 +16,17 @@ 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`. + * `keyset.encrypt('..')` returns a `Ciphertext`. A ciphertext read + * from stored bytes with no kind named decrypts to whatever type was + * encrypted, so its type allows any scalar. */ -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/index.ts b/languages/typescript/packages/recipher-js/src/index.ts index b7f032637..6ce14d743 100644 --- a/languages/typescript/packages/recipher-js/src/index.ts +++ b/languages/typescript/packages/recipher-js/src/index.ts @@ -38,4 +38,21 @@ export { type RecipherErrorFields, type Severity, } from './error' +export { type Kind, kinds, 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, + type Scalar, + type Value, + VcDate, + VcDecimal, + VcTimestamp, + VcUuid, + type WrapperConstructor, +} 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..5976b785f --- /dev/null +++ b/languages/typescript/packages/recipher-js/src/kinds.ts @@ -0,0 +1,52 @@ +/** + * Kinds: the types of value, by the engine's names for them. A kind says + * what type a stored ciphertext decrypts to, as in + * `Ciphertext.fromBytes(bytes, kinds.string)`. + * + * A kind is plain data, `{ name }`, that contains 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. + */ +import type { OpenedJson, VcDate, VcDecimal, VcTimestamp } 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 + /** Carries `T` for the type checker. The property never exists at run time. */ + readonly __value?: T +} + +function kind(name: Name): Kind { + return Object.freeze({ name }) +} + +/** The TypeScript type of a value of kind `K`. */ +export type ValueOf = K extends Kind ? T : never + +/** + * 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', VcDecimal>('decimal'), + date: kind<'date', VcDate>('date'), + timestamp: kind<'timestamp', Date | VcTimestamp>('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..3bdcae4d3 --- /dev/null +++ b/languages/typescript/packages/recipher-js/src/value-types.ts @@ -0,0 +1,127 @@ +/** + * The types of the values the SDK encrypts, and of what they decrypt to. + * + * This module holds types only, and imports nothing. The addon's generated + * declarations (`native.d.ts`) name these types in their signatures, so a + * module here that loaded the addon would make the declarations import + * themselves. + */ + +declare const wrapper: unique symbol + +/** A calendar date, such as `new VcDate('2026-11-23')`. The class comes from vitaminc. */ +export interface VcDate { + /** The date as `YYYY-MM-DD`. */ + readonly value: string + toJSON(): string + readonly [wrapper]: 'VcDate' +} + +/** A UTC instant, to the nanosecond. The class comes from vitaminc. */ +export interface VcTimestamp { + /** The instant as RFC 3339 text, with nanoseconds. */ + readonly value: string + toJSON(): string + readonly [wrapper]: 'VcTimestamp' +} + +/** A decimal with its scale, such as `new VcDecimal('1.50')`. The class comes from vitaminc. */ +export interface VcDecimal { + /** The decimal as text, with its scale. */ + readonly value: string + toJSON(): string + readonly [wrapper]: 'VcDecimal' +} + +/** + * A universally unique identifier (UUID). The class comes from vitaminc. + * The engine has no plaintext type for a UUID yet. Encrypting a `VcUuid` is + * an `Err` with the code `recipher_js::uuid`. `VcUuid` is not a `Scalar`. + */ +export interface VcUuid { + /** The UUID as hyphenated hex. */ + readonly value: string + toJSON(): string + readonly [wrapper]: 'VcUuid' +} + +/** A value that is one scalar: a single value, not a JSON document. */ +export type Scalar = + | string + | boolean + | number + | bigint + | Uint8Array + | Date + | VcTimestamp + | VcDate + | VcDecimal + | null + +/** + * A JSON value. An integer outside the safe range of a `number` is a + * `bigint`, within the 64-bit range (`-(2n ** 63n)` to `2n ** 64n - 1n`). + * + * `encrypt` refuses a whole `number` whose absolute value is at least 2^53 + * but less than 2^64. An integer was likely meant. + */ +export type JsonValue = + | null + | boolean + | number + | bigint + | string + | readonly JsonValue[] + | { readonly [key: string]: JsonValue } + +/** A JSON document as it decrypts. */ +export type OpenedJson = + | null + | boolean + | number + | bigint + | string + | OpenedJson[] + | { [key: string]: OpenedJson } + +declare const document: unique symbol + +/** + * What marks a `Json`, the native addon's class for a JSON document, so + * that no other object type-checks as one. The marker never exists at run + * time. + */ +export interface JsonMarker { + readonly [document]: true +} + +/** A value that `encrypt` takes. */ +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 VcTimestamp + ? Date | VcTimestamp + : V extends VcDate + ? VcDate + : V extends VcDecimal + ? VcDecimal + : V extends null + ? null + : V extends JsonMarker + ? OpenedJson + : never + +/** Any scalar type that a stored ciphertext can decrypt to. */ +export type OpenedScalar = Opened 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..10f2f64ca --- /dev/null +++ b/languages/typescript/packages/recipher-js/src/values.ts @@ -0,0 +1,134 @@ +/** + * The values the SDK encrypts, and the types they decrypt to. + * + * A value's type decides how it is encrypted. The mapping is vitaminc's + * mapping for JavaScript. vitaminc is the CipherStash Rust library that the + * engine's plaintext types come from. + * + * | 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 holds it | `bigint` | + * | `Uint8Array`, `Buffer` | bytes | `Uint8Array` | + * | `Date` | a timestamp | `Date` | + * | `VcTimestamp` | a timestamp, in nanoseconds | `Date` when it is whole milliseconds, else `VcTimestamp` | + * | `VcDate` | a calendar date | `VcDate` | + * | `VcDecimal` | a decimal, with its scale | `VcDecimal` | + * | `null` | null | `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 plain object is refused. Wrap it in `json(..)`. + * + * The wrapper classes (`VcDate`, `VcTimestamp`, `VcDecimal`, and `VcUuid`) + * and `json` come from the native addon. When the addon did not load, + * stand-ins take their place. Each stand-in constructs as the class does. + * `encrypt` then resolves to the `Err` that says why the addon did not load. + */ +import type * as Native from '../native' +import { type Binding, binding } from './binding' +import type { + VcDate as VcDateValue, + VcDecimal as VcDecimalValue, + VcTimestamp as VcTimestampValue, + VcUuid as VcUuidValue, +} from './value-types' + +export type { + JsonValue, + Opened, + OpenedJson, + OpenedScalar, + Scalar, + Value, +} from './value-types' + +/** A calendar date, such as `new VcDate('2026-11-23')`. The class comes from vitaminc. */ +export type VcDate = VcDateValue +/** A UTC instant, to the nanosecond. The class comes from vitaminc. */ +export type VcTimestamp = VcTimestampValue +/** A decimal with its scale, such as `new VcDecimal('1.50')`. The class comes from vitaminc. */ +export type VcDecimal = VcDecimalValue +/** + * A universally unique identifier (UUID). The class comes from vitaminc. + * The engine has no plaintext type for a UUID yet. Encrypting a `VcUuid` is + * an `Err` with the code `recipher_js::uuid`. `VcUuid` is not a `Scalar`. + */ +export type VcUuid = VcUuidValue + +/** The constructor of one of vitaminc's wrapper classes. */ +export interface WrapperConstructor { + new (text: string): W + readonly prototype: W +} + +type WrapperName = 'VcDate' | 'VcTimestamp' | 'VcDecimal' | 'VcUuid' + +/** + * The class that the native addon defines. When the addon did not load, a + * stand-in class instead. The stand-in keeps its text, is frozen, and + * serialises to JSON as vitaminc's class does. + */ +function wrapperClass(name: WrapperName): WrapperConstructor { + 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 WrapperConstructor + } + const StandIn = class { + readonly value: string + constructor(text: string) { + this.value = String(text) + Object.freeze(this) + } + toJSON(): string { + return this.value + } + } + Object.defineProperty(StandIn, 'name', { value: name }) + // biome-ignore lint/plugin: a stand-in for the class, which constructs as it does. + return Object.freeze(StandIn) as unknown as WrapperConstructor +} + +/** A calendar date. */ +export const VcDate: WrapperConstructor = wrapperClass('VcDate') +/** A UTC instant to the nanosecond. */ +export const VcTimestamp: WrapperConstructor = + wrapperClass('VcTimestamp') +/** A decimal with its scale. */ +export const VcDecimal: WrapperConstructor = + wrapperClass('VcDecimal') +/** A UUID. */ +export const VcUuid: WrapperConstructor = wrapperClass('VcUuid') + +/** + * 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`, which makes a JSON document to encrypt as one ciphertext. */ +export type JsonFunction = Binding['json'] + +/** + * 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. + * + * `json` never throws. A document that cannot be encrypted is an `Err` from + * `encrypt`. Examples are a document that contains 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`, which `encrypt` refuses 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..0973100ab --- /dev/null +++ b/languages/typescript/packages/recipher-js/type-tests/values.ts @@ -0,0 +1,92 @@ +// 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, + OpenedJson, + OpenedScalar, + RecipherError, + Result, + VcDate, + VcDecimal, + VcTimestamp, + VcUuid, +} from '../src/index' +import { Ciphertext, json, kinds } 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 is one ciphertext, typed by what it opens as. 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: VcTimestamp +const fine = await keyset.encrypt(instant) +check< + Exact, RecipherError>> +>() +declare const day: VcDate +const dated = await keyset.encrypt(day) +check, RecipherError>>>() +declare const price: VcDecimal +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, one or many. +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' }) +// A UUID is not in the engine's value model yet. +declare const uuid: VcUuid +// @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) +// @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: a VcDate is not a VcDecimal. +expectType(day) + +// A ciphertext read from stored bytes is typed by the kind named, and as +// any scalar when none is. +declare const stored: Uint8Array +const typed = Ciphertext.fromBytes(stored, kinds.int64) +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') From f99259a4e9f4a7aae23ccc8319159cafb4d83aa5 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 15:53:58 +1100 Subject: [PATCH 02/25] refactor(recipher-js): name the wrapper classes RcDate, RcTimestamp, RcDecimal and RcUuid The classes kept vitaminc's Vc prefix when the value bridge was copied into this repository. They are recipher's classes now: the bridge defines them, the addon exports them, and the package's TypeScript declares them. So each is named for recipher. The rename covers every place a class is named: the bridge's `wrappers.js` and `Wrapper::class_name`, the addon's exports, the loader's export list, the TypeScript types and constants, the README, and the tests and their pinned case names. The old names get no alias: the package is private and nothing is released. The bridge's README says vitaminc names the classes VcDate and so on, for a reader who compares the copy with its source. --- conformance/vitaminc-aead/README.md | 2 +- .../typescript/packages/recipher-js/README.md | 10 ++-- .../__tests__/addon/builds.test.ts | 4 +- .../__tests__/addon/values.test.ts | 36 ++++++------ .../__tests__/unit/binding.test.ts | 16 ++--- .../packages/recipher-js/crate/src/error.rs | 2 +- .../packages/recipher-js/crate/src/js.rs | 4 +- .../packages/recipher-js/crate/src/lib.rs | 2 +- .../packages/recipher-js/src/binding.ts | 8 +-- .../packages/recipher-js/src/index.ts | 8 +-- .../packages/recipher-js/src/kinds.ts | 8 +-- .../packages/recipher-js/src/value-types.ts | 42 +++++++------- .../packages/recipher-js/src/values.ts | 46 +++++++-------- .../packages/recipher-js/type-tests/values.ts | 26 ++++----- .../packages/recipher-js/value-napi/README.md | 18 +++--- .../recipher-js/value-napi/src/js_ref.rs | 6 +- .../recipher-js/value-napi/src/scalar.rs | 4 +- .../recipher-js/value-napi/src/wrappers.js | 8 +-- .../recipher-js/value-napi/src/wrappers.rs | 24 ++++---- .../value-napi/tests/addon/src/lib.rs | 2 +- .../recipher-js/value-napi/tests/encrypt.cjs | 12 ++-- .../recipher-js/value-napi/tests/frames.cjs | 58 +++++++++---------- .../value-napi/tests/kind_inventory.cjs | 12 ++-- .../value-napi/tests/object-safety.cjs | 24 ++++---- .../value-napi/tests/testdata/js-frames.json | 30 +++++----- .../value-napi/tests/value-conformance.cjs | 54 ++++++++--------- 26 files changed, 234 insertions(+), 232 deletions(-) diff --git a/conformance/vitaminc-aead/README.md b/conformance/vitaminc-aead/README.md index 0da8d0d3a..1848ed7d0 100644 --- a/conformance/vitaminc-aead/README.md +++ b/conformance/vitaminc-aead/README.md @@ -64,7 +64,7 @@ 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 + finer one is read as an `RcTimestamp` 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. diff --git a/languages/typescript/packages/recipher-js/README.md b/languages/typescript/packages/recipher-js/README.md index 5f73b7b00..5699413cc 100644 --- a/languages/typescript/packages/recipher-js/README.md +++ b/languages/typescript/packages/recipher-js/README.md @@ -59,9 +59,9 @@ The `recipher-value-napi` crate, in `value-napi/`, converts JavaScript values by | `bigint` | an integer, at the narrowest width that holds it | `bigint` | | `Uint8Array`, `Buffer` | bytes | `Uint8Array` | | `Date` | a timestamp | `Date` | -| `new VcTimestamp('2026-11-23T01:02:03.000000001Z')` | a timestamp, in nanoseconds | `Date` when it is whole milliseconds, else `VcTimestamp` | -| `new VcDate('2026-11-23')` | a calendar date | `VcDate` | -| `new VcDecimal('1.50')` | a decimal, with its scale | `VcDecimal` | +| `new RcTimestamp('2026-11-23T01:02:03.000000001Z')` | a timestamp, in nanoseconds | `Date` when it is whole milliseconds, else `RcTimestamp` | +| `new RcDate('2026-11-23')` | a calendar date | `RcDate` | +| `new RcDecimal('1.50')` | a decimal, with its scale | `RcDecimal` | | `null` | null | `null` | | `json(value)` | a JSON document, as its JSON text | the document, from the `Ciphertext` that `encrypt` returned or one read with `kinds.json` | @@ -70,9 +70,9 @@ The `recipher-value-napi` crate, in `value-napi/`, converts JavaScript values by The `number` `5` does not equal the integer `5n`. - A plain object is refused. Wrap it in `json(..)`. -- The package exports `VcUuid`, for a universally unique identifier (UUID). +- The package exports `RcUuid`, for a universally unique identifier (UUID). The engine has no plaintext type for a UUID yet. - Encrypting a `VcUuid` is an `Err` with the code `recipher_js::uuid`. + Encrypting an `RcUuid` is an `Err` with the code `recipher_js::uuid`. - vitaminc's rules refuse each of these values, with an error code for each: - a `Map` or a `Set`; - a class instance; 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 c2f36f36b..2fb4d4482 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/builds.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/builds.test.ts @@ -55,8 +55,8 @@ const MISSING = ` const recipher = await import(process.argv[1]) const testing = await import(process.argv[2]) const out = {} -out.date = new recipher.VcDate('2026-11-23').value -out.dateFrozen = Object.isFrozen(new recipher.VcDate('2026-11-23')) +out.date = new recipher.RcDate('2026-11-23').value +out.dateFrozen = Object.isFrozen(new recipher.RcDate('2026-11-23')) out.json = String(recipher.json({ a: 1 })) out.create = (await recipher.Cipher.create()).err().code out.testing = (await testing.testCipher()).err().code diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts index 1b23051ac..ee0164a93 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts @@ -4,10 +4,10 @@ import { Ciphertext, json, kinds, - VcDate, - VcDecimal, - VcTimestamp, - VcUuid, + RcDate, + RcDecimal, + RcTimestamp, + RcUuid, } from '../../src/index' import { testCipher } from '../../src/testing' @@ -32,9 +32,9 @@ async function encryptOne( | bigint | Uint8Array | Date - | VcDate - | VcTimestamp - | VcDecimal + | RcDate + | RcTimestamp + | RcDecimal | null, ) { return (await c.defaultKeyset().encrypt(value)).unwrap() @@ -85,23 +85,23 @@ describe('every value in the mapping round-trips', () => { }) it("vitaminc's wrapper classes", async () => { - const day = await roundTrip(new VcDate('2026-11-23')) - expect(day).toBeInstanceOf(VcDate) - expect((day as VcDate).value).toBe('2026-11-23') + const day = await roundTrip(new RcDate('2026-11-23')) + expect(day).toBeInstanceOf(RcDate) + expect((day as RcDate).value).toBe('2026-11-23') const fine = await roundTrip( - new VcTimestamp('2026-11-23T01:02:03.000000001Z'), + new RcTimestamp('2026-11-23T01:02:03.000000001Z'), ) - expect(fine).toBeInstanceOf(VcTimestamp) - expect((fine as VcTimestamp).value).toBe('2026-11-23T01:02:03.000000001Z') + expect(fine).toBeInstanceOf(RcTimestamp) + expect((fine as RcTimestamp).value).toBe('2026-11-23T01:02:03.000000001Z') // A timestamp of whole milliseconds opens as a Date. - const whole = await roundTrip(new VcTimestamp('2026-11-23T01:02:03.000Z')) + const whole = await roundTrip(new RcTimestamp('2026-11-23T01:02:03.000Z')) expect(whole).toBeInstanceOf(Date) - const price = await roundTrip(new VcDecimal('1.50')) - expect(price).toBeInstanceOf(VcDecimal) - expect((price as VcDecimal).value).toBe('1.50') + const price = await roundTrip(new RcDecimal('1.50')) + expect(price).toBeInstanceOf(RcDecimal) + expect((price as RcDecimal).value).toBe('1.50') }) it('null', async () => { @@ -297,7 +297,7 @@ describe('a ciphertext read back with a kind', () => { describe('refusals', () => { it('a UUID, which the engine does not hold yet', async () => { const keyset = (await cipher()).defaultKeyset() - const uuid = new VcUuid('123e4567-e89b-12d3-a456-426614174000') + const uuid = new RcUuid('123e4567-e89b-12d3-a456-426614174000') // @ts-expect-error: a UUID is not a scalar of the engine's value model. const result = await keyset.encrypt(uuid) expect(result.err()?.code).toBe('recipher_js::uuid') 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 97f52590a..ce380c354 100644 --- a/languages/typescript/packages/recipher-js/__tests__/unit/binding.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/unit/binding.test.ts @@ -19,10 +19,10 @@ function fakeBuild(overrides: Record = {}) { createTesting: () => Promise.resolve('cipher'), installResult: () => true, json: () => ({}), - VcDate: class {}, - VcTimestamp: class {}, - VcDecimal: class {}, - VcUuid: class {}, + RcDate: class {}, + RcTimestamp: class {}, + RcDecimal: class {}, + RcUuid: class {}, ...overrides, } } @@ -53,10 +53,10 @@ describe('load', () => { 'createTesting', 'installResult', 'json', - 'VcDate', - 'VcTimestamp', - 'VcDecimal', - 'VcUuid', + 'RcDate', + 'RcTimestamp', + 'RcDecimal', + 'RcUuid', ]) { const loaded = load( requiring(fakeBuild({ [name]: undefined })), diff --git a/languages/typescript/packages/recipher-js/crate/src/error.rs b/languages/typescript/packages/recipher-js/crate/src/error.rs index 4d1b30720..7a8235050 100644 --- a/languages/typescript/packages/recipher-js/crate/src/error.rs +++ b/languages/typescript/packages/recipher-js/crate/src/error.rs @@ -40,7 +40,7 @@ pub(crate) enum Error { help("Use `null` for a value that is not there.") )] Undefined, - /// A `VcUuid`. The engine's value model, the set of value types the + /// A `RcUuid`. The engine's value model, the set of value types the /// engine reads, has no UUID type. #[error("a UUID cannot be encrypted yet: the engine's value model does not hold one")] #[diagnostic(code(recipher_js::uuid), help("Encrypt its text instead."))] diff --git a/languages/typescript/packages/recipher-js/crate/src/js.rs b/languages/typescript/packages/recipher-js/crate/src/js.rs index b35abe75e..294bd6e2e 100644 --- a/languages/typescript/packages/recipher-js/crate/src/js.rs +++ b/languages/typescript/packages/recipher-js/crate/src/js.rs @@ -35,7 +35,7 @@ use crate::error::{Error, RecipherErrorFields}; /// Returns one of these errors: /// /// - `recipher_js::undefined` for `undefined`; -/// - `recipher_js::uuid` for a `VcUuid`; +/// - `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; @@ -102,7 +102,7 @@ fn not_built(env: &Env, fault: &JsFault) -> RecipherErrorFields { } } -/// Returns whether `value` is a vitaminc `VcUuid`. +/// Returns whether `value` is a vitaminc `RcUuid`. fn is_uuid(env: &Env, value: &Unknown<'_>) -> bool { Wrappers::get(env) .and_then(|wrappers| wrappers.classify(value)) diff --git a/languages/typescript/packages/recipher-js/crate/src/lib.rs b/languages/typescript/packages/recipher-js/crate/src/lib.rs index a5c918bb5..1ab0421d9 100644 --- a/languages/typescript/packages/recipher-js/crate/src/lib.rs +++ b/languages/typescript/packages/recipher-js/crate/src/lib.rs @@ -84,7 +84,7 @@ pub fn binding_interface() -> u32 { } /// Exports the wrapper classes of vitaminc, CipherStash's cryptography -/// library: `VcDate`, `VcTimestamp`, `VcDecimal` and `VcUuid`. Each class +/// library: `RcDate`, `RcTimestamp`, `RcDecimal` and `RcUuid`. Each class /// stands for a type that JavaScript does not have. The addon exports them /// so JavaScript can construct them, and so decrypted values are instances /// of them. diff --git a/languages/typescript/packages/recipher-js/src/binding.ts b/languages/typescript/packages/recipher-js/src/binding.ts index d885b4f17..2d152afed 100644 --- a/languages/typescript/packages/recipher-js/src/binding.ts +++ b/languages/typescript/packages/recipher-js/src/binding.ts @@ -48,10 +48,10 @@ const EXPORTS = [ 'createTesting', 'installResult', 'json', - 'VcDate', - 'VcTimestamp', - 'VcDecimal', - 'VcUuid', + 'RcDate', + 'RcTimestamp', + 'RcDecimal', + 'RcUuid', ] as const /** diff --git a/languages/typescript/packages/recipher-js/src/index.ts b/languages/typescript/packages/recipher-js/src/index.ts index 6ce14d743..020433670 100644 --- a/languages/typescript/packages/recipher-js/src/index.ts +++ b/languages/typescript/packages/recipher-js/src/index.ts @@ -48,11 +48,11 @@ export { type Opened, type OpenedJson, type OpenedScalar, + RcDate, + RcDecimal, + RcTimestamp, + RcUuid, type Scalar, type Value, - VcDate, - VcDecimal, - VcTimestamp, - VcUuid, type WrapperConstructor, } from './values' diff --git a/languages/typescript/packages/recipher-js/src/kinds.ts b/languages/typescript/packages/recipher-js/src/kinds.ts index 5976b785f..e9c11b480 100644 --- a/languages/typescript/packages/recipher-js/src/kinds.ts +++ b/languages/typescript/packages/recipher-js/src/kinds.ts @@ -7,7 +7,7 @@ * 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. */ -import type { OpenedJson, VcDate, VcDecimal, VcTimestamp } from './value-types' +import type { OpenedJson, RcDate, RcDecimal, RcTimestamp } from './value-types' /** A kind: the type of a value, by the engine's name for it. */ export interface Kind { @@ -44,9 +44,9 @@ export const kinds = Object.freeze({ uint128: kind<'uint128', bigint>('uint128'), float32: kind<'float32', number>('float32'), float64: kind<'float64', number>('float64'), - decimal: kind<'decimal', VcDecimal>('decimal'), - date: kind<'date', VcDate>('date'), - timestamp: kind<'timestamp', Date | VcTimestamp>('timestamp'), + 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 index 3bdcae4d3..5be1b0533 100644 --- a/languages/typescript/packages/recipher-js/src/value-types.ts +++ b/languages/typescript/packages/recipher-js/src/value-types.ts @@ -9,40 +9,40 @@ declare const wrapper: unique symbol -/** A calendar date, such as `new VcDate('2026-11-23')`. The class comes from vitaminc. */ -export interface VcDate { +/** A calendar date, such as `new RcDate('2026-11-23')`. The class comes from vitaminc. */ +export interface RcDate { /** The date as `YYYY-MM-DD`. */ readonly value: string toJSON(): string - readonly [wrapper]: 'VcDate' + readonly [wrapper]: 'RcDate' } /** A UTC instant, to the nanosecond. The class comes from vitaminc. */ -export interface VcTimestamp { +export interface RcTimestamp { /** The instant as RFC 3339 text, with nanoseconds. */ readonly value: string toJSON(): string - readonly [wrapper]: 'VcTimestamp' + readonly [wrapper]: 'RcTimestamp' } -/** A decimal with its scale, such as `new VcDecimal('1.50')`. The class comes from vitaminc. */ -export interface VcDecimal { +/** A decimal with its scale, such as `new RcDecimal('1.50')`. The class comes from vitaminc. */ +export interface RcDecimal { /** The decimal as text, with its scale. */ readonly value: string toJSON(): string - readonly [wrapper]: 'VcDecimal' + readonly [wrapper]: 'RcDecimal' } /** * A universally unique identifier (UUID). The class comes from vitaminc. - * The engine has no plaintext type for a UUID yet. Encrypting a `VcUuid` is - * an `Err` with the code `recipher_js::uuid`. `VcUuid` is not a `Scalar`. + * The engine has no plaintext type for a UUID yet. Encrypting an `RcUuid` is + * an `Err` with the code `recipher_js::uuid`. `RcUuid` is not a `Scalar`. */ -export interface VcUuid { +export interface RcUuid { /** The UUID as hyphenated hex. */ readonly value: string toJSON(): string - readonly [wrapper]: 'VcUuid' + readonly [wrapper]: 'RcUuid' } /** A value that is one scalar: a single value, not a JSON document. */ @@ -53,9 +53,9 @@ export type Scalar = | bigint | Uint8Array | Date - | VcTimestamp - | VcDate - | VcDecimal + | RcTimestamp + | RcDate + | RcDecimal | null /** @@ -111,12 +111,12 @@ export type Opened = V extends string ? Uint8Array : V extends Date ? Date - : V extends VcTimestamp - ? Date | VcTimestamp - : V extends VcDate - ? VcDate - : V extends VcDecimal - ? VcDecimal + : V extends RcTimestamp + ? Date | RcTimestamp + : V extends RcDate + ? RcDate + : V extends RcDecimal + ? RcDecimal : V extends null ? null : V extends JsonMarker diff --git a/languages/typescript/packages/recipher-js/src/values.ts b/languages/typescript/packages/recipher-js/src/values.ts index 10f2f64ca..6562ae161 100644 --- a/languages/typescript/packages/recipher-js/src/values.ts +++ b/languages/typescript/packages/recipher-js/src/values.ts @@ -13,16 +13,16 @@ * | `bigint` | an integer, at the narrowest width that holds it | `bigint` | * | `Uint8Array`, `Buffer` | bytes | `Uint8Array` | * | `Date` | a timestamp | `Date` | - * | `VcTimestamp` | a timestamp, in nanoseconds | `Date` when it is whole milliseconds, else `VcTimestamp` | - * | `VcDate` | a calendar date | `VcDate` | - * | `VcDecimal` | a decimal, with its scale | `VcDecimal` | + * | `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` | null | `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 plain object is refused. Wrap it in `json(..)`. * - * The wrapper classes (`VcDate`, `VcTimestamp`, `VcDecimal`, and `VcUuid`) + * The wrapper classes (`RcDate`, `RcTimestamp`, `RcDecimal`, and `RcUuid`) * and `json` come from the native addon. When the addon did not load, * stand-ins take their place. Each stand-in constructs as the class does. * `encrypt` then resolves to the `Err` that says why the addon did not load. @@ -30,10 +30,10 @@ import type * as Native from '../native' import { type Binding, binding } from './binding' import type { - VcDate as VcDateValue, - VcDecimal as VcDecimalValue, - VcTimestamp as VcTimestampValue, - VcUuid as VcUuidValue, + RcDate as RcDateValue, + RcDecimal as RcDecimalValue, + RcTimestamp as RcTimestampValue, + RcUuid as RcUuidValue, } from './value-types' export type { @@ -45,18 +45,18 @@ export type { Value, } from './value-types' -/** A calendar date, such as `new VcDate('2026-11-23')`. The class comes from vitaminc. */ -export type VcDate = VcDateValue +/** A calendar date, such as `new RcDate('2026-11-23')`. The class comes from vitaminc. */ +export type RcDate = RcDateValue /** A UTC instant, to the nanosecond. The class comes from vitaminc. */ -export type VcTimestamp = VcTimestampValue -/** A decimal with its scale, such as `new VcDecimal('1.50')`. The class comes from vitaminc. */ -export type VcDecimal = VcDecimalValue +export type RcTimestamp = RcTimestampValue +/** A decimal with its scale, such as `new RcDecimal('1.50')`. The class comes from vitaminc. */ +export type RcDecimal = RcDecimalValue /** * A universally unique identifier (UUID). The class comes from vitaminc. - * The engine has no plaintext type for a UUID yet. Encrypting a `VcUuid` is - * an `Err` with the code `recipher_js::uuid`. `VcUuid` is not a `Scalar`. + * The engine has no plaintext type for a UUID yet. Encrypting an `RcUuid` is + * an `Err` with the code `recipher_js::uuid`. `RcUuid` is not a `Scalar`. */ -export type VcUuid = VcUuidValue +export type RcUuid = RcUuidValue /** The constructor of one of vitaminc's wrapper classes. */ export interface WrapperConstructor { @@ -64,7 +64,7 @@ export interface WrapperConstructor { readonly prototype: W } -type WrapperName = 'VcDate' | 'VcTimestamp' | 'VcDecimal' | 'VcUuid' +type WrapperName = 'RcDate' | 'RcTimestamp' | 'RcDecimal' | 'RcUuid' /** * The class that the native addon defines. When the addon did not load, a @@ -93,15 +93,15 @@ function wrapperClass(name: WrapperName): WrapperConstructor { } /** A calendar date. */ -export const VcDate: WrapperConstructor = wrapperClass('VcDate') +export const RcDate: WrapperConstructor = wrapperClass('RcDate') /** A UTC instant to the nanosecond. */ -export const VcTimestamp: WrapperConstructor = - wrapperClass('VcTimestamp') +export const RcTimestamp: WrapperConstructor = + wrapperClass('RcTimestamp') /** A decimal with its scale. */ -export const VcDecimal: WrapperConstructor = - wrapperClass('VcDecimal') +export const RcDecimal: WrapperConstructor = + wrapperClass('RcDecimal') /** A UUID. */ -export const VcUuid: WrapperConstructor = wrapperClass('VcUuid') +export const RcUuid: WrapperConstructor = wrapperClass('RcUuid') /** * A JSON document to encrypt as one ciphertext, as its JSON text. Make one diff --git a/languages/typescript/packages/recipher-js/type-tests/values.ts b/languages/typescript/packages/recipher-js/type-tests/values.ts index 0973100ab..471ca0e70 100644 --- a/languages/typescript/packages/recipher-js/type-tests/values.ts +++ b/languages/typescript/packages/recipher-js/type-tests/values.ts @@ -5,12 +5,12 @@ import type { Keyset, OpenedJson, OpenedScalar, + RcDate, + RcDecimal, + RcTimestamp, + RcUuid, RecipherError, Result, - VcDate, - VcDecimal, - VcTimestamp, - VcUuid, } from '../src/index' import { Ciphertext, json, kinds } from '../src/index' @@ -32,17 +32,17 @@ const bytes = await keyset.encrypt(new Uint8Array(1)) check, RecipherError>>>() const when = await keyset.encrypt(new Date()) check, RecipherError>>>() -declare const instant: VcTimestamp +declare const instant: RcTimestamp const fine = await keyset.encrypt(instant) check< - Exact, RecipherError>> + Exact, RecipherError>> >() -declare const day: VcDate +declare const day: RcDate const dated = await keyset.encrypt(day) -check, RecipherError>>>() -declare const price: VcDecimal +check, RecipherError>>>() +declare const price: RcDecimal const priced = await keyset.encrypt(price) -check, RecipherError>>>() +check, RecipherError>>>() const document = await keyset.encrypt(json({ a: [1, 2n, null] })) check, RecipherError>>>() @@ -64,7 +64,7 @@ if (many.isOk()) { // @ts-expect-error: a plain object is not a value. void keyset.encrypt({ name: 'Ada' }) // A UUID is not in the engine's value model yet. -declare const uuid: VcUuid +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. @@ -76,8 +76,8 @@ 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: a VcDate is not a VcDecimal. -expectType(day) +// @ts-expect-error: an RcDate is not an RcDecimal. +expectType(day) // A ciphertext read from stored bytes is typed by the kind named, and as // any scalar when none is. diff --git a/languages/typescript/packages/recipher-js/value-napi/README.md b/languages/typescript/packages/recipher-js/value-napi/README.md index 6ae681334..a5e47bde3 100644 --- a/languages/typescript/packages/recipher-js/value-napi/README.md +++ b/languages/typescript/packages/recipher-js/value-napi/README.md @@ -7,6 +7,8 @@ The `recipher-js` addon reads and builds every value through it. This crate is a copy of `vitaminc-aead-napi` 0.10.0, from [`cipherstash/vitaminc`](https://github.com/cipherstash/vitaminc) at commit `b3f69b12c1fde38faff2becec04f9e633dbd4f1c`, renamed. It is not published. +Its wrapper classes are `RcDate`, `RcTimestamp`, `RcDecimal` and `RcUuid`. +vitaminc names them `VcDate` and so on. `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 @@ -34,8 +36,8 @@ the outgoing value. This crate supplies both sides of that conversion: passthrough payload `P` converts through `NapiPassthrough`, implemented for `PassthroughFrame` (the sink-based tree's payload) and `()`, which applies the tree's nesting limit to the payload too. -- **`Wrappers`** — the wrapper classes `VcDate`, `VcTimestamp`, - `VcDecimal` and `VcUuid`, defined once per environment and exported by an +- **`Wrappers`** — the wrapper classes `RcDate`, `RcTimestamp`, + `RcDecimal` and `RcUuid`, 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. @@ -89,16 +91,16 @@ 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 +whole milliseconds and an `RcTimestamp` 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 @@ -118,7 +120,7 @@ on an `int64` field. 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 +class holding its text: `new RcDecimal("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 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..cefb62a67 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 @@ -18,9 +18,9 @@ //! | 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. +//! `RcDate` is `Date` over the day count, `RcTimestamp` is +//! `Timestamp(Nanos)` over the nanosecond count, `RcDecimal` is `Decimal` +//! over the mantissa and `RcUuid` is `Uuid` over sixteen bytes. //! //! A getter that throws, a string with an unpaired surrogate, a BigInt out //! of range or a `Date` outside the wire's range stops the walk through 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..4cc05a005 100644 --- a/languages/typescript/packages/recipher-js/value-napi/src/scalar.rs +++ b/languages/typescript/packages/recipher-js/value-napi/src/scalar.rs @@ -262,7 +262,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 +296,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()) 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..ae9032809 100644 --- a/languages/typescript/packages/recipher-js/value-napi/src/wrappers.js +++ b/languages/typescript/packages/recipher-js/value-napi/src/wrappers.js @@ -77,10 +77,10 @@ } return freeze({ __proto__: null, - VcDate: define('VcDate'), - VcTimestamp: define('VcTimestamp'), - VcDecimal: define('VcDecimal'), - VcUuid: define('VcUuid'), + RcDate: define('RcDate'), + RcTimestamp: define('RcTimestamp'), + RcDecimal: define('RcDecimal'), + RcUuid: define('RcUuid'), // 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..49c88f714 100644 --- a/languages/typescript/packages/recipher-js/value-napi/src/wrappers.rs +++ b/languages/typescript/packages/recipher-js/value-napi/src/wrappers.rs @@ -1,4 +1,4 @@ -//! 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 @@ -28,13 +28,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 +50,10 @@ 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", } } } @@ -114,7 +114,7 @@ impl<'e> Wrappers<'e> { } /// An object holding every class under its name, for an addon to - /// re-export: `VcDate`, `VcTimestamp`, `VcDecimal` and `VcUuid`. + /// 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)?; @@ -214,9 +214,9 @@ 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:?}")); } } } 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..ed87d24e8 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 @@ -20,7 +20,7 @@ use vitaminc_protected::{Controlled, Protected}; #[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)?)?; } Ok(()) 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..8ff31f1ed 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,7 @@ 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 { RcDate, RcTimestamp, RcDecimal, RcUuid } = addon const aad = 'section-6' const rows = { @@ -25,14 +25,14 @@ const rows = { 'plain object': { name: 'Ada', tags: ['math'], - born: new VcDate('1815-12-10'), + born: new 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: new RcDate('2024-02-29'), + RcTimestamp: new RcTimestamp('1969-12-31T23:59:59.999999999Z'), + RcDecimal: new RcDecimal('-1.50'), + RcUuid: new 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..477d997c5 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,7 @@ 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 { RcDate, RcTimestamp, RcDecimal, RcUuid } = addon const golden = path.join(__dirname, 'testdata/js-frames.json') const vendored = path.join(__dirname, 'testdata/corpus-frames.json') @@ -151,72 +151,72 @@ 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', + () => new RcDate('1970-01-01'), 'record-values-v1/date-epoch', ], [ - 'VcDate 1969-12-31', - () => new VcDate('1969-12-31'), + 'RcDate 1969-12-31', + () => new RcDate('1969-12-31'), 'record-values-v1/date-before-epoch', ], [ - 'VcDate 0001-01-01', - () => new VcDate('0001-01-01'), + 'RcDate 0001-01-01', + () => new RcDate('0001-01-01'), 'record-values-v1/date-year-one', ], [ - 'VcDate 9999-12-31', - () => new VcDate('9999-12-31'), + 'RcDate 9999-12-31', + () => new RcDate('9999-12-31'), 'record-values-v1/date-year-9999', ], [ - 'VcTimestamp epoch', - () => new VcTimestamp('1970-01-01T00:00:00Z'), + 'RcTimestamp epoch', + () => new 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', + () => new 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', + () => new 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', + () => new 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', + () => new RcTimestamp('9999-12-30T22:00:00.999999999Z'), 'record-values-v1/timestamp-year-9999', ], [ - 'VcDecimal 42', - () => new VcDecimal('42'), + 'RcDecimal 42', + () => new RcDecimal('42'), 'record-values-v1/decimal-scale-0', ], [ - 'VcDecimal scale 28', - () => new VcDecimal('0.0000000000000000000000000001'), + 'RcDecimal scale 28', + () => new RcDecimal('0.0000000000000000000000000001'), 'record-values-v1/decimal-scale-28', ], [ - 'VcDecimal -1234.5600', - () => new VcDecimal('-1234.5600'), + 'RcDecimal -1234.5600', + () => new RcDecimal('-1234.5600'), 'record-values-v1/decimal-trailing-zeros', ], [ - 'VcDecimal max mantissa', - () => new VcDecimal('79228162514264337593543950335'), + 'RcDecimal max mantissa', + () => new 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', () => new RcDecimal('-0.00')], + ['RcUuid', () => new 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/kind_inventory.cjs b/languages/typescript/packages/recipher-js/value-napi/tests/kind_inventory.cjs index ea7342f68..7392735ee 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,7 @@ 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 { RcDate, RcTimestamp, RcDecimal, RcUuid } = addon assert.deepStrictEqual(addon.kindInventory(), { null: null, undefined: undefined, @@ -24,13 +24,13 @@ assert.deepStrictEqual(addon.kindInventory(), { float64: 2.5, string: 'hello', bytes: Buffer.from([0, 255]), - date: new VcDate('2024-02-29'), + date: new 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: new RcTimestamp('1970-01-01T00:00:00.000001000Z'), + timestampNanos: new RcTimestamp('1969-12-31T23:59:59.999999999Z'), + decimal: new RcDecimal('1.50'), + uuid: new RcUuid('123e4567-e89b-12d3-a456-426614174000'), array: [true], object: { k: true }, passthrough: true, 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..b35450f64 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,12 @@ 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(new addon.RcDecimal('2.50')).value, '2.50') assert.deepEqual(roundTrip({ k: 'v' }), { k: 'v' }) // A wrapper instance is built by its constructor, so it is a real instance. -const date = roundTrip(new addon.VcDate('2026-10-09')) -assert.ok(date instanceof addon.VcDate) +const date = roundTrip(new addon.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 +155,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 = new addon.RcDecimal('1.50') assert.throws(() => { 'use strict' decimal.value = '999.99' @@ -175,7 +175,7 @@ try { } assert.throws( () => - Object.defineProperty(addon.VcUuid, Symbol.hasInstance, { + Object.defineProperty(addon.RcUuid, Symbol.hasInstance, { value: () => true, }), TypeError, @@ -200,7 +200,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: [new addon.RcDecimal('1.50')] } }, ], }, e: { t: 'eseq', v: leaf }, @@ -280,7 +280,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(new addon.RcTimestamp('2016-12-31T23:59:60Z')), { code: 'ERR_INVALID_TIMESTAMP' }, ) @@ -562,8 +562,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(new addon.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 +575,7 @@ 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(new addon.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..90824142e 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,13 @@ function expected(row, value = row.value) { case 'bytes': return Buffer.from(value, 'hex') case 'date': - return new VcDate(value) + return new RcDate(value) case 'decimal': - return new VcDecimal(value) + return new RcDecimal(value) case 'timestamp': - return row.js_date ? new Date(value) : new VcTimestamp(value) + return row.js_date ? new Date(value) : new RcTimestamp(value) case 'uuid': - return new VcUuid(value) + return new RcUuid(value) default: return value } @@ -125,25 +125,25 @@ 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(new RcDecimal(decimal)), { name: 'TypeError', code: 'ERR_NON_FINITE_DECIMAL', }) assert.throws( - () => addon.encode(new VcDecimal('79228162514264337593543950336')), + () => addon.encode(new RcDecimal('79228162514264337593543950336')), { code: 'ERR_INVALID_DECIMAL' }, ) -assert.throws(() => addon.encode(new VcDate('2023-02-29')), { +assert.throws(() => addon.encode(new RcDate('2023-02-29')), { code: 'ERR_INVALID_DATE', }) -assert.throws(() => addon.encode(new VcUuid('not-a-uuid')), { +assert.throws(() => addon.encode(new 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')), { +assert.throws(() => addon.encode(new RcTimestamp('2016-12-31T23:59:60Z')), { code: 'ERR_INVALID_TIMESTAMP', }) assert.deepEqual(addon.decode(addon.encode(new Date(-1))), new Date(-1)) @@ -158,7 +158,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 = new RcUuid('123e4567-e89b-12d3-a456-426614174000') assert.equal( addon.encode(uuid).toString('hex'), 'f305000b10000000123e4567e89b12d3a456426614174000', @@ -166,15 +166,15 @@ 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(new RcUuid('123E4567-E89B-12D3-A456-426614174000')), ), uuid, ) const nested = { items: [ 1n, - new VcDate('2024-02-29'), - new VcDecimal('1.50'), + new RcDate('2024-02-29'), + new RcDecimal('1.50'), new Date(0), uuid, ], @@ -197,7 +197,7 @@ assert.throws( assert.throws(() => addon.encode('\ud800')) // A wrapper takes a string and nothing else; the text itself is checked // when the value is encrypted, so one rule applies however it was made. -for (const Wrapper of [VcDate, VcTimestamp, VcDecimal, VcUuid]) { +for (const Wrapper of [RcDate, RcTimestamp, RcDecimal, RcUuid]) { for (const payload of [ new Date(0), { y: 2024 }, @@ -215,10 +215,10 @@ for (const Wrapper of [VcDate, VcTimestamp, VcDecimal, VcUuid]) { } } 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,22 +243,22 @@ 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(new RcTimestamp(timestamp))), + new 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(new RcTimestamp('+012000-01-01T00:00:00.000000001Z')), { code: 'ERR_INVALID_TIMESTAMP' }, ) -assert.throws(() => addon.encode(new VcTimestamp('9999-12-30T22:00:01Z')), { +assert.throws(() => addon.encode(new 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')), { +assert.throws(() => addon.encode(new RcDate('+010000-01-01')), { code: 'ERR_INVALID_DATE', }) assert.deepEqual( @@ -266,14 +266,14 @@ assert.deepEqual( 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 finer one 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'), + new 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 +288,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 = new 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') From 27b7ac1fdafbc674a4d421f28b56429dc24652f5 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 15:55:11 +1100 Subject: [PATCH 03/25] docs(recipher-js): the value bridge defines the value mapping, not vitaminc The README, the TypeScript docs, the Rust docs that reach `native.d.ts` and four test names said the value mapping, the wrapper classes and the `ERR_*` codes were vitaminc's. They were, while the bridge was a vitaminc crate. The bridge is `recipher-value-napi` now, in this package, so the text names it. A crate that really is vitaminc's keeps its name: `vitaminc-aead` and `vitaminc-protected` in the manifests and the imports. `native.d.ts` is regenerated, for the two doc comments it copies. --- .../typescript/packages/recipher-js/README.md | 12 ++++++------ .../recipher-js/__tests__/addon/value.test.ts | 2 +- .../recipher-js/__tests__/addon/values.test.ts | 6 +++--- .../packages/recipher-js/crate/Cargo.toml | 8 ++++---- .../packages/recipher-js/crate/src/cipher.rs | 6 +++--- .../recipher-js/crate/src/ciphertext.rs | 8 ++++---- .../recipher-js/crate/src/engine_tests.rs | 4 ++-- .../packages/recipher-js/crate/src/error.rs | 4 ++-- .../packages/recipher-js/crate/src/js.rs | 4 ++-- .../packages/recipher-js/crate/src/lib.rs | 9 ++++----- .../packages/recipher-js/native.d.ts | 10 +++++----- .../packages/recipher-js/src/error.ts | 6 +++--- .../packages/recipher-js/src/value-types.ts | 8 ++++---- .../packages/recipher-js/src/values.ts | 18 +++++++++--------- 14 files changed, 52 insertions(+), 53 deletions(-) diff --git a/languages/typescript/packages/recipher-js/README.md b/languages/typescript/packages/recipher-js/README.md index 5699413cc..6f949ba46 100644 --- a/languages/typescript/packages/recipher-js/README.md +++ b/languages/typescript/packages/recipher-js/README.md @@ -47,9 +47,9 @@ const opened = await cipher.decrypt(sealed.value) ## Values A value's type decides how it is encrypted. -vitaminc defines the mapping. -vitaminc is the CipherStash Rust library that the engine's plaintext types come from. -The `recipher-value-napi` crate, in `value-napi/`, converts JavaScript values by that mapping, in both directions: +The value bridge defines the mapping. +The value bridge is the `recipher-value-napi` crate, in `value-napi/`. +It converts JavaScript values in both directions: | Value | Encrypted as | Decrypts as | |---|---|---| @@ -73,7 +73,7 @@ The `recipher-value-napi` crate, in `value-napi/`, converts JavaScript values by - The package exports `RcUuid`, for a universally unique identifier (UUID). The engine has no plaintext type for a UUID yet. Encrypting an `RcUuid` is an `Err` with the code `recipher_js::uuid`. -- vitaminc's rules refuse each of these values, with an error code for each: +- 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; @@ -108,7 +108,7 @@ The document is encrypted as its JSON text, as the engine's `JsonPlaintext` type - 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 vitaminc does not build those properties in JavaScript. + The reason is that the value bridge does not build those properties in JavaScript. - **Read a stored document back with `kinds.json`.** The bytes do not record that a value is JSON. `Ciphertext.fromBytes(bytes, kinds.json)` decrypts to the document. @@ -172,7 +172,7 @@ 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. | | `url` | A documentation page for the error, where it has one. | 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 dae8b9873..74bff6764 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/value.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/value.test.ts @@ -121,7 +121,7 @@ describe('failures are values', () => { 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'], diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts index ee0164a93..7398283d9 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts @@ -84,7 +84,7 @@ describe('every value in the mapping round-trips', () => { expect((opened as Date).getTime()).toBe(date.getTime()) }) - it("vitaminc's wrapper classes", async () => { + it('the wrapper classes', async () => { const day = await roundTrip(new RcDate('2026-11-23')) expect(day).toBeInstanceOf(RcDate) expect((day as RcDate).value).toBe('2026-11-23') @@ -243,7 +243,7 @@ describe('a JSON document', () => { } }) - it('refuses a property vitaminc reserves, naming the rule, both ways', async () => { + 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}']) { @@ -304,7 +304,7 @@ describe('refusals', () => { expect(result.err()?.message).toContain('UUID') }) - it("an integer vitaminc cannot hold, with vitaminc's code", async () => { + 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) diff --git a/languages/typescript/packages/recipher-js/crate/Cargo.toml b/languages/typescript/packages/recipher-js/crate/Cargo.toml index b7ea0bf79..63d04c62c 100644 --- a/languages/typescript/packages/recipher-js/crate/Cargo.toml +++ b/languages/typescript/packages/recipher-js/crate/Cargo.toml @@ -28,8 +28,8 @@ stack-encrypt = { path = "../../../../../packages/stack-encrypt", default-featur 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. +# Node. `napi6` for BigInt and property enumeration, which the value bridge's +# walk needs; `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. @@ -49,8 +49,8 @@ serde_json = "1" # The engine's opaque path wipes a value it did not seal. The version the # engine resolves. zeroize = "1" -# A kind named to `Ciphertext.fromBytes`, read from its frame through -# vitaminc's frame serde. +# A kind named to `Ciphertext.fromBytes`, read from its frame through the +# frame's serde. serde = { version = "1", features = ["derive"] } [dev-dependencies] diff --git a/languages/typescript/packages/recipher-js/crate/src/cipher.rs b/languages/typescript/packages/recipher-js/crate/src/cipher.rs index dad97feff..9284e8bb9 100644 --- a/languages/typescript/packages/recipher-js/crate/src/cipher.rs +++ b/languages/typescript/packages/recipher-js/crate/src/cipher.rs @@ -160,9 +160,9 @@ impl Keyset { /// 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. /// - /// A value's type sets how it is encrypted. The mapping of JavaScript - /// types comes from vitaminc, CipherStash's cryptography library. A - /// `Json` from `json(..)` is encrypted as a JSON document. + /// 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. /// /// 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`. diff --git a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs index e858dc136..d2a91ea4b 100644 --- a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs +++ b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs @@ -198,10 +198,10 @@ fn as_kind(kind: ValueKind, value: OwnedFrame) -> Outcome { /// 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. 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. pub(crate) fn bytes_of(value: Unknown<'_>) -> Option> { if !value.is_typedarray().unwrap_or(false) { return None; 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 2f531ba9e..04f27d49e 100644 --- a/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs +++ b/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs @@ -57,8 +57,8 @@ async fn the_engine_opens_what_the_sdk_sealed() { 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(); - // vitaminc reads a `bigint` at its narrowest width. The engine decrypts - // it at any width that fits it. + // 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)); diff --git a/languages/typescript/packages/recipher-js/crate/src/error.rs b/languages/typescript/packages/recipher-js/crate/src/error.rs index 7a8235050..dcc0d6a12 100644 --- a/languages/typescript/packages/recipher-js/crate/src/error.rs +++ b/languages/typescript/packages/recipher-js/crate/src/error.rs @@ -160,8 +160,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. diff --git a/languages/typescript/packages/recipher-js/crate/src/js.rs b/languages/typescript/packages/recipher-js/crate/src/js.rs index 294bd6e2e..81fb7f83c 100644 --- a/languages/typescript/packages/recipher-js/crate/src/js.rs +++ b/languages/typescript/packages/recipher-js/crate/src/js.rs @@ -85,7 +85,7 @@ pub fn elements<'e>( /// /// 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 vitaminc, CipherStash's cryptography library, does not build. +/// 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)) @@ -102,7 +102,7 @@ fn not_built(env: &Env, fault: &JsFault) -> RecipherErrorFields { } } -/// Returns whether `value` is a vitaminc `RcUuid`. +/// Returns whether `value` is an `RcUuid`. fn is_uuid(env: &Env, value: &Unknown<'_>) -> bool { Wrappers::get(env) .and_then(|wrappers| wrappers.classify(value)) diff --git a/languages/typescript/packages/recipher-js/crate/src/lib.rs b/languages/typescript/packages/recipher-js/crate/src/lib.rs index 1ab0421d9..6f8cf490f 100644 --- a/languages/typescript/packages/recipher-js/crate/src/lib.rs +++ b/languages/typescript/packages/recipher-js/crate/src/lib.rs @@ -83,11 +83,10 @@ pub fn binding_interface() -> u32 { BINDING_INTERFACE } -/// Exports the wrapper classes of vitaminc, CipherStash's cryptography -/// library: `RcDate`, `RcTimestamp`, `RcDecimal` and `RcUuid`. Each class -/// stands for a type that JavaScript does not have. The addon exports them -/// so JavaScript can construct them, and so decrypted values are instances -/// of them. +/// Exports the value bridge's wrapper classes: `RcDate`, `RcTimestamp`, +/// `RcDecimal` and `RcUuid`. Each class stands for a type that JavaScript +/// does not have. The addon exports them so JavaScript can construct them, +/// and so decrypted values are instances of them. // 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))] diff --git a/languages/typescript/packages/recipher-js/native.d.ts b/languages/typescript/packages/recipher-js/native.d.ts index 134f254a6..31a65ac40 100644 --- a/languages/typescript/packages/recipher-js/native.d.ts +++ b/languages/typescript/packages/recipher-js/native.d.ts @@ -163,9 +163,9 @@ export declare class Keyset { * 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. * - * A value's type sets how it is encrypted. The mapping of JavaScript - * types comes from vitaminc, CipherStash's cryptography library. A - * `Json` from `json(..)` is encrypted as a JSON document. + * 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. * * 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`. @@ -257,8 +257,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/error.ts b/languages/typescript/packages/recipher-js/src/error.ts index 4ba76d069..94fd3a955 100644 --- a/languages/typescript/packages/recipher-js/src/error.ts +++ b/languages/typescript/packages/recipher-js/src/error.ts @@ -19,9 +19,9 @@ export type { ErrorCause, RecipherErrorFields, Severity } * * - `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; + * - 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. diff --git a/languages/typescript/packages/recipher-js/src/value-types.ts b/languages/typescript/packages/recipher-js/src/value-types.ts index 5be1b0533..6ed8e152c 100644 --- a/languages/typescript/packages/recipher-js/src/value-types.ts +++ b/languages/typescript/packages/recipher-js/src/value-types.ts @@ -9,7 +9,7 @@ declare const wrapper: unique symbol -/** A calendar date, such as `new RcDate('2026-11-23')`. The class comes from vitaminc. */ +/** A calendar date, such as `new RcDate('2026-11-23')`. */ export interface RcDate { /** The date as `YYYY-MM-DD`. */ readonly value: string @@ -17,7 +17,7 @@ export interface RcDate { readonly [wrapper]: 'RcDate' } -/** A UTC instant, to the nanosecond. The class comes from vitaminc. */ +/** A UTC instant, to the nanosecond. */ export interface RcTimestamp { /** The instant as RFC 3339 text, with nanoseconds. */ readonly value: string @@ -25,7 +25,7 @@ export interface RcTimestamp { readonly [wrapper]: 'RcTimestamp' } -/** A decimal with its scale, such as `new RcDecimal('1.50')`. The class comes from vitaminc. */ +/** A decimal with its scale, such as `new RcDecimal('1.50')`. */ export interface RcDecimal { /** The decimal as text, with its scale. */ readonly value: string @@ -34,7 +34,7 @@ export interface RcDecimal { } /** - * A universally unique identifier (UUID). The class comes from vitaminc. + * A universally unique identifier (UUID). * The engine has no plaintext type for a UUID yet. Encrypting an `RcUuid` is * an `Err` with the code `recipher_js::uuid`. `RcUuid` is not a `Scalar`. */ diff --git a/languages/typescript/packages/recipher-js/src/values.ts b/languages/typescript/packages/recipher-js/src/values.ts index 6562ae161..fd60fc449 100644 --- a/languages/typescript/packages/recipher-js/src/values.ts +++ b/languages/typescript/packages/recipher-js/src/values.ts @@ -1,9 +1,9 @@ /** * The values the SDK encrypts, and the types they decrypt to. * - * A value's type decides how it is encrypted. The mapping is vitaminc's - * mapping for JavaScript. vitaminc is the CipherStash Rust library that the - * engine's plaintext types come from. + * 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 | * |---|---|---| @@ -45,20 +45,20 @@ export type { Value, } from './value-types' -/** A calendar date, such as `new RcDate('2026-11-23')`. The class comes from vitaminc. */ +/** A calendar date, such as `new RcDate('2026-11-23')`. */ export type RcDate = RcDateValue -/** A UTC instant, to the nanosecond. The class comes from vitaminc. */ +/** A UTC instant, to the nanosecond. */ export type RcTimestamp = RcTimestampValue -/** A decimal with its scale, such as `new RcDecimal('1.50')`. The class comes from vitaminc. */ +/** A decimal with its scale, such as `new RcDecimal('1.50')`. */ export type RcDecimal = RcDecimalValue /** - * A universally unique identifier (UUID). The class comes from vitaminc. + * A universally unique identifier (UUID). * The engine has no plaintext type for a UUID yet. Encrypting an `RcUuid` is * an `Err` with the code `recipher_js::uuid`. `RcUuid` is not a `Scalar`. */ export type RcUuid = RcUuidValue -/** The constructor of one of vitaminc's wrapper classes. */ +/** The constructor of a wrapper class. */ export interface WrapperConstructor { new (text: string): W readonly prototype: W @@ -69,7 +69,7 @@ type WrapperName = 'RcDate' | 'RcTimestamp' | 'RcDecimal' | 'RcUuid' /** * The class that the native addon defines. When the addon did not load, a * stand-in class instead. The stand-in keeps its text, is frozen, and - * serialises to JSON as vitaminc's class does. + * serialises to JSON as the class does. */ function wrapperClass(name: WrapperName): WrapperConstructor { if (binding.isOk()) { From 1e200d66884c9a8478f3ce140a4c9c74b97d227f Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 15:56:51 +1100 Subject: [PATCH 04/25] refactor(recipher-js): declare each wrapper class beside its type, with no renamed import `src/values.ts` imported each wrapper type under a second name (`RcDate as RcDateValue`), re-declared it (`export type RcDate = RcDateValue`) and then declared the constant. That is two aliases for one class. The import is now a namespace (`import type * as Types`), and each constant has its type on the next line. One alias has to stay: a class is a constant and a type of one name, and TypeScript refuses a module that exports a type from another module and a constant under the same name (TS2323, or TS2300 when an index re-exports both). The types stay in `value-types.ts` because the addon's declarations name them. Each class has one doc comment, on its constant. --- .../packages/recipher-js/src/values.ts | 47 ++++++++++--------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/languages/typescript/packages/recipher-js/src/values.ts b/languages/typescript/packages/recipher-js/src/values.ts index fd60fc449..dc88907a0 100644 --- a/languages/typescript/packages/recipher-js/src/values.ts +++ b/languages/typescript/packages/recipher-js/src/values.ts @@ -29,12 +29,7 @@ */ import type * as Native from '../native' import { type Binding, binding } from './binding' -import type { - RcDate as RcDateValue, - RcDecimal as RcDecimalValue, - RcTimestamp as RcTimestampValue, - RcUuid as RcUuidValue, -} from './value-types' +import type * as Types from './value-types' export type { JsonValue, @@ -45,19 +40,6 @@ export type { Value, } from './value-types' -/** A calendar date, such as `new RcDate('2026-11-23')`. */ -export type RcDate = RcDateValue -/** A UTC instant, to the nanosecond. */ -export type RcTimestamp = RcTimestampValue -/** A decimal with its scale, such as `new RcDecimal('1.50')`. */ -export type RcDecimal = RcDecimalValue -/** - * A universally unique identifier (UUID). - * The engine has no plaintext type for a UUID yet. Encrypting an `RcUuid` is - * an `Err` with the code `recipher_js::uuid`. `RcUuid` is not a `Scalar`. - */ -export type RcUuid = RcUuidValue - /** The constructor of a wrapper class. */ export interface WrapperConstructor { new (text: string): W @@ -92,16 +74,35 @@ function wrapperClass(name: WrapperName): WrapperConstructor { return Object.freeze(StandIn) as unknown as WrapperConstructor } -/** A calendar date. */ +// A class is a constant and a type of one name. `./value-types` declares the +// types, because the addon's declarations name them, and 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 `new RcDate('2026-11-23')`. */ export const RcDate: WrapperConstructor = wrapperClass('RcDate') -/** A UTC instant to the nanosecond. */ +export type RcDate = Types.RcDate + +/** + * A UTC instant, to the nanosecond, such as + * `new RcTimestamp('2026-11-23T01:02:03.000000001Z')`. + */ export const RcTimestamp: WrapperConstructor = wrapperClass('RcTimestamp') -/** A decimal with its scale. */ +export type RcTimestamp = Types.RcTimestamp + +/** A decimal with its scale, such as `new RcDecimal('1.50')`. */ export const RcDecimal: WrapperConstructor = wrapperClass('RcDecimal') -/** A UUID. */ +export type RcDecimal = Types.RcDecimal + +/** + * A universally unique identifier (UUID). The engine has no plaintext type + * for a UUID yet. Encrypting an `RcUuid` is an `Err` with the code + * `recipher_js::uuid`. `RcUuid` is not a `Scalar`. + */ export const RcUuid: WrapperConstructor = wrapperClass('RcUuid') +export type RcUuid = Types.RcUuid /** * A JSON document to encrypt as one ciphertext, as its JSON text. Make one From dab69c5867db481029420e2759036baeb3141c27 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 15:56:58 +1100 Subject: [PATCH 05/25] fix(recipher-js): a stand-in wrapper class constructs as the addon's class does The stand-in for a wrapper class, used when the addon did not load, differed from the class it stands in for. `new RcDate(20261123)` kept the text '20261123' where the class throws a TypeError. `String(..)` gave '[object Object]', Node's `inspect` showed the object, and the prototype was not frozen. The stand-in now throws the same TypeError for an argument that is not a string, has the class's `toString` and inspect hook, and freezes its prototype. A test in the addon suite compares everything a caller can observe of a stand-in with the same of the class, for all four classes. A unit test checks the stand-in alone, where no addon is built. The README and the module docs said one call throws. A wrapper class's constructor throws too, with or without the addon, so they say that. --- .../typescript/packages/recipher-js/README.md | 5 ++ .../__tests__/addon/values.test.ts | 61 +++++++++++++++++++ .../recipher-js/__tests__/unit/values.test.ts | 54 ++++++++++++++++ .../packages/recipher-js/crate/src/lib.rs | 7 ++- .../packages/recipher-js/src/index.ts | 5 +- .../packages/recipher-js/src/values.ts | 43 ++++++++++--- 6 files changed, 162 insertions(+), 13 deletions(-) create mode 100644 languages/typescript/packages/recipher-js/__tests__/unit/values.test.ts diff --git a/languages/typescript/packages/recipher-js/README.md b/languages/typescript/packages/recipher-js/README.md index 6f949ba46..c358701cf 100644 --- a/languages/typescript/packages/recipher-js/README.md +++ b/languages/typescript/packages/recipher-js/README.md @@ -156,6 +156,11 @@ const opened = await Promise.all( A static method, such as `Ciphertext.fromBytes`, works on its own. +A wrapper class's constructor throws too. +The constructor takes a string, so `new RcDate(20261123)` throws a `TypeError`. +The constructor does not check the text. +`encrypt` returns an `Err` for text that is not a date. + A `RecipherError` is an error report that a call returns as a value. Most errors come from the engine. The SDK's own errors have a code that starts with `recipher_js::`. diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts index 7398283d9..dbc6e3d7a 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts @@ -1,3 +1,4 @@ +import { inspect } from 'node:util' import { describe, expect, it } from 'vitest' import { type Cipher, @@ -10,6 +11,7 @@ import { RcUuid, } from '../../src/index' import { testCipher } from '../../src/testing' +import { standInWrapper } from '../../src/values' async function cipher(): Promise { return (await testCipher()).unwrap() @@ -109,6 +111,65 @@ describe('every value in the mapping round-trips', () => { }) }) +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 names = ['RcDate', 'RcTimestamp', 'RcDecimal', 'RcUuid'] as const + + /** What a caller can observe of a class and one instance of it. */ + function observed( + cls: new (text: string) => object, + text: string, + ): Record { + const instance = new cls(text) + let thrown: unknown + try { + // @ts-expect-error: the constructor takes a string. + new cls(20261123) + } catch (error) { + thrown = error + } + return { + name: cls.name, + value: Object.getOwnPropertyDescriptor(instance, 'value'), + keys: Object.keys(instance), + string: String(instance), + json: JSON.stringify(instance), + inspected: inspect(instance), + frozen: [ + Object.isFrozen(instance), + Object.isFrozen(cls), + Object.isFrozen(cls.prototype), + ], + thrown: [ + thrown instanceof TypeError, + thrown instanceof Error ? thrown.message : thrown, + ], + } + } + + it('takes a string, and throws a TypeError for anything else', () => { + for (const name of names) { + // @ts-expect-error: the constructor takes a string. + expect(() => new classes[name](20261123)).toThrow(TypeError) + expect(new classes[name](texts[name]).value).toBe(texts[name]) + } + }) + + it('has a stand-in that constructs as it does', () => { + for (const name of names) { + expect(observed(standInWrapper(name), texts[name])).toEqual( + observed(classes[name], texts[name]), + ) + } + }) +}) + describe('an array of values', () => { it('is an array of ciphertexts in, an array of values out, in order', async () => { const c = await cipher() 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..4e41cd550 --- /dev/null +++ b/languages/typescript/packages/recipher-js/__tests__/unit/values.test.ts @@ -0,0 +1,54 @@ +/** + * The stand-in wrapper classes, which take the place of the addon's classes + * when the addon did not load. None of these tests needs the addon. + */ +import { inspect } from 'node:util' +import { describe, expect, it } from 'vitest' +import { standInWrapper } from '../../src/values' + +const NAMES = ['RcDate', 'RcTimestamp', 'RcDecimal', 'RcUuid'] as const + +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).name).toBe(name) + } + }) + + it('keeps its text in a read-only, enumerable `value`', () => { + const RcDate = standInWrapper<{ value: string }>('RcDate') + const day = new RcDate('2026-11-23') + expect(Object.getOwnPropertyDescriptor(day, 'value')).toEqual({ + value: '2026-11-23', + writable: false, + enumerable: true, + configurable: false, + }) + expect(Object.keys(day)).toEqual(['value']) + expect(Object.isFrozen(day)).toBe(true) + }) + + it('gives its text to String, JSON.stringify and inspect', () => { + const RcDecimal = standInWrapper('RcDecimal') + const price = new RcDecimal('1.50') + expect(String(price)).toBe('1.50') + expect(JSON.stringify({ price })).toBe('{"price":"1.50"}') + expect(inspect(price)).toBe('RcDecimal(1.50)') + }) + + it('throws a TypeError for an argument that is not a string', () => { + const RcDate = standInWrapper('RcDate') + for (const argument of [20261123, undefined, null, {}, ['2026-11-23']]) { + // @ts-expect-error: the constructor takes a string. + expect(() => new RcDate(argument)).toThrow( + new TypeError('RcDate takes a string'), + ) + } + }) + + it('is frozen, with a frozen prototype', () => { + const RcUuid = standInWrapper('RcUuid') + expect(Object.isFrozen(RcUuid)).toBe(true) + expect(Object.isFrozen(RcUuid.prototype)).toBe(true) + }) +}) diff --git a/languages/typescript/packages/recipher-js/crate/src/lib.rs b/languages/typescript/packages/recipher-js/crate/src/lib.rs index 6f8cf490f..185da8256 100644 --- a/languages/typescript/packages/recipher-js/crate/src/lib.rs +++ b/languages/typescript/packages/recipher-js/crate/src/lib.rs @@ -21,10 +21,13 @@ //! 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 wrapper classes are the value bridge's JavaScript. Their +//! constructors throw a `TypeError` for an argument that is not a string. +//! //! 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 diff --git a/languages/typescript/packages/recipher-js/src/index.ts b/languages/typescript/packages/recipher-js/src/index.ts index 020433670..b1019d7a3 100644 --- a/languages/typescript/packages/recipher-js/src/index.ts +++ b/languages/typescript/packages/recipher-js/src/index.ts @@ -19,10 +19,13 @@ * 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. * - * 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 wrapper class's constructor, such as `new RcDate(..)`, also throws a + * `TypeError` when its argument is not a string. */ export { Cipher, diff --git a/languages/typescript/packages/recipher-js/src/values.ts b/languages/typescript/packages/recipher-js/src/values.ts index dc88907a0..48050a021 100644 --- a/languages/typescript/packages/recipher-js/src/values.ts +++ b/languages/typescript/packages/recipher-js/src/values.ts @@ -26,6 +26,9 @@ * and `json` come from the native addon. When the addon did not load, * stand-ins take their place. Each stand-in constructs as the class does. * `encrypt` then resolves to the `Err` that says why the addon did not load. + * + * A wrapper class's constructor takes a string. It throws a `TypeError` for + * any other argument. The text is checked when the value is encrypted. */ import type * as Native from '../native' import { type Binding, binding } from './binding' @@ -49,31 +52,51 @@ export interface WrapperConstructor { type WrapperName = 'RcDate' | 'RcTimestamp' | 'RcDecimal' | 'RcUuid' /** - * The class that the native addon defines. When the addon did not load, a - * stand-in class instead. The stand-in keeps its text, is frozen, and - * serialises to JSON as the class does. + * A stand-in for the wrapper class `name`, for when the native addon did + * not load. It constructs as the addon's class does: it takes a string and + * throws a `TypeError` for anything else, keeps the text in a read-only + * `value`, is frozen, and gives the same text to `String`, `JSON.stringify` + * and Node's `inspect`. */ -function wrapperClass(name: WrapperName): WrapperConstructor { - 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 WrapperConstructor - } +export function standInWrapper(name: WrapperName): WrapperConstructor { const StandIn = class { readonly value: string constructor(text: string) { - this.value = String(text) + if (typeof text !== 'string') { + throw new TypeError(`${name} takes a string`) + } + this.value = text Object.freeze(this) } toJSON(): string { return this.value } + toString(): string { + return this.value + } + [Symbol.for('nodejs.util.inspect.custom')](): string { + return `${name}(${this.value})` + } } Object.defineProperty(StandIn, 'name', { value: name }) + Object.freeze(StandIn.prototype) // biome-ignore lint/plugin: a stand-in for the class, which constructs as it does. return Object.freeze(StandIn) as unknown as WrapperConstructor } +/** + * The class that the native addon defines. When the addon did not load, a + * stand-in class instead. + */ +function wrapperClass(name: WrapperName): WrapperConstructor { + 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 WrapperConstructor + } + return standInWrapper(name) +} + // A class is a constant and a type of one name. `./value-types` declares the // types, because the addon's declarations name them, and a module cannot // export a type from another module and a constant under the same name. So From cceea6a93cd9731816673e26939c40ec7f20165d Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 15:57:12 +1100 Subject: [PATCH 06/25] docs(recipher-js): a plain object is json(..) today, and opaque(..) when it is built The README told the reader to wrap a plain object in `json(..)`, as if that were the only form. The SDK's design gives the caller two: a JSON document, or the engine's opaque format for a whole object. `opaque(..)` is not built yet, so `json(..)` is the one that works today. The README and the values module now say why an object is refused, name both forms, and say which one exists. --- languages/typescript/packages/recipher-js/README.md | 6 ++++-- languages/typescript/packages/recipher-js/src/values.ts | 6 +++++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/languages/typescript/packages/recipher-js/README.md b/languages/typescript/packages/recipher-js/README.md index c358701cf..fed5fb9f6 100644 --- a/languages/typescript/packages/recipher-js/README.md +++ b/languages/typescript/packages/recipher-js/README.md @@ -68,8 +68,10 @@ It converts JavaScript values in both directions: - Integers are a `bigint`. A `number` is a float. The `number` `5` does not equal the integer `5n`. -- A plain object is refused. - Wrap it in `json(..)`. +- 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(..)` will encrypt a whole object in the engine's own format, and is not built yet. - The package exports `RcUuid`, for a universally unique identifier (UUID). The engine has no plaintext type for a UUID yet. Encrypting an `RcUuid` is an `Err` with the code `recipher_js::uuid`. diff --git a/languages/typescript/packages/recipher-js/src/values.ts b/languages/typescript/packages/recipher-js/src/values.ts index 48050a021..446c7b668 100644 --- a/languages/typescript/packages/recipher-js/src/values.ts +++ b/languages/typescript/packages/recipher-js/src/values.ts @@ -20,7 +20,11 @@ * | `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 plain object is refused. Wrap it in `json(..)`. + * equal the integer `5n`. + * + * A plain object is refused, because an object has no single stored form. + * `json(..)` encrypts it as a JSON document. `opaque(..)` will encrypt a + * whole object in the engine's own format, and is not built yet. * * The wrapper classes (`RcDate`, `RcTimestamp`, `RcDecimal`, and `RcUuid`) * and `json` come from the native addon. When the addon did not load, From c001978842d5c7354c31023002c0aecec2bac084 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 16:12:13 +1100 Subject: [PATCH 07/25] feat(recipher-js): the value bridge reads and builds JSON documents The JavaScript rules for a JSON document were in the addon, as a sink that turned a frame into a `serde_json::Value` and a walk that turned one back. They are a value mapping, so they belong in the value bridge. This commit adds them there. The addon moves to them in the next one. Encrypting: `JsRef::to_json(max_depth)` walks a JavaScript value and writes the text of a JSON document. - The walk is the bridge's own, with a second mode that reads only what a document holds. So holes, getters that throw, unpaired surrogates, reserved property names and objects that are not plain are refused as they are for any value. - A whole `number` within 2^53 - 1 of zero is written as an integer, as `JSON.stringify` writes it. napi-rs's `serde_json` conversion writes a whole number above 2^32 as a float (`5000000000.0`), which Rust's `serde_json` and Go's `encoding/json` refuse for an integer field. - A whole `number` from 2^53 up to 2^64 is refused: its digits may not be the ones written. A `bigint` is its exact digits within 64 bits, and refused outside them by one check, whatever its size. - `undefined`, a number that is not finite, bytes, a `Date` and a wrapper class instance are refused as `recipher_js::not_json`, with a message that names the kind of value and no part of it. - The text goes straight into a `vitaminc_protected::Buffer`, which wipes each allocation it outgrows. No tree of the document is built. - The depth limit is the caller's: the bridge has no second constant. `Refusal::TooDeep` now carries its limit, so its message states the limit that applied. Decrypting: `JsBuilder::build_json(env, &Value)` builds the JavaScript value. Each scalar goes through napi-rs's own conversion: an integer in the safe range is a `number`, any other a `bigint`, a float a `number`. Arrays and objects are built here from own data properties, with the reserved names refused. napi-rs assigns each member, so a member named `__proto__` becomes the object's prototype and a setter on a polluted prototype receives the decrypted value. `tests/json.cjs` checks every rule in a live Node, and pins what napi-rs's conversion does in both directions, so a change in it shows. The walk's recursive functions hold less than before: reading a scalar and choosing an object's shape moved into helpers, so the second mode costs a nested level no more stack. A debug build walks the test suite's deepest values at the same stack size as before. Cargo.lock: `recipher-value-napi` gains `serde` and `serde_json`, which the workspace already resolves. The test addon's lock gains the same. --- .../packages/recipher-js/Cargo.lock | 2 + .../recipher-js/value-napi/Cargo.toml | 10 +- .../packages/recipher-js/value-napi/README.md | 84 ++- .../recipher-js/value-napi/src/error.rs | 51 +- .../packages/recipher-js/value-napi/src/js.rs | 15 +- .../recipher-js/value-napi/src/js_ref.rs | 190 +++++- .../recipher-js/value-napi/src/json.rs | 576 ++++++++++++++++++ .../recipher-js/value-napi/src/lib.rs | 3 +- .../recipher-js/value-napi/src/scalar.rs | 180 +++++- .../value-napi/tests/addon/Cargo.lock | 6 + .../value-napi/tests/addon/Cargo.toml | 8 +- .../value-napi/tests/addon/src/lib.rs | 66 +- .../recipher-js/value-napi/tests/json.cjs | 501 +++++++++++++++ .../recipher-js/value-napi/tests/node.rs | 1 + 14 files changed, 1646 insertions(+), 47 deletions(-) create mode 100644 languages/typescript/packages/recipher-js/value-napi/src/json.rs create mode 100644 languages/typescript/packages/recipher-js/value-napi/tests/json.cjs diff --git a/languages/typescript/packages/recipher-js/Cargo.lock b/languages/typescript/packages/recipher-js/Cargo.lock index 30094cce9..ad187e6e9 100644 --- a/languages/typescript/packages/recipher-js/Cargo.lock +++ b/languages/typescript/packages/recipher-js/Cargo.lock @@ -2526,6 +2526,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/value-napi/Cargo.toml b/languages/typescript/packages/recipher-js/value-napi/Cargo.toml index 8250bffe2..1848d1dc3 100644 --- a/languages/typescript/packages/recipher-js/value-napi/Cargo.toml +++ b/languages/typescript/packages/recipher-js/value-napi/Cargo.toml @@ -22,8 +22,14 @@ 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"] } +# 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"] } +# A JSON document: `serde_json` writes each scalar of its text, and a +# decrypted document arrives as a `serde_json::Value`. `serde` is named 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 a5e47bde3..9bf074967 100644 --- a/languages/typescript/packages/recipher-js/value-napi/README.md +++ b/languages/typescript/packages/recipher-js/value-napi/README.md @@ -29,6 +29,10 @@ the outgoing value. This crate supplies both sides of that conversion: - **`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. +- **`JsRef::to_json`** and **`JsBuilder::build_json`** — a JSON document. + The first writes a JavaScript value as the text of a document, and the + second builds the JavaScript value of a `serde_json::Value`. See + [JSON documents](#json-documents). - **`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 @@ -147,6 +151,81 @@ 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`. +## JSON documents + +A JSON document is encrypted as its JSON text, so that Rust, Go and +JavaScript all read the same 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 + +The walk is the one every value goes through, with every rule in +[Safety notes](#safety-notes). It reads only what a JSON document holds: + +| 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 | +| any other finite `number` | a float | +| `bigint` within 64 bits | an integer, with its digits | +| anything else | refused | + +- **A whole number is an integer.** `5000000000` is written `5000000000`, + as `JSON.stringify` writes it, and never `5000000000.0`. Rust's + `serde_json` and Go's `encoding/json` refuse a number with a fraction for + an integer field. `-0` is written `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, and an + integer was probably meant. A `bigint` holds it exactly. A number of 2^64 + or more is no integer that a reader takes, so it is a float. +- **A `bigint` is its exact digits**, from -2^63 to 2^64 - 1. That is the + range a JSON parser in Rust or Go reads. A `bigint` outside it is + refused, whatever its size. +- **Everything else is refused**: `undefined`, `NaN` and the infinities, + bytes (a `Buffer`, a typed array, a `DataView`), a `Date`, and a wrapper + class instance. Each has the code `recipher_js::not_json`, and a message + that names the kind of value and no part of it. A function and a symbol + are `recipher_js::not_a_value`, as for any value. Nothing calls a + `toJSON` method. +- **`max_depth` is the reader's limit**, in levels of arrays and objects: + `[1]` is one level. A document nested deeper is `recipher_js::too_deep`. + The walk's own limit of 128 applies too. +- **The text is written straight into a protected buffer.** The buffer + wipes each allocation it outgrows, and wipes itself when it is dropped. + No tree of the document is built on the way. An object's members are + written in the order JavaScript lists them. + +### Building a document + +| 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. A `bigint` that is in the safe range +comes back as a `number`: `5n` is written `5`, and `5` is read as `5`. + +Each scalar is converted by napi-rs's own `serde_json` conversion, which +has this number rule. An array and an object are built here, from own data +properties, and a member named `__proto__`, `constructor` or `prototype` +is refused. napi-rs's conversion of a whole document assigns each member +(`object[key] = value`). An assignment gives a member named `__proto__` to +the object as its prototype, and runs a setter that a polluted prototype +defines, which then receives the decrypted value. + +`build_json` copies nothing out of the document. The caller owns the +document, and wipes it. + +napi-rs's conversion in the other direction, from a JavaScript value to a +`serde_json::Value`, is not used. It writes a whole number above 2^32 as a +float and a wide `bigint` as a string. It drops a member that is +`undefined`, and reads a `Date` as `{}`. It also reads inherited properties, +and 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 @@ -163,8 +242,9 @@ 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. +for an exception the application threw. `JsRef::to_frame`, +`JsRef::to_json`, `JsBuilder::build` and `JsBuilder::build_json` return the +`JsFault` itself. This crate is a library consumed by the Node addon (cdylib/npm package); it is not itself loadable from Node. 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..c8b4e25ec 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,14 @@ 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 most levels of arrays and objects the value may nest. + limit: usize, + }, /// An array with a hole. #[error("an array has a hole")] #[diagnostic( @@ -55,6 +59,10 @@ pub enum Refusal { )] #[diagnostic(code(recipher_js::unpaired_surrogate))] UnpairedSurrogate, + /// A value that a JSON document cannot hold. + #[error("a JSON document cannot hold {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 +70,35 @@ pub enum Refusal { Scalar(#[from] ConversionError), } +/// A value that has no form in a JSON document. Each variant displays as +/// what the value is, and never as 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, either side of zero. A + /// `number` that large may not have the digits that were written. + #[error( + "a whole number from 2^53 up to 2^64 held as a `number`, whose digits may not be the \ + ones written; give it as a `bigint`" + )] + UnsafeInteger, + /// A `bigint` below -2^63 or above 2^64 - 1. + #[error("a `bigint` outside the 64-bit range (below -2^63 or above 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 it as text")] + 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 +259,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 +277,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..149c31833 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 hold. +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 cefb62a67..215920a2b 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 @@ -26,6 +26,22 @@ //! 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`]. +//! +//! # A JSON document +//! +//! [`JsRef::to_json`] walks a value as a JSON document. The walk is the +//! same one, with the same safety rules, but it reads only what a JSON +//! document holds: +//! +//! | JavaScript | In the document | +//! | ------------------------------------ | ------------------------------- | +//! | `null`, `boolean`, `string` | the same | +//! | `Array`, plain object | an array, an object | +//! | whole `number` within 2^53 - 1 | an integer | +//! | whole `number` from 2^53 up 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 +54,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 +68,15 @@ 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 what a JSON document holds: 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 +89,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 +111,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 +138,68 @@ 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`] are the walk's recursion: a nested level costs one frame of +/// each. So they hold as little as they can, and everything that reads a +/// scalar or builds a refusal is in a helper whose frame is gone before a +/// container recurses. A document at the depth limit then walks in a debug +/// build too. +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`, which 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 +208,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 +215,71 @@ fn js_walk(value: Unknown<'_>, depth: usize, sink: S) -> Result(value: Unknown<'_>, depth: usize, sink: S) -> Result { +/// What an object is, to the walk. +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, +} + +/// What `value` is, or the refusal of an object the walk does not read. +/// +/// A JSON document holds none of the scalar shapes: bytes, a `Date` and a +/// wrapper class instance. Each is refused here by what it is, before it +/// is read. +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().map_err(js_fault::)? { - return Err(js_fault::(not_bytes_error("DataView"))); + if value.is_dataview()? { + if json { + return Err(not_json_error(NoJsonForm::Bytes)); + } + return Err(not_bytes_error("DataView")); } - if value.is_array().map_err(js_fault::)? { - return js_array(value, depth, sink); + if value.is_array()? { + return Ok(Shape::Array); } - if value.is_date().map_err(js_fault::)? { - return js_date(value, sink); + if value.is_date()? { + if json { + return Err(not_json_error(NoJsonForm::Typed)); + } + return Ok(Shape::Date); } - match js_classify(value).map_err(js_fault::)? { - Some(wrapper) => js_wrapped(value, wrapper, sink), - None => js_map(value, depth, sink), + match js_classify(value)? { + Some(_) if json => Err(not_json_error(NoJsonForm::Typed)), + Some(wrapper) => Ok(Shape::Wrapped(wrapper)), + None => Ok(Shape::Map), + } +} + +/// 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 +333,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 +349,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 +383,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() } @@ -316,7 +441,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..647564cfd --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/src/json.rs @@ -0,0 +1,576 @@ +//! JSON documents: a JavaScript value as the text of one, and a document +//! 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. The walk is the one every value goes through, so the +//! same safety rules apply: only plain objects are read, by their own +//! enumerable string keys, and a hole, a getter that throws, an unpaired +//! surrogate and a reserved property name are refused. The +//! [`js_ref`](crate::js_ref) module lists what a document holds. +//! +//! The text is written straight into a [`Buffer`], which wipes each +//! allocation it outgrows and wipes itself when it is dropped. No tree of +//! the document is built on the way, so no copy of it is left behind. +//! +//! # Decrypting: a document to a JavaScript value +//! +//! [`JsBuilder::build_json`] builds the JavaScript value of a +//! `serde_json::Value`. Each scalar is converted by napi-rs's own +//! conversion for its type. For a number that is: +//! +//! - an integer within 2^53 - 1 of zero: a `number`; +//! - any other integer: a `bigint`, so no digit is lost; +//! - a float: a `number`. +//! +//! An array and an object are written here, not by napi-rs. napi-rs assigns +//! each element and member (`object[key] = value`). An assignment runs a +//! setter that a polluted prototype defines, which would receive the +//! decrypted value. It also gives a member named `__proto__` to the object +//! as its prototype. So this module defines each element and member as an +//! own data property, and 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, on the JavaScript + /// thread. The text is plaintext, and comes back in a buffer that is + /// wiped when it is dropped. + /// + /// `max_depth` is the most levels of arrays and objects the document + /// may nest: the limit of whatever will read the text. `[1]` is one + /// level. The walk's own limit, [`MAX_DEPTH`], applies too. + /// + /// An object's members are written in the order JavaScript lists them. + /// + /// # Errors + /// + /// A [`JsFault`]: its [`refusal`](JsFault::refusal) names the rule a + /// refused value broke. A value with no JSON form is + /// [`Refusal::NotJson`], and a document nested past `max_depth` is + /// [`Refusal::TooDeep`]. No error holds 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. + /// + /// An integer within 2^53 - 1 of zero is a `number`, any other integer + /// is a `bigint`, and a float is a `number`. An array and an object are + /// built from own data properties. + /// + /// This function copies nothing out of `document`: the caller still + /// owns it, and wipes it. + /// + /// # Errors + /// + /// A [`JsFault`]. [`Refusal::ReservedKey`] is an object with a member + /// named `__proto__`, `constructor` or `prototype`, and + /// [`Refusal::TooDeep`] is 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`, which sits `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's conversion of a `serde_json::Number`: see the module + // docs for 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. +/// +/// It writes what a JSON document holds: a null, a boolean, an integer, a +/// finite float, text, a sequence and a map. It refuses anything else. An +/// integer is written with its digits at any width. The reader of the text +/// decides which integers it takes. +/// +/// A walk that fails part way leaves the text written so far in the +/// buffer. The buffer is the caller's, 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, and a float in the shortest form that reads back +/// as the same float. `serde_json` writes each straight into `out`. +fn write_scalar(out: &mut Buffer, value: &T) -> Result<(), JsFault> { + // The only failure is the writer's, and this writer does not fail. The + // error's text is dropped, so nothing of the value can leave in it. + 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` has no `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 what it takes. + 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 takes 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 hold 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 is no level, so it 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 4cc05a005..0ec094bb1 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,62 @@ fn unsigned(value: u128) -> Int { } } +/// The largest whole number a JavaScript `number` holds 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; + +/// A JavaScript `number` as a JSON document holds it. +/// +/// A whole number within the safe range (2^53 - 1 either side of zero) 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 is refused. A `number` that large +/// may not have the digits that were written, and an integer was probably +/// meant, which a `bigint` holds exactly. Any other finite number is a +/// float: one with a fraction, or one of 2^64 or more. +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 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 holds it: a signed or an +/// unsigned 64-bit integer. A JSON parser in Rust or Go reads no wider, 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`, and 2^63 is no `i64`: negate as `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) { @@ -341,6 +399,126 @@ 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 and the next number a `number` can hold, the largest below + // 2^64, and the same below zero. + 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, + -18_446_744_073_709_549_568.0, + ] { + assert_eq!( + json_number(number), + Err(NoJsonForm::UnsafeInteger), + "{number}" + ); + } + } + + #[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: no integer the document's readers take. + 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/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..097253c54 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" +# A refusal's code, which is its 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 ed87d24e8..e7ac29f8a 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 @@ -6,7 +6,7 @@ use napi::bindgen_prelude::{AsyncTask, Buffer, JsObjectValue, Object, Unknown}; use napi::{Env, Error, Result, Status, Task}; use napi_derive::napi; -use recipher_value_napi::{JsBuilder, JsCipherText, JsFault, JsRef, Wrappers}; +use recipher_value_napi::{JsBuilder, JsCipherText, JsFault, JsRef, Refusal, Wrappers}; use vitaminc_aead::seal::Cipher; use vitaminc_aead::{ decrypt, decrypt_into, encrypt, to_frame, CipherText, Context, DecryptError, Encrypt, @@ -73,6 +73,70 @@ 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"))?; + 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/json.cjs b/languages/typescript/packages/recipher-js/value-napi/tests/json.cjs new file mode 100644 index 000000000..bd8e6870e --- /dev/null +++ b/languages/typescript/packages/recipher-js/value-napi/tests/json.cjs @@ -0,0 +1,501 @@ +// JSON documents at the N-API boundary: a JavaScript value written as the +// text of a document (`JsRef::to_json`), and a document built as a +// JavaScript value (`JsBuilder::build_json`). The last section pins what +// napi-rs's own `serde_json` conversion does, which is why the bridge reads +// a value itself and writes arrays and objects itself. Run by tests/node.rs +// with the test addon's path. +const assert = require('node:assert/strict') +const path = require('node:path') +const addon = require(path.resolve(process.argv[2])) + +// 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, + 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 takes 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 holds any part of the value. + assert.ok(!/\d{6}/.test(refused.message), refused.message) +} + +// NaN and the infinities have no JSON form. JSON.stringify writes them as +// null, which would decrypt as another 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 RcDate = addon.RcDate +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/], + [new RcDate('2026-11-23'), /a date/], + [new addon.RcTimestamp('2026-11-23T01:02:03.000000001Z'), /a date/], + [new addon.RcDecimal('1.50'), /a decimal/], + [new addon.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. + [new 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 no value 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] +} +// A getter that throws surfaces as the error it threw, and is no 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, whole or not. +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: it 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)))) + +// --- What napi-rs's own conversion does --- +// +// The bridge uses napi-rs's conversion for a document's scalars only. These +// cases pin why. 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, and 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(new RcDate('2026-11-23')), + '{"value":"2026-11-23"}', +) +// An inherited property is read, and 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 one 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, and 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/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() From e0cc1c6856e5949fd9393b1c709129e0f383fd5a Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 16:17:00 +1100 Subject: [PATCH 08/25] refactor(recipher-js): the addon passes a JSON document between the bridge and the engine The addon's `json.rs` held 580 lines that converted a frame to a `serde_json::Value` and back, with the JavaScript number rules. The engine already takes a document, as `JsonPlaintext`, and the value bridge now reads and builds one. So the addon converts nothing. Encrypting: `json(..)` asks the bridge for the document's JSON text (`JsRef::to_json`) and keeps the text in the `Json`, in a buffer that is wiped when it drops. `encrypt` gives the text to the engine's parser (`JsonPlaintext::parse`), and the engine encrypts the document through the same single-value path as before. Text is the hand-off because the engine reads a document from text in every other SDK. Decrypting: the worker gives the decrypted text to the engine's parser (`read_json`), and the JavaScript thread asks the bridge to build the document (`JsBuilder::build_json`). A decrypted value is now an `Opened`: a frame, or a document. What is gone: the `ToJson` sink and its `Out` trait, `FromJson`, `walk`, `number_of`, the `float` and `integer` rules, and the addon's `NotJson` and `JsonTooDeep` errors. The bridge reports both refusals, under the same codes. `Json::of` has an example, and says why it returns an `Option` of a `Result`. `json(..)` has an example too, and its doc says what a caller sees: the number rules in both directions, that `json({ a: 5n })` decrypts as `{ a: 5 }`, and that an object's members come back sorted by key, which is how the engine stores them. The addon suite checks each rule through `keyset.encrypt(json(..))`. It reads the stored text back, so `json({ n: 5000000000 })` is pinned as `{"n":5000000000}`, the text a Go or a Rust reader takes as an integer. `native.d.ts` is regenerated for the `json` doc comment. --- .../__tests__/addon/values.test.ts | 233 ++++++- .../packages/recipher-js/crate/src/cipher.rs | 2 +- .../recipher-js/crate/src/ciphertext.rs | 19 +- .../recipher-js/crate/src/engine_tests.rs | 70 +- .../packages/recipher-js/crate/src/error.rs | 14 - .../packages/recipher-js/crate/src/js.rs | 54 +- .../packages/recipher-js/crate/src/json.rs | 625 ++++-------------- .../packages/recipher-js/native.d.ts | 37 +- 8 files changed, 495 insertions(+), 559 deletions(-) diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts index dbc6e3d7a..16200d392 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts @@ -246,10 +246,145 @@ describe('a JSON document', () => { }) }) - it('refuses a number that is an integer outside the safe range', async () => { + /** 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({ n: 2 ** 60 })) - expect(result.err()?.code).toBe('recipher_js::not_json') + 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 () => { + // A reader in Go or Rust takes `5000000000`, and refuses + // `5000000000.0`, for an integer field. + 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, 1e20]) + expect(JSON.parse(text as string)).toEqual([1.5, 2 ** 64, 1e20]) + // Each has a fraction or an exponent, so no reader takes 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() + // Sealed as the engine seals 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)]) { + const refused = await refusal({ n: unsafe }) + expect(refused.code).toBe('recipher_js::not_json') + expect(refused.message).toContain('bigint') + // The message holds no part of the value. + expect(refused.message).not.toMatch(/\d{6}/) + } + }) + + 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 () => { @@ -257,6 +392,91 @@ describe('a JSON document', () => { // @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'), + new RcDate('2031-04-01'), + new RcTimestamp('2031-04-01T00:00:00.000000001Z'), + new RcDecimal('4111.1111'), + new RcUuid('123e4567-e89b-12d3-a456-426614174000'), + ]) { + 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 () => { @@ -286,6 +506,7 @@ describe('a JSON document', () => { // 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 () => { @@ -307,7 +528,11 @@ describe('a JSON document', () => { 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}']) { + 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, sealed as the engine seals one: as its diff --git a/languages/typescript/packages/recipher-js/crate/src/cipher.rs b/languages/typescript/packages/recipher-js/crate/src/cipher.rs index 9284e8bb9..b22563791 100644 --- a/languages/typescript/packages/recipher-js/crate/src/cipher.rs +++ b/languages/typescript/packages/recipher-js/crate/src/cipher.rs @@ -350,7 +350,7 @@ fn open<'e>( move |env, opened| { let mut values = opened .into_iter() - .map(|value| js::build(env, value)) + .map(|value| js::build_opened(env, value)) .collect::>>()?; if many { return values.into_unknown(env).map_err(not_made); diff --git a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs index d2a91ea4b..1321f9879 100644 --- a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs +++ b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs @@ -12,6 +12,7 @@ use napi_derive::napi; use serde::Deserialize; 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}; @@ -36,6 +37,16 @@ pub struct Ciphertext { opens_as: Option, } +/// A decrypted value, before the addon builds it in JavaScript. Both forms +/// are plaintext, and 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`. When `opens_as` is `None`, the ciphertext decrypts as /// the type it was encrypted as. Otherwise it decrypts as that kind. @@ -66,11 +77,11 @@ impl Ciphertext { /// Returns `recipher_js::opened_type` for a value encrypted as another /// type. Returns `recipher_js::not_a_document` when the kind is JSON but /// the value is not a JSON document. - pub(crate) fn opened(&self, value: OwnedFrame) -> Outcome { + pub(crate) fn opened(&self, value: OwnedFrame) -> Outcome { match self.opens_as { - None => Ok(value), - Some(ValueKind::Json) => crate::json::opened(&value), - Some(kind) => as_kind(kind, value), + None => Ok(Opened::Value(value)), + Some(ValueKind::Json) => crate::json::opened(&value).map(Opened::Document), + Some(kind) => as_kind(kind, value).map(Opened::Value), } } } 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 04f27d49e..dd3a18da3 100644 --- a/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs +++ b/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs @@ -18,7 +18,7 @@ use stack_encrypt::{Encrypt, StackCipher}; use uuid::Uuid; use crate::cipher::{open_in, seal, unseal, Confined, Engine}; -use crate::ciphertext::Ciphertext; +use crate::ciphertext::{Ciphertext, Opened}; use crate::value::OneValue; const SEED: [u8; 32] = [7; 32]; @@ -104,7 +104,7 @@ async fn the_sdk_opens_what_the_engine_sealed_of_every_type() { } #[tokio::test] -async fn a_json_document_the_engine_sealed_opens_as_json_with_its_big_integer() { +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 @@ -113,40 +113,23 @@ async fn a_json_document_the_engine_sealed_opens_as_json_with_its_big_integer() .await .unwrap(); let ciphertext = Ciphertext::new(sealed.clone(), Some(ValueKind::Json)); - let opened = ciphertext.opened(sdk_open(sealed).await).unwrap(); - // A safe integer decrypts as a float, for a JavaScript `number`. An - // integer outside the safe range decrypts as an integer, for a - // JavaScript `bigint`. - let expected = crate::json::document(&opened).unwrap(); - assert_eq!( - expected.value(), - &serde_json::json!({"id": u64::MAX, "n": 5}) - ); - assert_eq!( - opened.frame(), - OwnedFrame::of(&OpenedDocument).unwrap().frame(), - "the opened frame holds `n` as a float and `id` as an integer" - ); + 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})); } -/// `{"id": u64::MAX, "n": 5.0}`, as the crate decrypts the document above. -struct OpenedDocument; - -impl Encrypt for &OpenedDocument { - fn visit(self, sink: S) -> Result { - use stack_encrypt::dynamic::plaintext::MapSink; - let mut map = sink.map(Some(2))?; - let _ = u64::MAX.visit(map.entry("id")?)?; - let _ = 5.0f64.visit(map.entry("n")?)?; - map.end() - } +/// Encrypts the document that `text` is the JSON text of, through the +/// crate, as `keyset.encrypt(json(..))` does once the bridge has written +/// the text. +async fn sdk_seal_json(text: &str) -> stack_encrypt::Ciphertext { + let document = crate::json::plaintext(text.as_bytes()).unwrap(); + sdk_seal(vec![OneValue::json(document)]).await.remove(0) } #[tokio::test] async fn a_json_document_the_sdk_sealed_is_the_engines_json_plaintext() { - let frame = OwnedFrame::of(&Document).unwrap(); - let document = crate::json::document(&frame).unwrap(); - let sealed = sdk_seal(vec![OneValue::json(document)]).await.remove(0); + let sealed = sdk_seal_json(r#"{"name":"Ada","age":36,"big":18446744073709551615}"#).await; let opened: JsonPlaintext = engine() .await .default_keyset() @@ -159,20 +142,19 @@ async fn a_json_document_the_sdk_sealed_is_the_engines_json_plaintext() { ); } -/// `{"name": "Ada", "age": 36.0, "big": u64::MAX}`, in the form a -/// JavaScript caller passes it: a number is a float, and a `bigint` is an -/// integer. -struct Document; - -impl Encrypt for &Document { - fn visit(self, sink: S) -> Result { - use stack_encrypt::dynamic::plaintext::MapSink; - let mut map = sink.map(Some(3))?; - let _ = "Ada".visit(map.entry("name")?)?; - let _ = 36.0f64.visit(map.entry("age")?)?; - let _ = u64::MAX.visit(map.entry("big")?)?; - map.end() - } +#[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] diff --git a/languages/typescript/packages/recipher-js/crate/src/error.rs b/languages/typescript/packages/recipher-js/crate/src/error.rs index dcc0d6a12..2abd818d7 100644 --- a/languages/typescript/packages/recipher-js/crate/src/error.rs +++ b/languages/typescript/packages/recipher-js/crate/src/error.rs @@ -64,16 +64,6 @@ pub(crate) enum Error { #[error("an object is not a value")] #[diagnostic(code(recipher_js::plain_object), help("Wrap it in json(..)."))] PlainObject, - /// A value that the engine cannot encrypt as a JSON document. - #[error("the value is not a JSON document the engine seals: {what}")] - #[diagnostic(code(recipher_js::not_json))] - NotJson { what: &'static str }, - /// A JSON document nested deeper than the engine's JSON parser reads. - #[error( - "the value is not a JSON document the engine seals: it is nested deeper than 127 levels of arrays and objects" - )] - #[diagnostic(code(recipher_js::too_deep))] - JsonTooDeep, /// The engine refused to encrypt a value in the form it was given. #[error("the engine could not seal the value as given")] #[diagnostic(code(recipher_js::not_sealed))] @@ -519,8 +509,6 @@ mod tests { Error::Threw, Error::NotAScalar, Error::PlainObject, - Error::NotJson { what: "bytes" }, - Error::JsonTooDeep, Error::NotSealed, Error::NotACiphertext, Error::NotBytes, @@ -542,8 +530,6 @@ mod tests { | Error::Threw | Error::NotAScalar | Error::PlainObject - | Error::NotJson { .. } - | Error::JsonTooDeep | Error::NotSealed | Error::NotACiphertext | Error::NotBytes diff --git a/languages/typescript/packages/recipher-js/crate/src/js.rs b/languages/typescript/packages/recipher-js/crate/src/js.rs index 81fb7f83c..8bd1c71d3 100644 --- a/languages/typescript/packages/recipher-js/crate/src/js.rs +++ b/languages/typescript/packages/recipher-js/crate/src/js.rs @@ -7,9 +7,14 @@ //! `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 -//! not convert any value itself. +//! 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. +//! +//! A JSON document goes through the bridge too. `JsRef::to_json` reads a +//! JavaScript value as the document's JSON text, and +//! `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 //! scalar is a value that is not an array or an object. For a scalar, the @@ -25,7 +30,9 @@ use napi::bindgen_prelude::{FromNapiValue, JsObjectValue, JsValue, Object, Unkno 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}; /// Reads a JavaScript value into a frame of the engine's value model. @@ -54,6 +61,30 @@ 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. /// @@ -91,6 +122,23 @@ pub fn build(env: &Env, value: OwnedFrame) -> Result, RecipherErrorF 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 { diff --git a/languages/typescript/packages/recipher-js/crate/src/json.rs b/languages/typescript/packages/recipher-js/crate/src/json.rs index 72ac85574..f59f1f3fc 100644 --- a/languages/typescript/packages/recipher-js/crate/src/json.rs +++ b/languages/typescript/packages/recipher-js/crate/src/json.rs @@ -1,71 +1,43 @@ -//! JSON documents: the [`Json`] class that `json(..)` makes, and the -//! conversion between a frame and the engine's [`JsonPlaintext`]. +//! JSON documents: the [`Json`] class that `json(..)` makes. //! -//! The engine is the Stack Encrypt engine, the `stack-encrypt` crate. The -//! engine's value model is the set of value types it reads. A frame is a -//! byte buffer that contains one value of the model. A sink receives a -//! value from a frame one part at a time: one scalar, array or map. +//! The engine is the Stack Encrypt engine, the `stack-encrypt` crate. It +//! encrypts a JSON document as the document's JSON text, through its +//! [`JsonPlaintext`] type. Rust and Go encrypt a document the same way, so +//! each SDK decrypts the documents of the others. //! -//! # Encrypting +//! The value bridge, the `recipher-value-napi` crate, converts between a +//! JavaScript value and a JSON document. This module converts nothing. It +//! passes the document between the bridge and the engine: //! -//! JavaScript has one number type, and a `number` cannot represent every -//! integer that a JSON document can. So a document's values become JSON -//! values by these rules: +//! - Encrypting. `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 parser, which makes the [`JsonPlaintext`] that the engine +//! encrypts. +//! - Decrypting. [`opened`] gives the decrypted text to the engine's +//! parser. The bridge then builds the JavaScript value of the document. //! -//! - An object, an array, text, a boolean and null stay as they are. -//! - A `number` that is a safe integer is written as that integer, as -//! `JSON.stringify` writes it. A safe integer is at most 2^53 - 1 from -//! zero. -//! - A whole `number` between 2^53 and 2^64 from zero is refused. The -//! caller probably meant an integer, and the `number`'s digits are not the -//! ones the caller wrote. -//! - Any other finite `number` is written as a float. -//! - A `bigint` is written as its digits. A `bigint` outside the 64-bit -//! range that the engine's parser reads is refused. -//! - Any other value is refused, because it has no JSON form. Examples are -//! bytes, a date, a timestamp, a decimal, a UUID and `undefined`. -//! - A document nested deeper than 127 levels is refused, because the -//! engine's parser would refuse it when the document is decrypted. -//! -//! # Decrypting -//! -//! An integer in the safe range becomes a `number`, and an integer outside -//! it becomes a `bigint`, so no digit is lost. A float becomes a `number`. -//! -//! The engine encrypts the document as its JSON text, through -//! [`JsonPlaintext`], and reads it back with the engine's JSON parser. -//! Everything built along the way, including map keys, is wiped when it is -//! dropped. +//! 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 serde_json::{Map, Number, Value}; use stack_encrypt::dynamic::frame::OwnedFrame; -use stack_encrypt::dynamic::plaintext::{ - Error as SinkError, FixedType, Float, Int, Logical, MapSink, Physical, SeqSink, Sink, - SourceError, -}; use stack_encrypt::dynamic::read_json; -use stack_encrypt::json::{wipe_value, JsonPlaintext}; -use stack_encrypt::{Encrypt, EncryptRef}; -use vitaminc_protected::OpaqueDebug; -use zeroize::Zeroizing; +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. +/// 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; -/// The largest integer that a JavaScript `number` represents exactly: -/// 2^53 - 1. -const MAX_SAFE: u64 = (1 << 53) - 1; - -/// 2^64: the smallest magnitude larger than every 64-bit integer. -const TWO_TO_64: f64 = 18_446_744_073_709_551_616.0; - /// A JSON document to encrypt as one ciphertext, as its JSON text. Nothing /// inside the document can be searched. Make one with `json(..)`. /// @@ -78,7 +50,8 @@ const TWO_TO_64: f64 = 18_446_744_073_709_551_616.0; #[napi] #[derive(OpaqueDebug)] pub struct Json { - document: Result, + /// The document's JSON text, or the reason `json(..)` refused it. + text: Result, } #[napi] @@ -91,9 +64,32 @@ impl Json { } impl Json { - /// Returns the document of `value` as a value to encrypt, when `value` - /// is a `Json`. Returns the failure instead when the document cannot be - /// encrypted. Returns `None` when `value` is not a `Json`. + /// Returns the document that `value` holds, when `value` is a `Json`. + /// + /// The result answers two questions, 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`, and this is its document. + /// + /// The `Option` says whether `value` is a `Json`. The `Result` says + /// whether that `Json`'s document can be encrypted. A single `Result` + /// could not tell "not a `Json`" from "a `Json` that was refused". + /// + /// `encrypt` calls it to choose how to read each value: + /// + /// ```ignore + /// let leaf = match Json::of(env, value) { + /// // `keyset.encrypt(json({ name: 'Ada' }))`: the document, or + /// // the refusal that `json(..)` kept. + /// Some(document) => OneValue::json(document?), + /// // `keyset.encrypt('Ada')`: any other value. + /// None => OneValue::scalar(js::read(env, value)?)?, + /// }; + /// ``` pub(crate) fn of( env: &Env, value: Unknown<'_>, @@ -106,477 +102,142 @@ impl Json { .map(|json| json.document()) } - /// Returns the document as a value to encrypt, or the failure that - /// stops it being encrypted. - pub(crate) fn document(&self) -> Result { - match &self.document { - // The copy is wiped when the `JsonPlaintext` that contains it - // drops. - Ok(document) => Ok(JsonPlaintext::from(document.value().clone())), - Err(error) => Err(error.clone()), + /// Returns the document as the engine's [`JsonPlaintext`], or the + /// refusal that `json(..)` kept. Each call parses the text again, so + /// each `encrypt` of one `Json` gets a document of its own to wipe. + fn document(&self) -> Result { + match &self.text { + Ok(text) => plaintext(text.risky_ref()), + Err(refusal) => Err(refusal.clone()), } } } -/// Makes a JSON document to encrypt as one ciphertext. The document is a -/// plain object, an array, text, a number, a `bigint`, a boolean or `null`, -/// nested at most 127 levels. +/// 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`. It nests at most 127 levels of arrays and objects. /// -/// Give an integer outside a `number`'s safe range as a `bigint`, within 64 -/// bits. The safe range is at most 2^53 - 1 from zero. A whole `number` -/// between 2^53 and 2^64 from zero is refused, because the caller probably -/// meant an integer. +/// A number is stored by these rules: +/// +/// - 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 is refused. Its digits may not +/// be the ones you wrote. Give it as a `bigint`. +/// - 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, +/// and are refused. /// /// `json(..)` reads the document now. `json(..)` never throws: `encrypt` /// returns an `Err` for a document that cannot be encrypted. #[napi(js_name = "json", ts_args_type = "document: JsonValue")] pub fn json_document(env: &Env, document: Unknown<'_>) -> Json { Json { - document: js::read(env, document).and_then(|frame| self::document(&frame)), - } -} - -/// The JSON sink returns the SDK's own errors: [`Error::NotJson`] or -/// [`Error::JsonTooDeep`]. Each has fixed text that includes no part of the -/// value. -impl SinkError for Error { - fn source(_: SourceError) -> Self { - Self::NotJson { - what: "it could not be read", - } - } -} - -/// Returns the document in a frame, as the engine's [`JsonPlaintext`]. -pub(crate) fn document(frame: &OwnedFrame) -> Result { - frame - .visit(ToJson { - out: Root, - depth: 0, - }) - .map(JsonPlaintext::from) - .map_err(RecipherErrorFields::from) -} - -/// Returns the value of a decrypted document's text, as a frame. The -/// conversion follows the rules in the module docs. -pub(crate) fn opened(frame: &OwnedFrame) -> Result { - let document = read_json(frame.frame()).map_err(|_| Error::NotADocument)?; - OwnedFrame::of(&FromJson(document.value())).map_err(|_| Error::BuildValue.into()) -} - -/// The place a built JSON value goes. -trait Out { - type Ok; - fn put(self, value: Value) -> Result; -} - -/// The built value is the result. -struct Root; - -impl Out for Root { - type Ok = Value; - fn put(self, value: Value) -> Result { - Ok(value) - } -} - -/// The built value is the next element of an array. -struct Element<'s>(&'s mut Vec); - -impl Out for Element<'_> { - type Ok = (); - fn put(self, value: Value) -> Result<(), Error> { - self.0.push(value); - Ok(()) - } -} - -/// The built value is the member `key` of an object. Until the key is in -/// the object, it is kept in a buffer that is wiped when dropped. So a -/// member that is refused, or dropped unfinished, leaves no copy of its key. -struct Member<'s> { - object: &'s mut Map, - key: Zeroizing, -} - -impl Out for Member<'_> { - type Ok = (); - fn put(mut self, value: Value) -> Result<(), Error> { - let key = std::mem::take(&mut *self.key); - let _ = self.object.insert(key, value); - Ok(()) - } -} - -/// A sink that builds a JSON value at `depth` levels of nesting, and passes -/// it to `O`. -struct ToJson { - out: O, - depth: usize, -} - -/// Returns the JSON number for a float, by the rules in the module docs. -fn float(value: f64) -> Result { - if !value.is_finite() { - return Err(Error::NotJson { - what: "a number that is not finite", - }); - } - let magnitude = value.abs(); - if value.fract() == 0.0 && magnitude <= MAX_SAFE as f64 { - // The value is a safe integer, so the conversion is exact. - #[allow(clippy::cast_possible_truncation)] - return Ok(Value::Number(Number::from(value as i64))); - } - if value.fract() == 0.0 && magnitude < TWO_TO_64 { - return Err(Error::NotJson { - what: "a whole number between 2^53 and 2^64 held as a number, whose digits may not be \ - the ones meant; use a bigint", - }); - } - Number::from_f64(value) - .map(Value::Number) - .ok_or(Error::NotJson { - what: "a number that is not finite", - }) -} - -/// Returns the JSON number for an integer. An integer outside the 64-bit -/// range is refused. -fn integer(value: Int) -> Result { - let wide = match value { - Int::I8(n) => i128::from(n), - Int::I16(n) => i128::from(n), - Int::I32(n) => i128::from(n), - Int::I64(n) => i128::from(n), - Int::I128(n) => n, - Int::U8(n) => i128::from(n), - Int::U16(n) => i128::from(n), - Int::U32(n) => i128::from(n), - Int::U64(n) => i128::from(n), - Int::U128(n) => i128::try_from(n).unwrap_or(i128::MAX), - }; - if let Ok(n) = i64::try_from(wide) { - return Ok(Value::Number(Number::from(n))); - } - if let Ok(n) = u64::try_from(wide) { - return Ok(Value::Number(Number::from(n))); - } - Err(Error::NotJson { - what: "a bigint outside the 64-bit range (below -2^63 or above 2^64 - 1)", - }) -} - -impl ToJson { - /// Returns the depth of an array or object that starts here. A depth - /// past the limit is refused. - fn nested(&self) -> Result { - let depth = self.depth + 1; - if depth > MAX_DEPTH { - return Err(Error::JsonTooDeep); - } - Ok(depth) - } -} - -impl Sink for ToJson { - type Ok = O::Ok; - type Error = Error; - type Seq = JsonArray; - type Map = JsonObject; - - fn scalar(self, ty: Option, value: Physical<'_>) -> Result { - let value = match (ty, value) { - (None, Physical::Null) => Value::Null, - (None, Physical::Bool(b)) => Value::Bool(b), - (None, Physical::Text(text)) => Value::String(text.to_owned()), - (None, Physical::Float(Float::F64(n))) => float(n)?, - (None, Physical::Float(Float::F32(n))) => float(f64::from(n))?, - (None, Physical::Int(n)) => integer(n)?, - (None, Physical::Bytes(_)) => return Err(Error::NotJson { what: "bytes" }), - (Some(Logical::Undefined), _) => return Err(Error::NotJson { what: "undefined" }), - (Some(_), _) => { - return Err(Error::NotJson { - what: "a date, a timestamp, a decimal or a UUID; write it as text", - }) - } - }; - self.out.put(value) - } - - fn typed_null(self, _: FixedType) -> Result { - self.out.put(Value::Null) - } - - fn seq(self, len: Option) -> Result, Error> { - let depth = self.nested()?; - Ok(JsonArray { - out: Some(self.out), - depth, - items: Vec::with_capacity(len.unwrap_or(0).min(1024)), - }) - } - - fn map(self, _: Option) -> Result, Error> { - let depth = self.nested()?; - Ok(JsonObject { - out: Some(self.out), - depth, - members: Map::new(), - }) - } - - fn passthrough(self, _: &P) -> Result { - Err(Error::NotJson { - what: "a passthrough", - }) - } -} - -/// An array being built. Its items are wiped if it is dropped unfinished. -struct JsonArray { - out: Option, - depth: usize, - items: Vec, -} - -impl Drop for JsonArray { - fn drop(&mut self) { - for item in &mut self.items { - wipe_value(item); - } - } -} - -impl SeqSink for JsonArray { - type Ok = O::Ok; - type Error = Error; - type Element<'s> - = ToJson> - where - Self: 's; - - fn element(&mut self) -> Result>, Error> { - Ok(ToJson { - out: Element(&mut self.items), - depth: self.depth, - }) - } - - fn end(mut self) -> Result { - let items = std::mem::take(&mut self.items); - match self.out.take() { - Some(out) => out.put(Value::Array(items)), - None => Err(Error::NotJson { - what: "it could not be read", - }), - } + text: js::read_json(env, document, MAX_DEPTH), } } -/// An object being built. Its members are wiped if it is dropped -/// unfinished. -struct JsonObject { - out: Option, - depth: usize, - members: Map, -} - -impl Drop for JsonObject { - fn drop(&mut self) { - let mut members = Value::Object(std::mem::take(&mut self.members)); - wipe_value(&mut members); - } -} - -impl MapSink for JsonObject { - type Ok = O::Ok; - type Error = Error; - type Entry<'s> - = ToJson> - where - Self: 's; - - fn entry(&mut self, key: &str) -> Result>, Error> { - Ok(ToJson { - out: Member { - object: &mut self.members, - key: Zeroizing::new(key.to_owned()), - }, - depth: self.depth, - }) - } - - fn end(mut self) -> Result { - let members = std::mem::take(&mut self.members); - match self.out.take() { - Some(out) => out.put(Value::Object(members)), - None => Err(Error::NotJson { - what: "it could not be read", - }), - } - } -} - -/// A JSON value, written into a sink by the rules in the module docs. -struct FromJson<'v>(&'v Value); - -impl Encrypt for &FromJson<'_> { - fn visit(self, sink: S) -> Result { - walk(self.0, sink) - } -} - -fn walk(value: &Value, sink: S) -> Result { - match value { - Value::Null => sink.scalar(None, Physical::Null), - Value::Bool(b) => sink.scalar(None, Physical::Bool(*b)), - Value::String(text) => sink.scalar(None, Physical::Text(text)), - Value::Number(number) => sink.scalar(None, number_of(number)), - Value::Array(items) => { - let mut seq = sink.seq(Some(items.len()))?; - for item in items { - walk(item, seq.element()?)?; - } - seq.end() - } - Value::Object(members) => { - let mut map = sink.map(Some(members.len()))?; - for (key, member) in members { - walk(member, map.entry(key)?)?; - } - map.end() - } - } +/// Returns the document that `text` is the JSON text of, as the value the +/// engine encrypts. +/// +/// # Errors +/// +/// Returns `recipher_js::not_sealed` for text that the engine's parser +/// refuses. The bridge writes no such text. +pub(crate) fn plaintext(text: &[u8]) -> Result { + std::str::from_utf8(text) + .ok() + .and_then(|text| JsonPlaintext::parse(text).ok()) + .ok_or_else(|| Error::NotSealed.into()) } -/// Returns a number in the form JavaScript reads it: a `number` for a float -/// or a safe integer, and a `bigint` for any other integer. -fn number_of(number: &Number) -> Physical<'static> { - if let Some(n) = number.as_i64() { - if n.unsigned_abs() <= MAX_SAFE { - // The integer is in the safe range, so the conversion is exact. - #[allow(clippy::cast_precision_loss)] - return Physical::Float(Float::F64(n as f64)); - } - return Physical::Int(Int::I64(n)); - } - if let Some(n) = number.as_u64() { - return Physical::Int(Int::U64(n)); - } - Physical::Float(Float::F64(number.as_f64().unwrap_or(f64::NAN))) +/// 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::{document, opened, MAX_DEPTH}; + use super::{opened, plaintext, MAX_DEPTH}; use serde_json::json; use stack_encrypt::dynamic::frame::OwnedFrame; - use stack_encrypt::json::JsonPlaintext; - - fn frame_of_text(text: &str) -> OwnedFrame { - OwnedFrame::of(text).unwrap() - } - - /// Arrays nested `.0` levels deep. The innermost array is empty. - struct Nested(usize); - - impl stack_encrypt::Encrypt for &Nested { - fn visit( - self, - sink: S, - ) -> Result { - use stack_encrypt::dynamic::plaintext::SeqSink; - let mut seq = sink.seq(Some(usize::from(self.0 > 1)))?; - if self.0 > 1 { - let _ = (&Nested(self.0 - 1)).visit(seq.element()?)?; - } - seq.end() - } - } - /// Returns a frame of `depth` nested arrays, each inside the one before. - fn nested(depth: usize) -> OwnedFrame { - OwnedFrame::of(&Nested(depth)).unwrap() + /// The text of `levels` arrays, each inside the one before. + fn nested(levels: usize) -> String { + format!("{}{}", "[".repeat(levels), "]".repeat(levels)) } #[test] - fn a_safe_integer_float_is_written_as_an_integer() { - let frame = OwnedFrame::of(vec![5.0f64, 1.5]).unwrap(); - assert_eq!(document(&frame).unwrap().value(), &json!([5, 1.5])); - } - - #[test] - fn a_whole_number_between_2_53_and_2_64_is_refused() { - let frame = OwnedFrame::of(9_007_199_254_740_993.0f64).unwrap(); - let error = document(&frame).unwrap_err(); - assert_eq!(error.code, "recipher_js::not_json"); - assert!(error.message.contains("bigint")); - } - - #[test] - fn a_large_float_is_written_as_a_float_and_reads_back_the_same() { - for value in [1e20f64, f64::MAX, -6.02e23] { - let written = document(&OwnedFrame::of(value).unwrap()).unwrap(); - assert_eq!(written.value().as_f64(), Some(value)); - // The engine's parser reads the text back as the same float. - let text = stack_encrypt::json::to_text(written.value()).unwrap(); - let read = JsonPlaintext::parse(std::str::from_utf8(&text).unwrap()).unwrap(); - assert_eq!(read.value().as_f64(), Some(value)); - } - } - - #[test] - fn a_bigint_is_written_as_its_digits_within_64_bits() { - let frame = OwnedFrame::of(u64::MAX).unwrap(); + fn the_text_of_a_document_is_the_document_the_engine_encrypts() { + let document = + plaintext(br#"{"n":5000000000,"big":18446744073709551615,"f":1.5}"#).unwrap(); assert_eq!( - document(&frame).unwrap().value(), - &json!(18_446_744_073_709_551_615u64) + document.value(), + &json!({"n": 5_000_000_000u64, "big": u64::MAX, "f": 1.5}) ); - assert!(document(&OwnedFrame::of(u128::MAX).unwrap()).is_err()); - assert!(document(&OwnedFrame::of(i128::MIN).unwrap()).is_err()); } #[test] - fn bytes_have_no_json_form() { - let frame = OwnedFrame::of(vec![1u8, 2, 3]).unwrap(); - assert_eq!(document(&frame).unwrap_err().code, "recipher_js::not_json"); + fn the_depth_limit_is_the_depth_the_engine_reads() { + assert!(plaintext(nested(MAX_DEPTH).as_bytes()).is_ok()); + let refused = plaintext(nested(MAX_DEPTH + 1).as_bytes()).unwrap_err(); + assert_eq!(refused.code, "recipher_js::not_sealed"); } #[test] - fn a_document_nests_as_deep_as_the_engine_reads_and_no_deeper() { - assert!(document(&nested(MAX_DEPTH)).is_ok()); - let refused = document(&nested(MAX_DEPTH + 1)).unwrap_err(); - assert_eq!(refused.code, "recipher_js::too_deep"); + fn text_the_engine_does_not_read_is_refused_without_the_text() { + for text in [ + &b"{not json"[..], + br#"{"a":1,"a":2}"#, + b"18446744073709551616", + b"\xff", + ] { + let refused = plaintext(text).unwrap_err(); + assert_eq!(refused.code, "recipher_js::not_sealed"); + assert!(!refused.message.contains("not json")); + } } #[test] - fn an_opened_integer_is_a_number_when_safe_and_an_integer_when_not() { - let opened = opened(&frame_of_text( - r#"{"small": 5, "big": 18446744073709551615, "f": 1.5}"#, - )) - .unwrap(); - // In the decrypted frame, the small integer is now a float, and the - // big one is still an integer. The frame reads back as the same - // document. - let read = document(&opened).unwrap(); + fn decrypted_text_opens_as_its_document() { + let text = + OwnedFrame::of(r#"{"small": 5, "big": 18446744073709551615, "f": 1e20}"#).unwrap(); assert_eq!( - read.value(), - &json!({"small": 5, "big": 18_446_744_073_709_551_615u64, "f": 1.5}) + opened(&text).unwrap().value(), + &json!({"small": 5, "big": u64::MAX, "f": 1e20}) ); } - #[test] - fn a_document_another_sdk_wrote_with_a_large_float_encrypts_again() { - let opened = opened(&frame_of_text(r#"{"x": 1e20}"#)).unwrap(); - assert_eq!(document(&opened).unwrap().value(), &json!({"x": 1e20})); - } - #[test] fn text_that_is_not_a_document_does_not_open() { - let error = opened(&frame_of_text("{not json")).unwrap_err(); + 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/native.d.ts b/languages/typescript/packages/recipher-js/native.d.ts index 31a65ac40..66b8b10bf 100644 --- a/languages/typescript/packages/recipher-js/native.d.ts +++ b/languages/typescript/packages/recipher-js/native.d.ts @@ -236,14 +236,37 @@ 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. The document is a - * plain object, an array, text, a number, a `bigint`, a boolean or `null`, - * nested at most 127 levels. + * Makes a JSON document to encrypt as one ciphertext. * - * Give an integer outside a `number`'s safe range as a `bigint`, within 64 - * bits. The safe range is at most 2^53 - 1 from zero. A whole `number` - * between 2^53 and 2^64 from zero is refused, because the caller probably - * meant an integer. + * ```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`. It nests at most 127 levels of arrays and objects. + * + * A number is stored by these rules: + * + * - 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 is refused. Its digits may not + * be the ones you wrote. Give it as a `bigint`. + * - 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, + * and are refused. * * `json(..)` reads the document now. `json(..)` never throws: `encrypt` * returns an `Err` for a document that cannot be encrypted. From 760206248aaa16970a084005ce2696eb63047ce2 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 16:19:05 +1100 Subject: [PATCH 09/25] fix(recipher-js): refuse a hole in the array given to encrypt or decrypt `js::elements` read every index of the array with `get_element` and never asked whether the index was an own property. A hole has none, so the read went to the prototype chain. With `Array.prototype[1] = 'injected'`, `keyset.encrypt(['a', , 'b'])` was `Ok` and decrypted to `['a', 'injected', 'b']`. In the same way, `cipher.decrypt([ct, , ct])` decrypted a ciphertext the caller never passed. With no pollution a hole was `recipher_js::undefined` or `not_a_ciphertext`, not the `sparse_array` refusal the README lists. Each index is now checked with `has_own_property` before it is read, as the bridge's walk does for an array inside a value, and a hole is `recipher_js::sparse_array`. The result is no longer allocated from the array's length, which JavaScript reports and `new Array(2 ** 32 - 1)` makes for free. Two tests fail without the fix: one for a hole, to encrypt and to decrypt, and one for a hole with a polluted `Array.prototype`. --- .../__tests__/addon/values.test.ts | 42 ++++++++++++++++++ .../packages/recipher-js/crate/src/js.rs | 43 ++++++++++++++----- 2 files changed, 75 insertions(+), 10 deletions(-) diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts index 16200d392..e65d3d639 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts @@ -213,6 +213,48 @@ describe('an array of values', () => { 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. diff --git a/languages/typescript/packages/recipher-js/crate/src/js.rs b/languages/typescript/packages/recipher-js/crate/src/js.rs index 8bd1c71d3..413368da1 100644 --- a/languages/typescript/packages/recipher-js/crate/src/js.rs +++ b/languages/typescript/packages/recipher-js/crate/src/js.rs @@ -90,9 +90,11 @@ pub fn read_json( /// /// # Errors /// -/// Returns the bridge's refusal, or `recipher_js::threw`, when an element -/// cannot be read. For example, an element behind a getter that throws -/// cannot be read. +/// 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>, @@ -101,13 +103,34 @@ pub fn elements<'e>( return None; } let array = Object::from_unknown(value).ok()?; - let read = || -> napi::Result>> { - let len = array.get_array_length()?; - (0..len) - .map(|at| array.get_element::>(at)) - .collect() - }; - Some(read().map_err(|error| refused(env, &error.into()))) + 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. From bb51af76b87f8453dfef21a208c8f640fa25da86 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 16:20:59 +1100 Subject: [PATCH 10/25] fix(recipher-js): Ciphertext.fromBytes takes only a kind the package exports `kind_of` accepted any name the engine's `ValueKind` parses, except `array` and `object`. So `Ciphertext.fromBytes(bytes, { name: 'uuid' })` was `Ok`, though `kinds` has no UUID kind and the method's doc promises `recipher_js::not_a_kind`. Every decrypt of that ciphertext then failed with `recipher_js::opened_type`. The addon now lists the kinds a stored ciphertext can be read as, and refuses any other name. A kind the engine adds later is refused until the package exports it. A test in the addon suite reads a ciphertext as every kind in `kinds`, and checks that the engine's other names are refused, so the Rust list and the TypeScript `kinds` cannot drift apart unseen. --- .../__tests__/addon/values.test.ts | 17 ++++++ .../recipher-js/crate/src/ciphertext.rs | 58 ++++++++++++++++++- 2 files changed, 73 insertions(+), 2 deletions(-) diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts index e65d3d639..9378a9e86 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts @@ -620,6 +620,23 @@ describe('a ciphertext read back with a kind', () => { const result = Ciphertext.fromBytes(bytes, { name: 'nothing' }) 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) + } + // 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('refusals', () => { diff --git a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs index 1321f9879..c2aea05f4 100644 --- a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs +++ b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs @@ -164,11 +164,34 @@ fn kind_of(env: &Env, value: Option>) -> Outcome> .name .parse::() .ok() - .filter(|kind| !matches!(kind, ValueKind::Array | ValueKind::Object)) + .filter(|kind| readable(*kind)) .ok_or(Error::NotAKind)?; Ok(Some(kind)) } +/// 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. fn integer(kind: ValueKind) -> bool { matches!( @@ -224,10 +247,41 @@ pub(crate) fn bytes_of(value: Unknown<'_>) -> Option> { #[cfg(test)] mod tests { - use super::as_kind; + use super::{as_kind, readable}; use stack_encrypt::dynamic::frame::OwnedFrame; use stack_encrypt::dynamic::ValueKind; + #[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(); From 629362b3f95471d39a58439a480ca15e529bf004 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 16:22:38 +1100 Subject: [PATCH 11/25] test(recipher-js): pin the help of every error the addon defines `an_error_of_the_sdks_own_has_its_code_message_and_help` once asserted the help of `not_a_ciphertext`, and now asserts that of `undefined`. So no test checked the help of `not_a_ciphertext`, `uuid`, `not_a_scalar`, `plain_object`, `no_testing`, `no_result` or `build_value`. A help could be dropped or reworded with no test failing. A new test checks the help of every variant: the text for a variant that has help, and none for a variant that leaves the caller nothing to do. Its match has no wildcard, so a new variant does not compile without an entry. --- .../packages/recipher-js/crate/src/error.rs | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/languages/typescript/packages/recipher-js/crate/src/error.rs b/languages/typescript/packages/recipher-js/crate/src/error.rs index 2abd818d7..c594d2dc7 100644 --- a/languages/typescript/packages/recipher-js/crate/src/error.rs +++ b/languages/typescript/packages/recipher-js/crate/src/error.rs @@ -545,6 +545,41 @@ 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("Use `null` for a value that is not there."), + Error::Uuid => Some("Encrypt its text instead."), + Error::NotAScalar | Error::PlainObject => Some("Wrap it in json(..)."), + Error::NotACiphertext => Some("Read stored bytes with Ciphertext.fromBytes."), + 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::NotSealed + | Error::NotBytes + | Error::NotAKind + | Error::OpenedType { .. } + | Error::NotADocument + | Error::TestingSeed => None, + } + } + + #[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(); From b1a38b01e0c416ddd2b7051c6a653b581ee339b2 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 16:23:25 +1100 Subject: [PATCH 12/25] docs(recipher-js): only Rust's keyset.encrypt writes the single-value form today Three doc comments said that Rust and Go write the same bytes as `keyset.encrypt` here. Go has no call that encrypts one value on its own, so the claim was true of Rust only. Each now names what does write that form: Rust's `keyset.encrypt`. The `Scalar` trait is `vitaminc-aead`'s, so the doc on `OneValue` names the crate. `native.d.ts` is regenerated for the `Ciphertext` class doc. --- .../packages/recipher-js/crate/src/ciphertext.rs | 2 +- .../packages/recipher-js/crate/src/json.rs | 4 ++-- .../packages/recipher-js/crate/src/value.rs | 14 +++++++------- .../typescript/packages/recipher-js/native.d.ts | 2 +- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs index c2aea05f4..142cdcd80 100644 --- a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs +++ b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs @@ -23,7 +23,7 @@ use crate::outcome::{failed, not_made, settle, Outcome}; /// 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 for two reasons. First, diff --git a/languages/typescript/packages/recipher-js/crate/src/json.rs b/languages/typescript/packages/recipher-js/crate/src/json.rs index f59f1f3fc..cd3ab1566 100644 --- a/languages/typescript/packages/recipher-js/crate/src/json.rs +++ b/languages/typescript/packages/recipher-js/crate/src/json.rs @@ -2,8 +2,8 @@ //! //! The engine is the Stack Encrypt engine, the `stack-encrypt` crate. It //! encrypts a JSON document as the document's JSON text, through its -//! [`JsonPlaintext`] type. Rust and Go encrypt a document the same way, so -//! each SDK decrypts the documents of the others. +//! [`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. It diff --git a/languages/typescript/packages/recipher-js/crate/src/value.rs b/languages/typescript/packages/recipher-js/crate/src/value.rs index e0c0f1a8a..55433eda2 100644 --- a/languages/typescript/packages/recipher-js/crate/src/value.rs +++ b/languages/typescript/packages/recipher-js/crate/src/value.rs @@ -20,15 +20,15 @@ use crate::error::{Error, RecipherErrorFields}; /// /// The engine encrypts the value through its opaque scalar path. That path /// encrypts a whole value as one leaf. Rust's `keyset.encrypt(value)` uses -/// the same path. So each ciphertext has the form that Rust and Go write -/// for the same value. +/// the same path. So each ciphertext has the form that Rust's +/// `keyset.encrypt` writes for the same value. /// /// The engine encrypts a value as one opaque leaf only when its type -/// implements `Scalar`, a trait of vitaminc, CipherStash's cryptography -/// library. An [`OwnedFrame`] can contain any value of the model, including -/// an array or a map. So an [`OwnedFrame`] is not a `Scalar`. This type -/// checks that the frame contains one scalar. The check runs once, before -/// the engine reads the value. +/// implements `Scalar`, a trait of the `vitaminc-aead` crate. An +/// [`OwnedFrame`] can contain any value of the model, including an array or +/// a map. So an [`OwnedFrame`] is not a `Scalar`. This type checks that the +/// frame contains one scalar. The check runs once, before the engine reads +/// the value. /// /// The opaque path also needs a value it can wipe (`Zeroize`). Wiping drops /// the value, and the value wipes its own buffer when it drops. `Debug` diff --git a/languages/typescript/packages/recipher-js/native.d.ts b/languages/typescript/packages/recipher-js/native.d.ts index 66b8b10bf..eb03f4fbe 100644 --- a/languages/typescript/packages/recipher-js/native.d.ts +++ b/languages/typescript/packages/recipher-js/native.d.ts @@ -88,7 +88,7 @@ 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 for two reasons. First, From 4f8179ae9947615660c46a6dd6daca09f5991a25 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 16:30:00 +1100 Subject: [PATCH 13/25] docs(recipher-js): the JSON rules as the bridge implements them The README's JSON section and the TypeScript docs described only part of what `json(..)` does, and only on the way in. They now give the rules in both directions, in one table: which numbers are stored as an integer, which as a float, which are refused, and what each decrypts as. They also say three things a caller would otherwise find out by surprise: - a whole number such as `5000000000` is stored as an integer, so code in Rust or Go can read it into an integer field; - `json({ a: 5n })` decrypts as `{ a: 5 }`, because an integer in the safe range comes back as a `number`; - a decrypted object lists its members sorted by key, because that is how the engine stores them. AGENTS.md says the bridge converts JSON documents and the addon's `json.rs` holds only the `Json` class, and that a wrapper class's constructor throws for an argument that is not a string. --- AGENTS.md | 2 +- .../typescript/packages/recipher-js/README.md | 51 +++++++++++++++---- .../packages/recipher-js/src/value-types.ts | 13 +++-- .../packages/recipher-js/src/values.ts | 17 ++++++- 4 files changed, 67 insertions(+), 16 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0b93fd6c3..c72acf0e6 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`, `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). 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), stand-ins for a build that did not load, and the types the generated signatures name (`src/kinds.ts`, `src/value-types.ts`). `native.d.ts` imports those types, so a module it imports from must never load the addon: the declarations would import themselves and tsup's declaration build fails. 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, and `JsBuilder::build_json` builds a decrypted document): the addon's `json.rs` holds 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/`) holds only `Result`, `RecipherError`, the loader (`src/binding.ts`, which hands the addon the `Ok`, `Err` and `RecipherError` classes), stand-ins for a build that did not load, and the types the generated signatures name (`src/kinds.ts`, `src/value-types.ts`). `native.d.ts` imports those types, so a module it imports from must never load the addon: the declarations would import themselves and tsup's declaration build fails. A method called without its object throws a `TypeError` (#1801), and so does a wrapper class's constructor (`new RcDate(..)`) given anything but a string; 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/languages/typescript/packages/recipher-js/README.md b/languages/typescript/packages/recipher-js/README.md index fed5fb9f6..2891ac233 100644 --- a/languages/typescript/packages/recipher-js/README.md +++ b/languages/typescript/packages/recipher-js/README.md @@ -95,18 +95,49 @@ const opened = await cipher.decrypt(sealed.unwrap()) `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. -- An integer outside a `number`'s safe range is a `bigint`. - The `bigint` must be in the 64-bit range that the engine's parser reads: `-(2n ** 63n)` to `2n ** 64n - 1n`. - A `bigint` outside that range is refused. -- A whole `number` is refused when its absolute value is at least 2^53 but less than 2^64. - An integer was likely meant. - The `number` does not keep the digits that were written. +```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`. +It can nest 127 levels of arrays and objects. + +A number is stored and decrypted by these rules: + +| 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 | refused | | +| 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 | | + +- 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`. + It is never stored as `1764288000000.0`, which code in Rust or Go refuses for an integer field. +- A whole `number` from 2^53 up to 2^64 is refused, either side of zero. + A `number` that large may not keep the digits you wrote. Use a `bigint` instead. - Any other finite `number`, such as `1e20`, is a float. -- Bytes, a `Date`, the wrapper classes, and `undefined` have no JSON form. - The package refuses them. - The package also refuses a document nested deeper than 127 levels. +- 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`. +- A document is read by the same rules as 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`. diff --git a/languages/typescript/packages/recipher-js/src/value-types.ts b/languages/typescript/packages/recipher-js/src/value-types.ts index 6ed8e152c..d7f5df587 100644 --- a/languages/typescript/packages/recipher-js/src/value-types.ts +++ b/languages/typescript/packages/recipher-js/src/value-types.ts @@ -61,9 +61,12 @@ export type Scalar = /** * A JSON value. An integer outside the safe range of a `number` is a * `bigint`, within the 64-bit range (`-(2n ** 63n)` to `2n ** 64n - 1n`). + * The safe range is 2^53 - 1 either side of zero. * - * `encrypt` refuses a whole `number` whose absolute value is at least 2^53 - * but less than 2^64. An integer was likely meant. + * A whole `number` in the safe range is stored as an integer, and any other + * `number` as a float. `encrypt` refuses a whole `number` whose absolute + * value is at least 2^53 but less than 2^64, because it may not keep the + * digits that were written. `encrypt` also refuses `NaN` and the infinities. */ export type JsonValue = | null @@ -74,7 +77,11 @@ export type JsonValue = | readonly JsonValue[] | { readonly [key: string]: JsonValue } -/** A JSON document as it decrypts. */ +/** + * 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 members of an + * object are sorted by key. + */ export type OpenedJson = | null | boolean diff --git a/languages/typescript/packages/recipher-js/src/values.ts b/languages/typescript/packages/recipher-js/src/values.ts index 446c7b668..636806515 100644 --- a/languages/typescript/packages/recipher-js/src/values.ts +++ b/languages/typescript/packages/recipher-js/src/values.ts @@ -147,9 +147,22 @@ export type JsonFunction = Binding['json'] * 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 is + * refused: give it as a `bigint`. A `bigint` is stored as its exact digits, + * within 64 bits. + * + * 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 bytes or a `Date`, and a - * document nested deeper than 127 levels. + * `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 From e69aba2812db27feee57f7acb557e1dea4379d5d Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 16:49:42 +1100 Subject: [PATCH 14/25] test(recipher-js): pin the depth limit of a JSON document the bridge builds `JsBuilder::build_json` stops at the bridge's depth limit, so a document that no parser has bounded cannot overflow the stack. No test reached that check: the test addon parsed its documents with `serde_json`, which stops at 127 levels, below the limit of 128. A mutation run over the bridge's new code showed it. Four mutants of `json_to_js` survived: the comparison with the limit, twice, and the step to the next level, for an array and for an object. The test addon now builds a nested document itself, and the Node suite builds 128 levels and is refused at 129, for arrays and for objects. All four mutants are caught. --- .../value-napi/tests/addon/src/lib.rs | 24 ++++++++++++++++++- .../recipher-js/value-napi/tests/json.cjs | 14 +++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) 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 e7ac29f8a..8bd85133a 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 @@ -109,8 +109,30 @@ fn refusal_code(refusal: &Refusal) -> 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) +} + +/// `levels` JSON containers of one `wrap` kind ("array" or "object") +/// around `true`, built here and then built as a JavaScript value. A +/// parser would refuse the deepest of these documents, so the build's own +/// depth limit is what 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) { + match JsBuilder::build_json(env, document) { Ok(value) => out.set_named_property("value", value)?, Err(fault) => match fault.refusal() { Some(refusal) => { diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/json.cjs b/languages/typescript/packages/recipher-js/value-napi/tests/json.cjs index bd8e6870e..70b577ffd 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/json.cjs +++ b/languages/typescript/packages/recipher-js/value-napi/tests/json.cjs @@ -416,6 +416,20 @@ 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 --- // From c378520bef4a66d4eb88d70b6bd0b0772e1683a3 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 16:49:43 +1100 Subject: [PATCH 15/25] docs(recipher-js): "An RcUuid", in the doc of the addon's uuid error The rename left the article of the old name. --- languages/typescript/packages/recipher-js/crate/src/error.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/languages/typescript/packages/recipher-js/crate/src/error.rs b/languages/typescript/packages/recipher-js/crate/src/error.rs index c594d2dc7..0870d7f28 100644 --- a/languages/typescript/packages/recipher-js/crate/src/error.rs +++ b/languages/typescript/packages/recipher-js/crate/src/error.rs @@ -40,7 +40,7 @@ pub(crate) enum Error { help("Use `null` for a value that is not there.") )] Undefined, - /// A `RcUuid`. The engine's value model, the set of value types the + /// An `RcUuid`. The engine's value model, the set of value types the /// engine reads, has no UUID type. #[error("a UUID cannot be encrypted yet: the engine's value model does not hold one")] #[diagnostic(code(recipher_js::uuid), help("Encrypt its text instead."))] From e9ad2aa2e10b73d9312eddc2846fcc5fe7785fe8 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 19:11:44 +1100 Subject: [PATCH 16/25] docs(recipher-js): plain language for the values and JSON prose Rewrite the comments, doc comments and Markdown that the values work added, so that each passes the plain-language checker. No code changes. - One idea in each sentence, and lists for parallel cases. - Each term is defined where a doc first uses it: engine, value bridge, walk, frame, kind, wrapper class, safe range. - Things have literal verbs: a document "contains" a value. - The value bridge's README is rewritten in full, with headings for the safety rules. - `native.d.ts` is regenerated, because the build copies the doc comments of the `#[napi]` items into it. - The addon's crate docs no longer link to the private `js` module, so `cargo doc` with warnings denied passes. --- AGENTS.md | 2 +- conformance/vitaminc-aead/README.md | 10 +- .../typescript/packages/recipher-js/README.md | 47 +- .../__tests__/addon/builds.test.ts | 16 +- .../__tests__/addon/values.test.ts | 21 +- .../recipher-js/__tests__/unit/values.test.ts | 2 +- .../packages/recipher-js/crate/Cargo.toml | 15 +- .../recipher-js/crate/src/ciphertext.rs | 32 +- .../recipher-js/crate/src/engine_tests.rs | 6 +- .../packages/recipher-js/crate/src/js.rs | 24 +- .../packages/recipher-js/crate/src/json.rs | 52 +- .../packages/recipher-js/crate/src/lib.rs | 26 +- .../packages/recipher-js/crate/src/value.rs | 2 +- .../packages/recipher-js/native-header.d.ts | 9 +- .../packages/recipher-js/native.d.ts | 46 +- .../packages/recipher-js/src/cipher.ts | 9 +- .../packages/recipher-js/src/error.ts | 21 +- .../packages/recipher-js/src/index.ts | 10 +- .../packages/recipher-js/src/kinds.ts | 15 +- .../packages/recipher-js/src/value-types.ts | 37 +- .../packages/recipher-js/src/values.ts | 65 +- .../packages/recipher-js/type-tests/values.ts | 9 +- .../recipher-js/value-napi/Cargo.toml | 16 +- .../packages/recipher-js/value-napi/README.md | 593 +++++++++++------- .../recipher-js/value-napi/src/error.rs | 13 +- .../packages/recipher-js/value-napi/src/js.rs | 2 +- .../recipher-js/value-napi/src/js_ref.rs | 94 +-- .../recipher-js/value-napi/src/json.rs | 144 +++-- .../recipher-js/value-napi/src/scalar.rs | 38 +- .../recipher-js/value-napi/src/wrappers.rs | 42 +- .../value-napi/tests/addon/Cargo.toml | 2 +- .../value-napi/tests/addon/src/lib.rs | 8 +- .../recipher-js/value-napi/tests/json.cjs | 59 +- .../value-napi/tests/value-conformance.cjs | 4 +- 34 files changed, 879 insertions(+), 612 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c72acf0e6..584162db1 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`, `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, and `JsBuilder::build_json` builds a decrypted document): the addon's `json.rs` holds 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/`) holds only `Result`, `RecipherError`, the loader (`src/binding.ts`, which hands the addon the `Ok`, `Err` and `RecipherError` classes), stand-ins for a build that did not load, and the types the generated signatures name (`src/kinds.ts`, `src/value-types.ts`). `native.d.ts` imports those types, so a module it imports from must never load the addon: the declarations would import themselves and tsup's declaration build fails. A method called without its object throws a `TypeError` (#1801), and so does a wrapper class's constructor (`new RcDate(..)`) given anything but a string; 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 calls throw a `TypeError`: a method called without its object (#1801), and a wrapper class's constructor given anything but a string, as in `new RcDate(20261123)`. 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 1848ed7d0..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 an `RcTimestamp` 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/README.md b/languages/typescript/packages/recipher-js/README.md index 2891ac233..7ad658e8c 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. @@ -49,14 +50,14 @@ const opened = await cipher.decrypt(sealed.value) 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/`. -It converts JavaScript values in both directions: +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 holds it | `bigint` | +| `bigint` | an integer, at the narrowest width that fits it | `bigint` | | `Uint8Array`, `Buffer` | bytes | `Uint8Array` | | `Date` | a timestamp | `Date` | | `new RcTimestamp('2026-11-23T01:02:03.000000001Z')` | a timestamp, in nanoseconds | `Date` when it is whole milliseconds, else `RcTimestamp` | @@ -65,13 +66,16 @@ It converts JavaScript values in both directions: | `null` | null | `null` | | `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. + The constructor of a wrapper class takes the value as text. - Integers are a `bigint`. A `number` is a float. The `number` `5` does not equal the integer `5n`. - 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(..)` will encrypt a whole object in the engine's own format, and is not built yet. + `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). The engine has no plaintext type for a UUID yet. Encrypting an `RcUuid` is an `Err` with the code `recipher_js::uuid`. @@ -108,22 +112,23 @@ const opened = (await cipher.decrypt(sealed)).unwrap() ``` A document is a plain object, an array, a string, a number, a `bigint`, a boolean, or `null`. -It can nest 127 levels of arrays and objects. +A document can nest 127 levels of arrays and objects. -A number is stored and decrypted by these rules: +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 | refused | | +| a whole `number` from 2^53 up to 2^64 | refused | 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 | | +| 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`. - It is never stored as `1764288000000.0`, which code in Rust or Go refuses for an integer field. + 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 is refused, either side of zero. A `number` that large may not keep the digits you wrote. Use a `bigint` instead. @@ -136,13 +141,14 @@ A number is stored and decrypted by these rules: 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`. -- A document is read by the same rules as any value. +- 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. @@ -175,6 +181,7 @@ 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. `ciphertexts.map(cipher.decrypt)` passes `decrypt` on its own, without its cipher. @@ -212,7 +219,7 @@ if (opened.isErr()) { | --- | --- | | `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`. | @@ -249,14 +256,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, gives `Ciphertext` its type parameter, and marks `Json` so that no other object type-checks as one. -The modules it imports types from never load the addon, so the declarations never import themselves. `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. @@ -271,7 +286,7 @@ 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 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 2fb4d4482..d09a1bd7c 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/builds.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/builds.test.ts @@ -1,10 +1,14 @@ /** - * 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. And the package with no native build at all. Each 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 { cpSync, existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts index 9378a9e86..6bc33ebb9 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts @@ -97,7 +97,7 @@ describe('every value in the mapping round-trips', () => { expect(fine).toBeInstanceOf(RcTimestamp) expect((fine as RcTimestamp).value).toBe('2026-11-23T01:02:03.000000001Z') - // A timestamp of whole milliseconds opens as a Date. + // A timestamp of whole milliseconds decrypts as a Date. const whole = await roundTrip(new RcTimestamp('2026-11-23T01:02:03.000Z')) expect(whole).toBeInstanceOf(Date) @@ -281,7 +281,8 @@ describe('a JSON document', () => { 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 as a bigint. + // 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, @@ -306,8 +307,8 @@ describe('a JSON document', () => { } it('stores a whole number as an integer, at every size', async () => { - // A reader in Go or Rust takes `5000000000`, and refuses - // `5000000000.0`, for an integer field. + // 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}}`) @@ -327,7 +328,7 @@ describe('a JSON document', () => { it('stores any other number as a float', async () => { const text = await storedText([1.5, 2 ** 64, 1e20]) expect(JSON.parse(text as string)).toEqual([1.5, 2 ** 64, 1e20]) - // Each has a fraction or an exponent, so no reader takes an integer. + // 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]/) } @@ -387,7 +388,7 @@ describe('a JSON document', () => { it('opens a document another SDK wrote, whatever its numbers', async () => { const c = await cipher() const keyset = c.defaultKeyset() - // Sealed as the engine seals a document: as its JSON text. + // 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}', @@ -407,7 +408,7 @@ describe('a JSON document', () => { const refused = await refusal({ n: unsafe }) expect(refused.code).toBe('recipher_js::not_json') expect(refused.message).toContain('bigint') - // The message holds no part of the value. + // The message contains no part of the value. expect(refused.message).not.toMatch(/\d{6}/) } }) @@ -577,8 +578,8 @@ describe('a JSON document', () => { ]) { const refused = await keyset.encrypt(json(JSON.parse(text))) expect(refused.err()?.code).toBe('recipher_js::reserved_key') - // A document another SDK wrote, sealed as the engine seals one: as its - // JSON text. + // 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) @@ -616,7 +617,7 @@ describe('a ciphertext read back with a kind', () => { it('refuses something that is not a kind', () => { const bytes = new Uint8Array(4) - // A kind is plain data, so this compiles; the build checks the name. + // 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') }) diff --git a/languages/typescript/packages/recipher-js/__tests__/unit/values.test.ts b/languages/typescript/packages/recipher-js/__tests__/unit/values.test.ts index 4e41cd550..5fb635c6d 100644 --- a/languages/typescript/packages/recipher-js/__tests__/unit/values.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/unit/values.test.ts @@ -1,5 +1,5 @@ /** - * The stand-in wrapper classes, which take the place of the addon's classes + * 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 { inspect } from 'node:util' diff --git a/languages/typescript/packages/recipher-js/crate/Cargo.toml b/languages/typescript/packages/recipher-js/crate/Cargo.toml index 63d04c62c..f09e93bd7 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 the value bridge'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. @@ -49,14 +50,14 @@ serde_json = "1" # The engine's opaque path wipes a value it did not seal. The version the # engine resolves. zeroize = "1" -# A kind named to `Ciphertext.fromBytes`, read from its frame through the -# frame's serde. +# 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 seal through the engine's typed API, +# 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 } diff --git a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs index 142cdcd80..d2e9e8832 100644 --- a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs +++ b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs @@ -38,7 +38,7 @@ pub struct Ciphertext { } /// A decrypted value, before the addon builds it in JavaScript. Both forms -/// are plaintext, and both are wiped when they drop. +/// 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. @@ -75,8 +75,8 @@ impl Ciphertext { /// # Errors /// /// Returns `recipher_js::opened_type` for a value encrypted as another - /// type. Returns `recipher_js::not_a_document` when the kind is JSON but - /// the value is not a JSON document. + /// 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 { match self.opens_as { None => Ok(Opened::Value(value)), @@ -88,21 +88,25 @@ impl Ciphertext { #[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. /// - /// Give a kind, such as `kinds.string`, to decrypt the value as that - /// kind. Decrypting then refuses a value encrypted as another type. + /// 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. /// /// 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 - /// bytes are not a `Uint8Array`, and `recipher_js::not_a_kind` when the - /// kind is not one of `kinds`. 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`. #[napi( ts_type = "(bytes: Uint8Array, kind: K): Result>, RecipherError> static fromBytes(bytes: Uint8Array): Result" @@ -233,9 +237,9 @@ fn as_kind(kind: ValueKind, value: OwnedFrame) -> Outcome { /// value. A `Buffer` is a `Uint8Array`. /// /// The function reads the bytes as a borrowed slice. That is how the value -/// bridge 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. +/// 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; 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 dd3a18da3..a66c6975f 100644 --- a/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs +++ b/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs @@ -119,9 +119,9 @@ async fn a_json_document_the_engine_sealed_opens_as_that_document() { assert_eq!(opened.value(), &serde_json::json!({"id": u64::MAX, "n": 5})); } -/// Encrypts the document that `text` is the JSON text of, through the -/// crate, as `keyset.encrypt(json(..))` does once the bridge has written -/// the text. +/// 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 { let document = crate::json::plaintext(text.as_bytes()).unwrap(); sdk_seal(vec![OneValue::json(document)]).await.remove(0) diff --git a/languages/typescript/packages/recipher-js/crate/src/js.rs b/languages/typescript/packages/recipher-js/crate/src/js.rs index 413368da1..36b4a6464 100644 --- a/languages/typescript/packages/recipher-js/crate/src/js.rs +++ b/languages/typescript/packages/recipher-js/crate/src/js.rs @@ -4,17 +4,18 @@ //! 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. +//! `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 JSON document goes through the bridge too. `JsRef::to_json` reads a -//! JavaScript value as the document's JSON text, and -//! `JsBuilder::build_json` builds the JavaScript value of a decrypted -//! document. This module does not convert any value itself. +//! 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 //! scalar is a value that is not an array or an object. For a scalar, the @@ -151,7 +152,8 @@ pub fn build(env: &Env, value: OwnedFrame) -> Result, RecipherErrorF /// # Errors /// /// Returns the errors of [`build`]. A document with a member named -/// `__proto__`, `constructor` or `prototype` is `recipher_js::reserved_key`. +/// `__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), diff --git a/languages/typescript/packages/recipher-js/crate/src/json.rs b/languages/typescript/packages/recipher-js/crate/src/json.rs index cd3ab1566..f4eab84dd 100644 --- a/languages/typescript/packages/recipher-js/crate/src/json.rs +++ b/languages/typescript/packages/recipher-js/crate/src/json.rs @@ -1,19 +1,19 @@ //! JSON documents: the [`Json`] class that `json(..)` makes. //! -//! The engine is the Stack Encrypt engine, the `stack-encrypt` crate. It -//! encrypts a JSON document as the document's JSON text, through its +//! 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. It -//! passes the document between the bridge and the engine: +//! JavaScript value and a JSON document. This module converts nothing. This +//! module passes the document between the bridge and the engine: //! -//! - Encrypting. `json(..)` asks the bridge for the document's JSON text, +//! - 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 parser, which makes the [`JsonPlaintext`] that the engine -//! encrypts. -//! - Decrypting. [`opened`] gives the decrypted text to the engine's +//! engine's parser. The parser makes the [`JsonPlaintext`] that the +//! engine 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 @@ -64,22 +64,23 @@ impl Json { } impl Json { - /// Returns the document that `value` holds, when `value` is a `Json`. + /// Returns the document in `value`, when `value` is a `Json`. /// - /// The result answers two questions, so it has three cases: + /// 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`, and this is its document. + /// - `Some(Ok(..))`: `value` is a `Json`. The result contains its + /// document. /// - /// The `Option` says whether `value` is a `Json`. The `Result` says - /// whether that `Json`'s document can be encrypted. A single `Result` + /// 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 it to choose how to read each value: + /// `encrypt` calls this function to choose how to read each value: /// /// ```ignore /// let leaf = match Json::of(env, value) { @@ -123,14 +124,15 @@ impl Json { /// ``` /// /// The document is a plain object, an array, text, a number, a `bigint`, a -/// boolean or `null`. It nests at most 127 levels of arrays and objects. +/// boolean, or `null`. A document nests at most 127 levels of arrays and +/// objects. /// -/// A number is stored by these rules: +/// 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 is refused. Its digits may not -/// be the ones you wrote. Give it as a `bigint`. +/// - A whole `number` from 2^53 up to 2^64 is refused. A `number` that +/// large may not keep the digits you wrote. Pass a `bigint` instead. /// - 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. @@ -142,11 +144,11 @@ impl Json { /// 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, -/// and are refused. +/// `undefined`, bytes, a `Date`, and the wrapper classes have no JSON form. +/// Each one is refused. /// -/// `json(..)` reads the document now. `json(..)` never throws: `encrypt` -/// returns an `Err` for a document that cannot be encrypted. +/// `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 { @@ -154,8 +156,8 @@ pub fn json_document(env: &Env, document: Unknown<'_>) -> Json { } } -/// Returns the document that `text` is the JSON text of, as the value the -/// engine encrypts. +/// Parses `text`, the JSON text of a document, into the value the engine +/// encrypts. /// /// # Errors /// @@ -168,7 +170,7 @@ pub(crate) fn plaintext(text: &[u8]) -> Result u32 { } /// Exports the value bridge's wrapper classes: `RcDate`, `RcTimestamp`, -/// `RcDecimal` and `RcUuid`. Each class stands for a type that JavaScript -/// does not have. The addon exports them so JavaScript can construct them, -/// and so decrypted values are instances of them. +/// `RcDecimal`, and `RcUuid`. Each class represents a type that JavaScript +/// does not have. The addon exports the classes so that JavaScript can +/// construct them. 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))] diff --git a/languages/typescript/packages/recipher-js/crate/src/value.rs b/languages/typescript/packages/recipher-js/crate/src/value.rs index 55433eda2..9a44eb73e 100644 --- a/languages/typescript/packages/recipher-js/crate/src/value.rs +++ b/languages/typescript/packages/recipher-js/crate/src/value.rs @@ -16,7 +16,7 @@ use crate::error::{Error, RecipherErrorFields}; /// /// The value model is the set of value types the engine reads. A scalar is /// a value of the model that is not an array or a map, such as text, a -/// number or bytes. +/// number, or bytes. /// /// The engine encrypts the value through its opaque scalar path. That path /// encrypts a whole value as one leaf. Rust's `keyset.encrypt(value)` uses diff --git a/languages/typescript/packages/recipher-js/native-header.d.ts b/languages/typescript/packages/recipher-js/native-header.d.ts index f46b05b92..aa384aed7 100644 --- a/languages/typescript/packages/recipher-js/native-header.d.ts +++ b/languages/typescript/packages/recipher-js/native-header.d.ts @@ -21,9 +21,12 @@ declare const opens: unique symbol /** * `T` is the type the ciphertext decrypts to. For example, - * `keyset.encrypt('..')` returns a `Ciphertext`. A ciphertext read - * from stored bytes with no kind named decrypts to whatever type was - * encrypted, so its type allows any scalar. + * `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 interface Ciphertext { /** Stores `T` for the type checker. The property never exists at run time. */ diff --git a/languages/typescript/packages/recipher-js/native.d.ts b/languages/typescript/packages/recipher-js/native.d.ts index eb03f4fbe..c51aa318c 100644 --- a/languages/typescript/packages/recipher-js/native.d.ts +++ b/languages/typescript/packages/recipher-js/native.d.ts @@ -21,9 +21,12 @@ declare const opens: unique symbol /** * `T` is the type the ciphertext decrypts to. For example, - * `keyset.encrypt('..')` returns a `Ciphertext`. A ciphertext read - * from stored bytes with no kind named decrypts to whatever type was - * encrypted, so its type allows any scalar. + * `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 interface Ciphertext { /** Stores `T` for the type checker. The property never exists at run time. */ @@ -98,21 +101,25 @@ export declare class Cipher { */ 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. * - * Give a kind, such as `kinds.string`, to decrypt the value as that - * kind. Decrypting then refuses a value encrypted as another type. + * 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. * * 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 - * bytes are not a `Uint8Array`, and `recipher_js::not_a_kind` when the - * kind is not one of `kinds`. 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`. */ static fromBytes(bytes: Uint8Array, kind: K): Result>, RecipherError> static fromBytes(bytes: Uint8Array): Result @@ -246,14 +253,15 @@ export declare function installResult(classes: { Ok: typeof Ok; Err: typeof Err; * ``` * * The document is a plain object, an array, text, a number, a `bigint`, a - * boolean or `null`. It nests at most 127 levels of arrays and objects. + * boolean, or `null`. A document nests at most 127 levels of arrays and + * objects. * - * A number is stored by these rules: + * 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 is refused. Its digits may not - * be the ones you wrote. Give it as a `bigint`. + * - A whole `number` from 2^53 up to 2^64 is refused. A `number` that + * large may not keep the digits you wrote. Pass a `bigint` instead. * - 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. @@ -265,11 +273,11 @@ export declare function installResult(classes: { Ok: typeof Ok; Err: typeof Err; * 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, - * and are refused. + * `undefined`, bytes, a `Date`, and the wrapper classes have no JSON form. + * Each one is refused. * - * `json(..)` reads the document now. `json(..)` never throws: `encrypt` - * returns an `Err` for a document that cannot be encrypted. + * `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 diff --git a/languages/typescript/packages/recipher-js/src/cipher.ts b/languages/typescript/packages/recipher-js/src/cipher.ts index 559fe9449..53c1d7c44 100644 --- a/languages/typescript/packages/recipher-js/src/cipher.ts +++ b/languages/typescript/packages/recipher-js/src/cipher.ts @@ -22,9 +22,12 @@ 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 ciphertext read - * from stored bytes with no kind named decrypts to whatever type was - * encrypted, so its type allows any scalar. + * `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 /** A cipher: the Stack Encrypt engine, and the keysets it can use. */ diff --git a/languages/typescript/packages/recipher-js/src/error.ts b/languages/typescript/packages/recipher-js/src/error.ts index 94fd3a955..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`; + * - `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 b1019d7a3..e7971d155 100644 --- a/languages/typescript/packages/recipher-js/src/index.ts +++ b/languages/typescript/packages/recipher-js/src/index.ts @@ -16,16 +16,18 @@ * 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. * * 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 wrapper class's constructor, such as `new RcDate(..)`, also throws a - * `TypeError` when its argument is not a string. + * A wrapper class represents a type that JavaScript does not have, such as + * `RcDate` for a calendar date. A wrapper class's constructor, such as + * `new RcDate(..)`, also throws a `TypeError` when its argument is not a + * string. */ export { Cipher, diff --git a/languages/typescript/packages/recipher-js/src/kinds.ts b/languages/typescript/packages/recipher-js/src/kinds.ts index e9c11b480..1ddb7c6eb 100644 --- a/languages/typescript/packages/recipher-js/src/kinds.ts +++ b/languages/typescript/packages/recipher-js/src/kinds.ts @@ -1,11 +1,12 @@ /** - * Kinds: the types of value, by the engine's names for them. A kind says - * what type a stored ciphertext decrypts to, as in - * `Ciphertext.fromBytes(bytes, kinds.string)`. + * 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 }`, that contains 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 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. */ import type { OpenedJson, RcDate, RcDecimal, RcTimestamp } from './value-types' @@ -13,7 +14,7 @@ import type { OpenedJson, RcDate, RcDecimal, RcTimestamp } from './value-types' export interface Kind { /** The engine's name for the kind, such as `int32`. */ readonly name: Name - /** Carries `T` for the type checker. The property never exists at run time. */ + /** Stores `T` for the type checker. The property never exists at run time. */ readonly __value?: T } diff --git a/languages/typescript/packages/recipher-js/src/value-types.ts b/languages/typescript/packages/recipher-js/src/value-types.ts index d7f5df587..38d391128 100644 --- a/languages/typescript/packages/recipher-js/src/value-types.ts +++ b/languages/typescript/packages/recipher-js/src/value-types.ts @@ -1,10 +1,10 @@ /** * The types of the values the SDK encrypts, and of what they decrypt to. * - * This module holds types only, and imports nothing. The addon's generated - * declarations (`native.d.ts`) name these types in their signatures, so a - * module here that loaded the addon would make the declarations import - * themselves. + * 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 @@ -59,13 +59,15 @@ export type Scalar = | null /** - * A JSON value. An integer outside the safe range of a `number` is a - * `bigint`, within the 64-bit range (`-(2n ** 63n)` to `2n ** 64n - 1n`). - * The safe range is 2^53 - 1 either side of zero. + * A JSON value. * - * A whole `number` in the safe range is stored as an integer, and any other - * `number` as a float. `encrypt` refuses a whole `number` whose absolute - * value is at least 2^53 but less than 2^64, because it may not keep the + * 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. `encrypt` also refuses `NaN` and the infinities. */ export type JsonValue = @@ -78,9 +80,10 @@ export type 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 members of an - * object are sorted by key. + * 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 @@ -94,15 +97,15 @@ export type OpenedJson = declare const document: unique symbol /** - * What marks a `Json`, the native addon's class for a JSON document, so - * that no other object type-checks as one. The marker never exists at run - * time. + * 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` takes. */ +/** A value that `encrypt` accepts. */ export type Value = Scalar | JsonMarker /** The type that a value of type `V` decrypts to. */ diff --git a/languages/typescript/packages/recipher-js/src/values.ts b/languages/typescript/packages/recipher-js/src/values.ts index 636806515..5e3eb48ee 100644 --- a/languages/typescript/packages/recipher-js/src/values.ts +++ b/languages/typescript/packages/recipher-js/src/values.ts @@ -10,7 +10,7 @@ * | `string` | text | `string` | * | `boolean` | a boolean | `boolean` | * | `number` | a 64-bit float | `number` | - * | `bigint` | an integer, at the narrowest width that holds it | `bigint` | + * | `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` | @@ -23,16 +23,20 @@ * equal the integer `5n`. * * A plain object is refused, because an object has no single stored form. - * `json(..)` encrypts it as a JSON document. `opaque(..)` will encrypt a - * whole object in the engine's own format, and is not built yet. + * `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 wrapper classes (`RcDate`, `RcTimestamp`, `RcDecimal`, and `RcUuid`) - * and `json` come from the native addon. When the addon did not load, - * stand-ins take their place. Each stand-in constructs as the class does. - * `encrypt` then resolves to the `Err` that says why the addon did not load. + * 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. When the addon did not load, this + * module exports stand-ins instead. A stand-in's constructor accepts and + * refuses the same arguments as the class's constructor. `encrypt` then + * resolves to the `Err` that says why the addon did not load. * - * A wrapper class's constructor takes a string. It throws a `TypeError` for - * any other argument. The text is checked when the value is encrypted. + * A wrapper class's constructor takes a string. The constructor throws a + * `TypeError` for any other argument. The text is checked later, when the + * value is encrypted. */ import type * as Native from '../native' import { type Binding, binding } from './binding' @@ -56,11 +60,15 @@ export interface WrapperConstructor { type WrapperName = 'RcDate' | 'RcTimestamp' | 'RcDecimal' | 'RcUuid' /** - * A stand-in for the wrapper class `name`, for when the native addon did - * not load. It constructs as the addon's class does: it takes a string and - * throws a `TypeError` for anything else, keeps the text in a read-only - * `value`, is frozen, and gives the same text to `String`, `JSON.stringify` - * and Node's `inspect`. + * A stand-in for the wrapper class `name`, for when the native addon did not + * load. The stand-in matches the addon's class in these ways: + * + * - The constructor takes a string, and throws a `TypeError` for anything + * else. + * - A read-only `value` contains the text. + * - The class, its prototype, and each instance are frozen. + * - `String`, `JSON.stringify`, and Node's `inspect` get the same text as + * from the addon's class. */ export function standInWrapper(name: WrapperName): WrapperConstructor { const StandIn = class { @@ -84,7 +92,7 @@ export function standInWrapper(name: WrapperName): WrapperConstructor { } Object.defineProperty(StandIn, 'name', { value: name }) Object.freeze(StandIn.prototype) - // biome-ignore lint/plugin: a stand-in for the class, which constructs as it does. + // biome-ignore lint/plugin: a stand-in with the constructor behaviour of the class. return Object.freeze(StandIn) as unknown as WrapperConstructor } @@ -101,10 +109,10 @@ function wrapperClass(name: WrapperName): WrapperConstructor { return standInWrapper(name) } -// A class is a constant and a type of one name. `./value-types` declares the -// types, because the addon's declarations name them, and 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 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 `new RcDate('2026-11-23')`. */ export const RcDate: WrapperConstructor = wrapperClass('RcDate') @@ -139,13 +147,16 @@ export type RcUuid = Types.RcUuid */ export type Json = Native.Json -/** The type of `json`, which makes a JSON document to encrypt as one ciphertext. */ +/** + * The type of `json`. `json` makes a JSON document to encrypt as one + * ciphertext. + */ export type JsonFunction = Binding['json'] /** - * 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. + * 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 })) @@ -153,15 +164,15 @@ export type JsonFunction = Binding['json'] * * 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 is - * refused: give it as a `bigint`. A `bigint` is stored as its exact digits, - * within 64 bits. + * refused. Pass a `bigint` instead. A `bigint` is stored as its exact + * digits, within 64 bits. * * 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 + * `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() @@ -170,6 +181,6 @@ export const json: JsonFunction = binding.isOk() /** The stand-in for `json` when the native addon did not load. */ function standInJson(): Json { - // biome-ignore lint/plugin: a stand-in `Json`, which `encrypt` refuses with the load error. + // 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/values.ts b/languages/typescript/packages/recipher-js/type-tests/values.ts index 471ca0e70..dcb5e4b68 100644 --- a/languages/typescript/packages/recipher-js/type-tests/values.ts +++ b/languages/typescript/packages/recipher-js/type-tests/values.ts @@ -21,7 +21,8 @@ type Exact = [A] extends [B] ? ([B] extends [A] ? true : false) : false function expectType(_: T): void {} function check<_ extends true>(): void {} -// One value is one ciphertext, typed by what it opens as. A literal widens. +// 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) @@ -50,7 +51,7 @@ check, RecipherError>>>() const many = await keyset.encrypt(['a', 'b']) check[], RecipherError>>>() -// Decrypting gives the type back, one or many. +// Decrypting gives the type back, for one ciphertext or for an array. if (text.isOk()) { const opened = await cipher.decrypt(text.value) check>>() @@ -79,8 +80,8 @@ void json({ d: new Date() }) // @ts-expect-error: an RcDate is not an RcDecimal. expectType(day) -// A ciphertext read from stored bytes is typed by the kind named, and as -// any scalar when none is. +// A ciphertext read from stored bytes has the type of the kind named. With +// no kind, its type is any scalar. declare const stored: Uint8Array const typed = Ciphertext.fromBytes(stored, kinds.int64) check, RecipherError>>>() diff --git a/languages/typescript/packages/recipher-js/value-napi/Cargo.toml b/languages/typescript/packages/recipher-js/value-napi/Cargo.toml index 1848d1dc3..2fc4ad5fa 100644 --- a/languages/typescript/packages/recipher-js/value-napi/Cargo.toml +++ b/languages/typescript/packages/recipher-js/value-napi/Cargo.toml @@ -19,14 +19,16 @@ 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. `serde-json` converts a `serde_json::Number` to a JavaScript -# `number` or `bigint`, for a decrypted JSON document. +# 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"] } -# A JSON document: `serde_json` writes each scalar of its text, and a -# decrypted document arrives as a `serde_json::Value`. `serde` is named for +# 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" diff --git a/languages/typescript/packages/recipher-js/value-napi/README.md b/languages/typescript/packages/recipher-js/value-napi/README.md index 9bf074967..aa8ad2981 100644 --- a/languages/typescript/packages/recipher-js/value-napi/README.md +++ b/languages/typescript/packages/recipher-js/value-napi/README.md @@ -1,69 +1,99 @@ # recipher-value-napi -The JavaScript value bridge of `@cipherstash/recipher`: it reads a Node-API -value as vitaminc's plaintext model, and builds a JavaScript value from it. -The `recipher-js` addon reads and builds every value through it. - -This crate is a copy of `vitaminc-aead-napi` 0.10.0, from -[`cipherstash/vitaminc`](https://github.com/cipherstash/vitaminc) at commit -`b3f69b12c1fde38faff2becec04f9e633dbd4f1c`, renamed. It is not published. -Its wrapper classes are `RcDate`, `RcTimestamp`, `RcDecimal` and `RcUuid`. -vitaminc names them `VcDate` and so on. +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`. + `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. -- **`JsRef::to_json`** and **`JsBuilder::build_json`** — a JSON document. - The first writes a JavaScript value as the text of a document, and the - second builds the JavaScript value of a `serde_json::Value`. See +`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`** — 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 +- **`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 `RcDate`, `RcTimestamp`, - `RcDecimal` and `RcUuid`, 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`. 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'); @@ -79,13 +109,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. -## The mapping +## How JavaScript values map to the plaintext model -| JavaScript | Scalar | +The walk reads each JavaScript value as the value in this table: + +| JavaScript | Read as | | ----------------------------------- | ---------------------------------------- | | `null` | null | | `undefined` | null, logical type `Undefined` | @@ -102,66 +135,111 @@ for integer values, as shown by `42n`; JavaScript `number` values are floats. | `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 an `RcTimestamp` 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 RcDecimal("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, such +as `new RcDecimal("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. + +- **The constructor takes a string and nothing else.** This crate checks the + text, and builds the scalar 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`, `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 the constructor 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. `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. +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 -The walk is the one every value goes through, with every rule in -[Safety notes](#safety-notes). It reads only what a JSON document holds: +`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 | | --------------------------------------- | ---------------------------- | @@ -173,143 +251,206 @@ The walk is the one every value goes through, with every rule in | `bigint` within 64 bits | an integer, with its digits | | anything else | refused | -- **A whole number is an integer.** `5000000000` is written `5000000000`, - as `JSON.stringify` writes it, and never `5000000000.0`. Rust's - `serde_json` and Go's `encoding/json` refuse a number with a fraction for - an integer field. `-0` is written `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, and an - integer was probably meant. A `bigint` holds it exactly. A number of 2^64 - or more is no integer that a reader takes, so it is a float. -- **A `bigint` is its exact digits**, from -2^63 to 2^64 - 1. That is the - range a JSON parser in Rust or Go reads. A `bigint` outside it is - refused, whatever its size. -- **Everything else is refused**: `undefined`, `NaN` and the infinities, - bytes (a `Buffer`, a typed array, a `DataView`), a `Date`, and a wrapper - class instance. Each has the code `recipher_js::not_json`, and a message - that names the kind of value and no part of it. A function and a symbol - are `recipher_js::not_a_value`, as for any value. Nothing calls a - `toJSON` method. -- **`max_depth` is the reader's limit**, in levels of arrays and objects: - `[1]` is one level. A document nested deeper is `recipher_js::too_deep`. - The walk's own limit of 128 applies too. -- **The text is written straight into a protected buffer.** The buffer +- **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 is not an integer that any reader accepts, so it is a float. +- **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. - No tree of the document is built on the way. An object's members are - written in the order JavaScript lists them. + `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. A `bigint` that is in the safe range -comes back as a `number`: `5n` is written `5`, and `5` is read as `5`. +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`. -Each scalar is converted by napi-rs's own `serde_json` conversion, which -has this number rule. An array and an object are built here, from own data -properties, and a member named `__proto__`, `constructor` or `prototype` -is refused. napi-rs's conversion of a whole document assigns each member -(`object[key] = value`). An assignment gives a member named `__proto__` to -the object as its prototype, and runs a setter that a polluted prototype -defines, which then receives the decrypted value. +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: -`build_json` copies nothing out of the document. The caller owns the -document, and wipes it. +- 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. -napi-rs's conversion in the other direction, from a JavaScript value to a -`serde_json::Value`, is not used. It writes a whole number above 2^32 as a -float and a wide `bigint` as a string. It drops a member that is -`undefined`, and reads a `Date` as `{}`. It also reads inherited properties, -and replaces an unpaired surrogate. `tests/json.cjs` pins each of these. +`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`, -`JsRef::to_json`, `JsBuilder::build` and `JsBuilder::build_json` 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 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). +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. + +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 @@ -317,8 +458,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 c8b4e25ec..523528c75 100644 --- a/languages/typescript/packages/recipher-js/value-napi/src/error.rs +++ b/languages/typescript/packages/recipher-js/value-napi/src/error.rs @@ -29,7 +29,8 @@ pub enum Refusal { #[error("the value is nested deeper than {limit} levels")] #[diagnostic(code(recipher_js::too_deep))] TooDeep { - /// The most levels of arrays and objects the value may nest. + /// The largest number of levels of arrays and objects that the value + /// may nest. limit: usize, }, /// An array with a hole. @@ -59,7 +60,7 @@ pub enum Refusal { )] #[diagnostic(code(recipher_js::unpaired_surrogate))] UnpairedSurrogate, - /// A value that a JSON document cannot hold. + /// A value that a JSON document cannot contain. #[error("a JSON document cannot hold {0}")] #[diagnostic(code(recipher_js::not_json))] NotJson(NoJsonForm), @@ -70,15 +71,15 @@ pub enum Refusal { Scalar(#[from] ConversionError), } -/// A value that has no form in a JSON document. Each variant displays as -/// what the value is, and never as the value. +/// 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`. + /// `NaN`, `Infinity`, or `-Infinity`. #[error("a number that is not finite")] NonFinite, /// A whole `number` from 2^53 up to 2^64, either side of zero. A @@ -91,7 +92,7 @@ pub enum NoJsonForm { /// A `bigint` below -2^63 or above 2^64 - 1. #[error("a `bigint` outside the 64-bit range (below -2^63 or above 2^64 - 1)")] BigIntRange, - /// A `Buffer`, a typed array or a `DataView`. + /// A `Buffer`, a typed array, or a `DataView`. #[error("bytes")] Bytes, /// A `Date` or a wrapper class instance. 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 149c31833..35edbe724 100644 --- a/languages/typescript/packages/recipher-js/value-napi/src/js.rs +++ b/languages/typescript/packages/recipher-js/value-napi/src/js.rs @@ -30,7 +30,7 @@ pub(crate) fn depth_error() -> JsFault { too_deep(MAX_DEPTH) } -/// The refusal of a value that a JSON document cannot hold. +/// 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()) 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 215920a2b..aa4cdf7f9 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,31 +19,41 @@ //! | `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: -//! `RcDate` is `Date` over the day count, `RcTimestamp` is -//! `Timestamp(Nanos)` over the nanosecond count, `RcDecimal` is `Decimal` -//! over the mantissa and `RcUuid` 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. The walk is the -//! same one, with the same safety rules, but it reads only what a JSON -//! document holds: +//! [`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 | an integer | -//! | whole `number` from 2^53 up to 2^64 | refused | -//! | any other finite `number` | a float | -//! | `bigint` within 64 bits | an integer, with its digits | -//! | anything else | refused | +//! | 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 | +//! | 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, @@ -73,7 +85,8 @@ pub struct JsRef<'e> { pub(crate) enum Model { /// Every value in the module's first table. Value, - /// Only what a JSON document holds: the module's second table. + /// Only the values a JSON document can contain: the module's second + /// table. Json, } @@ -89,9 +102,9 @@ 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. + /// 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) } @@ -144,12 +157,15 @@ 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`] are the walk's recursion: a nested level costs one frame of -/// each. So they hold as little as they can, and everything that reads a -/// scalar or builds a refusal is in a helper whose frame is gone before a -/// container recurses. A document at the depth limit then walks in a debug -/// build too. +/// 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, @@ -165,7 +181,7 @@ fn js_walk( } } -/// A value of type `ty`, which is not an object. +/// A value of type `ty`. The value is not an object. fn js_primitive( value: Unknown<'_>, ty: ValueType, @@ -215,7 +231,7 @@ fn js_primitive( } } -/// What an object is, to the walk. +/// The kind of object, as the walk classifies it. enum Shape { /// A `Buffer` or a typed array. Bytes, @@ -229,11 +245,11 @@ enum Shape { Map, } -/// What `value` is, or the refusal of an object the walk does not read. +/// The shape of `value`, or the refusal of an object the walk does not read. /// -/// A JSON document holds none of the scalar shapes: bytes, a `Date` and a -/// wrapper class instance. Each is refused here by what it is, before it -/// is 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 diff --git a/languages/typescript/packages/recipher-js/value-napi/src/json.rs b/languages/typescript/packages/recipher-js/value-napi/src/json.rs index 647564cfd..ad07117f6 100644 --- a/languages/typescript/packages/recipher-js/value-napi/src/json.rs +++ b/languages/typescript/packages/recipher-js/value-napi/src/json.rs @@ -1,35 +1,46 @@ -//! JSON documents: a JavaScript value as the text of one, and a document -//! as a JavaScript value. +//! 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. The walk is the one every value goes through, so the -//! same safety rules apply: only plain objects are read, by their own -//! enumerable string keys, and a hole, a getter that throws, an unpaired -//! surrogate and a reserved property name are refused. The -//! [`js_ref`](crate::js_ref) module lists what a document holds. +//! [`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 text is written straight into a [`Buffer`], which wipes each -//! allocation it outgrows and wipes itself when it is dropped. No tree of -//! the document is built on the way, so no copy of it is left behind. +//! - 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`. Each scalar is converted by napi-rs's own -//! conversion for its type. For a number that is: +//! `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. //! -//! - an integer within 2^53 - 1 of zero: a `number`; -//! - any other integer: a `bigint`, so no digit is lost; -//! - a float: a `number`. +//! 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 array and an object are written here, not by napi-rs. napi-rs assigns -//! each element and member (`object[key] = value`). An assignment runs a -//! setter that a polluted prototype defines, which would receive the -//! decrypted value. It also gives a member named `__proto__` to the object -//! as its prototype. So this module defines each element and member as an -//! own data property, and refuses the three reserved property names, as +//! - 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; @@ -48,22 +59,27 @@ use crate::js::{ use crate::{JsBuilder, JsRef}; impl JsRef<'_> { - /// Write the value as the text of a JSON document, on the JavaScript - /// thread. The text is plaintext, and comes back in a buffer that is - /// wiped when it is dropped. + /// 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 most levels of arrays and objects the document - /// may nest: the limit of whatever will read the text. `[1]` is one - /// level. The walk's own limit, [`MAX_DEPTH`], applies too. + /// `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. /// - /// An object's members are written in the order JavaScript lists them. + /// The method writes an object's members in the order JavaScript lists + /// them. /// /// # Errors /// - /// A [`JsFault`]: its [`refusal`](JsFault::refusal) names the rule a - /// refused value broke. A value with no JSON form is - /// [`Refusal::NotJson`], and a document nested past `max_depth` is - /// [`Refusal::TooDeep`]. No error holds any part of the value. + /// 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 @@ -77,18 +93,23 @@ impl JsRef<'_> { impl<'e> JsBuilder<'e> { /// The JavaScript value of a JSON document. /// - /// An integer within 2^53 - 1 of zero is a `number`, any other integer - /// is a `bigint`, and a float is a `number`. An array and an object are - /// built from own data properties. + /// 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`: the caller still - /// owns it, and wipes it. + /// This function copies nothing out of `document`. `document` still + /// belongs to the caller, and the caller wipes it. /// /// # Errors /// - /// A [`JsFault`]. [`Refusal::ReservedKey`] is an object with a member - /// named `__proto__`, `constructor` or `prototype`, and - /// [`Refusal::TooDeep`] is a document nested past [`MAX_DEPTH`]. + /// 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 @@ -97,7 +118,7 @@ impl<'e> JsBuilder<'e> { } } -/// The JavaScript value of `value`, which sits `depth` levels down in its +/// 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 { @@ -106,8 +127,8 @@ fn json_to_js<'e>(env: &'e Env, value: &Value, depth: usize) -> Result Ok(Null.into_unknown(env)?), Value::Bool(flag) => Ok((*flag).into_unknown(env)?), - // napi-rs's conversion of a `serde_json::Number`: see the module - // docs for which numbers become a `bigint`. + // 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) => { @@ -144,13 +165,13 @@ fn json_to_js<'e>(env: &'e Env, value: &Value, depth: usize) -> Result { out: &'b mut Buffer, /// How many more levels of sequences and maps may open here. @@ -193,12 +214,16 @@ impl io::Write for Append<'_> { } } -/// Writes one scalar as `serde_json` writes it: text with its escapes, an -/// integer as its digits, and a float in the shortest form that reads back -/// as the same float. `serde_json` writes each straight into `out`. +/// 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> { - // The only failure is the writer's, and this writer does not fail. The - // error's text is dropped, so nothing of the value can leave in it. + // 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")) } @@ -218,7 +243,7 @@ impl<'b> Sink for JsonText<'b> { (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` has no `i128`. + // 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)) => { @@ -411,7 +436,8 @@ mod tests { 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 what it takes. + // 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() @@ -438,7 +464,7 @@ mod tests { -0.0, ] { let written = text(float); - // A fraction or an exponent: a reader takes it as a float, never + // 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(); @@ -529,7 +555,7 @@ mod tests { let fault = text_within(Nested(limit + 1), limit).expect_err("past the limit"); assert_eq!(fault.refusal(), Some(Refusal::TooDeep { limit })); } - // A scalar is no level, so it is a document at any 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. 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 0ec094bb1..266be479a 100644 --- a/languages/typescript/packages/recipher-js/value-napi/src/scalar.rs +++ b/languages/typescript/packages/recipher-js/value-napi/src/scalar.rs @@ -118,24 +118,24 @@ fn unsigned(value: u128) -> Int { } } -/// The largest whole number a JavaScript `number` holds exactly: 2^53 - 1, -/// `Number.MAX_SAFE_INTEGER`. +/// 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; -/// A JavaScript `number` as a JSON document holds it. +/// A JavaScript `number` as a JSON document stores it. /// -/// A whole number within the safe range (2^53 - 1 either side of zero) 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`. +/// 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 is refused. A `number` that large -/// may not have the digits that were written, and an integer was probably -/// meant, which a `bigint` holds exactly. Any other finite number is a -/// float: one with a fraction, or one of 2^64 or more. +/// A whole number from 2^53 up to 2^64 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. Any other finite number is a float: +/// a number with a fraction, or a number of 2^64 or more. pub(crate) fn json_number(value: f64) -> Result, NoJsonForm> { if !value.is_finite() { return Err(NoJsonForm::NonFinite); @@ -151,9 +151,9 @@ pub(crate) fn json_number(value: f64) -> Result, NoJsonForm> { Ok(Physical::Float(Float::F64(value))) } -/// A JavaScript `bigint` as a JSON document holds it: a signed or an -/// unsigned 64-bit integer. A JSON parser in Rust or Go reads no wider, so -/// a `bigint` outside that range is refused, whatever its size. +/// 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..) @@ -163,7 +163,8 @@ pub(crate) fn json_bigint(negative: bool, words: &[u64]) -> Result Wrappers<'e> { Ok(Self { classes }) } - /// An object holding every class under its name, for an addon to - /// re-export: `RcDate`, `RcTimestamp`, `RcDecimal` and `RcUuid`. + /// 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)?; 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 097253c54..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 @@ -16,7 +16,7 @@ crate-type = ["cdylib"] napi = { version = "3", default-features = false, features = ["napi6", "serde-json"] } napi-derive = "3" serde_json = "1" -# A refusal's code, which is its diagnostic code. +# 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 = "../.." } 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 8bd85133a..9d9744a2a 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 @@ -112,10 +112,10 @@ pub fn json_value<'e>(env: &'e Env, text: String) -> Result> { json_built(env, &document) } -/// `levels` JSON containers of one `wrap` kind ("array" or "object") -/// around `true`, built here and then built as a JavaScript value. A -/// parser would refuse the deepest of these documents, so the build's own -/// depth limit is what applies. +/// 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); diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/json.cjs b/languages/typescript/packages/recipher-js/value-napi/tests/json.cjs index 70b577ffd..b9e414d38 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/json.cjs +++ b/languages/typescript/packages/recipher-js/value-napi/tests/json.cjs @@ -1,9 +1,11 @@ -// JSON documents at the N-API boundary: a JavaScript value written as the -// text of a document (`JsRef::to_json`), and a document built as a -// JavaScript value (`JsBuilder::build_json`). The last section pins what -// napi-rs's own `serde_json` conversion does, which is why the bridge reads -// a value itself and writes arrays and objects itself. Run by tests/node.rs -// with the test addon's path. +// 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])) @@ -36,7 +38,7 @@ const built = (json) => { // --- Writing a value as JSON text --- -// An object, an array, a string, a boolean and null stay as they are. The +// 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: [] } }), @@ -86,7 +88,7 @@ for (const float of [ ]) { const written = text(float) assert.equal(JSON.parse(written), float, written) - // A fraction or an exponent, so no reader takes it as an integer. + // A fraction or an exponent, so no reader reads it as an integer. assert.match(written, /[.e]/, written) } @@ -104,12 +106,12 @@ for (const unsafe of [ const refused = refusal({ n: unsafe }) assert.equal(refused.code, NOT_JSON, String(unsafe)) assert.match(refused.message, /bigint/) - // No message holds any part of the value. + // No message contains any part of the value. assert.ok(!/\d{6}/.test(refused.message), refused.message) } -// NaN and the infinities have no JSON form. JSON.stringify writes them as -// null, which would decrypt as another value. +// 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, @@ -146,7 +148,7 @@ for (const wide of [ 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 +// 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 RcDate = addon.RcDate const noJsonForm = [ @@ -179,7 +181,7 @@ for (const [value, message] of noJsonForm) { } } -// A function and a symbol are no value at all. +// 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') @@ -229,7 +231,8 @@ try { } finally { delete Array.prototype[1] } -// A getter that throws surfaces as the error it threw, and is no refusal. +// 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( () => @@ -326,7 +329,7 @@ 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, whole or not. +// 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) @@ -352,8 +355,8 @@ assert.deepEqual( }, ) -// An array and an object are ordinary ones, of own data properties that -// are writable, enumerable and configurable. +// 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)) @@ -400,7 +403,7 @@ try { delete Array.prototype[0] } -// A member with a reserved name is refused, at any depth: it is never +// 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 [ @@ -434,20 +437,20 @@ for (const wrap of ['array', 'object']) { // --- What napi-rs's own conversion does --- // // The bridge uses napi-rs's conversion for a document's scalars only. These -// cases pin why. If one of them fails after a napi-rs update, read the -// change and decide again. +// 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. +// 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, and a Date, a Map and a wrapper -// class instance are read as objects. +// 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]])), '{}') @@ -455,14 +458,14 @@ assert.equal( addon.napiJsonText(new RcDate('2026-11-23')), '{"value":"2026-11-23"}', ) -// An inherited property is read, and an unpaired surrogate is replaced. +// 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 one the bridge documents, and +// Building a value. The number rule is the rule that the bridge documents and // uses. assert.deepEqual( addon.napiJsonValue( @@ -483,8 +486,8 @@ assert.deepEqual( 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, and the result has no such property of its own. +// 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) { 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 90824142e..665b49655 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 @@ -265,8 +265,8 @@ 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 an RcTimestamp, 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), From 1cf2f553e757448c6513f6821217ac3359a3f8ce Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 20:53:19 +1100 Subject: [PATCH 17/25] fix(recipher-js): error messages for values in the SDK's own words A TypeScript developer reads these messages without knowing the engine. The messages said "seal", "open", "hold", and "takes". The README says "encrypt", "decrypt", "contain", and "accept", so the messages now use those words. Each message says what was wrong with the value that was passed, and the help says what to do. No error code, error field, or refusal changes. Only the text changes, with the tests and docs that quote it. - The addon's errors say "encrypt" and "decrypt". `not_a_scalar` and `plain_object` say that the value cannot be encrypted as one value, and the help says what `json(..)` does. - `not_a_kind` now states the fault in the message. The rule that was the message is now the help. - `opened_type` names the kind that the caller gave, in backticks. No message names the kind that a value decrypted as. - A refused JSON value reads "a JSON document cannot contain ...". The messages for a large `number` and for a typed value end with a sentence that says what to pass. - A wrapper class's constructor throws "RcDate accepts only a string". The addon's class and the stand-in throw the same text. --- .../typescript/packages/recipher-js/README.md | 4 +- .../recipher-js/__tests__/addon/value.test.ts | 2 +- .../__tests__/addon/values.test.ts | 6 +-- .../recipher-js/__tests__/unit/values.test.ts | 4 +- .../packages/recipher-js/crate/src/error.rs | 50 ++++++++++++------- .../packages/recipher-js/src/values.ts | 12 ++--- .../packages/recipher-js/value-napi/README.md | 2 +- .../recipher-js/value-napi/src/error.rs | 10 ++-- .../recipher-js/value-napi/src/json.rs | 2 +- .../recipher-js/value-napi/src/wrappers.js | 2 +- .../value-napi/tests/value-conformance.cjs | 2 +- 11 files changed, 56 insertions(+), 40 deletions(-) diff --git a/languages/typescript/packages/recipher-js/README.md b/languages/typescript/packages/recipher-js/README.md index 7ad658e8c..e15271fe5 100644 --- a/languages/typescript/packages/recipher-js/README.md +++ b/languages/typescript/packages/recipher-js/README.md @@ -68,7 +68,7 @@ The value bridge converts JavaScript values in both directions: - `RcTimestamp`, `RcDate`, `RcDecimal`, and `RcUuid` are wrapper classes. A wrapper class represents a type that JavaScript does not have. - The constructor of a wrapper class takes the value as text. + The constructor of a wrapper class accepts the value as text. - Integers are a `bigint`. A `number` is a float. The `number` `5` does not equal the integer `5n`. @@ -197,7 +197,7 @@ const opened = await Promise.all( A static method, such as `Ciphertext.fromBytes`, works on its own. A wrapper class's constructor throws too. -The constructor takes a string, so `new RcDate(20261123)` throws a `TypeError`. +The constructor accepts only a string, so `new RcDate(20261123)` throws a `TypeError`. The constructor does not check the text. `encrypt` returns an `Err` for text that is not a date. 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 74bff6764..3325598dc 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/value.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/value.test.ts @@ -136,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') }) diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts index 6bc33ebb9..d438e42c1 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts @@ -129,7 +129,7 @@ describe('a wrapper class', () => { const instance = new cls(text) let thrown: unknown try { - // @ts-expect-error: the constructor takes a string. + // @ts-expect-error: the constructor accepts only a string. new cls(20261123) } catch (error) { thrown = error @@ -153,9 +153,9 @@ describe('a wrapper class', () => { } } - it('takes a string, and throws a TypeError for anything else', () => { + it('accepts only a string, and throws a TypeError for anything else', () => { for (const name of names) { - // @ts-expect-error: the constructor takes a string. + // @ts-expect-error: the constructor accepts only a string. expect(() => new classes[name](20261123)).toThrow(TypeError) expect(new classes[name](texts[name]).value).toBe(texts[name]) } diff --git a/languages/typescript/packages/recipher-js/__tests__/unit/values.test.ts b/languages/typescript/packages/recipher-js/__tests__/unit/values.test.ts index 5fb635c6d..ae656e243 100644 --- a/languages/typescript/packages/recipher-js/__tests__/unit/values.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/unit/values.test.ts @@ -39,9 +39,9 @@ describe('a stand-in wrapper class', () => { it('throws a TypeError for an argument that is not a string', () => { const RcDate = standInWrapper('RcDate') for (const argument of [20261123, undefined, null, {}, ['2026-11-23']]) { - // @ts-expect-error: the constructor takes a string. + // @ts-expect-error: the constructor accepts only a string. expect(() => new RcDate(argument)).toThrow( - new TypeError('RcDate takes a string'), + new TypeError('RcDate accepts only a string'), ) } }) diff --git a/languages/typescript/packages/recipher-js/crate/src/error.rs b/languages/typescript/packages/recipher-js/crate/src/error.rs index 0870d7f28..669245475 100644 --- a/languages/typescript/packages/recipher-js/crate/src/error.rs +++ b/languages/typescript/packages/recipher-js/crate/src/error.rs @@ -34,7 +34,7 @@ use stack_encrypt::ErrorPayload; #[derive(Debug, thiserror::Error, Diagnostic)] pub(crate) enum Error { /// `undefined` given as a value. - #[error("`undefined` is not a value")] + #[error("`undefined` cannot be encrypted")] #[diagnostic( code(recipher_js::undefined), help("Use `null` for a value that is not there.") @@ -42,8 +42,8 @@ pub(crate) enum Error { Undefined, /// An `RcUuid`. The engine's value model, the set of value types the /// engine reads, has no UUID type. - #[error("a UUID cannot be encrypted yet: the engine's value model does not hold one")] - #[diagnostic(code(recipher_js::uuid), help("Encrypt its text instead."))] + #[error("a UUID cannot be encrypted yet, because the engine has no UUID type")] + #[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. @@ -57,19 +57,25 @@ pub(crate) enum Error { #[diagnostic(code(recipher_js::threw))] Threw, /// An array inside an array, given as one value. - #[error("an array inside an array is not a value")] - #[diagnostic(code(recipher_js::not_a_scalar), help("Wrap it in json(..)."))] + #[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("an object is not a value")] - #[diagnostic(code(recipher_js::plain_object), help("Wrap it in json(..)."))] + #[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, /// The engine refused to encrypt a value in the form it was given. - #[error("the engine could not seal the value as given")] + #[error("the engine could not encrypt the value in the form it was given")] #[diagnostic(code(recipher_js::not_sealed))] NotSealed, /// `decrypt` given something that is not a `Ciphertext`. - #[error("decrypt takes a Ciphertext, or an array of them")] + #[error("decrypt accepts a Ciphertext, or an array of ciphertexts")] #[diagnostic( code(recipher_js::not_a_ciphertext), help("Read stored bytes with Ciphertext.fromBytes.") @@ -80,15 +86,18 @@ pub(crate) enum Error { #[diagnostic(code(recipher_js::not_bytes))] NotBytes, /// A kind that is not one of `kinds`. - #[error("a ciphertext opens as one of `kinds`, such as `kinds.string`")] - #[diagnostic(code(recipher_js::not_a_kind))] + #[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`.") + )] NotAKind, /// A ciphertext that decrypted to another kind than the one named. - #[error("the value opened, but it was not sealed as the kind named, {kind}")] + #[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 opened, but it is not a JSON document")] + #[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. @@ -399,7 +408,7 @@ mod tests { fn an_error_of_the_sdks_own_has_its_code_message_and_help() { let error = RecipherErrorFields::from(Error::Undefined); assert_eq!(error.code, "recipher_js::undefined"); - assert_eq!(error.message, "`undefined` is not a value"); + assert_eq!(error.message, "`undefined` cannot be encrypted"); assert_eq!( error.help.as_deref(), Some("Use `null` for a value that is not there.") @@ -551,9 +560,17 @@ mod tests { fn help_of(error: &Error) -> Option<&'static str> { match error { Error::Undefined => Some("Use `null` for a value that is not there."), - Error::Uuid => Some("Encrypt its text instead."), - Error::NotAScalar | Error::PlainObject => Some("Wrap it in json(..)."), + 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::NotACiphertext => Some("Read stored bytes with Ciphertext.fromBytes."), + Error::NotAKind => { + Some("Pass a kind that the package exports, such as `kinds.string`.") + } Error::NoTesting => { Some("Build it with `pnpm --filter @cipherstash/recipher build:debug`.") } @@ -564,7 +581,6 @@ mod tests { | Error::Threw | Error::NotSealed | Error::NotBytes - | Error::NotAKind | Error::OpenedType { .. } | Error::NotADocument | Error::TestingSeed => None, diff --git a/languages/typescript/packages/recipher-js/src/values.ts b/languages/typescript/packages/recipher-js/src/values.ts index 5e3eb48ee..a5ec56999 100644 --- a/languages/typescript/packages/recipher-js/src/values.ts +++ b/languages/typescript/packages/recipher-js/src/values.ts @@ -34,9 +34,9 @@ * refuses the same arguments as the class's constructor. `encrypt` then * resolves to the `Err` that says why the addon did not load. * - * A wrapper class's constructor takes a string. The constructor throws a - * `TypeError` for any other argument. The text is checked later, when the - * value is encrypted. + * A wrapper class's constructor accepts only a string. The constructor + * throws a `TypeError` for any other argument. The text is checked later, + * when the value is encrypted. */ import type * as Native from '../native' import { type Binding, binding } from './binding' @@ -63,8 +63,8 @@ type WrapperName = 'RcDate' | 'RcTimestamp' | 'RcDecimal' | 'RcUuid' * A stand-in for the wrapper class `name`, for when the native addon did not * load. The stand-in matches the addon's class in these ways: * - * - The constructor takes a string, and throws a `TypeError` for anything - * else. + * - The constructor accepts only a string, and throws a `TypeError` for + * anything else. * - A read-only `value` contains the text. * - The class, its prototype, and each instance are frozen. * - `String`, `JSON.stringify`, and Node's `inspect` get the same text as @@ -75,7 +75,7 @@ export function standInWrapper(name: WrapperName): WrapperConstructor { readonly value: string constructor(text: string) { if (typeof text !== 'string') { - throw new TypeError(`${name} takes a string`) + throw new TypeError(`${name} accepts only a string`) } this.value = text Object.freeze(this) diff --git a/languages/typescript/packages/recipher-js/value-napi/README.md b/languages/typescript/packages/recipher-js/value-napi/README.md index aa8ad2981..d75a3fcff 100644 --- a/languages/typescript/packages/recipher-js/value-napi/README.md +++ b/languages/typescript/packages/recipher-js/value-napi/README.md @@ -185,7 +185,7 @@ 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. -- **The constructor takes a string and nothing else.** This crate checks the +- **The constructor accepts only a string.** This crate checks the text, and builds the scalar 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 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 523528c75..d8a8b550c 100644 --- a/languages/typescript/packages/recipher-js/value-napi/src/error.rs +++ b/languages/typescript/packages/recipher-js/value-napi/src/error.rs @@ -61,7 +61,7 @@ pub enum Refusal { #[diagnostic(code(recipher_js::unpaired_surrogate))] UnpairedSurrogate, /// A value that a JSON document cannot contain. - #[error("a JSON document cannot hold {0}")] + #[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 @@ -85,18 +85,18 @@ pub enum NoJsonForm { /// A whole `number` from 2^53 up to 2^64, either side of zero. A /// `number` that large may not have the digits that were written. #[error( - "a whole number from 2^53 up to 2^64 held as a `number`, whose digits may not be the \ - ones written; give it as a `bigint`" + "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. Pass a `bigint` instead." )] UnsafeInteger, /// A `bigint` below -2^63 or above 2^64 - 1. - #[error("a `bigint` outside the 64-bit range (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 it as text")] + #[error("a date, a timestamp, a decimal, or a UUID. Write the value as a string instead.")] Typed, } diff --git a/languages/typescript/packages/recipher-js/value-napi/src/json.rs b/languages/typescript/packages/recipher-js/value-napi/src/json.rs index ad07117f6..016647318 100644 --- a/languages/typescript/packages/recipher-js/value-napi/src/json.rs +++ b/languages/typescript/packages/recipher-js/value-napi/src/json.rs @@ -540,7 +540,7 @@ mod tests { 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 hold bytes"); + assert_eq!(fault.reason(), "a JSON document cannot contain bytes"); assert_eq!(fault.status(), Status::InvalidArg); } 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 ae9032809..ef0b6697b 100644 --- a/languages/typescript/packages/recipher-js/value-napi/src/wrappers.js +++ b/languages/typescript/packages/recipher-js/value-napi/src/wrappers.js @@ -52,7 +52,7 @@ [name]: class { constructor(value) { if (typeof value !== 'string') { - throw new TypeError(`${name} takes a string`) + throw new TypeError(`${name} accepts only a string`) } defineProperty(this, 'value', { __proto__: null, 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 665b49655..301928cad 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 @@ -195,7 +195,7 @@ 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 +// A wrapper accepts only a string; the text itself is checked // when the value is encrypted, so one rule applies however it was made. for (const Wrapper of [RcDate, RcTimestamp, RcDecimal, RcUuid]) { for (const payload of [ From 78c2c78239819edd044a74b49ccff4d4f8b58dd4 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 23:16:40 +1100 Subject: [PATCH 18/25] fix(recipher-js): bump the binding interface, and say why a UUID is refused The engine accepts a UUID now. This version of the SDK still refuses an `RcUuid`, because it has no kind and no TypeScript type for a UUID yet. The README, two doc comments, a test, and the error message said that the engine has no UUID type. Those places now say that this version of the SDK does not encrypt a UUID yet. The test now checks the new message. `encrypt` and `decrypt` changed shape since the first addon build, but the binding interface number was still 1. So the TypeScript would load an older addon build and fail later, on a call. The number is now 2 in the crate and in `src/binding.ts`. The comments on both say what the number is for, and when to change it. --- .../typescript/packages/recipher-js/README.md | 2 +- .../recipher-js/__tests__/addon/values.test.ts | 8 +++++--- .../packages/recipher-js/crate/src/error.rs | 6 +++--- .../packages/recipher-js/crate/src/lib.rs | 14 +++++++++----- .../typescript/packages/recipher-js/src/binding.ts | 8 ++++++-- .../packages/recipher-js/src/value-types.ts | 4 ++-- .../typescript/packages/recipher-js/src/values.ts | 4 ++-- .../packages/recipher-js/type-tests/values.ts | 2 +- 8 files changed, 29 insertions(+), 19 deletions(-) diff --git a/languages/typescript/packages/recipher-js/README.md b/languages/typescript/packages/recipher-js/README.md index e15271fe5..7c743882a 100644 --- a/languages/typescript/packages/recipher-js/README.md +++ b/languages/typescript/packages/recipher-js/README.md @@ -77,7 +77,7 @@ The value bridge converts JavaScript values in both directions: `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). - The engine has no plaintext type for a UUID yet. + 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`; diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts index d438e42c1..407b4df17 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts @@ -641,13 +641,15 @@ describe('a ciphertext read back with a kind', () => { }) describe('refusals', () => { - it('a UUID, which the engine does not hold yet', async () => { + it('a UUID: this version of the SDK does not encrypt one yet', async () => { const keyset = (await cipher()).defaultKeyset() const uuid = new RcUuid('123e4567-e89b-12d3-a456-426614174000') - // @ts-expect-error: a UUID is not a scalar of the engine's value model. + // @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('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 () => { diff --git a/languages/typescript/packages/recipher-js/crate/src/error.rs b/languages/typescript/packages/recipher-js/crate/src/error.rs index 669245475..97c7fa4be 100644 --- a/languages/typescript/packages/recipher-js/crate/src/error.rs +++ b/languages/typescript/packages/recipher-js/crate/src/error.rs @@ -40,9 +40,9 @@ pub(crate) enum Error { help("Use `null` for a value that is not there.") )] Undefined, - /// An `RcUuid`. The engine's value model, the set of value types the - /// engine reads, has no UUID type. - #[error("a UUID cannot be encrypted yet, because the engine has no UUID type")] + /// 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 diff --git a/languages/typescript/packages/recipher-js/crate/src/lib.rs b/languages/typescript/packages/recipher-js/crate/src/lib.rs index 0e5615420..f351bb2c3 100644 --- a/languages/typescript/packages/recipher-js/crate/src/lib.rs +++ b/languages/typescript/packages/recipher-js/crate/src/lib.rs @@ -38,10 +38,14 @@ //! //! [`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)] @@ -77,7 +81,7 @@ 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 diff --git a/languages/typescript/packages/recipher-js/src/binding.ts b/languages/typescript/packages/recipher-js/src/binding.ts index 2d152afed..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 diff --git a/languages/typescript/packages/recipher-js/src/value-types.ts b/languages/typescript/packages/recipher-js/src/value-types.ts index 38d391128..c1c41cb82 100644 --- a/languages/typescript/packages/recipher-js/src/value-types.ts +++ b/languages/typescript/packages/recipher-js/src/value-types.ts @@ -35,8 +35,8 @@ export interface RcDecimal { /** * A universally unique identifier (UUID). - * The engine has no plaintext type for a UUID yet. Encrypting an `RcUuid` is - * an `Err` with the code `recipher_js::uuid`. `RcUuid` is not a `Scalar`. + * 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. */ diff --git a/languages/typescript/packages/recipher-js/src/values.ts b/languages/typescript/packages/recipher-js/src/values.ts index a5ec56999..ccaead18d 100644 --- a/languages/typescript/packages/recipher-js/src/values.ts +++ b/languages/typescript/packages/recipher-js/src/values.ts @@ -132,8 +132,8 @@ export const RcDecimal: WrapperConstructor = export type RcDecimal = Types.RcDecimal /** - * A universally unique identifier (UUID). The engine has no plaintext type - * for a UUID yet. Encrypting an `RcUuid` is an `Err` with the code + * 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: WrapperConstructor = wrapperClass('RcUuid') diff --git a/languages/typescript/packages/recipher-js/type-tests/values.ts b/languages/typescript/packages/recipher-js/type-tests/values.ts index dcb5e4b68..3c064d27b 100644 --- a/languages/typescript/packages/recipher-js/type-tests/values.ts +++ b/languages/typescript/packages/recipher-js/type-tests/values.ts @@ -64,7 +64,7 @@ if (many.isOk()) { // A plain object needs json(..). // @ts-expect-error: a plain object is not a value. void keyset.encrypt({ name: 'Ada' }) -// A UUID is not in the engine's value model yet. +// 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) From 89a3b274f8b9a579fade163c16e94b8c9c5bb691 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 29 Nov 2026 02:42:55 +1100 Subject: [PATCH 19/25] docs(recipher-js): give the bigint range in the json() docs The TypeScript doc of `json` said a `bigint` is stored "within 64 bits". The range is from -(2n ** 63n) to 2n ** 64n - 1n, which no single 64-bit type holds, and the doc did not say a `bigint` outside it is refused. The Rust doc and the README already give the range. This makes the TypeScript doc match them. --- languages/typescript/packages/recipher-js/src/values.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/languages/typescript/packages/recipher-js/src/values.ts b/languages/typescript/packages/recipher-js/src/values.ts index ccaead18d..1086adeef 100644 --- a/languages/typescript/packages/recipher-js/src/values.ts +++ b/languages/typescript/packages/recipher-js/src/values.ts @@ -165,7 +165,8 @@ export type JsonFunction = Binding['json'] * 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 is * refused. Pass a `bigint` instead. A `bigint` is stored as its exact - * digits, within 64 bits. + * 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 From 5c78ecf9e054cf1884ae927cb3bff45930771051 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 29 Nov 2026 13:57:55 +1100 Subject: [PATCH 20/25] fix(recipher-js): refuse a number below -2^63 without asking for a bigint json() refused a whole number from 2^53 up to 2^64 with a message that says to pass a bigint. Below -2^63 that advice is wrong. A bigint that size is outside the 64-bit range, so json() refuses it too. The integer has no exact form in a JSON document. A whole number below -2^63 and above -2^64 now has its own refusal, NoJsonForm::NoExactForm, under the same recipher_js::not_json code. The refusal says the integer has no exact form. The message does not ask for a bigint. From -2^53 down to -2^63 the message still asks for one, since a bigint of that size is accepted. The json() docs, the README files, and the type docs now state both rules. The tests cover these values: - the first number below -2^63, -1e19, and the last number above -2^64; - -2^63, as a number and as a bigint; - -2^64, as a float. --- .../typescript/packages/recipher-js/README.md | 7 ++- .../__tests__/addon/values.test.ts | 39 ++++++++++++-- .../packages/recipher-js/crate/src/js.rs | 2 +- .../packages/recipher-js/crate/src/json.rs | 8 ++- .../packages/recipher-js/native.d.ts | 8 ++- .../packages/recipher-js/src/value-types.ts | 4 +- .../packages/recipher-js/src/values.ts | 10 ++-- .../packages/recipher-js/value-napi/README.md | 8 ++- .../recipher-js/value-napi/src/error.rs | 16 ++++-- .../recipher-js/value-napi/src/js_ref.rs | 1 + .../recipher-js/value-napi/src/scalar.rs | 51 ++++++++++++++++--- .../recipher-js/value-napi/tests/json.cjs | 13 +++++ 12 files changed, 140 insertions(+), 27 deletions(-) diff --git a/languages/typescript/packages/recipher-js/README.md b/languages/typescript/packages/recipher-js/README.md index 7c743882a..5c763055f 100644 --- a/languages/typescript/packages/recipher-js/README.md +++ b/languages/typescript/packages/recipher-js/README.md @@ -119,7 +119,8 @@ 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 | refused | not applicable | +| 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` | @@ -129,9 +130,11 @@ These rules decide how a number is stored and decrypted: 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 is refused, either side of zero. +- 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 }`. diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts index 407b4df17..0e4ad61e7 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts @@ -326,8 +326,14 @@ describe('a JSON document', () => { }) it('stores any other number as a float', async () => { - const text = await storedText([1.5, 2 ** 64, 1e20]) - expect(JSON.parse(text as string)).toEqual([1.5, 2 ** 64, 1e20]) + 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]/) @@ -404,7 +410,13 @@ describe('a JSON document', () => { }) 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)]) { + 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') @@ -413,6 +425,27 @@ describe('a JSON document', () => { } }) + 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]) diff --git a/languages/typescript/packages/recipher-js/crate/src/js.rs b/languages/typescript/packages/recipher-js/crate/src/js.rs index 36b4a6464..d5a469e08 100644 --- a/languages/typescript/packages/recipher-js/crate/src/js.rs +++ b/languages/typescript/packages/recipher-js/crate/src/js.rs @@ -72,7 +72,7 @@ pub fn read(env: &Env, value: Unknown<'_>) -> Result 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); } @@ -426,15 +438,17 @@ mod tests { #[test] fn a_whole_number_from_2_53_up_to_2_64_is_refused() { - // 2^53, the next number a `number` can store, the largest `number` - // below 2^64, and the same three below zero. + // 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, - -18_446_744_073_709_549_568.0, + -9_007_199_254_740_994.0, + MINUS_TWO_TO_63, ] { assert_eq!( json_number(number), @@ -444,6 +458,29 @@ mod tests { } } + #[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 [ diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/json.cjs b/languages/typescript/packages/recipher-js/value-napi/tests/json.cjs index b9e414d38..0ab003f95 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/json.cjs +++ b/languages/typescript/packages/recipher-js/value-napi/tests/json.cjs @@ -81,7 +81,9 @@ for (const float of [ 5e-324, // 2^64 and above. 2 ** 64, + -(2 ** 64), 1e20, + -1e20, -6.02e23, Number.MAX_VALUE, -Number.MAX_VALUE, @@ -110,6 +112,17 @@ for (const unsafe of [ 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 [ From 2dbc9fdd7ca2ed91dcfd5bed3f110305812aa986 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 29 Nov 2026 16:12:01 +1100 Subject: [PATCH 21/25] feat(recipher-js)!: encrypt one value through dynamic::value, with a declared kind next removed the addon's OneValue wrapper. The engine's dynamic::value::encrypt now encrypts the one scalar in a frame. This commit removes this branch's OneValue too, and sends every single-value encrypt through dynamic::value::encrypt. A json(..) value goes in as its JSON text, with the declared kind json. The engine parses the text into the JsonPlaintext it encrypts, so the stored form does not change. keyset.encrypt takes a second argument, { kind }, with a kind from kinds. The addon passes the kind to the engine. The engine converts a value to the kind when the conversion is exact, as a record write does. The ciphertext then decrypts as that kind: 34 declared as uint64 decrypts as 34n. For an array of values, the kind applies to each value. The kind is an options object, not a positional argument, so that a context can be added later under its own name. Neither can then be passed in the other's place. The options refuse any key but kind, with recipher_js::options, so an option that this version does not have is never ignored. What changes for a JavaScript caller: - A lone null is now refused, with the new code recipher_js::null. The error's help says to store a database NULL, or to declare the kind of a fixed-width type. The engine refuses a null, because a ciphertext contains one value. - A null declared as a fixed-width kind is refused today as well. Issue #2023 changes the engine to encrypt it as a padded typed null. A Rust test and a JavaScript test check today's refusal, and name #2023. - The TypeScript types accept null only with a fixed-width kind. A null with no options still type-checks, and fails when the call runs. - json(..) declared as another kind, or kinds.json declared for a value that is not a json(..), is refused with recipher_js::json_kind. - A second argument that is not { kind } is refused. Before, a second argument was ignored. - recipher_js::not_sealed is gone. The engine reports a JSON text it cannot parse with its own code. The bridge writes no such text. - The codes for an array inside an array (recipher_js::not_a_scalar) and a plain object (recipher_js::plain_object) are the same. The addon now maps them from the engine's refusal. --- .../packages/recipher-js/Cargo.lock | 1 - .../typescript/packages/recipher-js/README.md | 37 ++++- .../recipher-js/__tests__/addon/value.test.ts | 7 +- .../__tests__/addon/values.test.ts | 115 +++++++++++++- .../packages/recipher-js/crate/Cargo.toml | 3 - .../packages/recipher-js/crate/src/cipher.rs | 143 ++++++++++++++---- .../recipher-js/crate/src/ciphertext.rs | 45 +++++- .../recipher-js/crate/src/engine_tests.rs | 102 ++++++++++++- .../packages/recipher-js/crate/src/error.rs | 42 ++++- .../packages/recipher-js/crate/src/json.rs | 76 ++++------ .../packages/recipher-js/crate/src/lib.rs | 1 - .../packages/recipher-js/crate/src/value.rs | 106 ------------- .../packages/recipher-js/native-header.d.ts | 8 +- .../packages/recipher-js/native.d.ts | 27 +++- .../packages/recipher-js/src/index.ts | 10 +- .../packages/recipher-js/src/kinds.ts | 57 ++++++- .../packages/recipher-js/type-tests/values.ts | 33 ++++ 17 files changed, 593 insertions(+), 220 deletions(-) delete mode 100644 languages/typescript/packages/recipher-js/crate/src/value.rs diff --git a/languages/typescript/packages/recipher-js/Cargo.lock b/languages/typescript/packages/recipher-js/Cargo.lock index 4b077932a..eb3a9efb8 100644 --- a/languages/typescript/packages/recipher-js/Cargo.lock +++ b/languages/typescript/packages/recipher-js/Cargo.lock @@ -2514,7 +2514,6 @@ dependencies = [ "uuid", "vitaminc-aead 0.10.0", "vitaminc-protected 0.10.0", - "zeroize", ] [[package]] diff --git a/languages/typescript/packages/recipher-js/README.md b/languages/typescript/packages/recipher-js/README.md index 5c763055f..dc85b3ab3 100644 --- a/languages/typescript/packages/recipher-js/README.md +++ b/languages/typescript/packages/recipher-js/README.md @@ -63,7 +63,7 @@ The value bridge converts JavaScript values in both directions: | `new RcTimestamp('2026-11-23T01:02:03.000000001Z')` | a timestamp, in nanoseconds | `Date` when it is whole milliseconds, else `RcTimestamp` | | `new RcDate('2026-11-23')` | a calendar date | `RcDate` | | `new RcDecimal('1.50')` | a decimal, with its scale | `RcDecimal` | -| `null` | null | `null` | +| `null` | refused with no kind: see [A declared kind](#a-declared-kind) | not applicable | | `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. @@ -95,6 +95,41 @@ 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 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. +- A ciphertext contains one value, and `null` is the absence of a value. + So a lone `null` is an `Err` with the code `recipher_js::null`. + Store a value that is not there as a database `NULL`. +- A lone `null` needs a declared kind. + The kind must be fixed-width: a boolean, an integer, a float, a decimal, a date, or a timestamp. + The engine will encrypt it as a typed null, padded to the size of a value, as a record field with `"null": "sealed"` stores one. + Issue #2023 makes that engine change. + The change has not merged yet. + Until then, a `null` with a kind is refused too. +- A `null` of a variable-width kind, such as `kinds.string` or `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. + ### JSON documents `json(value)` encrypts a whole document as one ciphertext. 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 3325598dc..715313824 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/value.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/value.test.ts @@ -208,7 +208,12 @@ describe('every other call returns or resolves to a Result', () => { 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) diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts index 0e4ad61e7..e24896055 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts @@ -36,8 +36,7 @@ async function encryptOne( | Date | RcDate | RcTimestamp - | RcDecimal - | null, + | RcDecimal, ) { return (await c.defaultKeyset().encrypt(value)).unwrap() } @@ -105,10 +104,6 @@ describe('every value in the mapping round-trips', () => { expect(price).toBeInstanceOf(RcDecimal) expect((price as RcDecimal).value).toBe('1.50') }) - - it('null', async () => { - expect(await roundTrip(null)).toBeNull() - }) }) describe('a wrapper class', () => { @@ -201,9 +196,9 @@ describe('an array of values', () => { it('may mix types', async () => { const c = await cipher() const sealed = ( - await c.defaultKeyset().encrypt(['a', 1n, true, null] as const) + await c.defaultKeyset().encrypt(['a', 1n, true, 1.5] as const) ).unwrap() - expect((await c.decrypt(sealed)).unwrap()).toEqual(['a', 1n, true, null]) + expect((await c.decrypt(sealed)).unwrap()).toEqual(['a', 1n, true, 1.5]) }) it('is empty in, empty out', async () => { @@ -673,6 +668,90 @@ describe('a ciphertext read back with a kind', () => { }) }) +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 a uint64, so the kind reads them back. + const stored = Ciphertext.fromBytes(sealed.toBytes(), kinds.uint64).unwrap() + expect((await c.decrypt(stored)).unwrap()).toBe(34n) + }) + + 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') + }) + + it('refuses a null of a fixed-width kind until #2023', async () => { + // Issue #2023 changes the engine to encrypt a null declared as 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 [kinds.int64, kinds.boolean, kinds.timestamp]) { + const result = await keyset.encrypt(null, { kind }) + expect(result.err()?.code).toBe('recipher_js::null') + } + }) + + 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' }, + {}, + ]) { + // @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() @@ -726,6 +805,26 @@ describe('refusals', () => { expect(result.err()?.code).toBe('recipher_js::undefined') }) + it('null with no declared kind, alone or in an array', async () => { + const keyset = (await cipher()).defaultKeyset() + for (const result of [ + await keyset.encrypt(null), + await keyset.encrypt(['fine', null]), + ]) { + expect(result.err()?.code).toBe('recipher_js::null') + expect(result.err()?.help).toContain('database `NULL`') + } + }) + + it('null declared as a variable-width kind', async () => { + const keyset = (await cipher()).defaultKeyset() + for (const kind of [kinds.string, kinds.bytes]) { + // @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') + } + }) + it('a string with an unpaired surrogate', async () => { const keyset = (await cipher()).defaultKeyset() const result = await keyset.encrypt('\uD800') diff --git a/languages/typescript/packages/recipher-js/crate/Cargo.toml b/languages/typescript/packages/recipher-js/crate/Cargo.toml index f09e93bd7..57a50d5b0 100644 --- a/languages/typescript/packages/recipher-js/crate/Cargo.toml +++ b/languages/typescript/packages/recipher-js/crate/Cargo.toml @@ -47,9 +47,6 @@ miette = "7.5.0" thiserror = "1.0.56" # For the structured fields of an engine error (`ErrorPayload::payload`). serde_json = "1" -# The engine's opaque path wipes a value it did not seal. The version the -# engine resolves. -zeroize = "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"] } diff --git a/languages/typescript/packages/recipher-js/crate/src/cipher.rs b/languages/typescript/packages/recipher-js/crate/src/cipher.rs index b22563791..a44df4418 100644 --- a/languages/typescript/packages/recipher-js/crate/src/cipher.rs +++ b/languages/typescript/packages/recipher-js/crate/src/cipher.rs @@ -18,9 +18,9 @@ use napi::bindgen_prelude::{ }; use napi::Env; use napi_derive::napi; -use stack_encrypt::dynamic::{frame::OwnedFrame, ValueKind}; +use stack_encrypt::dynamic::{frame::OwnedFrame, value, Found, Reason, ValueKind}; use stack_encrypt::kms::{DataKeySource, IndexKeySource, StackKms}; -use stack_encrypt::{CipherRef, DecryptFrom, EncryptInto, KeysetCipher, StackCipher}; +use stack_encrypt::{CipherRef, DecryptFrom, KeysetCipher, Pending, StackCipher}; use vitaminc_protected::OpaqueDebug; use crate::ciphertext::Ciphertext; @@ -28,7 +28,6 @@ use crate::error::{Error, RecipherErrorFields}; use crate::js; use crate::json::Json; use crate::outcome::{not_made, refused, spawn, Outcome}; -use crate::value::OneValue; /// The engine's cipher, with the key source it was built with. A napi class /// cannot be generic, so each key source is one variant. @@ -160,22 +159,38 @@ impl Keyset { /// 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. /// - /// 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. + /// 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 array of values, the kind applies to each + /// 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`. - /// The promise does not reject. + /// `null` is an `Err` with the code `recipher_js::null`. Store a value + /// that is not there as a database `NULL`. The promise does not reject. #[napi( ts_type = "(value: V): Promise>, RecipherError>> -encrypt(values: readonly 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: Option>, ) -> napi::Result>> { + 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), @@ -184,7 +199,7 @@ encrypt(values: readonly V[]): Promise { sealable.push(value); opens_as.push(kind); @@ -373,35 +388,107 @@ pub(crate) async fn open_in( }) } -/// Returns one value to encrypt, and the kind its ciphertext decrypts as. A -/// `Json`'s document decrypts as JSON. Any other value decrypts as the type -/// it was encrypted as. -fn one_value(env: &Env, value: Unknown<'_>) -> Outcome<(OneValue, Option)> { - if let Some(document) = Json::of(env, value) { - return Ok((OneValue::json(document?), Some(ValueKind::Json))); +/// 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. + 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::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(..)`. +fn one_value( + env: &Env, + value: Unknown<'_>, + declared: Option, +) -> Outcome<(Sealable, Option)> { + if let Some(text) = Json::of(env, value) { + if declared.is_some_and(|kind| kind != ValueKind::Json) { + return Err(Error::JsonKind.into()); + } + let sealable = Sealable { + value: text?, + kind: Some(ValueKind::Json), + }; + return Ok((sealable, Some(ValueKind::Json))); } - Ok((OneValue::scalar(js::read(env, value)?)?, None)) + if declared == Some(ValueKind::Json) { + return Err(Error::JsonKind.into()); + } + let sealable = Sealable { + value: js::read(env, value)?, + kind: declared, + }; + Ok((sealable, declared)) } -/// Encrypts values under `keyset`. Each value becomes one ciphertext with -/// its own data key. All the values use one key request, however many -/// there are. +/// Encrypts values under `keyset`, with the engine's +/// `dynamic::value::encrypt`. Each value becomes one ciphertext with its own +/// 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 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, { - values - .encrypt_into::, K>(keyset) + let calls = values + .iter() + .map(|sealable| value::encrypt(keyset, sealable.value.frame(), sealable.kind)) + .collect::, _>>() + .map_err(|error| refusal(&error))?; + // The engine has read every value. `drop` wipes the frames, so no value + // stays in a frame during the key request. + drop(values); + Pending::all(keyset, calls) .await - .map_err(|error| match error { - // No ciphertext exists yet, so the value caused this failure, - // not a damaged ciphertext. - stack_encrypt::Error::Aead => Error::NotSealed.into(), - error => RecipherErrorFields::engine(&error), - }) + .map_err(|error| RecipherErrorFields::engine(&error)) +} + +/// Returns the failure for a value that the engine refused to encrypt as +/// one ciphertext. +/// +/// 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`. +/// +/// Any other refusal keeps the engine's code. +fn refusal(error: &stack_encrypt::dynamic::Error) -> RecipherErrorFields { + if error.reason() != Some(Reason::NotAScalar) { + return RecipherErrorFields::engine(error); + } + match error.found() { + Some(Found::Kind(ValueKind::Array)) => Error::NotAScalar.into(), + Some(Found::Kind(ValueKind::Object)) => Error::PlainObject.into(), + Some(Found::Null) => Error::Null.into(), + _ => RecipherErrorFields::engine(error), + } } /// Decrypts ciphertexts through `cipher`: a cipher, or one keyset of it. diff --git a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs index d2e9e8832..50a4a98ff 100644 --- a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs +++ b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs @@ -153,24 +153,59 @@ struct KindArgument { name: String, } +/// The options of `keyset.encrypt`: `{ kind }`. Any other key is refused, +/// so an option that this version does not have is never ignored. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct EncryptOptions { + 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) = value.filter(|value| value.get_type().ok() != Some(ValueType::Undefined)) - else { + 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)?; - let kind = argument + 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`; +/// - `recipher_js::not_a_kind`, when the kind is not one of `kinds`. +pub(crate) fn declared_kind(env: &Env, value: Option>) -> Outcome> { + let Some(value) = given(value) else { + return Ok(None); + }; + let frame = js::read(env, value).map_err(|_| Error::Options)?; + let options: EncryptOptions = + stack_encrypt::dynamic::frame::serde::from_slice(frame.frame().as_bytes()) + .map_err(|_| Error::Options)?; + named(&options.kind).map(Some) +} + +/// Returns the kind that `argument` names, when it is one of `kinds`. +fn named(argument: &KindArgument) -> Outcome { + Ok(argument .name .parse::() .ok() .filter(|kind| readable(*kind)) - .ok_or(Error::NotAKind)?; - Ok(Some(kind)) + .ok_or(Error::NotAKind)?) } /// Returns whether a stored ciphertext can be read as `kind`: whether 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 a66c6975f..84509a5ab 100644 --- a/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs +++ b/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs @@ -17,9 +17,8 @@ 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, Opened}; -use crate::value::OneValue; const SEED: [u8; 32] = [7; 32]; @@ -31,12 +30,26 @@ async fn engine() -> StackCipher { .unwrap() } -fn one(value: P) -> OneValue { - OneValue::scalar(OwnedFrame::of(value).unwrap()).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(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() @@ -123,8 +136,7 @@ async fn a_json_document_the_engine_sealed_opens_as_that_document() { /// text. `keyset.encrypt(json(..))` does the same, after the bridge has /// written the text. async fn sdk_seal_json(text: &str) -> stack_encrypt::Ciphertext { - let document = crate::json::plaintext(text.as_bytes()).unwrap(); - sdk_seal(vec![OneValue::json(document)]).await.remove(0) + sdk_seal(vec![document(text)]).await.remove(0) } #[tokio::test] @@ -288,3 +300,79 @@ async fn an_empty_array_makes_no_request() { 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"); + assert!(refused + .help + .is_some_and(|help| help.contains("database `NULL`"))); + assert_eq!(cipher.kms().generates.load(Ordering::SeqCst), 0); +} + +/// A null declared as a fixed-width kind. 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_as_a_fixed_width_kind_is_refused_until_2023() { + let cipher = counting().await; + for kind in [ValueKind::Int64, ValueKind::Bool, ValueKind::Timestamp] { + let null = Sealable { + value: OwnedFrame::null(), + kind: Some(kind), + }; + let refused = seal(&cipher.default_keyset(), vec![null]) + .await + .unwrap_err(); + assert_eq!(refused.code, "recipher_js::null", "{kind:?}"); + } + assert_eq!(cipher.kms().generates.load(Ordering::SeqCst), 0); +} diff --git a/languages/typescript/packages/recipher-js/crate/src/error.rs b/languages/typescript/packages/recipher-js/crate/src/error.rs index 97c7fa4be..843e4766b 100644 --- a/languages/typescript/packages/recipher-js/crate/src/error.rs +++ b/languages/typescript/packages/recipher-js/crate/src/error.rs @@ -70,10 +70,14 @@ pub(crate) enum Error { help("To encrypt the object as a JSON document, wrap it in `json(..)`.") )] PlainObject, - /// The engine refused to encrypt a value in the form it was given. - #[error("the engine could not encrypt the value in the form it was given")] - #[diagnostic(code(recipher_js::not_sealed))] - NotSealed, + /// `null` given as one value. A ciphertext contains one value, and + /// `null` is the absence of one. + #[error("`null` cannot be encrypted as one value")] + #[diagnostic( + code(recipher_js::null), + help("Store a value that is not there as a database `NULL`. For a fixed-width type, such as a boolean, a number, a date, a timestamp or a decimal, declare its kind, as in `{{ kind: kinds.int64 }}`.") + )] + Null, /// `decrypt` given something that is not a `Ciphertext`. #[error("decrypt accepts a Ciphertext, or an array of ciphertexts")] #[diagnostic( @@ -85,6 +89,22 @@ 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( @@ -518,9 +538,11 @@ mod tests { Error::Threw, Error::NotAScalar, Error::PlainObject, - Error::NotSealed, + Error::Null, Error::NotACiphertext, Error::NotBytes, + Error::Options, + Error::JsonKind, Error::NotAKind, Error::OpenedType { kind: ValueKind::String, @@ -539,9 +561,11 @@ mod tests { | Error::Threw | Error::NotAScalar | Error::PlainObject - | Error::NotSealed + | Error::Null | Error::NotACiphertext | Error::NotBytes + | Error::Options + | Error::JsonKind | Error::NotAKind | Error::OpenedType { .. } | Error::NotADocument @@ -567,6 +591,11 @@ mod tests { Error::PlainObject => { Some("To encrypt the object as a JSON document, wrap it in `json(..)`.") } + Error::Null => Some("Store a value that is not there as a database `NULL`. For a fixed-width type, such as a boolean, a number, a date, a timestamp or a decimal, declare its kind, as in `{ kind: kinds.int64 }`."), + 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`.") @@ -579,7 +608,6 @@ mod tests { } Error::Value | Error::Threw - | Error::NotSealed | Error::NotBytes | Error::OpenedType { .. } | Error::NotADocument diff --git a/languages/typescript/packages/recipher-js/crate/src/json.rs b/languages/typescript/packages/recipher-js/crate/src/json.rs index 7c274e0d5..9df8a3f23 100644 --- a/languages/typescript/packages/recipher-js/crate/src/json.rs +++ b/languages/typescript/packages/recipher-js/crate/src/json.rs @@ -11,8 +11,8 @@ //! //! - 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 parser. The parser makes the [`JsonPlaintext`] that the -//! engine encrypts. +//! 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. //! @@ -74,7 +74,7 @@ impl Json { /// document. `json(..)` never throws, so it kept the refusal for /// `encrypt` to return. /// - `Some(Ok(..))`: `value` is a `Json`. The result contains its - /// document. + /// 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` @@ -84,31 +84,31 @@ impl Json { /// /// ```ignore /// let leaf = match Json::of(env, value) { - /// // `keyset.encrypt(json({ name: 'Ada' }))`: the document, or - /// // the refusal that `json(..)` kept. - /// Some(document) => OneValue::json(document?), + /// // `keyset.encrypt(json({ name: 'Ada' }))`: the document's + /// // text, or the refusal that `json(..)` kept. + /// Some(text) => Sealable { value: text?, kind: Some(ValueKind::Json) }, /// // `keyset.encrypt('Ada')`: any other value. - /// None => OneValue::scalar(js::read(env, value)?)?, + /// None => Sealable { value: js::read(env, value)?, kind: None }, /// }; /// ``` pub(crate) fn of( env: &Env, value: Unknown<'_>, - ) -> Option> { + ) -> Option> { if !Self::instance_of(env, &value).unwrap_or(false) { return None; } ClassInstance::::from_unknown(value) .ok() - .map(|json| json.document()) + .map(|json| json.text()) } - /// Returns the document as the engine's [`JsonPlaintext`], or the - /// refusal that `json(..)` kept. Each call parses the text again, so - /// each `encrypt` of one `Json` gets a document of its own to wipe. - fn document(&self) -> Result { + /// 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) => plaintext(text.risky_ref()), + Ok(text) => text_frame(text.risky_ref()), Err(refusal) => Err(refusal.clone()), } } @@ -160,18 +160,15 @@ pub fn json_document(env: &Env, document: Unknown<'_>) -> Json { } } -/// Parses `text`, the JSON text of a document, into the value the engine -/// encrypts. +/// 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::not_sealed` for text that the engine's parser -/// refuses. The bridge writes no such text. -pub(crate) fn plaintext(text: &[u8]) -> Result { - std::str::from_utf8(text) - .ok() - .and_then(|text| JsonPlaintext::parse(text).ok()) - .ok_or_else(|| Error::NotSealed.into()) +/// 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 @@ -187,44 +184,35 @@ pub(crate) fn opened(value: &OwnedFrame) -> Result 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 document = - plaintext(br#"{"n":5000000000,"big":18446744073709551615,"f":1.5}"#).unwrap(); + let text = text_frame(br#"{"n":5000000000,"big":18446744073709551615,"f":1.5}"#).unwrap(); assert_eq!( - document.value(), + 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() { - assert!(plaintext(nested(MAX_DEPTH).as_bytes()).is_ok()); - let refused = plaintext(nested(MAX_DEPTH + 1).as_bytes()).unwrap_err(); - assert_eq!(refused.code, "recipher_js::not_sealed"); - } - - #[test] - fn text_the_engine_does_not_read_is_refused_without_the_text() { - for text in [ - &b"{not json"[..], - br#"{"a":1,"a":2}"#, - b"18446744073709551616", - b"\xff", - ] { - let refused = plaintext(text).unwrap_err(); - assert_eq!(refused.code, "recipher_js::not_sealed"); - assert!(!refused.message.contains("not json")); - } + 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] diff --git a/languages/typescript/packages/recipher-js/crate/src/lib.rs b/languages/typescript/packages/recipher-js/crate/src/lib.rs index f351bb2c3..39c328460 100644 --- a/languages/typescript/packages/recipher-js/crate/src/lib.rs +++ b/languages/typescript/packages/recipher-js/crate/src/lib.rs @@ -64,7 +64,6 @@ mod error; mod js; mod json; mod outcome; -mod value; #[cfg(all(test, feature = "testing"))] mod engine_tests; diff --git a/languages/typescript/packages/recipher-js/crate/src/value.rs b/languages/typescript/packages/recipher-js/crate/src/value.rs deleted file mode 100644 index 9a44eb73e..000000000 --- a/languages/typescript/packages/recipher-js/crate/src/value.rs +++ /dev/null @@ -1,106 +0,0 @@ -//! A value that the engine encrypts as one leaf. -//! -//! The engine is the Stack Encrypt engine, the `stack-encrypt` crate. A -//! leaf is one value that the engine encrypts as a single ciphertext. - -use stack_encrypt::dynamic::plaintext::{depth, Error as _, Scalar, Sink, SourceError}; -use stack_encrypt::dynamic::{frame::OwnedFrame, ValueKind}; -use stack_encrypt::json::JsonPlaintext; -use stack_encrypt::Encrypt; -use vitaminc_protected::OpaqueDebug; - -use crate::error::{Error, RecipherErrorFields}; - -/// A value checked to be one leaf: one scalar of the engine's value model, -/// or one JSON document. -/// -/// The value model is the set of value types the engine reads. A scalar is -/// a value of the model that is not an array or a map, such as text, a -/// number, or bytes. -/// -/// The engine encrypts the value through its opaque scalar path. That path -/// encrypts a whole value as one leaf. Rust's `keyset.encrypt(value)` uses -/// the same path. So each ciphertext has the form that Rust's -/// `keyset.encrypt` writes for the same value. -/// -/// The engine encrypts a value as one opaque leaf only when its type -/// implements `Scalar`, a trait of the `vitaminc-aead` crate. An -/// [`OwnedFrame`] can contain any value of the model, including an array or -/// a map. So an [`OwnedFrame`] is not a `Scalar`. This type checks that the -/// frame contains one scalar. The check runs once, before the engine reads -/// the value. -/// -/// The opaque path also needs a value it can wipe (`Zeroize`). Wiping drops -/// the value, and the value wipes its own buffer when it drops. `Debug` -/// hides the value. -#[derive(OpaqueDebug)] -pub(crate) struct OneValue(Option); - -/// The value inside a [`OneValue`]: a scalar, or a JSON document. -#[derive(OpaqueDebug)] -enum Leaf { - Scalar(OwnedFrame), - Json(JsonPlaintext), -} - -impl OneValue { - /// Returns `value` as a [`OneValue`], if it is one scalar. - /// - /// # Errors - /// - /// Returns `recipher_js::not_a_scalar` for an array, and - /// `recipher_js::plain_object` for an object. - pub(crate) fn scalar(value: OwnedFrame) -> Result { - match value.frame().kind() { - Some(ValueKind::Array) => Err(Error::NotAScalar.into()), - Some(ValueKind::Object) => Err(Error::PlainObject.into()), - _ => Ok(Self(Some(Leaf::Scalar(value)))), - } - } - - /// Returns a JSON document as a [`OneValue`]. The engine encrypts it as - /// it encrypts any `JsonPlaintext`: as its JSON text. - pub(crate) fn json(document: JsonPlaintext) -> Self { - Self(Some(Leaf::Json(document))) - } -} - -impl zeroize::Zeroize for OneValue { - fn zeroize(&mut self) { - // Dropping the leaf wipes its buffer. - self.0 = None; - } -} - -impl Encrypt for &OneValue { - const DEPTH: Option = depth::SCALAR; - fn visit(self, sink: S) -> Result { - match &self.0 { - Some(Leaf::Scalar(frame)) => frame.visit(sink), - Some(Leaf::Json(document)) => document.visit(sink), - None => Err(S::Error::source(SourceError::msg("a wiped value"))), - } - } -} - -impl Scalar for &OneValue {} - -#[cfg(test)] -mod tests { - use super::OneValue; - use stack_encrypt::dynamic::frame::OwnedFrame; - - #[test] - fn a_scalar_is_one_value_and_a_container_is_not() { - assert!(OneValue::scalar(OwnedFrame::of("text").unwrap()).is_ok()); - assert!(OneValue::scalar(OwnedFrame::of(vec![1u8, 2]).unwrap()).is_ok()); - let refused = OneValue::scalar(OwnedFrame::of(vec!["a", "b"]).unwrap()).unwrap_err(); - assert_eq!(refused.code, "recipher_js::not_a_scalar"); - } - - #[test] - fn debug_hides_the_value() { - let value = OneValue::scalar(OwnedFrame::of("secret").unwrap()).unwrap(); - assert!(!format!("{value:?}").contains("secret")); - } -} diff --git a/languages/typescript/packages/recipher-js/native-header.d.ts b/languages/typescript/packages/recipher-js/native-header.d.ts index aa384aed7..8ce1737ef 100644 --- a/languages/typescript/packages/recipher-js/native-header.d.ts +++ b/languages/typescript/packages/recipher-js/native-header.d.ts @@ -5,7 +5,13 @@ // biome-ignore-start lint/correctness/noUnusedImports: the generated signatures after this header use these imports. import type { RecipherError } from './src/error' -import type { Kind, ValueOf } from './src/kinds' +import type { + Declared, + EncryptOptions, + Kind, + OpenedAs, + ValueOf, +} from './src/kinds' import type { Err, Ok, Result } from './src/result' import type { JsonMarker, diff --git a/languages/typescript/packages/recipher-js/native.d.ts b/languages/typescript/packages/recipher-js/native.d.ts index 0877758f9..4b9ad13c1 100644 --- a/languages/typescript/packages/recipher-js/native.d.ts +++ b/languages/typescript/packages/recipher-js/native.d.ts @@ -5,7 +5,13 @@ // biome-ignore-start lint/correctness/noUnusedImports: the generated signatures after this header use these imports. import type { RecipherError } from './src/error' -import type { Kind, ValueOf } from './src/kinds' +import type { + Declared, + EncryptOptions, + Kind, + OpenedAs, + ValueOf, +} from './src/kinds' import type { Err, Ok, Result } from './src/result' import type { JsonMarker, @@ -170,16 +176,27 @@ export declare class Keyset { * 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. * - * 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. + * 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 array of values, the kind applies to each + * 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`. - * The promise does not reject. + * `null` is an `Err` with the code `recipher_js::null`. Store a value + * that is not there as a database `NULL`. The promise does not reject. */ 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, or an array of them. A * ciphertext of another keyset fails with the code diff --git a/languages/typescript/packages/recipher-js/src/index.ts b/languages/typescript/packages/recipher-js/src/index.ts index e7971d155..04286308f 100644 --- a/languages/typescript/packages/recipher-js/src/index.ts +++ b/languages/typescript/packages/recipher-js/src/index.ts @@ -43,7 +43,15 @@ export { type RecipherErrorFields, type Severity, } from './error' -export { type Kind, kinds, type ValueOf } from './kinds' +export { + type Declared, + type EncryptOptions, + type FixedWidthName, + type Kind, + kinds, + type OpenedAs, + type ValueOf, +} from './kinds' export { Err, err, Ok, ok, type Result } from './result' export { type Json, diff --git a/languages/typescript/packages/recipher-js/src/kinds.ts b/languages/typescript/packages/recipher-js/src/kinds.ts index 1ddb7c6eb..dd70be52a 100644 --- a/languages/typescript/packages/recipher-js/src/kinds.ts +++ b/languages/typescript/packages/recipher-js/src/kinds.ts @@ -8,7 +8,13 @@ * 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. */ -import type { OpenedJson, RcDate, RcDecimal, RcTimestamp } from './value-types' +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 { @@ -25,6 +31,55 @@ function kind(name: Name): Kind { /** The TypeScript type of a value of kind `K`. */ export type ValueOf = K extends Kind ? T : 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 `number` that is a whole number. A + * `json` value is a `Json` from `json(..)`. A fixed-width kind also takes + * `null`. + */ +export type Declared = + | (K['name'] extends 'json' + ? JsonMarker + : ValueOf extends bigint + ? number | bigint + : ValueOf) + | (K['name'] extends FixedWidthName ? null : never) + +/** + * The type that a value of type `V`, encrypted with the declared kind `K`, + * decrypts to. + */ +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`. */ + 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 diff --git a/languages/typescript/packages/recipher-js/type-tests/values.ts b/languages/typescript/packages/recipher-js/type-tests/values.ts index 3c064d27b..e1777ca56 100644 --- a/languages/typescript/packages/recipher-js/type-tests/values.ts +++ b/languages/typescript/packages/recipher-js/type-tests/values.ts @@ -91,3 +91,36 @@ const untyped = Ciphertext.fromBytes(stored) check, RecipherError>>>() // @ts-expect-error: a kind is one of `kinds`. void Ciphertext.fromBytes(stored, 'string') + +// 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 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: kinds.int64 }) +check, RecipherError>>>() +// @ts-expect-error: a null of a variable-width kind is not a value. +void keyset.encrypt(null, { kind: kinds.string }) +// @ts-expect-error: a null of a variable-width kind is not a value. +void keyset.encrypt(null, { kind: kinds.bytes }) +// @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' }) From 6b52b680646c584837d3b5aeac33e28d5937513e Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 29 Nov 2026 16:18:04 +1100 Subject: [PATCH 22/25] fix(recipher-js): give a refused null value the code recipher_js::null_value feat/recipher-js-records already uses recipher_js::null for a null mode that the engine does not have. The two errors are about different things, so a lone null now has its own code, recipher_js::null_value. --- languages/typescript/packages/recipher-js/README.md | 2 +- .../recipher-js/__tests__/addon/values.test.ts | 6 +++--- .../packages/recipher-js/crate/src/cipher.rs | 9 +++++---- .../packages/recipher-js/crate/src/engine_tests.rs | 4 ++-- .../typescript/packages/recipher-js/crate/src/error.rs | 10 +++++----- languages/typescript/packages/recipher-js/native.d.ts | 5 +++-- 6 files changed, 19 insertions(+), 17 deletions(-) diff --git a/languages/typescript/packages/recipher-js/README.md b/languages/typescript/packages/recipher-js/README.md index dc85b3ab3..add38f161 100644 --- a/languages/typescript/packages/recipher-js/README.md +++ b/languages/typescript/packages/recipher-js/README.md @@ -119,7 +119,7 @@ const opened = (await cipher.decrypt(age)).unwrap() - 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. - A ciphertext contains one value, and `null` is the absence of a value. - So a lone `null` is an `Err` with the code `recipher_js::null`. + So a lone `null` is an `Err` with the code `recipher_js::null_value`. Store a value that is not there as a database `NULL`. - A lone `null` needs a declared kind. The kind must be fixed-width: a boolean, an integer, a float, a decimal, a date, or a timestamp. diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts index e24896055..3bde19837 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts @@ -717,7 +717,7 @@ describe('a declared kind', () => { const keyset = (await cipher()).defaultKeyset() for (const kind of [kinds.int64, kinds.boolean, kinds.timestamp]) { const result = await keyset.encrypt(null, { kind }) - expect(result.err()?.code).toBe('recipher_js::null') + expect(result.err()?.code).toBe('recipher_js::null_value') } }) @@ -811,7 +811,7 @@ describe('refusals', () => { await keyset.encrypt(null), await keyset.encrypt(['fine', null]), ]) { - expect(result.err()?.code).toBe('recipher_js::null') + expect(result.err()?.code).toBe('recipher_js::null_value') expect(result.err()?.help).toContain('database `NULL`') } }) @@ -821,7 +821,7 @@ describe('refusals', () => { for (const kind of [kinds.string, kinds.bytes]) { // @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') + expect(result.err()?.code).toBe('recipher_js::null_value') } }) diff --git a/languages/typescript/packages/recipher-js/crate/src/cipher.rs b/languages/typescript/packages/recipher-js/crate/src/cipher.rs index a44df4418..f2582f3c9 100644 --- a/languages/typescript/packages/recipher-js/crate/src/cipher.rs +++ b/languages/typescript/packages/recipher-js/crate/src/cipher.rs @@ -173,8 +173,9 @@ impl Keyset { /// /// 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` is an `Err` with the code `recipher_js::null`. Store a value - /// that is not there as a database `NULL`. The promise does not reject. + /// `null` 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_type = "(value: V): Promise>, RecipherError>> encrypt(values: readonly V[]): Promise>[], RecipherError>> @@ -476,7 +477,7 @@ where /// /// - an array inside an array: `recipher_js::not_a_scalar`; /// - a plain object: `recipher_js::plain_object`; -/// - `null`: `recipher_js::null`. +/// - `null`: `recipher_js::null_value`. /// /// Any other refusal keeps the engine's code. fn refusal(error: &stack_encrypt::dynamic::Error) -> RecipherErrorFields { @@ -486,7 +487,7 @@ fn refusal(error: &stack_encrypt::dynamic::Error) -> RecipherErrorFields { match error.found() { Some(Found::Kind(ValueKind::Array)) => Error::NotAScalar.into(), Some(Found::Kind(ValueKind::Object)) => Error::PlainObject.into(), - Some(Found::Null) => Error::Null.into(), + Some(Found::Null) => Error::NullValue.into(), _ => RecipherErrorFields::engine(error), } } 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 84509a5ab..e788fc59b 100644 --- a/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs +++ b/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs @@ -349,7 +349,7 @@ async fn a_null_with_no_declared_kind_is_refused_before_any_request() { let refused = seal(&cipher.default_keyset(), vec![null]) .await .unwrap_err(); - assert_eq!(refused.code, "recipher_js::null"); + assert_eq!(refused.code, "recipher_js::null_value"); assert!(refused .help .is_some_and(|help| help.contains("database `NULL`"))); @@ -372,7 +372,7 @@ async fn a_null_declared_as_a_fixed_width_kind_is_refused_until_2023() { let refused = seal(&cipher.default_keyset(), vec![null]) .await .unwrap_err(); - assert_eq!(refused.code, "recipher_js::null", "{kind:?}"); + assert_eq!(refused.code, "recipher_js::null_value", "{kind:?}"); } assert_eq!(cipher.kms().generates.load(Ordering::SeqCst), 0); } diff --git a/languages/typescript/packages/recipher-js/crate/src/error.rs b/languages/typescript/packages/recipher-js/crate/src/error.rs index 843e4766b..67937d929 100644 --- a/languages/typescript/packages/recipher-js/crate/src/error.rs +++ b/languages/typescript/packages/recipher-js/crate/src/error.rs @@ -74,10 +74,10 @@ pub(crate) enum Error { /// `null` is the absence of one. #[error("`null` cannot be encrypted as one value")] #[diagnostic( - code(recipher_js::null), + code(recipher_js::null_value), help("Store a value that is not there as a database `NULL`. For a fixed-width type, such as a boolean, a number, a date, a timestamp or a decimal, declare its kind, as in `{{ kind: kinds.int64 }}`.") )] - Null, + NullValue, /// `decrypt` given something that is not a `Ciphertext`. #[error("decrypt accepts a Ciphertext, or an array of ciphertexts")] #[diagnostic( @@ -538,7 +538,7 @@ mod tests { Error::Threw, Error::NotAScalar, Error::PlainObject, - Error::Null, + Error::NullValue, Error::NotACiphertext, Error::NotBytes, Error::Options, @@ -561,7 +561,7 @@ mod tests { | Error::Threw | Error::NotAScalar | Error::PlainObject - | Error::Null + | Error::NullValue | Error::NotACiphertext | Error::NotBytes | Error::Options @@ -591,7 +591,7 @@ mod tests { Error::PlainObject => { Some("To encrypt the object as a JSON document, wrap it in `json(..)`.") } - Error::Null => Some("Store a value that is not there as a database `NULL`. For a fixed-width type, such as a boolean, a number, a date, a timestamp or a decimal, declare its kind, as in `{ kind: kinds.int64 }`."), + Error::NullValue => Some("Store a value that is not there as a database `NULL`. For a fixed-width type, such as a boolean, a number, a date, a timestamp or a decimal, declare its kind, as in `{ kind: kinds.int64 }`."), 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.") diff --git a/languages/typescript/packages/recipher-js/native.d.ts b/languages/typescript/packages/recipher-js/native.d.ts index 4b9ad13c1..493cd2bf0 100644 --- a/languages/typescript/packages/recipher-js/native.d.ts +++ b/languages/typescript/packages/recipher-js/native.d.ts @@ -190,8 +190,9 @@ export declare class Keyset { * * 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` is an `Err` with the code `recipher_js::null`. Store a value - * that is not there as a database `NULL`. The promise does not reject. + * `null` 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: V): Promise>, RecipherError>> encrypt(values: readonly V[]): Promise>[], RecipherError>> From 988ae6a2c559f2f24c689d17ff6e57699cd4364d Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 29 Nov 2026 18:05:17 +1100 Subject: [PATCH 23/25] fix(recipher-js): refuse an unsafe number for an integer kind, and fix the null help A whole number outside 2^53 - 1 either side of zero, declared as an integer kind, was stored as the number it had become. For example, 12345678901234567890 declared as uint64 decrypted as 12345678901234567168n. Such a number is now refused before the engine reads it, with the code recipher_js::unsafe_integer. The help asks for a bigint. json(..) already refuses the same numbers. The other changes: - null as the options of encrypt is refused with recipher_js::options. Before, napi read it as no options. - The help for undefined no longer says to use null. A lone null is refused too. - The help for a refused null no longer suggests a declared kind that fails today. With no kind or a fixed-width kind, it says a declared kind will work once the engine encrypts typed nulls. With a variable-width kind, it says only to store a database NULL. - A value that does not convert to its declared kind keeps the engine's code and fields, with a help about the conversion. - A stored null decrypts as null when it is read with a fixed-width kind. So fromBytes with such a kind now has the type bigint | null, and so on for each fixed-width kind. - Declared distributes over a union of kinds. - encrypt with no kind no longer takes null in its type: Scalar has no null. OpenedScalar still has it, for a stored null. - A crate test checks that 34 declared as uint64 is stored as a uint64. --- .../typescript/packages/recipher-js/README.md | 27 ++++-- .../__tests__/addon/values.test.ts | 84 +++++++++++++++++- .../packages/recipher-js/crate/src/cipher.rs | 84 +++++++++++++----- .../recipher-js/crate/src/ciphertext.rs | 75 ++++++++++++++-- .../recipher-js/crate/src/engine_tests.rs | 88 +++++++++++++++++++ .../packages/recipher-js/crate/src/error.rs | 77 +++++++++++++--- .../packages/recipher-js/native-header.d.ts | 6 +- .../packages/recipher-js/native.d.ts | 26 +++--- .../packages/recipher-js/src/index.ts | 1 + .../packages/recipher-js/src/kinds.ts | 41 ++++++--- .../packages/recipher-js/src/value-types.ts | 33 ++++--- .../packages/recipher-js/src/values.ts | 8 +- .../packages/recipher-js/type-tests/values.ts | 26 +++++- 13 files changed, 488 insertions(+), 88 deletions(-) diff --git a/languages/typescript/packages/recipher-js/README.md b/languages/typescript/packages/recipher-js/README.md index add38f161..c2489b7d0 100644 --- a/languages/typescript/packages/recipher-js/README.md +++ b/languages/typescript/packages/recipher-js/README.md @@ -63,7 +63,7 @@ The value bridge converts JavaScript values in both directions: | `new RcTimestamp('2026-11-23T01:02:03.000000001Z')` | a timestamp, in nanoseconds | `Date` when it is whole milliseconds, else `RcTimestamp` | | `new RcDate('2026-11-23')` | a calendar date | `RcDate` | | `new RcDecimal('1.50')` | a decimal, with its scale | `RcDecimal` | -| `null` | refused with no kind: see [A declared kind](#a-declared-kind) | not applicable | +| `null` | refused: see [A declared kind](#a-declared-kind) | `null`, for a null stored another way | | `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. @@ -72,6 +72,9 @@ The value bridge converts JavaScript values in both directions: - 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. - 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. @@ -113,20 +116,24 @@ const opened = (await cipher.decrypt(age)).unwrap() 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. -- A ciphertext contains one value, and `null` is the absence of a value. - So a lone `null` is an `Err` with the code `recipher_js::null_value`. + `null` as the options is refused with the same code. +- A lone `null` is an `Err` with the code `recipher_js::null_value`, with a kind or without one. Store a value that is not there as a database `NULL`. -- A lone `null` needs a declared kind. - The kind must be fixed-width: a boolean, an integer, a float, a decimal, a date, or a timestamp. - The engine will encrypt it as a typed null, padded to the size of a value, as a record field with `"null": "sealed"` stores one. - Issue #2023 makes that engine change. - The change has not merged yet. - Until then, a `null` with a kind is refused too. +- Once the engine encrypts a typed null as one value, a `null` declared as 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: kinds.int64 })`, and the call is refused when it runs. - A `null` of a variable-width kind, such as `kinds.string` or `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. @@ -202,6 +209,8 @@ The ciphertext's TypeScript type allows any scalar: any type in the table above `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 stored null decrypts as `null` with a fixed-width kind, so the type of `Ciphertext.fromBytes(bytes, kinds.int64)` is `Ciphertext`. +With a variable-width kind, such as `kinds.string`, a stored null is refused. ## Results, not exceptions diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts index 3bde19837..e26793801 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts @@ -631,7 +631,9 @@ describe('a ciphertext read back with a kind', () => { const c = await cipher() const sealed = (await c.defaultKeyset().encrypt(42n)).unwrap() const stored = Ciphertext.fromBytes(sealed.toBytes(), kinds.int64).unwrap() - const opened: bigint = (await c.decrypt(stored)).unwrap() + // A stored null of a fixed-width kind decrypts as null, so the type + // allows one. + const opened: bigint | null = (await c.decrypt(stored)).unwrap() expect(opened).toBe(42n) }) @@ -675,11 +677,73 @@ describe('a declared kind', () => { await c.defaultKeyset().encrypt(34, { kind: kinds.uint64 }) ).unwrap() expect((await c.decrypt(sealed)).unwrap()).toBe(34n) - // The stored bytes are those of a uint64, so the kind reads them back. + // 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 = ( @@ -706,6 +770,9 @@ describe('a declared kind', () => { 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 fixed-width kind until #2023', async () => { @@ -718,6 +785,9 @@ describe('a declared kind', () => { for (const kind of [kinds.int64, kinds.boolean, kinds.timestamp]) { const result = await keyset.encrypt(null, { kind }) expect(result.err()?.code).toBe('recipher_js::null_value') + // The help does not suggest a call that fails today. + expect(result.err()?.help).toContain('database `NULL`') + expect(result.err()?.help).toContain('once the engine') } }) @@ -740,6 +810,7 @@ describe('a declared kind', () => { 'uint64', { kind: kinds.uint64, context: 'users' }, {}, + null, ]) { // @ts-expect-error: the options are `{ kind }`. const result = await keyset.encrypt(34, options) @@ -803,12 +874,17 @@ describe('refusals', () => { // @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') @@ -822,6 +898,10 @@ describe('refusals', () => { // @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`.', + ) } }) diff --git a/languages/typescript/packages/recipher-js/crate/src/cipher.rs b/languages/typescript/packages/recipher-js/crate/src/cipher.rs index f2582f3c9..6a9ea5f1c 100644 --- a/languages/typescript/packages/recipher-js/crate/src/cipher.rs +++ b/languages/typescript/packages/recipher-js/crate/src/cipher.rs @@ -14,9 +14,9 @@ use std::sync::Arc; use napi::bindgen_prelude::{ - JavaScriptClassExt, JsValue, Object, PromiseRaw, ToNapiValue, Unknown, + FromNapiValue, JavaScriptClassExt, JsValue, Object, PromiseRaw, ToNapiValue, Unknown, }; -use napi::Env; +use napi::{Env, ValueType}; use napi_derive::napi; use stack_encrypt::dynamic::{frame::OwnedFrame, value, Found, Reason, ValueKind}; use stack_encrypt::kms::{DataKeySource, IndexKeySource, StackKms}; @@ -168,14 +168,18 @@ impl Keyset { /// 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 array of values, the kind applies to each - /// value. + /// 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`. /// /// 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` 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. + /// `null` is an `Err` with the code `recipher_js::null_value`, with a + /// kind or without one. Store a value that is not there as a database + /// `NULL`. The promise does not reject. #[napi( ts_type = "(value: V): Promise>, RecipherError>> encrypt(values: readonly V[]): Promise>[], RecipherError>> @@ -186,7 +190,7 @@ encrypt>(values: readonly V[], options: En &self, env: &'e Env, value: Unknown<'_>, - options: Option>, + options: Unknown<'_>, ) -> napi::Result>> { let declared = match crate::ciphertext::declared_kind(env, options) { Ok(declared) => declared, @@ -417,6 +421,12 @@ pub(crate) struct Sealable { /// 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::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<'_>, @@ -435,6 +445,9 @@ fn one_value( if declared == Some(ValueKind::Json) { return Err(Error::JsonKind.into()); } + if declared.is_some_and(crate::ciphertext::integer) && unsafe_number(value) { + return Err(Error::UnsafeInteger.into()); + } let sealable = Sealable { value: js::read(env, value)?, kind: declared, @@ -442,6 +455,20 @@ fn one_value( Ok((sealable, declared)) } +/// 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 typed `keyset.decrypt` decrypts each ciphertext. The @@ -459,9 +486,11 @@ where { let calls = values .iter() - .map(|sealable| value::encrypt(keyset, sealable.value.frame(), sealable.kind)) - .collect::, _>>() - .map_err(|error| refusal(&error))?; + .map(|sealable| { + value::encrypt(keyset, sealable.value.frame(), sealable.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); @@ -470,8 +499,13 @@ 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. +/// 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: /// @@ -479,15 +513,23 @@ where /// - a plain object: `recipher_js::plain_object`; /// - `null`: `recipher_js::null_value`. /// -/// Any other refusal keeps the engine's code. -fn refusal(error: &stack_encrypt::dynamic::Error) -> RecipherErrorFields { - if error.reason() != Some(Reason::NotAScalar) { - return RecipherErrorFields::engine(error); - } - match error.found() { - Some(Found::Kind(ValueKind::Array)) => Error::NotAScalar.into(), - Some(Found::Kind(ValueKind::Object)) => Error::PlainObject.into(), - Some(Found::Null) => Error::NullValue.into(), +/// 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), } } diff --git a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs index 50a4a98ff..34a782236 100644 --- a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs +++ b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs @@ -71,12 +71,15 @@ impl Ciphertext { } /// Returns a decrypted value as the kind this ciphertext decrypts as. + /// A null decrypts as null when the kind is fixed-width, such as + /// `int64`. /// /// # Errors /// /// 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. + /// type, and for a null with a variable-width kind, such as `string`. + /// 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 { match self.opens_as { None => Ok(Opened::Value(value)), @@ -96,7 +99,9 @@ impl Ciphertext { /// 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. + /// `kinds.json` decrypts a JSON document. With a fixed-width kind, such + /// as `kinds.int64`, a stored null decrypts as `null`. With any other + /// kind, a stored null is refused. /// /// 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 @@ -108,7 +113,7 @@ impl Ciphertext { /// - `recipher_js::not_bytes`, when the bytes are not a `Uint8Array`; /// - `recipher_js::not_a_kind`, when the kind is not one of `kinds`. #[napi( - ts_type = "(bytes: Uint8Array, kind: K): Result>, RecipherError> + ts_type = "(bytes: Uint8Array, kind: K): Result>, RecipherError> static fromBytes(bytes: Uint8Array): Result" )] pub fn from_bytes<'e>( @@ -185,10 +190,12 @@ fn kind_of(env: &Env, value: Option>) -> Outcome> /// # Errors /// /// - `recipher_js::options`, when the options are not an object whose only -/// key is `kind`; +/// key is `kind`, `null` included; /// - `recipher_js::not_a_kind`, when the kind is not one of `kinds`. -pub(crate) fn declared_kind(env: &Env, value: Option>) -> Outcome> { - let Some(value) = given(value) else { +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)?; @@ -232,7 +239,7 @@ fn readable(kind: ValueKind) -> bool { } /// Returns whether `kind` is an integer kind. -fn integer(kind: ValueKind) -> bool { +pub(crate) fn integer(kind: ValueKind) -> bool { matches!( kind, ValueKind::Int8 @@ -248,13 +255,37 @@ fn integer(kind: ValueKind) -> bool { ) } +/// 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 list matches `FixedWidthName` in `src/kinds.ts`. +pub(crate) fn fixed_width(kind: ValueKind) -> bool { + integer(kind) + || matches!( + kind, + ValueKind::Bool + | ValueKind::Float32 + | ValueKind::Float64 + | ValueKind::Decimal + | ValueKind::Date + | ValueKind::Timestamp + ) +} + /// Returns `value` as `kind`. /// /// 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. +/// when the conversion is exact. When `kind` is fixed-width, a plain null +/// or a typed null is returned unchanged. Any other value is refused. fn as_kind(kind: ValueKind, value: OwnedFrame) -> Outcome { let refused = || RecipherErrorFields::from(Error::OpenedType { kind }); + if value.frame().is_null() { + return if fixed_width(kind) { + Ok(value) + } else { + Err(refused()) + }; + } let opened = value.frame().kind(); if opened == Some(kind) { return Ok(value); @@ -289,6 +320,7 @@ mod tests { use super::{as_kind, readable}; 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() { @@ -335,4 +367,29 @@ mod tests { assert!(as_kind(ValueKind::String, OwnedFrame::of(true).unwrap()).is_err()); assert!(as_kind(ValueKind::String, OwnedFrame::of("x").unwrap()).is_ok()); } + + #[test] + fn a_null_opens_as_null_for_a_fixed_width_kind_and_no_other() { + let typed = || OwnedFrame::typed_null(FixedType::plain(Width::I64).unwrap()); + for kind in [ + ValueKind::Int64, + ValueKind::UInt8, + ValueKind::Bool, + ValueKind::Float64, + ValueKind::Decimal, + ValueKind::Date, + ValueKind::Timestamp, + ] { + for null in [OwnedFrame::null(), typed()] { + let opened = as_kind(kind, null).unwrap(); + assert!(opened.frame().is_null(), "{kind}"); + } + } + // A value of a variable-width kind has no fixed size, so no null + // stands in for one. + for kind in [ValueKind::String, ValueKind::Bytes] { + let refused = as_kind(kind, OwnedFrame::null()).unwrap_err(); + assert_eq!(refused.code, "recipher_js::opened_type", "{kind}"); + } + } } 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 e788fc59b..2362ec8ec 100644 --- a/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs +++ b/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs @@ -373,6 +373,94 @@ async fn a_null_declared_as_a_fixed_width_kind_is_refused_until_2023() { .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}"); + } + // A kind never helps a null of a variable-width type, so the help + // suggests none. + for kind in [ValueKind::String, ValueKind::Bytes] { + let null = Sealable { + value: OwnedFrame::null(), + kind: Some(kind), + }; + let refused = seal(&cipher.default_keyset(), vec![null]) + .await + .unwrap_err(); + assert_eq!(refused.code, "recipher_js::null_value", "{kind:?}"); + assert_eq!( + refused.help.as_deref(), + Some("Store a value that is not there as a database `NULL`."), + "{kind:?}" + ); } 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 a fixed-width kind, and is refused with a +/// variable-width kind. +#[tokio::test] +async fn a_null_the_engine_sealed_opens_as_null_with_a_fixed_width_kind() { + let cipher = engine().await; + let tree = cipher + .default_keyset() + .encrypt_tree(None::, ()) + .await + .unwrap(); + let stack_encrypt::CipherText::Single(leaf) = tree else { + panic!("a null seals as one leaf"); + }; + let sealed = stack_encrypt::Ciphertext::from(leaf); + let read = Ciphertext::new(sealed.clone(), Some(ValueKind::Int64)); + let Opened::Value(opened) = read.opened(sdk_open(sealed.clone()).await).unwrap() else { + panic!("an int64 opens as a value"); + }; + assert!(opened.frame().is_null()); + let as_text = Ciphertext::new(sealed.clone(), Some(ValueKind::String)); + let refused = as_text.opened(sdk_open(sealed).await).unwrap_err(); + assert_eq!(refused.code, "recipher_js::opened_type"); +} + +/// 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(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(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 67937d929..8c76b3cc1 100644 --- a/languages/typescript/packages/recipher-js/crate/src/error.rs +++ b/languages/typescript/packages/recipher-js/crate/src/error.rs @@ -37,7 +37,7 @@ pub(crate) enum Error { #[error("`undefined` cannot be encrypted")] #[diagnostic( code(recipher_js::undefined), - help("Use `null` for a value that is not there.") + 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 @@ -71,13 +71,24 @@ pub(crate) enum Error { )] PlainObject, /// `null` given as one value. A ciphertext contains one value, and - /// `null` is the absence of one. + /// `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`], or [`NULL_HELP_FIXED_WIDTH`]. + #[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::null_value), - help("Store a value that is not there as a database `NULL`. For a fixed-width type, such as a boolean, a number, a date, a timestamp or a decimal, declare its kind, as in `{{ kind: kinds.int64 }}`.") + code(recipher_js::unsafe_integer), + help("The safe range is 2^53 - 1 either side of zero. Pass the integer as a `bigint` instead.") )] - NullValue, + UnsafeInteger, /// `decrypt` given something that is not a `Ciphertext`. #[error("decrypt accepts a Ciphertext, or an array of ciphertexts")] #[diagnostic( @@ -149,6 +160,31 @@ pub(crate) enum Error { BuildValue, } +/// The help of a refused `null` declared as a variable-width kind, such as +/// `string`. 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. The engine does not encrypt a typed null as one value +/// yet, so the help does not suggest a call that fails today. +pub(crate) const NULL_HELP_FIXED_WIDTH: &str = "Store a value that is not there as a database `NULL`. A `null` declared as a fixed-width kind, such as `kinds.int64`, 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 variable_width = declared.is_some_and(|kind| !crate::ciphertext::fixed_width(kind)); + Self::NullValue { + help: if variable_width { + NULL_HELP + } else { + NULL_HELP_FIXED_WIDTH + }, + } + } +} + /// How serious a failure is, as the diagnostic states it. #[napi(string_enum = "snake_case")] #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -346,7 +382,10 @@ 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_FIXED_WIDTH, + UNDESCRIBED_CAUSE, + }; use stack_encrypt::dynamic::ValueKind; #[test] @@ -431,7 +470,7 @@ mod tests { assert_eq!(error.message, "`undefined` cannot be encrypted"); assert_eq!( error.help.as_deref(), - Some("Use `null` for a value that is not there.") + 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()); @@ -538,7 +577,8 @@ mod tests { Error::Threw, Error::NotAScalar, Error::PlainObject, - Error::NullValue, + Error::null_value(None), + Error::UnsafeInteger, Error::NotACiphertext, Error::NotBytes, Error::Options, @@ -561,7 +601,8 @@ mod tests { | Error::Threw | Error::NotAScalar | Error::PlainObject - | Error::NullValue + | Error::NullValue { .. } + | Error::UnsafeInteger | Error::NotACiphertext | Error::NotBytes | Error::Options @@ -583,7 +624,7 @@ mod tests { /// new variant needs an entry here. fn help_of(error: &Error) -> Option<&'static str> { match error { - Error::Undefined => Some("Use `null` for a value that is not there."), + 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(..)`.") @@ -591,7 +632,10 @@ mod tests { Error::PlainObject => { Some("To encrypt the object as a JSON document, wrap it in `json(..)`.") } - Error::NullValue => Some("Store a value that is not there as a database `NULL`. For a fixed-width type, such as a boolean, a number, a date, a timestamp or a decimal, declare its kind, as in `{ kind: kinds.int64 }`."), + Error::NullValue { .. } => Some(NULL_HELP_FIXED_WIDTH), + 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.") @@ -615,6 +659,17 @@ mod tests { } } + #[test] + fn a_null_has_the_help_for_its_declared_kind() { + let help = |declared| RecipherErrorFields::from(Error::null_value(declared)).help; + for declared in [None, Some(ValueKind::Int64), Some(ValueKind::Timestamp)] { + assert_eq!(help(declared).as_deref(), Some(NULL_HELP_FIXED_WIDTH)); + } + for declared in [ValueKind::String, ValueKind::Bytes, ValueKind::Json] { + assert_eq!(help(Some(declared)).as_deref(), Some(NULL_HELP)); + } + } + #[test] fn every_error_states_its_help_and_no_other() { for error in every_error() { diff --git a/languages/typescript/packages/recipher-js/native-header.d.ts b/languages/typescript/packages/recipher-js/native-header.d.ts index 8ce1737ef..ba59797ff 100644 --- a/languages/typescript/packages/recipher-js/native-header.d.ts +++ b/languages/typescript/packages/recipher-js/native-header.d.ts @@ -10,7 +10,7 @@ import type { EncryptOptions, Kind, OpenedAs, - ValueOf, + ReadAs, } from './src/kinds' import type { Err, Ok, Result } from './src/result' import type { @@ -31,8 +31,8 @@ declare const opens: unique symbol * * 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. + * 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 { /** Stores `T` for the type checker. The property never exists at run time. */ diff --git a/languages/typescript/packages/recipher-js/native.d.ts b/languages/typescript/packages/recipher-js/native.d.ts index 493cd2bf0..7563d532a 100644 --- a/languages/typescript/packages/recipher-js/native.d.ts +++ b/languages/typescript/packages/recipher-js/native.d.ts @@ -10,7 +10,7 @@ import type { EncryptOptions, Kind, OpenedAs, - ValueOf, + ReadAs, } from './src/kinds' import type { Err, Ok, Result } from './src/result' import type { @@ -31,8 +31,8 @@ declare const opens: unique symbol * * 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. + * 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 { /** Stores `T` for the type checker. The property never exists at run time. */ @@ -115,7 +115,9 @@ export declare class Ciphertext { * 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. + * `kinds.json` decrypts a JSON document. With a fixed-width kind, such + * as `kinds.int64`, a stored null decrypts as `null`. With any other + * kind, a stored null is refused. * * 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 @@ -127,7 +129,7 @@ export declare class Ciphertext { * - `recipher_js::not_bytes`, when the bytes are not a `Uint8Array`; * - `recipher_js::not_a_kind`, when the kind is not one of `kinds`. */ - static fromBytes(bytes: Uint8Array, kind: K): Result>, RecipherError> + 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 @@ -185,14 +187,18 @@ export declare class Keyset { * 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 array of values, the kind applies to each - * value. + * 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`. * * 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` 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. + * `null` is an `Err` with the code `recipher_js::null_value`, with a + * kind or without one. Store a value that is not there as a database + * `NULL`. The promise does not reject. */ encrypt(value: V): Promise>, RecipherError>> encrypt(values: readonly V[]): Promise>[], RecipherError>> diff --git a/languages/typescript/packages/recipher-js/src/index.ts b/languages/typescript/packages/recipher-js/src/index.ts index 04286308f..ce4f05fc7 100644 --- a/languages/typescript/packages/recipher-js/src/index.ts +++ b/languages/typescript/packages/recipher-js/src/index.ts @@ -50,6 +50,7 @@ export { type Kind, kinds, type OpenedAs, + type ReadAs, type ValueOf, } from './kinds' export { Err, err, Ok, ok, type Result } from './result' diff --git a/languages/typescript/packages/recipher-js/src/kinds.ts b/languages/typescript/packages/recipher-js/src/kinds.ts index dd70be52a..0b9c37d01 100644 --- a/languages/typescript/packages/recipher-js/src/kinds.ts +++ b/languages/typescript/packages/recipher-js/src/kinds.ts @@ -31,6 +31,14 @@ function kind(name: Name): Kind { /** 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 stored + * null decrypts as `null` when `K` is fixed-width. + */ +export type ReadAs = K extends Kind + ? ValueOf | (K['name'] extends FixedWidthName ? 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 @@ -56,21 +64,32 @@ export type FixedWidthName = /** * The values that `encrypt` takes with the declared kind `K`. A value of an - * integer kind is a `bigint`, or a `number` that is a whole number. A - * `json` value is a `Json` from `json(..)`. A fixed-width kind also takes - * `null`. + * 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. + * + * 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`. */ -export type Declared = - | (K['name'] extends 'json' - ? JsonMarker - : ValueOf extends bigint - ? number | bigint - : ValueOf) - | (K['name'] extends FixedWidthName ? null : never) +export type Declared = K extends Kind + ? + | (K['name'] extends 'json' + ? JsonMarker + : ValueOf extends bigint + ? number | bigint + : ValueOf) + | (K['name'] extends FixedWidthName ? null : never) + : never /** * The type that a value of type `V`, encrypted with the declared kind `K`, - * decrypts to. + * 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 diff --git a/languages/typescript/packages/recipher-js/src/value-types.ts b/languages/typescript/packages/recipher-js/src/value-types.ts index 36f2d9add..e8db5afdf 100644 --- a/languages/typescript/packages/recipher-js/src/value-types.ts +++ b/languages/typescript/packages/recipher-js/src/value-types.ts @@ -45,7 +45,14 @@ export interface RcUuid { readonly [wrapper]: 'RcUuid' } -/** A value that is one scalar: a single value, not a JSON document. */ +/** + * 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 a fixed-width kind + * declared. Until the engine encrypts a typed null as one value, `encrypt` + * refuses that `null` when it runs. + */ export type Scalar = | string | boolean @@ -56,7 +63,6 @@ export type Scalar = | RcTimestamp | RcDate | RcDecimal - | null /** * A JSON value. @@ -107,7 +113,11 @@ export interface JsonMarker { readonly [document]: true } -/** A value that `encrypt` accepts. */ +/** + * 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. */ @@ -129,11 +139,14 @@ export type Opened = V extends string ? RcDate : V extends RcDecimal ? RcDecimal - : V extends null - ? null - : V extends JsonMarker - ? OpenedJson - : never + : V extends JsonMarker + ? OpenedJson + : never -/** Any scalar type that a stored ciphertext can decrypt to. */ -export type OpenedScalar = Opened +/** + * 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 index 33dc1241c..3786d9bd2 100644 --- a/languages/typescript/packages/recipher-js/src/values.ts +++ b/languages/typescript/packages/recipher-js/src/values.ts @@ -16,12 +16,18 @@ * | `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` | null | `null` | + * | `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 a fixed-width kind, + * such as `kinds.int64`, will encrypt once the engine encrypts a typed null + * as one value. A stored null still decrypts as `null`: 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 diff --git a/languages/typescript/packages/recipher-js/type-tests/values.ts b/languages/typescript/packages/recipher-js/type-tests/values.ts index e1777ca56..4ae4600c8 100644 --- a/languages/typescript/packages/recipher-js/type-tests/values.ts +++ b/languages/typescript/packages/recipher-js/type-tests/values.ts @@ -70,6 +70,11 @@ declare const uuid: RcUuid 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. @@ -84,7 +89,11 @@ expectType(day) // no kind, its type is any scalar. declare const stored: Uint8Array const typed = Ciphertext.fromBytes(stored, kinds.int64) -check, RecipherError>>>() +check, RecipherError>>>() +// A stored null of a fixed-width kind decrypts as null. No null stands in +// for a value of a variable-width kind. +const typedText = Ciphertext.fromBytes(stored, kinds.string) +check, RecipherError>>>() const typedJson = Ciphertext.fromBytes(stored, kinds.json) check, RecipherError>>>() const untyped = Ciphertext.fromBytes(stored) @@ -124,3 +133,18 @@ void keyset.encrypt('{"a":1}', { kind: kinds.json }) 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 }) From 0b88351a7588693da1cb92b67527f3d979cba56e Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 29 Nov 2026 18:38:07 +1100 Subject: [PATCH 24/25] feat(recipher-js)!: make null opt-in with nullable(kind), as Rust's Option A kind from `kinds` now takes no null, as a Rust type that is not an `Option` takes no `None`. `Ciphertext.fromBytes(bytes, kinds.int64)` is a `Ciphertext`. Decrypting a stored null with it is an `Err` with the new code `recipher_js::opened_null`, whose help says to read with `nullable(..)`. Rust's `decrypt::` refuses a null the same way. `nullable(kind)` is the kind that also takes `null`. The value is `{ name, nullable: true }`, frozen like each of `kinds`. `nullable` never throws. - Reading: a stored null opens as `null`, for a kind of any width. A stored null can exist for any type, such as one that Rust's `encrypt_tree(None::)` wrote. - Encrypting: a `null` declared as `nullable(..)` of a fixed-width kind goes to the engine as a typed null of the kind. The engine refuses it until #2023 lands, so it is an `Err` today. A test checks the refusal and names #2023. - A `null` with no kind, with a plain kind, or with `nullable(..)` of a variable-width kind does not compile. When the code runs, it is a `recipher_js::null_value` error. The help depends on the kind, and points to `nullable(..)` where that will help. - A value that is not `null` encrypts with `nullable(kind)` as it does with `kind`. The addon reads a kind with any other key, or with a `nullable` that is not `true`, as not a kind (`recipher_js::not_a_kind`). So a misspelt key is never read as a plain kind. A kind in the options of `encrypt` that is not a kind is now `recipher_js::not_a_kind` too, and no longer `recipher_js::options`. `ReadAs` now follows `nullable`, and `Declared` takes `null` only for `nullable(..)` of a fixed-width kind. The type tests cover each case, unions of kinds included. --- .../typescript/packages/recipher-js/README.md | 42 ++- .../__tests__/addon/values.test.ts | 164 ++++++++++- .../packages/recipher-js/crate/src/cipher.rs | 68 ++++- .../recipher-js/crate/src/ciphertext.rs | 268 ++++++++++++++---- .../recipher-js/crate/src/engine_tests.rs | 107 +++---- .../packages/recipher-js/crate/src/error.rs | 89 ++++-- .../packages/recipher-js/crate/src/json.rs | 2 +- .../packages/recipher-js/native.d.ts | 24 +- .../packages/recipher-js/src/index.ts | 3 + .../packages/recipher-js/src/kinds.ts | 91 +++++- .../packages/recipher-js/src/value-types.ts | 7 +- .../packages/recipher-js/src/values.ts | 9 +- .../packages/recipher-js/type-tests/values.ts | 84 +++++- 13 files changed, 752 insertions(+), 206 deletions(-) diff --git a/languages/typescript/packages/recipher-js/README.md b/languages/typescript/packages/recipher-js/README.md index c2489b7d0..9010588c8 100644 --- a/languages/typescript/packages/recipher-js/README.md +++ b/languages/typescript/packages/recipher-js/README.md @@ -63,7 +63,7 @@ The value bridge converts JavaScript values in both directions: | `new RcTimestamp('2026-11-23T01:02:03.000000001Z')` | a timestamp, in nanoseconds | `Date` when it is whole milliseconds, else `RcTimestamp` | | `new RcDate('2026-11-23')` | a calendar date | `RcDate` | | `new RcDecimal('1.50')` | a decimal, with its scale | `RcDecimal` | -| `null` | refused: see [A declared kind](#a-declared-kind) | `null`, for a null stored another way | +| `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. @@ -75,6 +75,7 @@ The value bridge converts JavaScript values in both directions: - 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. @@ -127,15 +128,28 @@ const opened = (await cipher.decrypt(age)).unwrap() - 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 lone `null` is an `Err` with the code `recipher_js::null_value`, with a kind or without one. +- 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`. -- Once the engine encrypts a typed null as one value, a `null` declared as a fixed-width kind will encrypt. + 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: kinds.int64 })`, and the call is refused when it runs. -- A `null` of a variable-width kind, such as `kinds.string` or `kinds.bytes`, is always refused. + 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 @@ -209,8 +223,22 @@ The ciphertext's TypeScript type allows any scalar: any type in the table above `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 stored null decrypts as `null` with a fixed-width kind, so the type of `Ciphertext.fromBytes(bytes, kinds.int64)` is `Ciphertext`. -With a variable-width kind, such as `kinds.string`, a stored null is refused. + +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 diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts index e26793801..b153f4d74 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts @@ -5,6 +5,7 @@ import { Ciphertext, json, kinds, + nullable, RcDate, RcDecimal, RcTimestamp, @@ -631,10 +632,15 @@ describe('a ciphertext read back with a kind', () => { const c = await cipher() const sealed = (await c.defaultKeyset().encrypt(42n)).unwrap() const stored = Ciphertext.fromBytes(sealed.toBytes(), kinds.int64).unwrap() - // A stored null of a fixed-width kind decrypts as null, so the type - // allows one. - const opened: bigint | null = (await c.decrypt(stored)).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 () => { @@ -652,11 +658,99 @@ describe('a ciphertext read back with a kind', () => { 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. @@ -775,22 +869,59 @@ describe('a declared kind', () => { expect(result.err()?.help).not.toContain('separately') }) - it('refuses a null of a fixed-width kind until #2023', async () => { - // Issue #2023 changes the engine to encrypt a null declared as 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. + 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 [kinds.int64, kinds.boolean, kinds.timestamp]) { + 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).toBe('recipher_js::null_value') - // The help does not suggest a call that fails today. + 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`. @@ -889,12 +1020,19 @@ describe('refusals', () => { ]) { 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]) { + 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') diff --git a/languages/typescript/packages/recipher-js/crate/src/cipher.rs b/languages/typescript/packages/recipher-js/crate/src/cipher.rs index 6a9ea5f1c..e8e5208f1 100644 --- a/languages/typescript/packages/recipher-js/crate/src/cipher.rs +++ b/languages/typescript/packages/recipher-js/crate/src/cipher.rs @@ -21,9 +21,10 @@ use napi_derive::napi; 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; @@ -175,11 +176,19 @@ impl Keyset { /// 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` is an `Err` with the code `recipher_js::null_value`, with a - /// kind or without one. Store a value that is not there as a database - /// `NULL`. The promise does not reject. + /// `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_type = "(value: V): Promise>, RecipherError>> encrypt(values: readonly V[]): Promise>[], RecipherError>> @@ -404,8 +413,9 @@ pub(crate) struct Sealable { /// text. pub(crate) value: OwnedFrame, /// The kind declared for the value. `None` stores the value as the - /// bridge read it. - pub(crate) kind: Option, + /// 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. @@ -422,6 +432,11 @@ pub(crate) struct Sealable { /// 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 @@ -430,22 +445,31 @@ pub(crate) struct Sealable { fn one_value( env: &Env, value: Unknown<'_>, - declared: Option, -) -> Outcome<(Sealable, Option)> { + declared: Option, +) -> Outcome<(Sealable, Option)> { + let kind = declared.map(|declared| declared.kind); if let Some(text) = Json::of(env, value) { - if declared.is_some_and(|kind| kind != ValueKind::Json) { + 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(ValueKind::Json), + 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, Some(ValueKind::Json))); + return Ok((sealable, declared)); } - if declared == Some(ValueKind::Json) { + if kind == Some(ValueKind::Json) { return Err(Error::JsonKind.into()); } - if declared.is_some_and(crate::ciphertext::integer) && unsafe_number(value) { + if kind.is_some_and(crate::ciphertext::integer) && unsafe_number(value) { return Err(Error::UnsafeInteger.into()); } let sealable = Sealable { @@ -455,6 +479,19 @@ fn one_value( 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()), + } +} + /// 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; @@ -487,7 +524,8 @@ where let calls = values .iter() .map(|sealable| { - value::encrypt(keyset, sealable.value.frame(), sealable.kind) + let kind = sealable.kind.map(|declared| declared.kind); + value::encrypt(keyset, sealable.value.frame(), kind) .map_err(|error| refusal(&error, sealable.kind)) }) .collect::>>()?; @@ -518,7 +556,7 @@ const CONVERSION_HELP: &str = "Pass a value of the declared kind, or one that co /// the engine's help. fn refusal( error: &stack_encrypt::dynamic::Error, - declared: Option, + declared: Option, ) -> RecipherErrorFields { match (error.reason(), error.found()) { (Some(Reason::NotAScalar), Some(Found::Kind(ValueKind::Array))) => Error::NotAScalar.into(), diff --git a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs index 34a782236..c6d16dbef 100644 --- a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs +++ b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs @@ -9,7 +9,7 @@ use napi::bindgen_prelude::{ }; use napi::{Env, ValueType}; use napi_derive::napi; -use serde::Deserialize; +use serde::{Deserialize, Deserializer}; use stack_encrypt::dynamic::frame::OwnedFrame; use stack_encrypt::dynamic::{read, ValueKind}; use stack_encrypt::json::JsonPlaintext; @@ -34,7 +34,32 @@ use crate::outcome::{failed, not_made, settle, Outcome}; #[derive(Clone, OpaqueDebug)] pub struct Ciphertext { sealed: stack_encrypt::Ciphertext, - opens_as: Option, + 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 @@ -50,7 +75,7 @@ pub(crate) enum Opened { impl Ciphertext { /// 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 { + pub(crate) fn new(sealed: stack_encrypt::Ciphertext, opens_as: Option) -> Self { Self { sealed, opens_as } } @@ -71,21 +96,17 @@ impl Ciphertext { } /// Returns a decrypted value as the kind this ciphertext decrypts as. - /// A null decrypts as null when the kind is fixed-width, such as - /// `int64`. + /// A null decrypts as null when the kind is nullable, as + /// `nullable(kinds.int64)` is. /// /// # Errors /// - /// Returns `recipher_js::opened_type` for a value encrypted as another - /// type, and for a null with a variable-width kind, such as `string`. - /// Returns `recipher_js::not_a_document` for a JSON kind whose value is - /// not a JSON document. + /// 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 { - match self.opens_as { - None => Ok(Opened::Value(value)), - Some(ValueKind::Json) => crate::json::opened(&value).map(Opened::Document), - Some(kind) => as_kind(kind, value).map(Opened::Value), - } + opened_as(self.opens_as, value) } } @@ -99,9 +120,10 @@ impl Ciphertext { /// 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. With a fixed-width kind, such - /// as `kinds.int64`, a stored null decrypts as `null`. With any other - /// kind, a stored null is refused. + /// `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 @@ -111,7 +133,8 @@ impl Ciphertext { /// 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`. + /// - `recipher_js::not_a_kind`, when the kind is not one of `kinds`, or + /// `nullable(..)` of one. #[napi( ts_type = "(bytes: Uint8Array, kind: K): Result>, RecipherError> static fromBytes(bytes: Uint8Array): Result" @@ -151,18 +174,49 @@ static fromBytes(bytes: Uint8Array): Result" } } -/// A kind, in the form the package's `kinds` object writes it: -/// `{ name: "string" }`. +/// 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 options of `keyset.encrypt`: `{ kind }`. Any other key is refused, -/// so an option that this version does not have is never ignored. +/// 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, } @@ -173,7 +227,7 @@ fn given(value: Option>) -> Option> { /// Returns the kind that `value` names, or `None` when `value` is absent or /// `undefined`. -fn kind_of(env: &Env, value: Option>) -> Outcome> { +fn kind_of(env: &Env, value: Option>) -> Outcome> { let Some(value) = given(value) else { return Ok(None); }; @@ -191,28 +245,36 @@ fn kind_of(env: &Env, value: Option>) -> Outcome> /// /// - `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`. -pub(crate) fn declared_kind(env: &Env, value: Unknown<'_>) -> Outcome> { +/// - `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 options: EncryptOptions = - stack_encrypt::dynamic::frame::serde::from_slice(frame.frame().as_bytes()) - .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`. -fn named(argument: &KindArgument) -> Outcome { - Ok(argument +/// 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_or(Error::NotAKind)?; + Ok(Declared { + kind, + nullable: argument.nullable.0, + }) } /// Returns whether a stored ciphertext can be read as `kind`: whether @@ -257,35 +319,21 @@ pub(crate) fn integer(kind: ValueKind) -> bool { /// 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 list matches `FixedWidthName` in `src/kinds.ts`. +/// 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 { - integer(kind) - || matches!( - kind, - ValueKind::Bool - | ValueKind::Float32 - | ValueKind::Float64 - | ValueKind::Decimal - | ValueKind::Date - | ValueKind::Timestamp - ) + kind.sealed_null().is_some() } -/// Returns `value` as `kind`. +/// 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. When `kind` is fixed-width, a plain null -/// or a typed null is returned unchanged. Any other value is refused. +/// 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 }); - if value.frame().is_null() { - return if fixed_width(kind) { - Ok(value) - } else { - Err(refused()) - }; - } let opened = value.frame().kind(); if opened == Some(kind) { return Ok(value); @@ -299,6 +347,24 @@ fn as_kind(kind: ValueKind, value: OwnedFrame) -> Outcome { 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`. /// @@ -317,7 +383,7 @@ pub(crate) fn bytes_of(value: Unknown<'_>) -> Option> { #[cfg(test)] mod tests { - use super::{as_kind, readable}; + 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}; @@ -368,9 +434,16 @@ mod tests { 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_fixed_width_kind_and_no_other() { + 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, @@ -379,17 +452,86 @@ mod tests { ValueKind::Decimal, ValueKind::Date, ValueKind::Timestamp, + ValueKind::String, + ValueKind::Bytes, + ValueKind::Json, ] { - for null in [OwnedFrame::null(), typed()] { - let opened = as_kind(kind, null).unwrap(); - assert!(opened.frame().is_null(), "{kind}"); + let declared = Declared { + kind, + nullable: true, + }; + for stored in [OwnedFrame::null(), typed()] { + let opened = opened_as(Some(declared), stored).unwrap(); + assert!(null(opened), "{kind}"); } } - // A value of a variable-width kind has no fixed size, so no null - // stands in for one. - for kind in [ValueKind::String, ValueKind::Bytes] { - let refused = as_kind(kind, OwnedFrame::null()).unwrap_err(); - assert_eq!(refused.code, "recipher_js::opened_type", "{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 2362ec8ec..3c054472f 100644 --- a/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs +++ b/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs @@ -18,7 +18,7 @@ use stack_encrypt::{Encrypt, StackCipher}; use uuid::Uuid; use crate::cipher::{open_in, seal, unseal, Confined, Engine, Sealable}; -use crate::ciphertext::{Ciphertext, Opened}; +use crate::ciphertext::{Ciphertext, Declared, Opened}; const SEED: [u8; 32] = [7; 32]; @@ -44,7 +44,7 @@ fn one(value: P) -> Sealable { fn document(text: &str) -> Sealable { Sealable { value: crate::json::text_frame(text.as_bytes()).unwrap(), - kind: Some(ValueKind::Json), + kind: Some(Declared::plain(ValueKind::Json)), } } @@ -125,7 +125,7 @@ async fn a_json_document_the_engine_sealed_opens_as_that_document() { .encrypt(document) .await .unwrap(); - let ciphertext = Ciphertext::new(sealed.clone(), Some(ValueKind::Json)); + 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"); }; @@ -356,18 +356,23 @@ async fn a_null_with_no_declared_kind_is_refused_before_any_request() { assert_eq!(cipher.kms().generates.load(Ordering::SeqCst), 0); } -/// A null declared as a fixed-width kind. 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. +/// 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_as_a_fixed_width_kind_is_refused_until_2023() { +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: OwnedFrame::null(), - kind: Some(kind), + value: crate::cipher::typed_null(Some(declared)).unwrap(), + kind: Some(declared), }; let refused = seal(&cipher.default_keyset(), vec![null]) .await @@ -377,50 +382,52 @@ async fn a_null_declared_as_a_fixed_width_kind_is_refused_until_2023() { let help = refused.help.unwrap_or_default(); assert!(help.contains("database `NULL`"), "{help}"); assert!(help.contains("once the engine"), "{help}"); - } - // A kind never helps a null of a variable-width type, so the help - // suggests none. - for kind in [ValueKind::String, ValueKind::Bytes] { - let null = Sealable { - value: OwnedFrame::null(), - kind: Some(kind), - }; - let refused = seal(&cipher.default_keyset(), vec![null]) - .await - .unwrap_err(); - assert_eq!(refused.code, "recipher_js::null_value", "{kind:?}"); - assert_eq!( - refused.help.as_deref(), - Some("Store a value that is not there as a database `NULL`."), - "{kind:?}" - ); + 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 a fixed-width kind, and is refused with a -/// variable-width kind. +/// 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_fixed_width_kind() { +async fn a_null_the_engine_sealed_opens_as_null_with_a_nullable_kind() { let cipher = engine().await; - let tree = cipher - .default_keyset() - .encrypt_tree(None::, ()) - .await - .unwrap(); - let stack_encrypt::CipherText::Single(leaf) = tree else { - panic!("a null seals as one leaf"); - }; - let sealed = stack_encrypt::Ciphertext::from(leaf); - let read = Ciphertext::new(sealed.clone(), Some(ValueKind::Int64)); - let Opened::Value(opened) = read.opened(sdk_open(sealed.clone()).await).unwrap() else { - panic!("an int64 opens as a value"); - }; - assert!(opened.frame().is_null()); - let as_text = Ciphertext::new(sealed.clone(), Some(ValueKind::String)); - let refused = as_text.opened(sdk_open(sealed).await).unwrap_err(); - assert_eq!(refused.code, "recipher_js::opened_type"); + 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 @@ -429,7 +436,7 @@ async fn a_null_the_engine_sealed_opens_as_null_with_a_fixed_width_kind() { async fn a_number_declared_as_uint64_is_stored_as_a_uint64() { let declared = Sealable { value: OwnedFrame::of(34.0f64).unwrap(), - kind: Some(ValueKind::UInt64), + kind: Some(Declared::plain(ValueKind::UInt64)), }; let sealed = sdk_seal(vec![declared]).await.remove(0); let typed: u64 = engine() @@ -453,7 +460,7 @@ async fn a_number_declared_as_uint64_is_stored_as_a_uint64() { 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(ValueKind::UInt64), + kind: Some(Declared::plain(ValueKind::UInt64)), }; let refused = seal(&engine().await.default_keyset(), vec![declared]) .await diff --git a/languages/typescript/packages/recipher-js/crate/src/error.rs b/languages/typescript/packages/recipher-js/crate/src/error.rs index 8c76b3cc1..06aea623b 100644 --- a/languages/typescript/packages/recipher-js/crate/src/error.rs +++ b/languages/typescript/packages/recipher-js/crate/src/error.rs @@ -29,6 +29,8 @@ 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)] @@ -76,7 +78,8 @@ pub(crate) enum Error { #[error("`null` cannot be encrypted as one value")] #[diagnostic(code(recipher_js::null_value))] NullValue { - /// What to do instead: [`NULL_HELP`], or [`NULL_HELP_FIXED_WIDTH`]. + /// What to do instead: [`NULL_HELP`], [`NULL_HELP_NULLABLE`], or + /// [`NULL_HELP_TYPED`]. #[help] help: &'static str, }, @@ -120,9 +123,19 @@ pub(crate) enum Error { #[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`.") + 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))] @@ -161,27 +174,31 @@ pub(crate) enum Error { } /// The help of a refused `null` declared as a variable-width kind, such as -/// `string`. A value of that kind has no fixed size, so no declared kind -/// makes a `null` of it encrypt. +/// `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. The engine does not encrypt a typed null as one value -/// yet, so the help does not suggest a call that fails today. -pub(crate) const NULL_HELP_FIXED_WIDTH: &str = "Store a value that is not there as a database `NULL`. A `null` declared as a fixed-width kind, such as `kinds.int64`, will encrypt once the engine encrypts typed nulls."; +/// 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 variable_width = declared.is_some_and(|kind| !crate::ciphertext::fixed_width(kind)); - Self::NullValue { - help: if variable_width { - NULL_HELP - } else { - NULL_HELP_FIXED_WIDTH - }, - } + 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 } } } @@ -383,9 +400,10 @@ impl From for RecipherErrorFields { #[cfg(test)] mod tests { use super::{ - Error, ErrorCause, RecipherErrorFields, Severity, NULL_HELP, NULL_HELP_FIXED_WIDTH, - UNDESCRIBED_CAUSE, + Error, ErrorCause, RecipherErrorFields, Severity, NULL_HELP, NULL_HELP_NULLABLE, + NULL_HELP_TYPED, UNDESCRIBED_CAUSE, }; + use crate::ciphertext::Declared; use stack_encrypt::dynamic::ValueKind; #[test] @@ -584,6 +602,7 @@ mod tests { Error::Options, Error::JsonKind, Error::NotAKind, + Error::OpenedNull, Error::OpenedType { kind: ValueKind::String, }, @@ -608,6 +627,7 @@ mod tests { | Error::Options | Error::JsonKind | Error::NotAKind + | Error::OpenedNull | Error::OpenedType { .. } | Error::NotADocument | Error::TestingSeed @@ -632,7 +652,7 @@ mod tests { Error::PlainObject => { Some("To encrypt the object as a JSON document, wrap it in `json(..)`.") } - Error::NullValue { .. } => Some(NULL_HELP_FIXED_WIDTH), + 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.", ), @@ -642,8 +662,9 @@ mod tests { } Error::NotACiphertext => Some("Read stored bytes with Ciphertext.fromBytes."), Error::NotAKind => { - Some("Pass a kind that the package exports, such as `kinds.string`.") + 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`.") } @@ -662,11 +683,31 @@ mod tests { #[test] fn a_null_has_the_help_for_its_declared_kind() { let help = |declared| RecipherErrorFields::from(Error::null_value(declared)).help; - for declared in [None, Some(ValueKind::Int64), Some(ValueKind::Timestamp)] { - assert_eq!(help(declared).as_deref(), Some(NULL_HELP_FIXED_WIDTH)); + 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)); } - for declared in [ValueKind::String, ValueKind::Bytes, ValueKind::Json] { - assert_eq!(help(Some(declared)).as_deref(), Some(NULL_HELP)); + // 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)); } } diff --git a/languages/typescript/packages/recipher-js/crate/src/json.rs b/languages/typescript/packages/recipher-js/crate/src/json.rs index 9df8a3f23..6c70bc1f5 100644 --- a/languages/typescript/packages/recipher-js/crate/src/json.rs +++ b/languages/typescript/packages/recipher-js/crate/src/json.rs @@ -86,7 +86,7 @@ impl Json { /// 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(ValueKind::Json) }, + /// 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 }, /// }; diff --git a/languages/typescript/packages/recipher-js/native.d.ts b/languages/typescript/packages/recipher-js/native.d.ts index 7563d532a..60c2dd73b 100644 --- a/languages/typescript/packages/recipher-js/native.d.ts +++ b/languages/typescript/packages/recipher-js/native.d.ts @@ -115,9 +115,10 @@ export declare class Ciphertext { * 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. With a fixed-width kind, such - * as `kinds.int64`, a stored null decrypts as `null`. With any other - * kind, a stored null is refused. + * `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 @@ -127,7 +128,8 @@ export declare class Ciphertext { * 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`. + * - `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 @@ -194,11 +196,19 @@ export declare class Keyset { * 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` is an `Err` with the code `recipher_js::null_value`, with a - * kind or without one. Store a value that is not there as a database - * `NULL`. The promise does not reject. + * `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: V): Promise>, RecipherError>> encrypt(values: readonly V[]): Promise>[], RecipherError>> diff --git a/languages/typescript/packages/recipher-js/src/index.ts b/languages/typescript/packages/recipher-js/src/index.ts index ce4f05fc7..afef6c4fd 100644 --- a/languages/typescript/packages/recipher-js/src/index.ts +++ b/languages/typescript/packages/recipher-js/src/index.ts @@ -49,6 +49,9 @@ export { type FixedWidthName, type Kind, kinds, + type Nullable, + type NullableKind, + nullable, type OpenedAs, type ReadAs, type ValueOf, diff --git a/languages/typescript/packages/recipher-js/src/kinds.ts b/languages/typescript/packages/recipher-js/src/kinds.ts index 0b9c37d01..5bfc81b0e 100644 --- a/languages/typescript/packages/recipher-js/src/kinds.ts +++ b/languages/typescript/packages/recipher-js/src/kinds.ts @@ -7,6 +7,10 @@ * 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, @@ -28,15 +32,74 @@ 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 stored - * null decrypts as `null` when `K` is fixed-width. + * 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 | (K['name'] extends FixedWidthName ? null : never) + ? ValueOf | (IsNullable extends true ? null : never) : never /** @@ -70,10 +133,13 @@ export type FixedWidthName = * value is a `Json` from `json(..)`. For a union of kinds, a value of any * kind in the union. * - * 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`. + * `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 ? @@ -82,7 +148,11 @@ export type Declared = K extends Kind : ValueOf extends bigint ? number | bigint : ValueOf) - | (K['name'] extends FixedWidthName ? null : never) + | (IsNullable extends true + ? K['name'] extends FixedWidthName + ? null + : never + : never) : never /** @@ -95,7 +165,10 @@ 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`. */ + /** + * The kind of the value, from `kinds`, such as `kinds.uint64`, or + * `nullable(..)` of one. + */ readonly kind: K } diff --git a/languages/typescript/packages/recipher-js/src/value-types.ts b/languages/typescript/packages/recipher-js/src/value-types.ts index e8db5afdf..6b5ff9a91 100644 --- a/languages/typescript/packages/recipher-js/src/value-types.ts +++ b/languages/typescript/packages/recipher-js/src/value-types.ts @@ -49,9 +49,10 @@ export interface 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 a fixed-width kind - * declared. Until the engine encrypts a typed null as one value, `encrypt` - * refuses that `null` when it runs. + * 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 diff --git a/languages/typescript/packages/recipher-js/src/values.ts b/languages/typescript/packages/recipher-js/src/values.ts index 3786d9bd2..e64493dda 100644 --- a/languages/typescript/packages/recipher-js/src/values.ts +++ b/languages/typescript/packages/recipher-js/src/values.ts @@ -23,9 +23,12 @@ * 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 a fixed-width kind, - * such as `kinds.int64`, will encrypt once the engine encrypts a typed null - * as one value. A stored null still decrypts as `null`: one in an older + * `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. diff --git a/languages/typescript/packages/recipher-js/type-tests/values.ts b/languages/typescript/packages/recipher-js/type-tests/values.ts index 4ae4600c8..85119647a 100644 --- a/languages/typescript/packages/recipher-js/type-tests/values.ts +++ b/languages/typescript/packages/recipher-js/type-tests/values.ts @@ -3,6 +3,7 @@ import type { Cipher, Keyset, + Nullable, OpenedJson, OpenedScalar, RcDate, @@ -12,7 +13,7 @@ import type { RecipherError, Result, } from '../src/index' -import { Ciphertext, json, kinds } from '../src/index' +import { Ciphertext, json, kinds, nullable } from '../src/index' declare const keyset: Keyset declare const cipher: Cipher @@ -85,13 +86,13 @@ void json({ d: new Date() }) // @ts-expect-error: an RcDate is not an RcDecimal. expectType(day) -// A ciphertext read from stored bytes has the type of the kind named. With -// no kind, its type is any scalar. +// 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>>>() -// A stored null of a fixed-width kind decrypts as null. No null stands in -// for a value of a variable-width kind. +check, RecipherError>>>() const typedText = Ciphertext.fromBytes(stored, kinds.string) check, RecipherError>>>() const typedJson = Ciphertext.fromBytes(stored, kinds.json) @@ -101,6 +102,30 @@ 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 }) @@ -115,14 +140,51 @@ const declaredDocument = await keyset.encrypt(json({ a: 1 }), { check< Exact, RecipherError>> >() -// A null declared as 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: kinds.int64 }) +// 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: kinds.string }) +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: kinds.bytes }) +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. From b284a8e423067841865d901438cb3bd8da809c19 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 29 Nov 2026 18:47:49 +1100 Subject: [PATCH 25/25] feat(recipher-js)!: make a wrapper with from(text) and get a Result `new RcDate(20261123)` threw a `TypeError`, and nothing else in the package throws apart from `unwrap` and `expect`. A wrapper is now made with a static factory that returns a `Result`: const born = RcDate.from('1815-12-10') // Result `RcDate.from`, `RcTimestamp.from`, `RcDecimal.from`, and `RcUuid.from` check the text in Rust, with the rule that `encrypt` uses. So an instance that exists is always valid. Bad text, or a value that is not a string, is an `Err` with the value bridge's code, such as `ERR_INVALID_DATE`. The `Err` contains no part of the text. `from` reads no `this`, so `texts.map(RcDate.from)` works. The addon installs the factory that `from` calls when the package loads it, next to the `Result` classes. The value bridge provides `Wrappers::from_text` for the check, and `Wrappers::install_from` to set the factory once for each environment. The classes have no constructor in their types, so `new RcDate('x')` does not compile. The constructor takes a token that only the classes' script contains. When `new` is called anyway, from JavaScript or past a cast, it throws a `TypeError` that names `RcDate.from(text)`. `new Cipher()` throws too, so `new` on a class whose type has no constructor is the second kind of call that throws. The README says so. A decrypted value is still built as an instance of the same classes, with the token. `instanceof`, the freezing, and the plain-object checks are unchanged. The text is still checked when the value is encrypted, because `Object.create` makes an object that `instanceof` accepts. The stand-in classes for an addon that did not load return the load error from `from`, and throw the same `TypeError` for `new`. --- AGENTS.md | 2 +- .../typescript/packages/recipher-js/README.md | 38 ++-- .../__tests__/addon/builds.test.ts | 6 +- .../__tests__/addon/values.test.ts | 146 ++++++++++----- .../recipher-js/__tests__/unit/values.test.ts | 50 +++--- .../packages/recipher-js/crate/src/js.rs | 36 +++- .../packages/recipher-js/crate/src/lib.rs | 14 +- .../packages/recipher-js/crate/src/outcome.rs | 5 + .../packages/recipher-js/native.d.ts | 4 + .../packages/recipher-js/src/index.ts | 12 +- .../packages/recipher-js/src/value-types.ts | 4 +- .../packages/recipher-js/src/values.ts | 104 ++++++----- .../packages/recipher-js/type-tests/values.ts | 33 +++- .../packages/recipher-js/value-napi/README.md | 37 ++-- .../recipher-js/value-napi/src/js_ref.rs | 7 +- .../recipher-js/value-napi/src/wrappers.js | 56 +++++- .../recipher-js/value-napi/src/wrappers.rs | 169 +++++++++++++++++- .../value-napi/tests/addon/src/lib.rs | 51 +++++- .../recipher-js/value-napi/tests/encrypt.cjs | 14 +- .../recipher-js/value-napi/tests/frames.cjs | 34 ++-- .../recipher-js/value-napi/tests/json.cjs | 19 +- .../value-napi/tests/kind_inventory.cjs | 17 +- .../value-napi/tests/object-safety.cjs | 27 ++- .../value-napi/tests/value-conformance.cjs | 127 +++++++++---- 24 files changed, 752 insertions(+), 260 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 64a6a70b2..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`, `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 calls throw a `TypeError`: a method called without its object (#1801), and a wrapper class's constructor given anything but a string, as in `new RcDate(20261123)`. 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/languages/typescript/packages/recipher-js/README.md b/languages/typescript/packages/recipher-js/README.md index 9010588c8..0c2a0367e 100644 --- a/languages/typescript/packages/recipher-js/README.md +++ b/languages/typescript/packages/recipher-js/README.md @@ -60,15 +60,29 @@ The value bridge converts JavaScript values in both directions: | `bigint` | an integer, at the narrowest width that fits it | `bigint` | | `Uint8Array`, `Buffer` | bytes | `Uint8Array` | | `Date` | a timestamp | `Date` | -| `new RcTimestamp('2026-11-23T01:02:03.000000001Z')` | a timestamp, in nanoseconds | `Date` when it is whole milliseconds, else `RcTimestamp` | -| `new RcDate('2026-11-23')` | a calendar date | `RcDate` | -| `new RcDecimal('1.50')` | a decimal, with its scale | `RcDecimal` | +| 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. - The constructor of a wrapper class accepts the value as text. + 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`. @@ -258,7 +272,9 @@ The other calls return an `Err` in these cases too: - 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: @@ -269,12 +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. -A wrapper class's constructor throws too. -The constructor accepts only a string, so `new RcDate(20261123)` throws a `TypeError`. -The constructor does not check the text. -`encrypt` returns an `Err` for text that is not a date. +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. 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 d09a1bd7c..ee918edf9 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/builds.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/builds.test.ts @@ -59,8 +59,8 @@ const MISSING = ` const recipher = await import(process.argv[1]) const testing = await import(process.argv[2]) const out = {} -out.date = new recipher.RcDate('2026-11-23').value -out.dateFrozen = Object.isFrozen(new recipher.RcDate('2026-11-23')) +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 @@ -94,7 +94,7 @@ describe('the package without its native build', () => { { encoding: 'utf8' }, ) expect(JSON.parse(output)).toEqual({ - date: '2026-11-23', + date: 'recipher_js::load', dateFrozen: true, json: 'Json(***)', create: 'recipher_js::load', diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts index b153f4d74..124b2b646 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts @@ -1,15 +1,17 @@ import { inspect } from 'node:util' import { describe, expect, it } from 'vitest' import { - type Cipher, + Cipher, Ciphertext, json, + Keyset, kinds, nullable, RcDate, RcDecimal, RcTimestamp, RcUuid, + RecipherError, } from '../../src/index' import { testCipher } from '../../src/testing' import { standInWrapper } from '../../src/values' @@ -87,21 +89,23 @@ describe('every value in the mapping round-trips', () => { }) it('the wrapper classes', async () => { - const day = await roundTrip(new RcDate('2026-11-23')) + 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( - new RcTimestamp('2026-11-23T01:02:03.000000001Z'), + 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(new RcTimestamp('2026-11-23T01:02:03.000Z')) + const whole = await roundTrip( + RcTimestamp.from('2026-11-23T01:02:03.000Z').unwrap(), + ) expect(whole).toBeInstanceOf(Date) - const price = await roundTrip(new RcDecimal('1.50')) + const price = await roundTrip(RcDecimal.from('1.50').unwrap()) expect(price).toBeInstanceOf(RcDecimal) expect((price as RcDecimal).value).toBe('1.50') }) @@ -115,53 +119,101 @@ describe('a wrapper class', () => { 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 - /** What a caller can observe of a class and one instance of it. */ - function observed( - cls: new (text: string) => object, - text: string, - ): Record { - const instance = new cls(text) - let thrown: unknown - try { - // @ts-expect-error: the constructor accepts only a string. - new cls(20261123) - } catch (error) { - thrown = error + 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) } - return { - name: cls.name, - value: Object.getOwnPropertyDescriptor(instance, 'value'), - keys: Object.keys(instance), - string: String(instance), - json: JSON.stringify(instance), - inspected: inspect(instance), - frozen: [ - Object.isFrozen(instance), - Object.isFrozen(cls), - Object.isFrozen(cls.prototype), - ], - thrown: [ - thrown instanceof TypeError, - thrown instanceof Error ? thrown.message : thrown, - ], + }) + + 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('accepts only a string, and throws a TypeError for anything else', () => { + 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) { - // @ts-expect-error: the constructor accepts only a string. - expect(() => new classes[name](20261123)).toThrow(TypeError) - expect(new classes[name](texts[name]).value).toBe(texts[name]) + 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('has a stand-in that constructs as it does', () => { + 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) { - expect(observed(standInWrapper(name), texts[name])).toEqual( - observed(classes[name], texts[name]), - ) + 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) } }) }) @@ -469,10 +521,10 @@ describe('a JSON document', () => { Buffer.from('4111 1111'), new Uint16Array(2), new Date('2031-04-01T00:00:00Z'), - new RcDate('2031-04-01'), - new RcTimestamp('2031-04-01T00:00:00.000000001Z'), - new RcDecimal('4111.1111'), - new RcUuid('123e4567-e89b-12d3-a456-426614174000'), + 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) @@ -957,7 +1009,7 @@ describe('a declared kind', () => { describe('refusals', () => { it('a UUID: this version of the SDK does not encrypt one yet', async () => { const keyset = (await cipher()).defaultKeyset() - const uuid = new RcUuid('123e4567-e89b-12d3-a456-426614174000') + 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') diff --git a/languages/typescript/packages/recipher-js/__tests__/unit/values.test.ts b/languages/typescript/packages/recipher-js/__tests__/unit/values.test.ts index ae656e243..8192b6d56 100644 --- a/languages/typescript/packages/recipher-js/__tests__/unit/values.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/unit/values.test.ts @@ -2,53 +2,45 @@ * 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 { inspect } from 'node:util' 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).name).toBe(name) + expect(standInWrapper(name, LOAD_ERROR).name).toBe(name) } }) - it('keeps its text in a read-only, enumerable `value`', () => { - const RcDate = standInWrapper<{ value: string }>('RcDate') - const day = new RcDate('2026-11-23') - expect(Object.getOwnPropertyDescriptor(day, 'value')).toEqual({ - value: '2026-11-23', - writable: false, - enumerable: true, - configurable: false, - }) - expect(Object.keys(day)).toEqual(['value']) - expect(Object.isFrozen(day)).toBe(true) + 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('gives its text to String, JSON.stringify and inspect', () => { - const RcDecimal = standInWrapper('RcDecimal') - const price = new RcDecimal('1.50') - expect(String(price)).toBe('1.50') - expect(JSON.stringify({ price })).toBe('{"price":"1.50"}') - expect(inspect(price)).toBe('RcDecimal(1.50)') - }) - - it('throws a TypeError for an argument that is not a string', () => { - const RcDate = standInWrapper('RcDate') - for (const argument of [20261123, undefined, null, {}, ['2026-11-23']]) { - // @ts-expect-error: the constructor accepts only a string. - expect(() => new RcDate(argument)).toThrow( - new TypeError('RcDate accepts only a string'), + 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', () => { - const RcUuid = standInWrapper('RcUuid') + 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/src/js.rs b/languages/typescript/packages/recipher-js/crate/src/js.rs index d5a469e08..9ce4770ed 100644 --- a/languages/typescript/packages/recipher-js/crate/src/js.rs +++ b/languages/typescript/packages/recipher-js/crate/src/js.rs @@ -27,7 +27,8 @@ //! and drops it without copying it. The exception's message may contain //! the value. -use napi::bindgen_prelude::{FromNapiValue, JsObjectValue, JsValue, Object, Unknown}; +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; @@ -35,6 +36,7 @@ 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. /// @@ -175,6 +177,38 @@ fn not_built(env: &Env, fault: &JsFault) -> RecipherErrorFields { } } +/// 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) diff --git a/languages/typescript/packages/recipher-js/crate/src/lib.rs b/languages/typescript/packages/recipher-js/crate/src/lib.rs index 39c328460..e14909dc8 100644 --- a/languages/typescript/packages/recipher-js/crate/src/lib.rs +++ b/languages/typescript/packages/recipher-js/crate/src/lib.rs @@ -26,8 +26,12 @@ //! and throws a `TypeError` before any of the addon's code runs. //! //! The wrapper classes are `RcDate`, `RcTimestamp`, `RcDecimal`, and -//! `RcUuid`. The value bridge defines them in JavaScript. A wrapper class's -//! constructor throws a `TypeError` for an argument that is not a string. +//! `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 @@ -92,9 +96,9 @@ pub fn binding_interface() -> u32 { /// 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 -/// construct them. A decrypted value is then an instance of the same -/// classes. +/// 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))] 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.d.ts b/languages/typescript/packages/recipher-js/native.d.ts index 60c2dd73b..d0235a006 100644 --- a/languages/typescript/packages/recipher-js/native.d.ts +++ b/languages/typescript/packages/recipher-js/native.d.ts @@ -269,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 diff --git a/languages/typescript/packages/recipher-js/src/index.ts b/languages/typescript/packages/recipher-js/src/index.ts index afef6c4fd..a9d50cad1 100644 --- a/languages/typescript/packages/recipher-js/src/index.ts +++ b/languages/typescript/packages/recipher-js/src/index.ts @@ -24,10 +24,12 @@ * for it, before any of the package's code runs. Call each method on its * object: `stored.map((ciphertext) => cipher.decrypt(ciphertext))`. * - * A wrapper class represents a type that JavaScript does not have, such as - * `RcDate` for a calendar date. A wrapper class's constructor, such as - * `new RcDate(..)`, also throws a `TypeError` when its argument is not a - * string. + * 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, @@ -71,5 +73,5 @@ export { RcUuid, type Scalar, type Value, - type WrapperConstructor, + type WrapperClass, } from './values' diff --git a/languages/typescript/packages/recipher-js/src/value-types.ts b/languages/typescript/packages/recipher-js/src/value-types.ts index 6b5ff9a91..dbadb0e45 100644 --- a/languages/typescript/packages/recipher-js/src/value-types.ts +++ b/languages/typescript/packages/recipher-js/src/value-types.ts @@ -9,7 +9,7 @@ declare const wrapper: unique symbol -/** A calendar date, such as `new RcDate('2026-11-23')`. */ +/** A calendar date, such as `RcDate.from('2026-11-23')`. */ export interface RcDate { /** The date as `YYYY-MM-DD`. */ readonly value: string @@ -25,7 +25,7 @@ export interface RcTimestamp { readonly [wrapper]: 'RcTimestamp' } -/** A decimal with its scale, such as `new RcDecimal('1.50')`. */ +/** A decimal with its scale, such as `RcDecimal.from('1.50')`. */ export interface RcDecimal { /** The decimal as text, with its scale. */ readonly value: string diff --git a/languages/typescript/packages/recipher-js/src/values.ts b/languages/typescript/packages/recipher-js/src/values.ts index e64493dda..111ef4fb5 100644 --- a/languages/typescript/packages/recipher-js/src/values.ts +++ b/languages/typescript/packages/recipher-js/src/values.ts @@ -38,17 +38,25 @@ * * 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. When the addon did not load, this - * module exports stand-ins instead. A stand-in's constructor accepts and - * refuses the same arguments as the class's constructor. `encrypt` then - * resolves to the `Err` that says why the addon did not load. + * 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's constructor accepts only a string. The constructor - * throws a `TypeError` for any other argument. The text is checked later, - * when the value is encrypted. + * 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 { @@ -60,62 +68,65 @@ export type { Value, } from './value-types' -/** The constructor of a wrapper class. */ -export interface WrapperConstructor { - new (text: string): W +/** + * 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. The stand-in matches the addon's class in these ways: - * - * - The constructor accepts only a string, and throws a `TypeError` for - * anything else. - * - A read-only `value` contains the text. - * - The class, its prototype, and each instance are frozen. - * - `String`, `JSON.stringify`, and Node's `inspect` get the same text as - * from the addon's class. + * 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): WrapperConstructor { +export function standInWrapper( + name: WrapperName, + error: RecipherError, +): WrapperClass { const StandIn = class { - readonly value: string - constructor(text: string) { - if (typeof text !== 'string') { - throw new TypeError(`${name} accepts only a string`) - } - this.value = text - Object.freeze(this) - } - toJSON(): string { - return this.value - } - toString(): string { - return this.value + constructor() { + throw new TypeError( + `${name} has no public constructor. Make one with ${name}.from(text), which returns a Result.`, + ) } - [Symbol.for('nodejs.util.inspect.custom')](): string { - return `${name}(${this.value})` + static from(): Result { + return err(error) } } Object.defineProperty(StandIn, 'name', { value: name }) Object.freeze(StandIn.prototype) - // biome-ignore lint/plugin: a stand-in with the constructor behaviour of the class. - return Object.freeze(StandIn) as unknown as WrapperConstructor + // 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): WrapperConstructor { +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 WrapperConstructor + return Reflect.get(binding.value, name) as WrapperClass } - return standInWrapper(name) + return standInWrapper(name, binding.error) } // A class is a constant and a type of one name. The addon's declarations @@ -123,21 +134,20 @@ function wrapperClass(name: WrapperName): WrapperConstructor { // 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 `new RcDate('2026-11-23')`. */ -export const RcDate: WrapperConstructor = wrapperClass('RcDate') +/** 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 - * `new RcTimestamp('2026-11-23T01:02:03.000000001Z')`. + * `RcTimestamp.from('2026-11-23T01:02:03.000000001Z')`. */ -export const RcTimestamp: WrapperConstructor = +export const RcTimestamp: WrapperClass = wrapperClass('RcTimestamp') export type RcTimestamp = Types.RcTimestamp -/** A decimal with its scale, such as `new RcDecimal('1.50')`. */ -export const RcDecimal: WrapperConstructor = - wrapperClass('RcDecimal') +/** A decimal with its scale, such as `RcDecimal.from('1.50')`. */ +export const RcDecimal: WrapperClass = wrapperClass('RcDecimal') export type RcDecimal = Types.RcDecimal /** @@ -145,7 +155,7 @@ export type RcDecimal = Types.RcDecimal * encrypt a UUID yet. Encrypting an `RcUuid` is an `Err` with the code * `recipher_js::uuid`. `RcUuid` is not a `Scalar`. */ -export const RcUuid: WrapperConstructor = wrapperClass('RcUuid') +export const RcUuid: WrapperClass = wrapperClass('RcUuid') export type RcUuid = Types.RcUuid /** diff --git a/languages/typescript/packages/recipher-js/type-tests/values.ts b/languages/typescript/packages/recipher-js/type-tests/values.ts index 85119647a..398e7b009 100644 --- a/languages/typescript/packages/recipher-js/type-tests/values.ts +++ b/languages/typescript/packages/recipher-js/type-tests/values.ts @@ -13,7 +13,16 @@ import type { RecipherError, Result, } from '../src/index' -import { Ciphertext, json, kinds, nullable } 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 @@ -210,3 +219,25 @@ check< 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/README.md b/languages/typescript/packages/recipher-js/value-napi/README.md index 3f931dbaf..bebed27a9 100644 --- a/languages/typescript/packages/recipher-js/value-napi/README.md +++ b/languages/typescript/packages/recipher-js/value-napi/README.md @@ -69,10 +69,11 @@ that goes out. This crate provides both sides of that conversion: applies the tree's nesting limit to the payload too. - **`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`. 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. + 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 @@ -178,22 +179,38 @@ when the conversion is exact. So `5` and `5n` are both the `int64` 5 on an JavaScript has no type of its own for a calendar date, a timestamp finer 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, such -as `new RcDecimal("1.50")`. +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. -- **The constructor accepts only a string.** This crate checks the - text, and builds the scalar from it, when the value is encrypted. So one - rule applies however the instance was made. +- **`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 the constructor on the other side. + 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 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 1428bffda..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 @@ -412,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)), 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 ef0b6697b..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} accepts only 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) } - return freeze({ + const classes = freeze({ __proto__: null, RcDate: define('RcDate'), RcTimestamp: define('RcTimestamp'), RcDecimal: define('RcDecimal'), RcUuid: define('RcUuid'), + }) + return freeze({ + __proto__: null, + 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 1ecf14d8f..c973975a3 100644 --- a/languages/typescript/packages/recipher-js/value-napi/src/wrappers.rs +++ b/languages/typescript/packages/recipher-js/value-napi/src/wrappers.rs @@ -20,16 +20,27 @@ //! 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`], so that -//! applications can construct them. The walk in the `js_ref` module -//! recognises an instance with `instanceof`. `JsBuilder` constructs -//! instances. +//! 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. /// @@ -66,6 +77,35 @@ impl Wrapper { 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), + } + } } const SOURCE: &str = include_str!("wrappers.js"); @@ -76,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. @@ -193,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) } } @@ -227,6 +336,50 @@ mod tests { assert_eq!(names, ["RcDate", "RcTimestamp", "RcDecimal", "RcUuid"]); for &wrapper in Wrapper::ALL { 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/src/lib.rs b/languages/typescript/packages/recipher-js/value-napi/tests/addon/src/lib.rs index 9d9744a2a..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, Refusal, 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 ["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] 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 8ff31f1ed..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 { RcDate, RcTimestamp, RcDecimal, RcUuid } = addon const aad = 'section-6' const rows = { @@ -25,14 +24,17 @@ const rows = { 'plain object': { name: 'Ada', tags: ['math'], - born: new RcDate('1815-12-10'), + born: addon.makeWrapper('RcDate', '1815-12-10'), x: undefined, }, 'null prototype': Object.assign(Object.create(null), { k: 'v' }), - RcDate: new RcDate('2024-02-29'), - RcTimestamp: new RcTimestamp('1969-12-31T23:59:59.999999999Z'), - RcDecimal: new RcDecimal('-1.50'), - RcUuid: new RcUuid('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 477d997c5..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 { RcDate, RcTimestamp, RcDecimal, RcUuid } = addon const golden = path.join(__dirname, 'testdata/js-frames.json') const vendored = path.join(__dirname, 'testdata/corpus-frames.json') @@ -152,71 +151,74 @@ const inputs = [ ['Date -1', () => new Date(-1)], [ 'RcDate 1970-01-01', - () => new RcDate('1970-01-01'), + () => addon.makeWrapper('RcDate', '1970-01-01'), 'record-values-v1/date-epoch', ], [ 'RcDate 1969-12-31', - () => new RcDate('1969-12-31'), + () => addon.makeWrapper('RcDate', '1969-12-31'), 'record-values-v1/date-before-epoch', ], [ 'RcDate 0001-01-01', - () => new RcDate('0001-01-01'), + () => addon.makeWrapper('RcDate', '0001-01-01'), 'record-values-v1/date-year-one', ], [ 'RcDate 9999-12-31', - () => new RcDate('9999-12-31'), + () => addon.makeWrapper('RcDate', '9999-12-31'), 'record-values-v1/date-year-9999', ], [ 'RcTimestamp epoch', - () => new RcTimestamp('1970-01-01T00:00:00Z'), + () => addon.makeWrapper('RcTimestamp', '1970-01-01T00:00:00Z'), 'record-values-v1/timestamp-epoch', ], [ 'RcTimestamp one nanosecond', - () => new RcTimestamp('2026-10-17T01:02:03.000000001Z'), + () => addon.makeWrapper('RcTimestamp', '2026-10-17T01:02:03.000000001Z'), 'record-values-v1/timestamp-nanosecond', ], [ 'RcTimestamp before epoch', - () => new RcTimestamp('1969-12-31T23:59:59.999999999Z'), + () => addon.makeWrapper('RcTimestamp', '1969-12-31T23:59:59.999999999Z'), 'record-values-v1/timestamp-before-epoch', ], [ 'RcTimestamp nanoseconds', - () => new RcTimestamp('2026-10-17T01:02:03.123456789Z'), + () => addon.makeWrapper('RcTimestamp', '2026-10-17T01:02:03.123456789Z'), 'record-values-v1/timestamp-microsecond-query', ], [ 'RcTimestamp year 9999', - () => new RcTimestamp('9999-12-30T22:00:00.999999999Z'), + () => addon.makeWrapper('RcTimestamp', '9999-12-30T22:00:00.999999999Z'), 'record-values-v1/timestamp-year-9999', ], [ 'RcDecimal 42', - () => new RcDecimal('42'), + () => addon.makeWrapper('RcDecimal', '42'), 'record-values-v1/decimal-scale-0', ], [ 'RcDecimal scale 28', - () => new RcDecimal('0.0000000000000000000000000001'), + () => addon.makeWrapper('RcDecimal', '0.0000000000000000000000000001'), 'record-values-v1/decimal-scale-28', ], [ 'RcDecimal -1234.5600', - () => new RcDecimal('-1234.5600'), + () => addon.makeWrapper('RcDecimal', '-1234.5600'), 'record-values-v1/decimal-trailing-zeros', ], [ 'RcDecimal max mantissa', - () => new RcDecimal('79228162514264337593543950335'), + () => addon.makeWrapper('RcDecimal', '79228162514264337593543950335'), 'record-values-v1/decimal-max-mantissa', ], - ['RcDecimal -0.00', () => new RcDecimal('-0.00')], - ['RcUuid', () => new RcUuid('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 index 0ab003f95..98887ae0f 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/json.cjs +++ b/languages/typescript/packages/recipher-js/value-napi/tests/json.cjs @@ -163,7 +163,6 @@ for (const wide of [ // 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 RcDate = addon.RcDate const noJsonForm = [ [undefined, /undefined/], [new Date(0), /a date/], @@ -173,13 +172,19 @@ const noJsonForm = [ [new Uint16Array(2), /bytes/], [new Float64Array(2), /bytes/], [new DataView(new ArrayBuffer(2)), /bytes/], - [new RcDate('2026-11-23'), /a date/], - [new addon.RcTimestamp('2026-11-23T01:02:03.000000001Z'), /a date/], - [new addon.RcDecimal('1.50'), /a decimal/], - [new addon.RcUuid('123e4567-e89b-12d3-a456-426614174000'), /a UUID/], + [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. - [new RcDate('not a date'), /a date/], + [addon.makeWrapper('RcDate', 'not a date'), /a date/], ] for (const [value, message] of noJsonForm) { for (const document of [ @@ -468,7 +473,7 @@ 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(new RcDate('2026-11-23')), + addon.napiJsonText(addon.makeWrapper('RcDate', '2026-11-23')), '{"value":"2026-11-23"}', ) // An inherited property is read. An unpaired surrogate is replaced. 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 7392735ee..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 { RcDate, RcTimestamp, RcDecimal, RcUuid } = 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 RcDate('2024-02-29'), + date: addon.makeWrapper('RcDate', '2024-02-29'), timestamp: new Date(0), timestampMillis: new Date(-1), - timestampMicros: new RcTimestamp('1970-01-01T00:00:00.000001000Z'), - timestampNanos: new RcTimestamp('1969-12-31T23:59:59.999999999Z'), - decimal: new RcDecimal('1.50'), - uuid: new RcUuid('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/object-safety.cjs b/languages/typescript/packages/recipher-js/value-napi/tests/object-safety.cjs index b35450f64..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,11 +142,21 @@ 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.RcDecimal('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.RcDate('2026-10-09')) +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 @@ -162,7 +172,7 @@ assert.ok( Object.prototype.writable = true Object.prototype.get = () => 'polluted' try { - const decimal = new addon.RcDecimal('1.50') + const decimal = addon.makeWrapper('RcDecimal', '1.50') assert.throws(() => { 'use strict' decimal.value = '999.99' @@ -200,7 +210,7 @@ const ct = { v: [ { t: 'eseq', v: leaf }, { t: 'pt', v: 5n }, - { t: 'pt', v: { a: [new addon.RcDecimal('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.RcTimestamp('2016-12-31T23:59:60Z')), + () => addon.encode(addon.makeWrapper('RcTimestamp', '2016-12-31T23:59:60Z')), { code: 'ERR_INVALID_TIMESTAMP' }, ) @@ -562,7 +572,7 @@ 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.RcDate('2024-02-29'))); + 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) => { @@ -575,7 +585,10 @@ assert.throws(() => addon.ciphertextWithPayload(60, HUGE), /nested too deeply/) ) }) assert.equal(reply, '2024-02-29') - assert.equal(roundTrip(new addon.RcDate('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/value-conformance.cjs b/languages/typescript/packages/recipher-js/value-napi/tests/value-conformance.cjs index 301928cad..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 @@ -18,13 +18,15 @@ function expected(row, value = row.value) { case 'bytes': return Buffer.from(value, 'hex') case 'date': - return new RcDate(value) + return addon.makeWrapper('RcDate', value) case 'decimal': - return new RcDecimal(value) + return addon.makeWrapper('RcDecimal', value) case 'timestamp': - return row.js_date ? new Date(value) : new RcTimestamp(value) + return row.js_date + ? new Date(value) + : addon.makeWrapper('RcTimestamp', value) case 'uuid': - return new RcUuid(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 RcDecimal(decimal)), { + assert.throws(() => addon.encode(addon.makeWrapper('RcDecimal', decimal)), { name: 'TypeError', code: 'ERR_NON_FINITE_DECIMAL', }) assert.throws( - () => addon.encode(new RcDecimal('79228162514264337593543950336')), + () => + addon.encode( + addon.makeWrapper('RcDecimal', '79228162514264337593543950336'), + ), { code: 'ERR_INVALID_DECIMAL' }, ) -assert.throws(() => addon.encode(new RcDate('2023-02-29')), { +assert.throws(() => addon.encode(addon.makeWrapper('RcDate', '2023-02-29')), { code: 'ERR_INVALID_DATE', }) -assert.throws(() => addon.encode(new RcUuid('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 RcTimestamp('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 RcUuid('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 RcUuid('123E4567-E89B-12D3-A456-426614174000')), + addon.encode( + addon.makeWrapper('RcUuid', '123E4567-E89B-12D3-A456-426614174000'), + ), ), uuid, ) const nested = { items: [ 1n, - new RcDate('2024-02-29'), - new RcDecimal('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 accepts only a string; the text itself is checked -// when the value is encrypted, so one rule applies however it was made. +// 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,13 +257,15 @@ for (const Wrapper of [RcDate, RcTimestamp, RcDecimal, RcUuid]) { 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 [ [RcDate, 'ERR_INVALID_DATE'], [RcTimestamp, 'ERR_INVALID_TIMESTAMP'], @@ -243,24 +295,33 @@ for (const timestamp of [ '9999-12-30T22:00:00.999999999Z', ]) { assert.deepEqual( - addon.decode(addon.encode(new RcTimestamp(timestamp))), - new RcTimestamp(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 RcTimestamp('+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 RcTimestamp('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 RcDate('+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'), @@ -273,7 +334,7 @@ assert.deepEqual( ) assert.deepEqual( addon.decode(Buffer.from('13ffffffffffffffffffc99a3b', 'hex')), - new RcTimestamp('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 RcDate('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')