From ce0079fd8c4ee7381f361fca0a8117eb74857ba8 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Wed, 25 Nov 2026 23:22:31 +1100 Subject: [PATCH 1/7] feat(recipher-js): records through the engine's Planned Encrypting one value at a time does not fit how applications store data: in rows, with some fields encrypted and searchable and some not. record(..), encrypt(..) and passthrough() declare a record as plain, frozen data, recognised by its type property, so a declaration from the CommonJS build works with a cipher from the ESM build. The addon builds the engine's plan from a declaration with the engine's own types, once for each declaration, and encrypts and decrypts whole rows, one field, or an array of one field through dynamic::Planned, so the stored bytes are the engine's and many rows make one key request. Each field is sealed under its field path, the record's name and then the field's name. A decrypted row goes through open_rows_in, beside the skeleton's open_in: both run the one confined! match, so whether a decrypt is confined to the default keyset is decided in one place for ciphertexts and rows alike, and a test pins it for rows. A refusal names the record and, where there is one, the field, with a recipher_js:: code. A decrypted row's inspect shows its field names and hides their values. RecordPlan derives Debug: it holds only declaration data. The record overloads of encrypt and decrypt, encryptField, decryptField, Cipher.create(options) and checkDeclarations are written on the Rust methods as ts_type strings, so native.d.ts stays the public type, and each returns its Result from Rust. src/record.ts never loads the addon, because the generated declarations import its types; checkDeclarations therefore lives with the other native entry points in src/cipher.ts, with a stand-in for an addon that did not load. Nothing is released, so the binding interface stays 1. Closes #1813 Closes #1803 --- AGENTS.md | 2 +- .../typescript/packages/recipher-js/README.md | 80 ++- .../__tests__/addon/builds.test.ts | 4 + .../__tests__/addon/records.test.ts | 353 ++++++++++ .../__tests__/unit/binding.test.ts | 3 + .../packages/recipher-js/crate/Cargo.toml | 13 +- .../packages/recipher-js/crate/src/cipher.rs | 451 +++++++++++- .../packages/recipher-js/crate/src/error.rs | 132 +++- .../packages/recipher-js/crate/src/frames.rs | 260 +++++++ .../packages/recipher-js/crate/src/js.rs | 109 +++ .../packages/recipher-js/crate/src/lib.rs | 6 +- .../packages/recipher-js/crate/src/record.rs | 645 ++++++++++++++++++ .../recipher-js/crate/src/record_tests.rs | 407 +++++++++++ .../packages/recipher-js/native-header.d.ts | 7 + .../packages/recipher-js/native.d.ts | 77 ++- .../packages/recipher-js/src/binding.ts | 1 + .../packages/recipher-js/src/cipher.ts | 15 + .../packages/recipher-js/src/error.ts | 5 +- .../packages/recipher-js/src/index.ts | 18 + .../packages/recipher-js/src/record.ts | 214 ++++++ .../recipher-js/type-tests/records.ts | 143 ++++ 21 files changed, 2909 insertions(+), 36 deletions(-) create mode 100644 languages/typescript/packages/recipher-js/__tests__/addon/records.test.ts create mode 100644 languages/typescript/packages/recipher-js/crate/src/frames.rs create mode 100644 languages/typescript/packages/recipher-js/crate/src/record.rs create mode 100644 languages/typescript/packages/recipher-js/crate/src/record_tests.rs create mode 100644 languages/typescript/packages/recipher-js/src/record.ts create mode 100644 languages/typescript/packages/recipher-js/type-tests/records.ts diff --git a/AGENTS.md b/AGENTS.md index 7ddf00563..f2359ae46 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`, `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). 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, the types the generated signatures name (`src/kinds.ts`, `src/value-types.ts`), and the record declarations (`src/record.ts`), which are plain data the addon reads. `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/README.md b/languages/typescript/packages/recipher-js/README.md index 5f73b7b00..07b76926c 100644 --- a/languages/typescript/packages/recipher-js/README.md +++ b/languages/typescript/packages/recipher-js/README.md @@ -126,6 +126,82 @@ The ciphertext's TypeScript type allows any scalar: any type in the table above 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. +## Records + +A record declares each field of a row once. +A field is encrypted, encrypted with indexes, or passed through unencrypted. + +```ts +import { encrypt, kinds, passthrough, record } from '@cipherstash/recipher' + +export const user = record('users', { + id: passthrough(), + email: encrypt(kinds.string, { index: ['equality'] }), + name: encrypt(kinds.string, { index: ['match'] }), + age: encrypt(kinds.int32, { index: ['equality'], null: 'sealed' }), + notes: encrypt(kinds.string, { null: 'sql' }), +}) + +// One row, or an array of rows in one key request. +const stored = await keyset.encrypt(user, row) +const opened = await cipher.decrypt(user, stored.unwrap()) +``` + +- A declaration is a plain, frozen object: `{ type: 'record', name, fields }`. + A library can read the record's name, its fields, and each field's declaration from it. +- The package has an ECMAScript module (ESM) build and a CommonJS build. + A declaration made by either build works with a cipher from the other. +- Each encrypted field names its kind, by the engine's name for it. + The kinds are `kinds.string`, `kinds.boolean`, `kinds.int8` to `kinds.int128`, `kinds.uint8` to `kinds.uint128`, `kinds.float32`, `kinds.float64`, `kinds.decimal`, `kinds.date`, `kinds.timestamp`, and `kinds.bytes`. +- An integer field takes a `bigint` at every width. + The field refuses a `bigint` outside its range. +- A context is data that a ciphertext is bound to. + The ciphertext decrypts only under the same context. + A field's context is its field path: the record's name, then the field's name. + The engine's typed Rust API decrypts the stored `email` field's ciphertext under `("users", "email")`. +- An index stores extra bytes, called index terms, beside a field's ciphertext. + A search can compare index terms without decrypting the field. + `equality` finds exact matches. + `match` finds text matches. + `ore` and `ope` compare order. +- The stored row has one object for each encrypted field. + The object has a `ciphertext` property. + The object also has one property for each index the field declares: `equality`, `match`, `ore`, or `ope`. + Each property is opaque bytes. +- A passthrough field keeps its value in the stored row. +- A field with `null: 'sealed'` encrypts a missing value like any other value. + A field with `null: 'sql'` is `null` in the stored row when the value is missing. +- `Plaintext` is the type of a row. + `Stored` is the type of a stored row. + A row of another shape does not compile. + `stored.notes.equality` does not compile either, because `notes` declares no index. +- A passthrough field is **not encrypted and not authenticated.** + Anyone with the stored row can read it, change it, or remove it. + Use a passthrough field only for values that are not secret. + Treat the value read back as untrusted. +- The engine checks a declaration the first time a cipher uses it. + The engine then keeps the plan it built from the declaration. +- `Cipher.create({ records })` checks the declarations before it looks for credentials. + `checkDeclarations(records)` checks them with no credentials. + A refusal names the record in `error.record`. + Where there is a field at fault, the refusal names it in `error.field`. +- Node's `inspect` shows a decrypted row's field names and hides their values. + `console.log` uses `inspect`, so it hides the values too. + The values are ordinary properties. + `JSON.stringify` or a spread still shows them. + +To update one field of a stored row, encrypt that field on its own. +An array of values gives an array of stored fields, with one key request: + +```ts +const email = await keyset.encryptField(user, 'email', 'ada@example.com') +const value = await cipher.decryptField(user, 'email', email.unwrap()) + +const emails = await keyset.encryptField(user, 'email', ['a@example.com', 'b@example.com']) +``` + +The stored field has the same form as that field in a whole stored row. + ## Results, not exceptions Every call returns, or resolves to, a `Result`. @@ -177,7 +253,7 @@ if (opened.isErr()) { | `help` | What to do about it, where the error knows. | | `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`. | +| `fields` | The error's structured fields, by `snake_case` name. Examples are a refused declaration's `reason` and a ZeroKMS failure's `request_kind`. | | `field` | The field at fault, where one is known. | | `record` | The record at fault, where there is one. | | `causes` | The errors behind this one, outermost first. Each cause has a `message`, and an engine error also has a `code`. A cause from another library has a fixed message, never that library's own text. | @@ -240,7 +316,7 @@ The ESM build and the CommonJS build load the same addon, so the two builds shar These features are not built yet: - `opaque(..)`, for a whole object; -- records; +- a `json` record field: this field needs `JsonSearch` from the Encrypt Query Language (EQL) extension for PostgreSQL; - search terms; - credentials passed in code; - named keysets; 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..28960a125 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/builds.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/builds.test.ts @@ -32,7 +32,10 @@ const read = cjs.Ciphertext.fromBytes(sealed.toBytes()).unwrap() const fromCjs_ = cjs.Ciphertext.fromBytes(new Uint8Array(1)) const fromEsm_ = esm.Ciphertext.fromBytes(new Uint8Array(1)) const okCjs = cjs.Ciphertext.fromBytes(sealed.toBytes()) +const people = cjs.record('people', { email: cjs.encrypt(cjs.kinds.string, { index: ['equality'] }) }) +const row = (await fromEsm.defaultKeyset().encrypt(people, { email: 'a@example.com' })).unwrap() const out = { + recordAcrossBuilds: (await fromEsm.decrypt(people, row)).unwrap().email, sameClasses: esm.Cipher === cjs.Cipher && esm.Ciphertext === cjs.Ciphertext, cipherIsCipher: fromCjs instanceof esm.Cipher && fromEsm instanceof cjs.Cipher, ciphertextIsCiphertext: sealed instanceof cjs.Ciphertext, @@ -118,6 +121,7 @@ describe('the ESM and CommonJS builds in one process', () => { { encoding: 'utf8' }, ) expect(JSON.parse(output)).toEqual({ + recordAcrossBuilds: 'a@example.com', sameClasses: true, cipherIsCipher: true, ciphertextIsCiphertext: true, diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/records.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/records.test.ts new file mode 100644 index 000000000..46be7f2dc --- /dev/null +++ b/languages/typescript/packages/recipher-js/__tests__/addon/records.test.ts @@ -0,0 +1,353 @@ +import { inspect } from 'node:util' +import { describe, expect, it } from 'vitest' +import { + Cipher, + checkDeclarations, + encrypt, + kinds, + type Plaintext, + passthrough, + record, + VcDate, + VcDecimal, +} from '../../src/index' +import { testCipher } from '../../src/testing' + +const user = record('users', { + id: passthrough(), + email: encrypt(kinds.string, { index: ['equality'] }), + name: encrypt(kinds.string, { index: ['match'] }), + age: encrypt(kinds.int32, { index: ['equality'], null: 'sealed' }), + score: encrypt(kinds.float64, { index: ['ore'] }), + notes: encrypt(kinds.string, { null: 'sql' }), +}) + +const ada: Plaintext = { + id: 7n, + email: 'ada@example.com', + name: 'Ada Lovelace', + age: 36n, + score: 99.5, + notes: null, +} + +async function cipher(): Promise { + return (await testCipher()).unwrap() +} + +describe('a record', () => { + it('round-trips one row', async () => { + const c = await cipher() + const stored = (await c.defaultKeyset().encrypt(user, ada)).unwrap() + expect((await c.decrypt(user, stored)).unwrap()).toEqual(ada) + expect((await c.defaultKeyset().decrypt(user, stored)).unwrap()).toEqual( + ada, + ) + }) + + it('stores a ciphertext and the declared terms for each sealed field', async () => { + const c = await cipher() + const stored = (await c.defaultKeyset().encrypt(user, ada)).unwrap() + expect(stored.id).toBe(7n) + expect(Object.keys(stored.email).sort()).toEqual(['ciphertext', 'equality']) + expect(Object.keys(stored.name).sort()).toEqual(['ciphertext', 'match']) + expect(Object.keys(stored.age).sort()).toEqual(['ciphertext', 'equality']) + expect(Object.keys(stored.score).sort()).toEqual(['ciphertext', 'ore']) + expect(stored.email.ciphertext).toBeInstanceOf(Uint8Array) + expect(stored.email.equality).toBeInstanceOf(Uint8Array) + // A field stored as SQL NULL is null when the value is absent. + expect(stored.notes).toBeNull() + }) + + it('derives the same equality term for the same value', async () => { + const c = await cipher() + const keyset = c.defaultKeyset() + const [a, b] = (await keyset.encrypt(user, [ada, ada])).unwrap() + expect(Buffer.from(a?.email.equality ?? [])).toEqual( + Buffer.from(b?.email.equality ?? []), + ) + expect(Buffer.from(a?.email.ciphertext ?? [])).not.toEqual( + Buffer.from(b?.email.ciphertext ?? []), + ) + }) + + it('takes a null where the field declares one', async () => { + const c = await cipher() + const row = { ...ada, age: null, notes: 'present' } + const stored = (await c.defaultKeyset().encrypt(user, row)).unwrap() + // A sealed null is stored like a value. + expect(stored.age).not.toBeNull() + expect((await c.decrypt(user, stored)).unwrap()).toEqual(row) + }) + + it('round-trips an array of rows, in order', async () => { + const c = await cipher() + const rows = [ada, { ...ada, id: 8n, email: 'grace@example.com', age: 45n }] + const stored = (await c.defaultKeyset().encrypt(user, rows)).unwrap() + expect(stored).toHaveLength(2) + expect((await c.decrypt(user, stored)).unwrap()).toEqual(rows) + }) + + it('holds every kind', async () => { + const everything = record('everything', { + text: encrypt(kinds.string), + flag: encrypt(kinds.boolean), + small: encrypt(kinds.uint8), + big: encrypt(kinds.int128), + real: encrypt(kinds.float32), + price: encrypt(kinds.decimal), + day: encrypt(kinds.date), + at: encrypt(kinds.timestamp), + blob: encrypt(kinds.bytes), + }) + const row: Plaintext = { + text: 'x', + flag: true, + small: 255n, + big: -(2n ** 100n), + real: 1.5, + price: new VcDecimal('1.50'), + day: new VcDate('2026-11-23'), + at: new Date('2026-11-23T01:02:03.456Z'), + blob: new Uint8Array([1, 2, 3]), + } + const c = await cipher() + const stored = (await c.defaultKeyset().encrypt(everything, row)).unwrap() + const opened = (await c.decrypt(everything, stored)).unwrap() + expect(opened.text).toBe('x') + expect(opened.flag).toBe(true) + expect(opened.small).toBe(255n) + expect(opened.big).toBe(-(2n ** 100n)) + expect(opened.real).toBe(1.5) + expect((opened.price as VcDecimal).value).toBe('1.50') + expect((opened.day as VcDate).value).toBe('2026-11-23') + expect((opened.at as Date).getTime()).toBe( + row.at instanceof Date ? row.at.getTime() : 0, + ) + expect(Buffer.from(opened.blob)).toEqual(Buffer.from([1, 2, 3])) + }) +}) + +describe('one field', () => { + it('encrypts alone to the form it has in a whole row', async () => { + const c = await cipher() + const keyset = c.defaultKeyset() + const email = ( + await keyset.encryptField(user, 'email', 'new@example.com') + ).unwrap() + expect(Object.keys(email).sort()).toEqual(['ciphertext', 'equality']) + expect((await c.decryptField(user, 'email', email)).unwrap()).toBe( + 'new@example.com', + ) + + // Its equality term is the term a whole row stores for the value. + const row = ( + await keyset.encrypt(user, { ...ada, email: 'new@example.com' }) + ).unwrap() + expect(Buffer.from(email.equality)).toEqual(Buffer.from(row.email.equality)) + + // And a whole row takes the field in place of its own. + const updated = { ...row, email } + expect((await c.decrypt(user, updated)).unwrap().email).toBe( + 'new@example.com', + ) + }) + + it("opens alone from a whole row's stored field", async () => { + const c = await cipher() + const row = (await c.defaultKeyset().encrypt(user, ada)).unwrap() + expect( + (await c.defaultKeyset().decryptField(user, 'name', row.name)).unwrap(), + ).toBe('Ada Lovelace') + }) + + it('refuses a field opened as another field of the same shape: each is sealed under its own path', async () => { + const pair = record('pair', { + a: encrypt(kinds.string, { index: ['equality'] }), + b: encrypt(kinds.string, { index: ['equality'] }), + }) + const c = await cipher() + const row = ( + await c.defaultKeyset().encrypt(pair, { a: 'x', b: 'y' }) + ).unwrap() + // Same shape, so this compiles and the engine reads it; only the context + // differs. The key service refuses the key, which it binds to the + // field path the value was sealed under. + const result = await c.decryptField(pair, 'a', row.b) + expect(result.err()?.code).toBe('stack_kms::retrieve_key_failed') + + // A row opened under a record of another name is refused the same way. + const other = record('other', pair.fields) + const moved = await c.decrypt(other, row) + expect(moved.err()?.code).toBe('stack_kms::retrieve_key_failed') + expect(moved.err()?.record).toBe('other') + }) + + it('encrypts and decrypts an array of one field in one call', async () => { + const c = await cipher() + const keyset = c.defaultKeyset() + const emails = ( + await keyset.encryptField(user, 'email', [ + 'a@example.com', + 'b@example.com', + ]) + ).unwrap() + expect(emails).toHaveLength(2) + expect((await c.decryptField(user, 'email', emails)).unwrap()).toEqual([ + 'a@example.com', + 'b@example.com', + ]) + }) + + it('stores a SQL null field alone as null', async () => { + const c = await cipher() + const notes = ( + await c.defaultKeyset().encryptField(user, 'notes', null) + ).unwrap() + expect(notes).toBeNull() + expect((await c.decryptField(user, 'notes', notes)).unwrap()).toBeNull() + }) + + it('refuses a field the record passes through or does not declare, naming it', async () => { + const keyset = (await cipher()).defaultKeyset() + // @ts-expect-error: id is passed through. + const passed = await keyset.encryptField(user, 'id', 1n) + expect(passed.err()?.code).toBe('recipher_js::no_field') + expect(passed.err()?.field).toBe('id') + expect(passed.err()?.record).toBe('users') + // @ts-expect-error: no such field. + const missing = await keyset.encryptField(user, 'missing', 'x') + expect(missing.err()?.field).toBe('missing') + }) +}) + +describe('a decrypted row', () => { + it('names its fields and hides their values when inspected', async () => { + const c = await cipher() + const stored = (await c.defaultKeyset().encrypt(user, ada)).unwrap() + const opened = (await c.decrypt(user, stored)).unwrap() + const shown = inspect(opened) + expect(shown).toContain('email: [hidden]') + expect(shown).not.toContain('ada@example.com') + expect(shown).not.toContain('Lovelace') + // The fields themselves are as they were. + expect(opened.email).toBe('ada@example.com') + expect(Object.keys(opened)).toEqual(Object.keys(ada)) + expect({ ...opened }).toEqual(ada) + }) +}) + +describe('refusals', () => { + it('an integer outside its field, naming the field', async () => { + const c = await cipher() + const result = await c + .defaultKeyset() + .encrypt(user, { ...ada, age: 2n ** 40n }) + expect(result.err()?.code).toBe('recipher_js::field_type') + expect(result.err()?.field).toBe('age') + expect(result.err()?.record).toBe('users') + }) + + it('a bigint outside 128 bits, naming the field', async () => { + const c = await cipher() + const result = await c + .defaultKeyset() + .encrypt(user, { ...ada, age: 2n ** 128n }) + expect(result.err()?.code).toBe('ERR_INTEGER_RANGE') + expect(result.err()?.field).toBe('age') + }) + + it('a null where the field takes none', async () => { + const keyset = (await cipher()).defaultKeyset() + // @ts-expect-error: email takes no null. + const result = await keyset.encrypt(user, { ...ada, email: null }) + expect(result.isErr()).toBe(true) + }) + + it('a row with a field the record does not declare', async () => { + const c = await cipher() + const row = { ...ada, extra: 'x' } + // A row widened past the record's type, as untyped input would be. + const result = await c + .defaultKeyset() + .encrypt(user, row as Plaintext) + expect(result.isErr()).toBe(true) + }) + + it('a declaration the engine refuses, naming the field', async () => { + const bad = record('bad', { + n: encrypt(kinds.int32, { index: ['match'] }), + }) + const checked = checkDeclarations([bad]) + expect(checked.err()?.code).toBe('stack_encrypt::dynamic_plan') + expect(checked.err()?.field).toBe('n') + expect(checked.err()?.record).toBe('bad') + + const c = await cipher() + const result = await c.defaultKeyset().encrypt(bad, { n: 1n }) + expect(result.err()?.code).toBe('stack_encrypt::dynamic_plan') + }) + + it('Cipher.create refuses a bad declaration before it looks for credentials', async () => { + const bad = record('bad', { + flag: encrypt(kinds.boolean, { index: ['ore'] }), + }) + const result = await Cipher.create({ records: [user, bad] }) + expect(result.err()?.code).toBe('stack_encrypt::dynamic_plan') + expect(result.err()?.record).toBe('bad') + }) + + it('a record name that is not a plain segment, blaming the record', () => { + for (const name of ['a/b', '']) { + const checked = checkDeclarations([ + record(name, { x: encrypt(kinds.string) }), + ]) + expect(checked.err()?.code).toBe('recipher_js::record_name') + expect(checked.err()?.record).toBe(name) + expect(checked.err()?.field).toBeUndefined() + expect(checked.err()?.message).toContain('record name') + } + }) + + it('a field name the engine reserves, naming the field', () => { + for (const name of ['bind', 'context_field']) { + const checked = checkDeclarations([ + record('r', { [name]: encrypt(kinds.string) }), + ]) + expect(checked.err()?.code).toBe('recipher_js::reserved_field') + expect(checked.err()?.field).toBe(name) + } + }) + + it('a row with a record that is not a declaration', async () => { + const keyset = (await cipher()).defaultKeyset() + // @ts-expect-error: the first argument is not a record. + const result = await keyset.encrypt({ name: 'users' }, ada) + expect(result.err()?.code).toBe('recipher_js::not_a_record') + }) + + it('a stored row with a term of an index the field does not declare, naming the field', async () => { + const c = await cipher() + const stored = (await c.defaultKeyset().encrypt(user, ada)).unwrap() + const stray = { + ...stored, + email: { ...stored.email, match: new Uint8Array([1, 2, 3]) }, + } + const result = await c.decrypt(user, stray) + expect(result.err()?.code).toBe('recipher_js::not_a_stored_row') + expect(result.err()?.field).toBe('email') + }) + + it('a stored row altered in storage does not open', async () => { + const c = await cipher() + const stored = (await c.defaultKeyset().encrypt(user, ada)).unwrap() + const ciphertext = Uint8Array.from(stored.email.ciphertext) + const last = ciphertext.length - 1 + ciphertext[last] = (ciphertext[last] ?? 0) ^ 1 + const result = await c.decrypt(user, { + ...stored, + email: { ...stored.email, ciphertext }, + }) + expect(result.err()?.code).toBe('stack_encrypt::aead') + }) +}) 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..da9e42bd3 100644 --- a/languages/typescript/packages/recipher-js/__tests__/unit/binding.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/unit/binding.test.ts @@ -16,6 +16,7 @@ function fakeBuild(overrides: Record = {}) { Ciphertext: class {}, Json: class {}, bindingInterface: () => BINDING_INTERFACE, + checkDeclarations: () => undefined, createTesting: () => Promise.resolve('cipher'), installResult: () => true, json: () => ({}), @@ -50,6 +51,7 @@ describe('load', () => { 'Ciphertext', 'Json', 'bindingInterface', + 'checkDeclarations', 'createTesting', 'installResult', 'json', @@ -140,6 +142,7 @@ describe('the classes of a build that did not load', () => { expect((await classes.Cipher.create()).err()).toBe(error) expect(classes.Ciphertext.fromBytes(new Uint8Array(4)).err()).toBe(error) expect((await classes.createTesting(new Uint8Array(32))).err()).toBe(error) + expect(classes.checkDeclarations([]).err()).toBe(error) }) it('recognise no value as one of theirs', () => { diff --git a/languages/typescript/packages/recipher-js/crate/Cargo.toml b/languages/typescript/packages/recipher-js/crate/Cargo.toml index b7ea0bf79..d2fad4c24 100644 --- a/languages/typescript/packages/recipher-js/crate/Cargo.toml +++ b/languages/typescript/packages/recipher-js/crate/Cargo.toml @@ -29,12 +29,15 @@ stack-auth = { path = "../../../../../packages/stack-auth", default-features = f # napi-rs 3, as `recipher-value-napi` is. Its default features load Node-API # by name at run time (`dyn-symbols`), so the crate's own tests link without # Node. `napi6` for BigInt and property enumeration, which vitaminc's walk -# needs; `tokio_rt` runs the engine's futures on napi's runtime. -napi = { version = "3", features = ["napi6", "tokio_rt", "serde-json"] } +# needs, and `napi9` (Node 18.17 and later) for `Symbol.for`, which keys a +# decrypted row's `inspect`; `tokio_rt` runs the engine's futures on napi's +# runtime. +napi = { version = "3", features = ["napi9", "tokio_rt", "serde-json"] } napi-derive = "3" # The value bridge: every JavaScript value is read and built through it. recipher-value-napi = { path = "../value-napi" } -# The frame `JsBuilder::build` takes. The version the engine resolves. +# The frame `JsBuilder::build` takes, and the frame writer a row is split +# with. The version the engine resolves. vitaminc-aead = "0.10.0" # `OpaqueDebug`, and the protected buffer a frame is held in. The version # the engine resolves. @@ -49,8 +52,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`, and a record's declaration, read +# from their frames through vitaminc's frame 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 aeed977ea..70bc6e460 100644 --- a/languages/typescript/packages/recipher-js/crate/src/cipher.rs +++ b/languages/typescript/packages/recipher-js/crate/src/cipher.rs @@ -28,6 +28,7 @@ use crate::error::{Error, RecipherErrorFields}; use crate::js; use crate::json::Json; use crate::outcome::{not_made, refused, spawn, Outcome}; +use crate::record::{field_value, one_field_row, open_rows, seal_rows, RecordPlan}; use crate::value::OneValue; /// The engine's cipher, with the key source it was built with. A napi class @@ -53,6 +54,26 @@ macro_rules! with_engine { }; } +/// Runs `$body` with `$cipher` bound to what a decrypt call may use, as +/// `$confined` says: the whole cipher, or its default keyset only. Every +/// decrypt goes through this macro, so keyset confinement is decided here +/// alone. +macro_rules! confined { + ($engine:expr, $confined:expr, |$cipher:ident| $body:expr) => { + with_engine!($engine, |whole| match $confined { + Confined::No => { + let $cipher = CipherRef::from(&**whole); + $body + } + Confined::ToDefault => { + let keyset = whole.default_keyset(); + let $cipher = CipherRef::from(&keyset); + $body + } + }) + }; +} + /// A cipher: the engine, and the keysets it can use. A keyset is a group /// of keys in ZeroKMS, CipherStash's key service. /// @@ -96,9 +117,24 @@ impl Cipher { /// - the credentials are refused; /// - ZeroKMS refuses to load the default keyset. /// + /// `options.records` lists record declarations to check now, before the + /// engine looks for credentials. If the engine refuses a declaration, + /// the promise resolves to an `Err` that names the record. + /// /// The promise does not reject. - #[napi(ts_return_type = "Promise>")] - pub fn create(env: &Env) -> napi::Result>> { + #[napi( + ts_args_type = "options?: CipherOptions", + ts_return_type = "Promise>" + )] + pub fn create<'e>( + env: &'e Env, + options: Option>, + ) -> napi::Result>> { + if let Err(error) = records_of_options(env, options) + .and_then(|records| records.map(|records| check(env, records)).unwrap_or(Ok(()))) + { + return refused(env, error); + } spawn( env, async { @@ -125,21 +161,53 @@ impl Cipher { /// /// 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. + /// ciphertexts were made under. A key request is one request to ZeroKMS + /// for data keys. + /// + /// With a record declaration as the first argument, decrypts a stored + /// row of that record, or an array of stored rows. A stored row is what + /// `keyset.encrypt` returns for a row. Node's `inspect` shows a + /// decrypted row's field names and hides their values. /// /// Resolves to an `Err` with the code `recipher_js::not_a_ciphertext` /// 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>" +decrypt(ciphertexts: readonly Ciphertext[]): Promise> +decrypt(record: R, row: Stored): Promise, RecipherError>> +decrypt(record: R, rows: readonly Stored[]): Promise[], RecipherError>>" )] pub fn decrypt<'e>( &self, env: &'e Env, - ciphertext: Unknown<'_>, + first: Unknown<'_>, + second: Option>, + ) -> napi::Result>> { + if js::is_record(env, &first) { + return open_rows_of(env, &self.engine, first, second, Confined::No); + } + if let Some(error) = js::second_without_record(env, &first, second.as_ref()) { + return refused(env, error); + } + open(env, &self.engine, first, Confined::No) + } + + /// Decrypts one field of a record's stored row, as `encryptField` or + /// `encrypt` stored it. An array of stored fields decrypts in one key + /// request. The promise does not reject. + #[napi( + ts_type = ">(record: R, field: F, stored: NoInfer[F]>): Promise[F], RecipherError>> +decryptField>(record: R, field: F, stored: readonly NoInfer[F]>[]): Promise[F][], RecipherError>>" + )] + pub fn decrypt_field<'e>( + &self, + env: &'e Env, + record: Unknown<'_>, + field: Unknown<'_>, + stored: Unknown<'_>, ) -> napi::Result>> { - open(env, &self.engine, ciphertext, Confined::No) + open_field(env, &self.engine, record, field, stored, Confined::No) } /// Returns the type's name. @@ -166,16 +234,33 @@ 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`. + /// + /// With a record declaration as the first argument, encrypts a row of + /// that record, or an array of rows in one key request. Each field is + /// encrypted under its field path: the record's name, then the field's + /// name. For each encrypted field, the stored row has the field's + /// ciphertext and its index terms. + /// /// 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(record: R, row: Plaintext): Promise, RecipherError>> +encrypt(record: R, rows: readonly Plaintext[]): Promise[], RecipherError>>" )] pub fn encrypt<'e>( &self, env: &'e Env, - value: Unknown<'_>, + first: Unknown<'_>, + second: Option>, ) -> napi::Result>> { + if js::is_record(env, &first) { + return seal_rows_of(env, &self.engine, first, second); + } + if let Some(error) = js::second_without_record(env, &first, second.as_ref()) { + return refused(env, error); + } + let value = first; let (many, values) = match js::elements(env, value) { Some(Ok(elements)) => (true, elements), Some(Err(error)) => return refused(env, error), @@ -221,18 +306,73 @@ encrypt(values: readonly V[]): Promise(ciphertexts: readonly Ciphertext[]): Promise> +decrypt(record: R, row: Stored): Promise, RecipherError>> +decrypt(record: R, rows: readonly Stored[]): Promise[], RecipherError>>" )] pub fn decrypt<'e>( &self, env: &'e Env, - ciphertext: Unknown<'_>, + first: Unknown<'_>, + second: Option>, ) -> napi::Result>> { - open(env, &self.engine, ciphertext, Confined::ToDefault) + if js::is_record(env, &first) { + return open_rows_of(env, &self.engine, first, second, Confined::ToDefault); + } + if let Some(error) = js::second_without_record(env, &first, second.as_ref()) { + return refused(env, error); + } + open(env, &self.engine, first, Confined::ToDefault) + } + + /// Encrypts one field of a record, to update that field alone. The + /// result is the field's stored form, the same form as in a whole stored + /// row. An array of values returns an array of stored fields, in one key + /// request. The promise does not reject. + #[napi( + ts_type = ">(record: R, field: F, value: NoInfer[F]>): Promise[F], RecipherError>> +encryptField>(record: R, field: F, values: readonly NoInfer[F]>[]): Promise[F][], RecipherError>>" + )] + pub fn encrypt_field<'e>( + &self, + env: &'e Env, + record: Unknown<'_>, + field: Unknown<'_>, + value: Unknown<'_>, + ) -> napi::Result>> { + seal_field(env, &self.engine, record, field, value) + } + + /// Decrypts one field of a record's stored row made under this keyset. + /// An array of stored fields decrypts in one key request. The promise + /// does not reject. + #[napi( + ts_type = ">(record: R, field: F, stored: NoInfer[F]>): Promise[F], RecipherError>> +decryptField>(record: R, field: F, stored: readonly NoInfer[F]>[]): Promise[F][], RecipherError>>" + )] + pub fn decrypt_field<'e>( + &self, + env: &'e Env, + record: Unknown<'_>, + field: Unknown<'_>, + stored: Unknown<'_>, + ) -> napi::Result>> { + open_field( + env, + &self.engine, + record, + field, + stored, + Confined::ToDefault, + ) } /// Returns the type's name. @@ -367,10 +507,20 @@ pub(crate) async fn open_in( sealed: Vec, confined: Confined, ) -> Outcome> { - with_engine!(engine, |cipher| match confined { - Confined::No => unseal(&**cipher, sealed).await, - Confined::ToDefault => unseal(&cipher.default_keyset(), sealed).await, - }) + confined!(engine, confined, |cipher| unseal(cipher, sealed).await) +} + +/// Decrypts stored rows of the record that `plan` describes, through +/// `engine`: through the whole cipher, or through its default keyset only, +/// as `confined` says. +pub(crate) async fn open_rows_in( + engine: &Engine, + plan: Arc, + rows: Vec, + confined: Confined, +) -> Outcome> { + confined!(engine, confined, |cipher| open_rows(cipher, plan, rows) + .await) } /// Returns one value to encrypt, and the kind its ciphertext decrypts as. A @@ -383,6 +533,273 @@ fn one_value(env: &Env, value: Unknown<'_>) -> Outcome<(OneValue, Option(env: &'e Env, records: Unknown<'_>) -> napi::Result> { + let checked = check(env, records); + crate::outcome::settle(env, checked, |env, ()| { + ().into_unknown(env).map_err(not_made) + }) +} + +/// Builds the plan of each declaration in `records`. The argument is one +/// declaration or an array of them. +fn check(env: &Env, records: Unknown<'_>) -> Outcome<()> { + let records = match js::elements(env, records) { + Some(records) => records?, + None => vec![records], + }; + for record in records { + let _ = plan_of(env, record)?; + } + Ok(()) +} + +/// Returns the `records` property of `Cipher.create`'s options, if the +/// options have one. +fn records_of_options<'e>(env: &Env, options: Option>) -> Outcome>> { + match options { + None => Ok(None), + Some(options) => js::property(env, options, "records"), + } +} + +/// Returns the plan of the declaration `record`. A plan is the engine's +/// description of how to encrypt each field of a record. +fn plan_of(env: &Env, record: Unknown<'_>) -> Outcome> { + if !js::is_record(env, &record) { + return Err(Error::NotARecord.into()); + } + RecordPlan::of(&js::read(env, record)?) +} + +/// Returns the values in `value`, and whether `value` was an array. The +/// values are the array's elements, or `value` alone. +fn one_or_many<'e>(env: &Env, value: Unknown<'e>) -> Outcome<(bool, Vec>)> { + match js::elements(env, value) { + Some(elements) => Ok((true, elements?)), + None => Ok((false, vec![value])), + } +} + +/// Returns a JavaScript array with one value for each result when `many` +/// is true, or the one result alone when it is false. +fn one_or_array<'e>( + env: &'e Env, + many: bool, + mut values: Vec>, +) -> Outcome> { + if many { + return values.into_unknown(env).map_err(not_made); + } + values.pop().ok_or_else(|| Error::NoResult.into()) +} + +/// Reads a row of `plan`'s record, with each value read as its field's +/// kind. When vitaminc refuses a value, the failure names the field the +/// value was read from. +fn read_row(env: &Env, plan: &RecordPlan, row: Unknown<'_>) -> Outcome { + let not_a_row = || RecipherErrorFields::from(Error::NotARow).in_record(plan.name()); + if row.get_type().ok() != Some(napi::ValueType::Object) || row.is_array().unwrap_or(false) { + return Err(not_a_row()); + } + let frame = js::read(env, row).map_err(|error| { + let field = plan.field_names().find(|name| { + js::property(env, row, name) + .map(|value| value.is_some_and(|value| js::read(env, value).is_err())) + .unwrap_or(true) + }); + error.in_record(plan.name()).at_field(field) + })?; + crate::record::conform_row(plan, &frame) +} + +/// Runs `keyset.encrypt(record, row | rows)`. +fn seal_rows_of<'e>( + env: &'e Env, + engine: &Arc, + record: Unknown<'_>, + rows: Option>, +) -> napi::Result>> { + let read = || -> Outcome<(Arc, bool, Vec)> { + let plan = plan_of(env, record)?; + let rows = rows.unwrap_or(().into_unknown(env).map_err(not_made)?); + let (many, rows) = one_or_many(env, rows)?; + let rows = rows + .into_iter() + .map(|row| read_row(env, &plan, row)) + .collect::>>()?; + Ok((plan, many, rows)) + }; + let (plan, many, rows) = match read() { + Ok(read) => read, + Err(error) => return refused(env, error), + }; + let engine = Arc::clone(engine); + spawn( + env, + async move { + with_engine!(&*engine, |cipher| { + seal_rows(&cipher.default_keyset(), plan, rows).await + }) + }, + move |env, stored| { + let values = stored + .into_iter() + .map(|row| js::build(env, row)) + .collect::>>()?; + one_or_array(env, many, values) + }, + ) +} + +/// Runs `cipher.decrypt(record, stored | stored[])` and `keyset.decrypt`. +fn open_rows_of<'e>( + env: &'e Env, + engine: &Arc, + record: Unknown<'_>, + stored: Option>, + confined: Confined, +) -> napi::Result>> { + let read = || -> Outcome<(Arc, bool, Vec)> { + let plan = plan_of(env, record)?; + let stored = stored.unwrap_or(().into_unknown(env).map_err(not_made)?); + let (many, rows) = one_or_many(env, stored)?; + let rows = rows + .into_iter() + .map(|row| js::read(env, row).map_err(|error| error.in_record(plan.name()))) + .collect::>>()?; + Ok((plan, many, rows)) + }; + let (plan, many, rows) = match read() { + Ok(read) => read, + Err(error) => return refused(env, error), + }; + let engine = Arc::clone(engine); + let names: Vec = plan.field_names().map(str::to_owned).collect(); + let record_name = plan.name().to_owned(); + spawn( + env, + async move { open_rows_in(&engine, plan, rows, confined).await }, + move |env, opened| { + let values = opened + .into_iter() + .map(|row| js::hidden(env, js::build(env, row)?, &record_name, &names)) + .collect::>>()?; + one_or_array(env, many, values) + }, + ) +} + +/// Returns the plan of the field `field` of `record` on its own, and the +/// field's name. +fn field_plan_of( + env: &Env, + record: Unknown<'_>, + field: Unknown<'_>, +) -> Outcome<(Arc, String)> { + let plan = plan_of(env, record)?; + let name = js::string(field) + .ok_or_else(|| RecipherErrorFields::from(Error::NoField).in_record(plan.name()))?; + Ok((plan.field(&name)?, name)) +} + +/// Runs `keyset.encryptField(record, field, value | values)`. +fn seal_field<'e>( + env: &'e Env, + engine: &Arc, + record: Unknown<'_>, + field: Unknown<'_>, + value: Unknown<'_>, +) -> napi::Result>> { + let read = || -> Outcome<(Arc, String, bool, Vec)> { + let (plan, name) = field_plan_of(env, record, field)?; + let (many, values) = one_or_many(env, value)?; + let rows = values + .into_iter() + .map(|value| { + let value = js::read(env, value) + .map_err(|error| error.in_record(plan.name()).at_field(Some(&name)))?; + crate::record::conform_row(&plan, &one_field_row(&name, &value)?) + }) + .collect::>>()?; + Ok((plan, name, many, rows)) + }; + let (plan, name, many, rows) = match read() { + Ok(read) => read, + Err(error) => return refused(env, error), + }; + let engine = Arc::clone(engine); + spawn( + env, + async move { + with_engine!(&*engine, |cipher| { + seal_rows(&cipher.default_keyset(), plan, rows).await + }) + }, + move |env, stored| { + let values = stored + .iter() + .map(|row| js::build(env, field_value(row, &name)?)) + .collect::>>()?; + one_or_array(env, many, values) + }, + ) +} + +/// Runs `cipher.decryptField(record, field, stored | stored[])` and +/// `keyset.decryptField`. +fn open_field<'e>( + env: &'e Env, + engine: &Arc, + record: Unknown<'_>, + field: Unknown<'_>, + stored: Unknown<'_>, + confined: Confined, +) -> napi::Result>> { + let read = || -> Outcome<(Arc, String, bool, Vec)> { + let (plan, name) = field_plan_of(env, record, field)?; + let (many, values) = one_or_many(env, stored)?; + let rows = values + .into_iter() + .map(|value| { + let value = js::read(env, value) + .map_err(|error| error.in_record(plan.name()).at_field(Some(&name)))?; + one_field_row(&name, &value) + }) + .collect::>>()?; + Ok((plan, name, many, rows)) + }; + let (plan, name, many, rows) = match read() { + Ok(read) => read, + Err(error) => return refused(env, error), + }; + let engine = Arc::clone(engine); + spawn( + env, + async move { + let opened = open_rows_in(&engine, plan, rows, confined).await?; + opened + .iter() + .map(|row| field_value(row, &name)) + .collect::>>() + }, + move |env, values| { + let values = values + .into_iter() + .map(|value| js::build(env, value)) + .collect::>>()?; + one_or_array(env, many, values) + }, + ) +} + /// 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. diff --git a/languages/typescript/packages/recipher-js/crate/src/error.rs b/languages/typescript/packages/recipher-js/crate/src/error.rs index 4d1b30720..a38530b9b 100644 --- a/languages/typescript/packages/recipher-js/crate/src/error.rs +++ b/languages/typescript/packages/recipher-js/crate/src/error.rs @@ -114,6 +114,83 @@ pub(crate) enum Error { help("Build it with `pnpm --filter @cipherstash/recipher build:debug`.") )] NoTesting, + /// A declaration that `record(..)` did not make. + #[error("the value is not a record")] + #[diagnostic( + code(recipher_js::not_a_record), + help("Declare a record with record(..).") + )] + NotARecord, + /// A field declared with something other than `encrypt(..)` or + /// `passthrough()`. + #[error("a field is declared with encrypt(..) or passthrough()")] + #[diagnostic(code(recipher_js::declaration))] + Declaration, + /// A field whose name the engine reserves. + #[error("the field's name is one the engine reserves")] + #[diagnostic( + code(recipher_js::reserved_field), + help("Name the field something else.") + )] + ReservedField, + /// A field's kind that is not one of `kinds`. + #[error("`{name}` is not one of `kinds`")] + #[diagnostic(code(recipher_js::kind))] + Kind { name: String }, + /// A field's index that is not one of the indexes the SDK names. + #[error("`{name}` is not an index")] + #[diagnostic(code(recipher_js::index))] + Index { name: String }, + /// A field's null mode that the engine does not have. A null mode says + /// how the engine stores a field's null. + #[error("`{mode}` is not a null mode")] + #[diagnostic(code(recipher_js::null), help("A null mode is `sealed` or `sql`."))] + Null { mode: String }, + /// A field path that could not be written as a context. + /// + /// A context is a value that a ciphertext is bound to, and decrypting + /// needs the same context. A field's context is its field path: the + /// record's name, then the field's name. + #[error("the field path could not be written")] + #[diagnostic(code(recipher_js::context))] + Context, + /// A record name the engine refuses as a segment of a field path. + #[error("the record name is not a plain segment of a field path")] + #[diagnostic( + code(recipher_js::record_name), + help("Use a record name that is not empty and holds no character the engine refuses in a field path, such as `/`.") + )] + RecordName, + /// A field name that the record does not encrypt. The record does not + /// declare the name, the name is a passthrough field's, or the name is + /// not a string. A passthrough field is stored as given, without + /// encryption. + #[error("the record declares no sealed field of that name")] + #[diagnostic( + code(recipher_js::no_field), + help("Name a field the record declares with encrypt(..). A passthrough field has no ciphertext.") + )] + NoField, + /// A row that is not an object of the record's fields. + #[error("a row is an object of the record's fields")] + #[diagnostic(code(recipher_js::not_a_row))] + NotARow, + /// A row's value that is not of its field's kind. + #[error("the value is not of the field's kind, {kind}, or does not fit it")] + #[diagnostic(code(recipher_js::field_type))] + FieldType { kind: ValueKind }, + /// A stored row that does not have the record's shape. A stored row is + /// what encrypting a row returns. + #[error("the stored row does not have the record's shape: {what}")] + #[diagnostic(code(recipher_js::not_a_stored_row))] + NotAStoredRow { what: &'static str }, + /// A stored row from the engine that the SDK cannot read. + #[error("the engine's stored row does not have the shape the SDK reads: {what}")] + #[diagnostic( + code(recipher_js::engine_result), + help("Report this as a bug in @cipherstash/recipher.") + )] + EngineResult { what: &'static str }, /// A call whose engine work returned no result. #[error("the engine returned no result")] #[diagnostic( @@ -174,8 +251,9 @@ pub struct RecipherErrorFields { /// diagnostic states another one. pub severity: Severity, /// The error's structured fields, keyed by `snake_case` name. For - /// example, a ZeroKMS failure has `request_kind`. The map is empty when - /// the error has no fields. + /// example, a refused plan has `field` and `reason`, and a ZeroKMS + /// failure has `request_kind`. A plan is the engine's rules for + /// encrypting a record. The map is empty when the error has no fields. #[napi(ts_type = "Record")] pub fields: serde_json::Map, /// The errors that caused this one, outermost first. @@ -317,6 +395,27 @@ impl RecipherErrorFields { pub(crate) fn engine(error: &E) -> Self { Self::diagnostic(error, Some(error.payload())) } + + /// Returns this failure, with the name of the record at fault. + pub(crate) fn in_record(mut self, record: &str) -> Self { + self.record = Some(record.to_owned()); + self + } + + /// Returns this failure, with the name of the field at fault, or with + /// no field. + pub(crate) fn at_field(mut self, field: Option<&str>) -> Self { + self.field = field.map(str::to_owned); + self + } + + /// Returns the engine's `reason` field, such as `no_fields`, when the + /// error's fields include one. + pub(crate) fn reason(&self) -> Option<&str> { + self.fields + .get("reason") + .and_then(serde_json::Value::as_str) + } } impl From for RecipherErrorFields { @@ -512,6 +611,7 @@ mod tests { /// Returns one of each variant of [`Error`]. The match has no wildcard, /// so the crate does not compile when a new variant has no entry here. fn every_error() -> Vec { + let name = || "x".to_owned(); let all = vec![ Error::Undefined, Error::Uuid, @@ -531,6 +631,21 @@ mod tests { Error::NotADocument, Error::TestingSeed, Error::NoTesting, + Error::NotARecord, + Error::Declaration, + Error::ReservedField, + Error::Kind { name: name() }, + Error::Index { name: name() }, + Error::Null { mode: name() }, + Error::Context, + Error::RecordName, + Error::NoField, + Error::NotARow, + Error::FieldType { + kind: ValueKind::Int8, + }, + Error::NotAStoredRow { what: "x" }, + Error::EngineResult { what: "x" }, Error::NoResult, Error::BuildValue, ]; @@ -552,6 +667,19 @@ mod tests { | Error::NotADocument | Error::TestingSeed | Error::NoTesting + | Error::NotARecord + | Error::Declaration + | Error::ReservedField + | Error::Kind { .. } + | Error::Index { .. } + | Error::Null { .. } + | Error::Context + | Error::RecordName + | Error::NoField + | Error::NotARow + | Error::FieldType { .. } + | Error::NotAStoredRow { .. } + | Error::EngineResult { .. } | Error::NoResult | Error::BuildValue => {} } diff --git a/languages/typescript/packages/recipher-js/crate/src/frames.rs b/languages/typescript/packages/recipher-js/crate/src/frames.rs new file mode 100644 index 000000000..5a763a8c5 --- /dev/null +++ b/languages/typescript/packages/recipher-js/crate/src/frames.rs @@ -0,0 +1,260 @@ +//! Helpers that read a map frame one entry at a time, and write a map frame +//! in a given order. +//! +//! A frame is a [`ValueFrame`]: a byte buffer that contains one value, in +//! the encoding of vitaminc, CipherStash's cryptography library. A map frame +//! contains a map. A sink receives a value from a frame one part at a time: +//! one scalar, array or map. +//! +//! The addon passes a record's row, and its stored row, between JavaScript +//! and the engine as one map frame each. The engine is the `stack-encrypt` +//! crate. The map has one entry for each of the record's fields. These +//! helpers split such a frame into one frame for each entry. They also +//! write entries back as one map, in the order given. + +use stack_encrypt::dynamic::plaintext::{ + Error as SinkError, FixedType, Logical, MapSink, Physical, SeqSink, Sink, SourceError, +}; +use stack_encrypt::dynamic::ValueFrame; +use stack_encrypt::{AsProtectedRef, Buffer, Encrypt, EncryptRef}; +use vitaminc_aead::frame::{FrameError, FrameWriteError}; +use vitaminc_aead::{Frame, FrameWriter}; + +/// Returns the entries of a map frame, each as its own frame, in the map's +/// order. Returns `None` when the frame is not a map. +pub(crate) fn entries(frame: &ValueFrame) -> Option> { + let buffers = frame.visit(Split).ok()?; + buffers + .into_iter() + .map(|(key, buffer)| { + ValueFrame::from_bytes(buffer.as_protected_ref()) + .map(|frame| (key, frame)) + .ok() + }) + .collect() +} + +/// Returns the bytes of a frame that contains only a bytes value, or `None` +/// for any other frame. +pub(crate) fn bytes_of(frame: &ValueFrame) -> Option> { + frame.visit(BytesOf).ok() +} + +/// One entry of a map that [`Map`] writes. +pub(crate) enum Entry<'a> { + /// A value, written as it is. + Value(&'a ValueFrame), + /// Bytes, written as a bytes value. + Bytes(Vec), + /// A frame given as its encoded bytes, such as a passthrough output's. + /// A passthrough output is a value the engine stores as given, without + /// encryption. The frame is parsed from the bytes and written without a + /// copy. + Frame(&'a [u8]), + /// A nested map. + Map(Map<'a>), + /// A null. + Null, +} + +/// A map whose entries are written in the order given. +pub(crate) struct Map<'a>(pub(crate) Vec<(&'a str, Entry<'a>)>); + +impl Encrypt for &Map<'_> { + fn visit(self, sink: S) -> Result { + let mut map = sink.map(Some(self.0.len()))?; + for (key, entry) in &self.0 { + let sink = map.entry(key)?; + match entry { + Entry::Value(frame) => { + let _ = frame.visit(sink)?; + } + Entry::Bytes(bytes) => { + let _ = sink.scalar(None, Physical::Bytes(bytes))?; + } + Entry::Frame(bytes) => { + let frame = Frame::parse(bytes) + .map_err(|error: FrameError| S::Error::source(SourceError::new(error)))?; + let _ = frame.visit(sink)?; + } + Entry::Map(inner) => { + let _ = inner.visit(sink)?; + } + Entry::Null => { + let _ = sink.scalar(None, Physical::Null)?; + } + } + } + map.end() + } +} + +/// A sink that writes each entry of a map into its own buffer. +struct Split; + +/// The entries that [`Split`] has written so far. +struct Collect(Vec<(String, Buffer)>); + +/// Returns the error that [`Split`] gives for any value that is not a map. +fn not_a_map() -> FrameWriteError { + FrameWriteError::source(SourceError::msg("not a map")) +} + +impl Sink for Split { + type Ok = Vec<(String, Buffer)>; + type Error = FrameWriteError; + type Seq = NotAMap; + type Map = Collect; + + fn scalar(self, _: Option, _: Physical<'_>) -> Result { + Err(not_a_map()) + } + fn typed_null(self, _: FixedType) -> Result { + Err(not_a_map()) + } + fn seq(self, _: Option) -> Result { + Err(not_a_map()) + } + fn map(self, len: Option) -> Result { + Ok(Collect(Vec::with_capacity(len.unwrap_or(0).min(256)))) + } + fn passthrough(self, _: &P) -> Result { + Err(not_a_map()) + } +} + +impl MapSink for Collect { + type Ok = Vec<(String, Buffer)>; + type Error = FrameWriteError; + type Entry<'s> + = FrameWriter<'s> + where + Self: 's; + + fn entry(&mut self, key: &str) -> Result, FrameWriteError> { + self.0.push((key.to_owned(), Buffer::new())); + match self.0.last_mut() { + Some((_, buffer)) => Ok(FrameWriter::new(buffer)), + None => Err(not_a_map()), + } + } + + fn end(self) -> Result { + Ok(self.0) + } +} + +/// A type that is never created, because [`Split`] refuses a sequence +/// before it would create one. +struct NotAMap; + +impl SeqSink for NotAMap { + type Ok = Vec<(String, Buffer)>; + type Error = FrameWriteError; + type Element<'s> + = Split + where + Self: 's; + + fn element(&mut self) -> Result { + Err(not_a_map()) + } + fn end(self) -> Result { + Err(not_a_map()) + } +} + +/// A sink that reads one bytes value. +struct BytesOf; + +/// An error with no text. The caller writes its own message. +struct NotBytes; + +impl SinkError for NotBytes { + fn source(_: SourceError) -> Self { + Self + } +} + +impl Sink for BytesOf { + type Ok = Vec; + type Error = NotBytes; + type Seq = NoBytes; + type Map = NoBytes; + + fn scalar(self, ty: Option, value: Physical<'_>) -> Result, NotBytes> { + match (ty, value) { + (None, Physical::Bytes(bytes)) => Ok(bytes.to_vec()), + _ => Err(NotBytes), + } + } + fn typed_null(self, _: FixedType) -> Result, NotBytes> { + Err(NotBytes) + } + fn seq(self, _: Option) -> Result { + Err(NotBytes) + } + fn map(self, _: Option) -> Result { + Err(NotBytes) + } + fn passthrough(self, _: &P) -> Result, NotBytes> { + Err(NotBytes) + } +} + +/// A type that is never created, because [`BytesOf`] refuses an array or a +/// map before it would create one. +struct NoBytes; + +impl SeqSink for NoBytes { + type Ok = Vec; + type Error = NotBytes; + type Element<'s> = BytesOf; + fn element(&mut self) -> Result { + Err(NotBytes) + } + fn end(self) -> Result, NotBytes> { + Err(NotBytes) + } +} + +impl MapSink for NoBytes { + type Ok = Vec; + type Error = NotBytes; + type Entry<'s> = BytesOf; + fn entry(&mut self, _: &str) -> Result { + Err(NotBytes) + } + fn end(self) -> Result, NotBytes> { + Err(NotBytes) + } +} + +#[cfg(test)] +mod tests { + use super::{bytes_of, entries, Entry, Map}; + use stack_encrypt::dynamic::ValueFrame; + + #[test] + fn a_map_splits_into_its_entries_and_writes_back_in_order() { + let a = ValueFrame::of("x").unwrap(); + let written = ValueFrame::of(&Map(vec![ + ("b", Entry::Value(&a)), + ("a", Entry::Bytes(vec![1, 2])), + ("c", Entry::Null), + ])) + .unwrap(); + let split = entries(&written).unwrap(); + let keys: Vec<_> = split.iter().map(|(key, _)| key.as_str()).collect(); + assert_eq!(keys, ["b", "a", "c"]); + assert_eq!(split[0].1, a); + assert_eq!(bytes_of(&split[1].1), Some(vec![1, 2])); + assert_eq!(bytes_of(&split[2].1), None); + } + + #[test] + fn anything_but_a_map_is_refused() { + let text = ValueFrame::of("x").unwrap(); + assert!(entries(&text).is_none()); + } +} diff --git a/languages/typescript/packages/recipher-js/crate/src/js.rs b/languages/typescript/packages/recipher-js/crate/src/js.rs index 82b042743..f38d4e493 100644 --- a/languages/typescript/packages/recipher-js/crate/src/js.rs +++ b/languages/typescript/packages/recipher-js/crate/src/js.rs @@ -23,6 +23,7 @@ use napi::bindgen_prelude::{FromNapiValue, JsObjectValue, JsValue, Object, Unknown}; use napi::{Env, Status, ValueType}; +use napi::{Property, PropertyAttributes}; use recipher_value_napi::{JsBuilder, JsFault, JsRef, Refusal, Wrapper, Wrappers}; use stack_encrypt::dynamic::ValueFrame; use stack_encrypt::AsProtectedRef; @@ -30,6 +31,7 @@ use vitaminc_aead::Frame; use vitaminc_protected::Controlled; use crate::error::{Error, RecipherErrorFields}; +use crate::outcome::not_made; /// Reads a JavaScript value into a frame of the engine's value model. /// @@ -111,6 +113,113 @@ fn is_uuid(env: &Env, value: &Unknown<'_>) -> bool { .is_ok_and(|wrapper| wrapper == Some(Wrapper::Uuid)) } +/// Returns the property `name` of `value`, when `value` is an object and +/// the property is not `undefined`. +/// +/// # Errors +/// +/// Returns `recipher_js::threw` when reading the property throws, as a getter +/// can. The addon drops what the getter threw. +pub(crate) fn property<'e>( + env: &Env, + value: Unknown<'e>, + name: &str, +) -> Result>, RecipherErrorFields> { + if value.get_type().ok() != Some(ValueType::Object) { + return Ok(None); + } + let object = Object::from_unknown(value).map_err(|error| refused(env, &error.into()))?; + let property = object + .get_named_property::>(name) + .map_err(|error| refused(env, &error.into()))?; + Ok((property.get_type().ok() != Some(ValueType::Undefined)).then_some(property)) +} + +/// Returns whether `value` is a record declaration, as `record(..)` makes +/// it. A record declaration lists a record's fields and how to store each +/// one. A declaration is an object whose `type` is `"record"`. The check +/// reads only that property, so it works for a declaration from any copy +/// of the package. +pub(crate) fn is_record(env: &Env, value: &Unknown<'_>) -> bool { + if value.is_array().unwrap_or(true) { + return false; + } + matches!( + property(env, *value, "type").map(|tag| tag.and_then(string)), + Ok(Some(tag)) if tag == "record" + ) +} + +/// Returns the failure for a call that has a second argument, when the +/// first argument is a plain object but not a record declaration. Such a +/// call passes a row with a record argument that is not a record. Returns +/// `None` for any other call. For example, `Array.prototype.map` passes a +/// value with its index, and that call gets `None`. +pub(crate) fn second_without_record( + env: &Env, + first: &Unknown<'_>, + second: Option<&Unknown<'_>>, +) -> Option { + let second = second?; + if second.get_type().ok() == Some(ValueType::Undefined) + || first.get_type().ok() != Some(ValueType::Object) + || first.is_array().unwrap_or(true) + { + return None; + } + let plain = Wrappers::get(env) + .and_then(|wrappers| wrappers.is_plain(*first)) + .unwrap_or(false); + plain.then(|| Error::NotARecord.into()) +} + +/// Returns the text of a JavaScript string, or `None` for any other value. +pub(crate) fn string(value: Unknown<'_>) -> Option { + if value.get_type().ok() != Some(ValueType::String) { + return None; + } + String::from_unknown(value).ok() +} + +/// Returns `row`, a decrypted row of `record`, with an added `inspect` +/// method. The method names the row's fields and hides their values. So +/// Node's `util.inspect` and `console.log` print +/// `users { email: [hidden], .. }`. The method is a property keyed by +/// `Symbol.for('nodejs.util.inspect.custom')`. The property is not +/// enumerable, so the row's own fields do not change. +pub(crate) fn hidden<'e>( + env: &'e Env, + row: Unknown<'e>, + record: &str, + fields: &[String], +) -> Result, RecipherErrorFields> { + let shown = format!( + "{record} {{ {} }}", + fields + .iter() + .map(|field| format!("{field}: [hidden]")) + .collect::>() + .join(", ") + ); + let mut object = Object::from_unknown(row).map_err(not_made)?; + let inspect = env + .create_function_from_closure::<(), String, _>("inspect", move |_| Ok(shown.clone())) + .map_err(not_made)?; + let key = env + .symbol_for("nodejs.util.inspect.custom") + .map_err(not_made)?; + let property = Property::new() + .with_name(env, key) + .map_err(not_made)? + .with_value(&inspect) + // The property is not enumerable, writable or configurable. So a + // copy, spread or comparison of the row does not include it, and + // nothing can replace it. + .with_property_attributes(PropertyAttributes::Default); + object.define_properties(&[property]).map_err(not_made)?; + Ok(row) +} + /// Returns the failure for a value the bridge refused. The bridge says /// which rule the value broke, and this function does not read the /// bridge's text. An exception may still be pending in JavaScript, and this diff --git a/languages/typescript/packages/recipher-js/crate/src/lib.rs b/languages/typescript/packages/recipher-js/crate/src/lib.rs index a5c918bb5..0ac9983a5 100644 --- a/languages/typescript/packages/recipher-js/crate/src/lib.rs +++ b/languages/typescript/packages/recipher-js/crate/src/lib.rs @@ -53,15 +53,19 @@ mod cipher; mod ciphertext; mod error; +mod frames; mod js; mod json; mod outcome; +mod record; mod value; #[cfg(all(test, feature = "testing"))] mod engine_tests; +#[cfg(all(test, feature = "testing"))] +mod record_tests; -pub use cipher::{create_testing, Cipher, Keyset}; +pub use cipher::{check_declarations, create_testing, Cipher, Keyset}; pub use ciphertext::Ciphertext; pub use error::RecipherErrorFields; pub use json::{json_document, Json}; diff --git a/languages/typescript/packages/recipher-js/crate/src/record.rs b/languages/typescript/packages/recipher-js/crate/src/record.rs new file mode 100644 index 000000000..89045ebb6 --- /dev/null +++ b/languages/typescript/packages/recipher-js/crate/src/record.rs @@ -0,0 +1,645 @@ +//! Records: declarations of fields, and the rows encrypted and decrypted +//! under them. +//! +//! A record declares the fields of a row and how to store each one. The +//! addon turns each declaration into the engine's [`Plan`] once. A plan is +//! the engine's description of how to encrypt each field of a row. The +//! engine is the Stack Encrypt engine, the `stack-encrypt` crate. Rows are +//! encrypted and decrypted through the engine's `dynamic::Planned`. +//! +//! # Declarations +//! +//! A declaration is the plain object that `record(..)` makes: +//! `{ type: "record", name, fields }`. Each field is one of these: +//! +//! - `{ type: "sealed", kind: { name }, index: [..], null? }`, a sealed +//! field, which the engine encrypts; +//! - `{ type: "passthrough" }`, a passthrough field, which the engine +//! stores as given, without encryption. +//! +//! Each field's context is its field path: the record's name, then the +//! field's name. A context is a value that a ciphertext is bound to, and +//! decrypting needs the same context. +//! +//! The addon builds the plan from the declaration with the engine's own +//! types: [`FieldPlan`], [`Output`], [`IndexSpec`], [`NullMode`] and +//! [`ValueKind`]. So the engine checks the plan, and the refusals are the +//! engine's. The addon builds a plan once for each declaration, and keeps +//! it for the life of the process. +//! +//! # Rows +//! +//! A row passes to the engine as one frame. A frame is a byte buffer that +//! contains one value. A row's frame contains a map of the record's fields. +//! +//! Before the engine reads a value, the engine's [`read`] reads it as its +//! field's kind. That step is needed because vitaminc, CipherStash's +//! cryptography library, reads a JavaScript `bigint` at the narrowest width +//! that fits it. +//! +//! A stored row is what encrypting a row returns. The stored row also +//! passes as one frame, with one entry for each field: +//! +//! - for a sealed field, an object of `ciphertext` and the field's index +//! terms, each as bytes; +//! - for a passthrough field, its value; +//! - for an absent field, a null. +//! +//! An index term is a value derived from a field's plaintext that lets a +//! database search the field without decrypting it. + +use std::collections::HashMap; +use std::sync::{Arc, LazyLock, Mutex, PoisonError}; + +use serde::de::{MapAccess, Visitor}; +use serde::{Deserialize, Deserializer}; +use stack_encrypt::dynamic::{ + context, read, FieldPlan, NullMode, Output, Plan, Planned, ValueFrame, ValueKind, +}; +use stack_encrypt::kms::{DataKeySource, IndexKeySource}; +use stack_encrypt::target::IndexSpec; +use stack_encrypt::{ + AsProtectedRef, CipherRef, CipherText, Controlled, DecryptFrom, EncryptInto, KeysetCipher, + PassthroughFrame, StackCipherText, +}; + +use crate::error::{Error, RecipherErrorFields}; +use crate::frames::{bytes_of, entries, Entry, Map}; +use crate::outcome::Outcome; + +/// The key of a field's ciphertext in a stored row. +const CIPHERTEXT: &str = "ciphertext"; + +/// Field names that the engine reserves for the top level of a plan. +const RESERVED: [&str; 2] = ["bind", "context_field"]; + +/// Returns the index that a declaration names, from the SDK's name for it. +fn index_named(name: &str) -> Option { + match name { + "equality" => Some(IndexSpec::Equality), + // The match index with its default options, as the engine reads the + // key `match` in a plan. + "match" => IndexSpec::parse("match"), + "ore" => Some(IndexSpec::Ore), + "ope" => Some(IndexSpec::Ope), + _ => None, + } +} + +/// Returns the SDK's name for an index, as a stored row writes it. +fn index_name(index: &IndexSpec) -> Option<&'static str> { + match index { + IndexSpec::Equality => Some("equality"), + IndexSpec::Match(_) => Some("match"), + IndexSpec::Ore => Some("ore"), + IndexSpec::Ope => Some("ope"), + IndexSpec::OreBlock | IndexSpec::Json(_) => None, + } +} + +/// A record's plan, built once from its declaration. A declaration contains +/// no secret, so `Debug` prints the whole plan. +#[derive(Debug)] +pub(crate) struct RecordPlan { + name: String, + plan: Plan, + /// The fields, in declaration order. + fields: Vec, + /// A plan for each sealed field on its own, keyed by the field's name. + alone: HashMap>, +} + +/// A field, as the addon uses it to read rows. +#[derive(Clone, Debug)] +struct Field { + name: String, + kind: Option, + indexes: Vec, + passthrough: bool, +} + +/// A declaration, as `record(..)` writes it. +#[derive(Deserialize)] +struct Declaration { + #[serde(rename = "type")] + tag: String, + name: String, + fields: Fields, +} + +/// The fields of a declaration, in the order they are declared. +struct Fields(Vec<(String, FieldDeclaration)>); + +impl<'de> Deserialize<'de> for Fields { + fn deserialize>(deserializer: D) -> Result { + struct InOrder; + impl<'de> Visitor<'de> for InOrder { + type Value = Fields; + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("an object of field declarations") + } + fn visit_map>(self, mut map: A) -> Result { + let mut fields = Vec::new(); + while let Some(entry) = map.next_entry()? { + fields.push(entry); + } + Ok(Fields(fields)) + } + } + deserializer.deserialize_map(InOrder) + } +} + +/// One field of a declaration. +#[derive(Deserialize)] +struct FieldDeclaration { + #[serde(rename = "type")] + tag: String, + #[serde(default)] + kind: Option, + #[serde(default)] + index: Vec, + #[serde(default)] + null: Option, +} + +/// A field's kind, as the package's `kinds` object writes it. +#[derive(Deserialize)] +struct KindDeclaration { + name: String, +} + +/// The plans built so far, keyed by the bytes of the declaration's frame. A +/// declaration contains no secret. +static PLANS: LazyLock, Arc>>> = + LazyLock::new(|| Mutex::new(HashMap::new())); + +impl RecordPlan { + /// Returns the plan of the declaration that the addon read into + /// `frame`. The plan is built the first time the declaration is seen. + /// + /// # Errors + /// + /// Returns `recipher_js::not_a_record`, or a refusal of the declaration. + /// A refusal names the record and, where there is one, the field. + pub(crate) fn of(frame: &ValueFrame) -> Outcome> { + let key = frame.risky_ref().to_vec(); + if let Some(plan) = PLANS + .lock() + .unwrap_or_else(PoisonError::into_inner) + .get(&key) + { + return Ok(Arc::clone(plan)); + } + let declaration: Declaration = + stack_encrypt::dynamic::frame::serde::from_slice(frame.risky_ref()) + .map_err(|_| Error::NotARecord)?; + if declaration.tag != "record" { + return Err(Error::NotARecord.into()); + } + let plan = Arc::new(Self::build(declaration.name, declaration.fields.0)?); + // Another call may have built the same plan at the same time. Every + // call uses the first plan stored. + let kept = PLANS + .lock() + .unwrap_or_else(PoisonError::into_inner) + .entry(key) + .or_insert(plan) + .clone(); + Ok(kept) + } + + fn build(name: String, declared: Vec<(String, FieldDeclaration)>) -> Outcome { + let mut fields = Vec::with_capacity(declared.len()); + let mut plans = Vec::with_capacity(declared.len()); + for (field_name, declaration) in declared { + let (field, plan) = field_of(&name, field_name, declaration)?; + fields.push(field); + plans.push(plan); + } + let plan = Plan::new(plans.clone()).map_err(|error| engine_refused(&name, &error))?; + let mut alone = HashMap::new(); + for (field, field_plan) in fields.iter().zip(plans) { + if field.passthrough { + continue; + } + let plan = + Plan::new(vec![field_plan]).map_err(|error| engine_refused(&name, &error))?; + let _ = alone.insert( + field.name.clone(), + Arc::new(Self { + name: name.clone(), + plan, + fields: vec![field.clone()], + alone: HashMap::new(), + }), + ); + } + Ok(Self { + name, + plan, + fields, + alone, + }) + } + + /// Returns the record's name. + pub(crate) fn name(&self) -> &str { + &self.name + } + + /// Returns the names of the fields, in declaration order. + pub(crate) fn field_names(&self) -> impl Iterator { + self.fields.iter().map(|field| field.name.as_str()) + } + + /// Returns the plan of the sealed field `name` on its own. The plan + /// uses the same field path, so the field's stored bytes have the same + /// form as in a whole row. + /// + /// # Errors + /// + /// Returns `recipher_js::no_field` for a name that the record does not + /// declare, or that names a passthrough field. + pub(crate) fn field(&self, name: &str) -> Outcome> { + self.alone.get(name).cloned().ok_or_else(|| { + RecipherErrorFields::from(Error::NoField) + .in_record(&self.name) + .at_field(Some(name)) + }) + } +} + +/// Returns a field, and the engine's plan for it. +fn field_of( + record: &str, + name: String, + declaration: FieldDeclaration, +) -> Outcome<(Field, FieldPlan)> { + let at = |error: Error| { + RecipherErrorFields::from(error) + .in_record(record) + .at_field(Some(&name)) + }; + if RESERVED.contains(&name.as_str()) { + return Err(at(Error::ReservedField)); + } + let passthrough = match declaration.tag.as_str() { + "sealed" => false, + "passthrough" => true, + _ => return Err(at(Error::Declaration)), + }; + let kind = match declaration.kind { + Some(kind) => Some( + kind.name + .parse::() + .map_err(|_| at(Error::Kind { name: kind.name }))?, + ), + None => None, + }; + let mut indexes = Vec::with_capacity(declaration.index.len()); + for index in declaration.index { + indexes.push(index_named(&index).ok_or_else(|| at(Error::Index { name: index }))?); + } + let null = match declaration.null { + None => None, + Some(mode) => Some( + [NullMode::Sealed, NullMode::Sql] + .into_iter() + .find(|known| known.name() == mode) + .ok_or_else(|| at(Error::Null { mode }))?, + ), + }; + let outputs = if passthrough { + vec![Output::Passthrough] + } else { + std::iter::once(Output::Ciphertext) + .chain(indexes.iter().cloned().map(Output::Term)) + .collect() + }; + let field_context = field_path(record, &name).ok_or_else(|| at(Error::Context))?; + let mut plan = FieldPlan::new(name.clone(), field_context, outputs) + .map_err(|error| engine_refused(record, &error))?; + if let Some(kind) = kind { + plan = plan + .with_type(kind) + .map_err(|error| engine_refused(record, &error))?; + } + if let Some(null) = null { + plan = plan.with_null(null); + } + Ok(( + Field { + name, + kind, + indexes, + passthrough, + }, + plan, + )) +} + +/// Returns a field's context: its field path, `[record, field]`, read by +/// the engine's own context reader. +fn field_path( + record: &str, + field: &str, +) -> Option>> { + let frame = stack_encrypt::dynamic::frame::serde::to_vec(&(record, field)).ok()?; + context(frame.as_protected_ref()).ok() +} + +/// Returns the engine's refusal of a declaration of `record`. +/// +/// The engine can refuse a context with the reason `context_not_label`. +/// Then either the record's name or the field's name is at fault. The +/// engine names the field in both cases. So this function checks the +/// record's name on its own, to find which name is at fault. +fn engine_refused(record: &str, error: &stack_encrypt::dynamic::Error) -> RecipherErrorFields { + let refused = RecipherErrorFields::engine(error).in_record(record); + if refused.reason() == Some("context_not_label") && !plain_segment(record) { + return RecipherErrorFields::from(Error::RecordName).in_record(record); + } + refused +} + +/// Returns whether the engine accepts `record` as the first segment of a +/// field path. The function asks the engine, by building a plan with a +/// field name that the engine accepts. +fn plain_segment(record: &str) -> bool { + field_path(record, "field") + .is_some_and(|context| FieldPlan::new("field", context, vec![Output::Ciphertext]).is_ok()) +} + +/// Returns a row with each value read as its field's kind, in the row's +/// order. +/// +/// # Errors +/// +/// Returns `recipher_js::not_a_row` for a row that is not an object. Returns +/// `recipher_js::field_type`, naming the field, for a value that is not of its +/// field's kind or does not fit it. +pub(crate) fn conform_row(plan: &RecordPlan, row: &ValueFrame) -> Outcome { + let not_a_row = || RecipherErrorFields::from(Error::NotARow).in_record(&plan.name); + let values = entries(row).ok_or_else(not_a_row)?; + let mut conformed: Vec<(String, ValueFrame)> = Vec::with_capacity(values.len()); + for (name, value) in values { + let kind = plan + .fields + .iter() + .find(|field| field.name == name) + .and_then(|field| field.kind); + let value = match kind { + // The engine checks a null against the field's null mode. + Some(kind) if value.kind().is_some() => read(kind, &value).map_err(|_| { + RecipherErrorFields::from(Error::FieldType { kind }) + .in_record(&plan.name) + .at_field(Some(&name)) + })?, + _ => value, + }; + conformed.push((name, value)); + } + let map = Map(conformed + .iter() + .map(|(name, value)| (name.as_str(), Entry::Value(value))) + .collect()); + ValueFrame::of(&map).map_err(|_| not_a_row()) +} + +/// Encrypts rows under a record's plan, in one key request for any number +/// of rows. A key request is one request to ZeroKMS, CipherStash's key +/// service, for data keys. Each row is a frame from [`conform_row`]. Each +/// result is a stored row. +/// +/// # Errors +/// +/// Returns the engine's refusal of a row that does not fit the plan. +pub(crate) async fn seal_rows( + keyset: &KeysetCipher<'_, K>, + plan: Arc, + rows: Vec, +) -> Outcome> +where + K: DataKeySource + IndexKeySource + Sync + 'static, +{ + let planned: Vec<_> = rows + .into_iter() + .map(|row| Planned::new(&plan.plan, row)) + .collect(); + let stored = planned + .encrypt_into::, K>(keyset) + .await + .map_err(|error| RecipherErrorFields::engine(&error).in_record(&plan.name))?; + stored + .into_iter() + .map(|row| stored_row(&plan, row)) + .collect() +} + +/// Decrypts stored rows under a record's plan. The function makes one key +/// request for each keyset the rows were encrypted under. A keyset is a +/// group of keys in ZeroKMS. Each data key is made under one keyset. +/// +/// Each stored row is a frame in the form [`seal_rows`] returns. Each +/// result is a row. +/// +/// # Errors +/// +/// Returns `recipher_js::not_a_stored_row`, naming the field, for a stored row +/// of another shape. Returns the engine's refusal of a stored row that does +/// not decrypt. +pub(crate) async fn open_rows<'c, K>( + cipher: impl Into>, + plan: Arc, + rows: Vec, +) -> Outcome> +where + K: DataKeySource + IndexKeySource + Sync + 'static, +{ + let mut trees = Vec::with_capacity(rows.len()); + for row in &rows { + trees.push(stored_tree(&plan, row)?); + } + let planned: Vec<_> = trees + .into_iter() + .map(|tree| Planned::new(&plan.plan, tree)) + .collect(); + Vec::::decrypt_from(planned, cipher) + .await + .map_err(|error| RecipherErrorFields::engine(&error).in_record(&plan.name)) +} + +/// Converts the stored row that the engine returned into the frame that the +/// SDK returns to JavaScript. +fn stored_row(plan: &RecordPlan, tree: StackCipherText) -> Outcome { + let CipherText::Map(entries) = tree else { + return Err(Error::EngineResult { + what: "a row is not a map of fields", + } + .into()); + }; + let mut fields: Vec<(&str, Entry<'_>)> = Vec::with_capacity(plan.fields.len()); + for field in &plan.fields { + let Some((_, outputs)) = entries.iter().find(|(name, _)| *name == field.name) else { + // A null stored as SQL `NULL` produces no entry. + fields.push((field.name.as_str(), Entry::Null)); + continue; + }; + let CipherText::Map(outputs) = outputs else { + return Err(Error::EngineResult { + what: "a field is not a map of outputs", + } + .into()); + }; + if field.passthrough { + let Some((_, CipherText::Passthrough(PassthroughFrame(frame)))) = outputs + .iter() + .find(|(key, _)| key == Output::Passthrough.key()) + else { + return Err(Error::EngineResult { + what: "a passthrough field has no passthrough", + } + .into()); + }; + fields.push((field.name.as_str(), Entry::Frame(frame))); + continue; + } + let mut stored: Vec<(&str, Entry<'_>)> = Vec::with_capacity(1 + field.indexes.len()); + for (key, node) in outputs { + match (Output::parse(key), node) { + (Some(Output::Ciphertext), CipherText::Single(leaf)) => { + let bytes = stack_encrypt::Ciphertext::from(leaf.clone()).to_bytes(); + stored.push((CIPHERTEXT, Entry::Bytes(bytes))); + } + (Some(Output::Term(index)), CipherText::Passthrough(PassthroughFrame(term))) => { + let name = index_name(&index).ok_or(Error::EngineResult { + what: "an index the SDK does not name", + })?; + stored.push((name, Entry::Frame(term))); + } + _ => { + return Err(Error::EngineResult { + what: "an output of an unexpected shape", + } + .into()) + } + } + } + fields.push((field.name.as_str(), Entry::Map(Map(stored)))); + } + ValueFrame::of(&Map(fields)).map_err(|_| { + Error::EngineResult { + what: "the stored row could not be written as a frame", + } + .into() + }) +} + +/// Converts a stored row that the SDK returned earlier into the engine's +/// stored record. +fn stored_tree(plan: &RecordPlan, row: &ValueFrame) -> Outcome { + let misfit = |field: Option<&str>, what: &'static str| { + RecipherErrorFields::from(Error::NotAStoredRow { what }) + .in_record(&plan.name) + .at_field(field) + }; + let stored = entries(row) + .ok_or_else(|| misfit(None, "a stored row is an object of the record's fields"))?; + let mut tree = Vec::with_capacity(stored.len()); + for (name, value) in stored { + let field = plan + .fields + .iter() + .find(|field| field.name == name) + .ok_or_else(|| misfit(Some(&name), "a field the record does not declare"))?; + if field.passthrough { + let node = CipherText::Passthrough(PassthroughFrame(value.risky_ref().to_vec())); + tree.push(( + name, + CipherText::Map(vec![(Output::Passthrough.key().to_owned(), node)]), + )); + continue; + } + if value.kind().is_none() { + // A null means the field is absent, as SQL `NULL` stores it. + continue; + } + let outputs = entries(&value).ok_or_else(|| { + misfit( + Some(&name), + "a sealed field is an object of its ciphertext and its terms", + ) + })?; + let mut nodes = Vec::with_capacity(outputs.len()); + for (key, output) in outputs { + let bytes = bytes_of(&output) + .ok_or_else(|| misfit(Some(&name), "an output that is not bytes"))?; + if key == CIPHERTEXT { + let ciphertext = + stack_encrypt::Ciphertext::from_bytes(&bytes).map_err(|error| { + RecipherErrorFields::engine(&error) + .in_record(&plan.name) + .at_field(Some(&name)) + })?; + nodes.push(( + Output::Ciphertext.key().to_owned(), + CipherText::Single(ciphertext.into()), + )); + continue; + } + let index = field + .indexes + .iter() + .find(|index| index_name(index) == Some(key.as_str())) + .ok_or_else(|| { + misfit(Some(&name), "a term of an index the field does not declare") + })?; + let term = vitaminc_aead::to_frame(bytes.as_slice()) + .map_err(|_| misfit(Some(&name), "a term that is not bytes"))?; + nodes.push(( + index.key().to_owned(), + CipherText::Passthrough(PassthroughFrame(term.risky_ref().to_vec())), + )); + } + tree.push((name, CipherText::Map(nodes))); + } + Ok(CipherText::Map(tree)) +} + +/// Returns the value of the field `name` in a one-field row. Returns a null +/// when the row has no such field. A null stored as SQL `NULL` gives a row +/// with no such field. +pub(crate) fn field_value(row: &ValueFrame, name: &str) -> Outcome { + let entries = entries(row).ok_or(Error::EngineResult { + what: "a one-field row is not a map of fields", + })?; + match entries.into_iter().find(|(key, _)| key == name) { + Some((_, value)) => Ok(value), + None => ValueFrame::of(&Null).map_err(|_| { + Error::EngineResult { + what: "a null could not be written", + } + .into() + }), + } +} + +/// A null. +struct Null; + +impl stack_encrypt::Encrypt for &Null { + fn visit(self, sink: S) -> Result { + sink.scalar(None, stack_encrypt::dynamic::plaintext::Physical::Null) + } +} + +/// Returns a one-field row: `{ name: value }`. +pub(crate) fn one_field_row(name: &str, value: &ValueFrame) -> Outcome { + ValueFrame::of(&Map(vec![(name, Entry::Value(value))])).map_err(|_| { + Error::EngineResult { + what: "a one-field row could not be written", + } + .into() + }) +} diff --git a/languages/typescript/packages/recipher-js/crate/src/record_tests.rs b/languages/typescript/packages/recipher-js/crate/src/record_tests.rs new file mode 100644 index 000000000..248587a95 --- /dev/null +++ b/languages/typescript/packages/recipher-js/crate/src/record_tests.rs @@ -0,0 +1,407 @@ +//! Tests of records through the crate against the engine. The tests cover +//! the plan built from a declaration, and rows encrypted to stored rows and +//! back. The tests also cover what the engine's typed Rust API reads from +//! stored rows. + +use std::borrow::Cow; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; + +use serde_json::json; +use stack_encrypt::dynamic::ValueFrame; +use stack_encrypt::kms::{ + DataKey, DataKeySource, DataKeyWithTag, DeterministicSource, Error, GenerateKeyPayload, + IdentifiedBy, IndexKey, IndexKeySource, KeySourceKind, OwnIdentity, RetrieveKeyPayload, + UnverifiedContext, +}; +use stack_encrypt::{AsProtectedRef, StackCipher}; +use uuid::Uuid; + +use crate::cipher::{open_rows_in, Confined, Engine}; +use crate::frames::{bytes_of, entries, Entry, Map}; +use crate::outcome::Outcome; +use crate::record::{conform_row, field_value, one_field_row, open_rows, seal_rows, RecordPlan}; + +const SEED: [u8; 32] = [3; 32]; + +fn plan(declaration: serde_json::Value) -> Outcome> { + let bytes = stack_encrypt::dynamic::frame::serde::to_vec(&declaration).unwrap(); + RecordPlan::of(&ValueFrame::from_bytes(bytes.as_protected_ref()).unwrap()) +} + +fn users() -> Arc { + plan(json!({ + "type": "record", + "name": "users", + "fields": { + "id": { "type": "passthrough" }, + "email": { "type": "sealed", "kind": { "name": "string" }, "index": ["equality"] }, + "name": { "type": "sealed", "kind": { "name": "string" }, "index": ["match"] }, + "age": { "type": "sealed", "kind": { "name": "int32" }, "index": ["equality"], "null": "sealed" }, + "notes": { "type": "sealed", "kind": { "name": "string" }, "null": "sql" }, + }, + })) + .unwrap() +} + +/// A row in the form JavaScript passes it, with an integer at its narrowest +/// width. +fn row(age: Option, notes: Option<&str>) -> ValueFrame { + let id = ValueFrame::of(7u64).unwrap(); + let email = ValueFrame::of("ada@example.com").unwrap(); + let name = ValueFrame::of("Ada Lovelace").unwrap(); + let age = age.map(|age| ValueFrame::of(age).unwrap()); + let notes = notes.map(|notes| ValueFrame::of(notes).unwrap()); + let frame = ValueFrame::of(&Map(vec![ + ("id", Entry::Value(&id)), + ("email", Entry::Value(&email)), + ("name", Entry::Value(&name)), + ("age", or_null(age.as_ref())), + ("notes", or_null(notes.as_ref())), + ])) + .unwrap(); + conform_row(&users(), &frame).unwrap() +} + +/// A value, or a null where there is none. +fn or_null(value: Option<&ValueFrame>) -> Entry<'_> { + value.map_or(Entry::Null, Entry::Value) +} + +async fn engine() -> StackCipher { + StackCipher::builder() + .kms(DeterministicSource::new(SEED)) + .init() + .await + .unwrap() +} + +/// The `ciphertext` bytes of the field `name` of a stored row. +fn ciphertext_of(stored: &ValueFrame, name: &str) -> Vec { + let field = field_value(stored, name).unwrap(); + let (_, ciphertext) = entries(&field) + .unwrap() + .into_iter() + .find(|(key, _)| key == "ciphertext") + .unwrap(); + bytes_of(&ciphertext).unwrap() +} + +fn keys(frame: &ValueFrame) -> Vec { + entries(frame) + .unwrap() + .into_iter() + .map(|(key, _)| key) + .collect() +} + +#[tokio::test] +async fn a_row_round_trips_and_its_absent_field_opens_as_null() { + let cipher = engine().await; + let stored = seal_rows(&cipher.default_keyset(), users(), vec![row(Some(36), None)]) + .await + .unwrap(); + let opened = open_rows(&cipher, users(), stored).await.unwrap().remove(0); + assert_eq!( + field_value(&opened, "age").unwrap(), + ValueFrame::of(36i32).unwrap(), + "the integer opens at the field's width" + ); + assert_eq!(field_value(&opened, "notes").unwrap().kind(), None); + assert_eq!( + field_value(&opened, "id").unwrap(), + ValueFrame::of(7u64).unwrap() + ); +} + +#[tokio::test] +async fn the_stored_row_has_a_ciphertext_and_the_declared_terms() { + let cipher = engine().await; + let stored = seal_rows( + &cipher.default_keyset(), + users(), + vec![row(Some(36), Some("hi"))], + ) + .await + .unwrap() + .remove(0); + let email = field_value(&stored, "email").unwrap(); + assert_eq!(keys(&email), ["ciphertext", "equality"]); + let name = field_value(&stored, "name").unwrap(); + assert_eq!(keys(&name), ["ciphertext", "match"]); + let notes = field_value(&stored, "notes").unwrap(); + assert_eq!(keys(¬es), ["ciphertext"]); +} + +#[tokio::test] +async fn a_fields_ciphertext_is_sealed_under_its_field_path() { + let cipher = engine().await; + let stored = seal_rows(&cipher.default_keyset(), users(), vec![row(Some(36), None)]) + .await + .unwrap() + .remove(0); + let bytes = ciphertext_of(&stored, "email"); + let keyset = cipher.default_keyset(); + let email: String = keyset + .decrypt_with_context( + stack_encrypt::Ciphertext::from_bytes(&bytes).unwrap(), + ("users", "email"), + ) + .await + .unwrap(); + assert_eq!(email, "ada@example.com"); + let elsewhere: Result = keyset + .decrypt_with_context( + stack_encrypt::Ciphertext::from_bytes(&bytes).unwrap(), + ("users", "name"), + ) + .await; + assert!(elsewhere.is_err()); +} + +#[tokio::test] +async fn one_field_opens_alone_and_a_field_alone_opens_through_the_engine() { + let cipher = engine().await; + let email = users().field("email").unwrap(); + + // A field of a whole row decrypts through the field's own plan. + let stored = seal_rows(&cipher.default_keyset(), users(), vec![row(Some(36), None)]) + .await + .unwrap() + .remove(0); + let alone = one_field_row("email", &field_value(&stored, "email").unwrap()).unwrap(); + let opened = open_rows(&cipher, Arc::clone(&email), vec![alone]) + .await + .unwrap() + .remove(0); + assert_eq!( + field_value(&opened, "email").unwrap(), + ValueFrame::of("ada@example.com").unwrap() + ); + + // A field encrypted on its own decrypts through the engine's typed API, + // under its field path. + let value = ValueFrame::of("grace@example.com").unwrap(); + let row = conform_row(&email, &one_field_row("email", &value).unwrap()).unwrap(); + let sealed = seal_rows(&cipher.default_keyset(), email, vec![row]) + .await + .unwrap() + .remove(0); + let opened: String = cipher + .default_keyset() + .decrypt_with_context( + stack_encrypt::Ciphertext::from_bytes(&ciphertext_of(&sealed, "email")).unwrap(), + ("users", "email"), + ) + .await + .unwrap(); + assert_eq!(opened, "grace@example.com"); +} + +#[test] +fn an_integer_is_read_at_its_fields_width_and_refused_outside_it() { + let small = plan(json!({ + "type": "record", + "name": "t", + "fields": { "n": { "type": "sealed", "kind": { "name": "int8" } } }, + })) + .unwrap(); + let fits = ValueFrame::of(&Map(vec![( + "n", + Entry::Value(&ValueFrame::of(5u64).unwrap()), + )])) + .unwrap(); + let read = conform_row(&small, &fits).unwrap(); + assert_eq!( + field_value(&read, "n").unwrap(), + ValueFrame::of(5i8).unwrap() + ); + let too_big = ValueFrame::of(&Map(vec![( + "n", + Entry::Value(&ValueFrame::of(300i16).unwrap()), + )])) + .unwrap(); + let refused = conform_row(&small, &too_big).unwrap_err(); + assert_eq!(refused.code, "recipher_js::field_type"); + assert_eq!(refused.field.as_deref(), Some("n")); + assert_eq!(refused.record.as_deref(), Some("t")); +} + +#[test] +fn the_engine_refuses_a_declaration_naming_the_record_and_the_field() { + let refused = plan(json!({ + "type": "record", + "name": "t", + "fields": { "n": { "type": "sealed", "kind": { "name": "int32" }, "index": ["match"] } }, + })) + .unwrap_err(); + assert_eq!(refused.code, "stack_encrypt::dynamic_plan"); + assert_eq!(refused.field.as_deref(), Some("n")); + assert_eq!(refused.record.as_deref(), Some("t")); + + let unknown = plan(json!({ + "type": "record", + "name": "t", + "fields": { "n": { "type": "sealed", "kind": { "name": "int31" } } }, + })) + .unwrap_err(); + assert_eq!(unknown.code, "recipher_js::kind"); +} + +#[test] +fn a_json_field_needs_the_eql_extension() { + let refused = plan(json!({ + "type": "record", + "name": "t", + "fields": { "doc": { "type": "sealed", "kind": { "name": "json" } } }, + })) + .unwrap_err(); + assert_eq!(refused.code, "stack_encrypt::dynamic_plan"); + assert_eq!(refused.reason(), Some("json_needs_target")); +} + +#[test] +fn a_bad_record_name_is_the_records_fault_and_a_bad_field_name_the_fields() { + let bad_record = plan(json!({ + "type": "record", + "name": "a/b", + "fields": { "x": { "type": "sealed", "kind": { "name": "string" } } }, + })) + .unwrap_err(); + assert_eq!(bad_record.code, "recipher_js::record_name"); + assert_eq!(bad_record.record.as_deref(), Some("a/b")); + assert_eq!(bad_record.field, None); + + let bad_field = plan(json!({ + "type": "record", + "name": "users", + "fields": { "a/b": { "type": "sealed", "kind": { "name": "string" } } }, + })) + .unwrap_err(); + assert_eq!(bad_field.reason(), Some("context_not_label")); + assert_eq!(bad_field.field.as_deref(), Some("a/b")); + assert_eq!(bad_field.record.as_deref(), Some("users")); +} + +/// 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 + } +} + +#[tokio::test] +async fn many_rows_and_many_fields_alone_are_one_key_request_each_way() { + let cipher = StackCipher::builder() + .kms(Counting { + inner: DeterministicSource::new(SEED), + generates: AtomicUsize::new(0), + retrieves: AtomicUsize::new(0), + }) + .init() + .await + .unwrap(); + let rows = vec![row(Some(1), None), row(Some(2), None), row(None, Some("x"))]; + let stored = seal_rows(&cipher.default_keyset(), users(), rows) + .await + .unwrap(); + assert_eq!(cipher.kms().generates.load(Ordering::SeqCst), 1); + let _ = open_rows(&cipher, users(), stored).await.unwrap(); + assert_eq!(cipher.kms().retrieves.load(Ordering::SeqCst), 1); + + // Three values of one field, as `encryptField` encrypts an array of + // them. + let email = users().field("email").unwrap(); + let rows = ["a", "b", "c"] + .into_iter() + .map(|text| { + let value = ValueFrame::of(text).unwrap(); + conform_row(&email, &one_field_row("email", &value).unwrap()).unwrap() + }) + .collect(); + let stored = seal_rows(&cipher.default_keyset(), Arc::clone(&email), rows) + .await + .unwrap(); + assert_eq!(cipher.kms().generates.load(Ordering::SeqCst), 2); + let _ = open_rows(&cipher, email, stored).await.unwrap(); + assert_eq!(cipher.kms().retrieves.load(Ordering::SeqCst), 2); +} + +#[test] +fn a_plan_is_built_once_for_a_declaration() { + assert!(Arc::ptr_eq(&users(), &users())); + let plan = users(); + assert!(Arc::ptr_eq( + &plan.field("email").unwrap(), + &plan.field("email").unwrap() + )); +} + +/// `keyset.decrypt` of a stored row is confined to its keyset and +/// `cipher.decrypt` is not, as for a ciphertext. The two differ only in the +/// `Confined` they pass to `open_rows_in`. +#[tokio::test] +async fn a_keyset_refuses_another_keysets_row_and_the_cipher_opens_it() { + let cipher = engine().await; + let other = cipher.keyset(IdentifiedBy::Name("another-keyset".to_owned().into())); + let refused_row = seal_rows(&other, users(), vec![row(Some(36), None)]) + .await + .unwrap(); + let stored = seal_rows(&other, users(), vec![row(Some(36), None)]) + .await + .unwrap(); + let engine = Engine::Testing(Box::new(cipher)); + + let refused = open_rows_in(&engine, users(), refused_row, Confined::ToDefault) + .await + .unwrap_err(); + assert_eq!(refused.code, "stack_encrypt::foreign_keyset"); + + let opened = open_rows_in(&engine, users(), stored, Confined::No) + .await + .unwrap() + .remove(0); + assert_eq!( + field_value(&opened, "email").unwrap(), + ValueFrame::of("ada@example.com").unwrap() + ); +} diff --git a/languages/typescript/packages/recipher-js/native-header.d.ts b/languages/typescript/packages/recipher-js/native-header.d.ts index f46b05b92..8a2e0e5c8 100644 --- a/languages/typescript/packages/recipher-js/native-header.d.ts +++ b/languages/typescript/packages/recipher-js/native-header.d.ts @@ -6,6 +6,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 { + CipherOptions, + Plaintext, + RecordDeclaration, + SealedFieldName, + Stored, +} from './src/record' 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 134f254a6..a46a81cc6 100644 --- a/languages/typescript/packages/recipher-js/native.d.ts +++ b/languages/typescript/packages/recipher-js/native.d.ts @@ -6,6 +6,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 { + CipherOptions, + Plaintext, + RecordDeclaration, + SealedFieldName, + Stored, +} from './src/record' import type { Err, Ok, Result } from './src/result' import type { JsonMarker, @@ -57,9 +64,13 @@ export declare class Cipher { * - the credentials are refused; * - ZeroKMS refuses to load the default keyset. * + * `options.records` lists record declarations to check now, before the + * engine looks for credentials. If the engine refuses a declaration, + * the promise resolves to an `Err` that names the record. + * * The promise does not reject. */ - static create(): Promise> + static create(options?: CipherOptions): Promise> /** * Returns the client's default keyset: the keyset that a ZeroKMS * administrator set for this client. Encrypting needs a keyset. @@ -71,7 +82,13 @@ export declare class Cipher { * * 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. + * ciphertexts were made under. A key request is one request to ZeroKMS + * for data keys. + * + * With a record declaration as the first argument, decrypts a stored + * row of that record, or an array of stored rows. A stored row is what + * `keyset.encrypt` returns for a row. Node's `inspect` shows a + * decrypted row's field names and hides their values. * * Resolves to an `Err` with the code `recipher_js::not_a_ciphertext` * when the argument, or an element of the array, is not a @@ -79,6 +96,15 @@ export declare class Cipher { */ decrypt(ciphertext: Ciphertext): Promise> decrypt(ciphertexts: readonly Ciphertext[]): Promise> + decrypt(record: R, row: Stored): Promise, RecipherError>> + decrypt(record: R, rows: readonly Stored[]): Promise[], RecipherError>> + /** + * Decrypts one field of a record's stored row, as `encryptField` or + * `encrypt` stored it. An array of stored fields decrypts in one key + * request. The promise does not reject. + */ + decryptField>(record: R, field: F, stored: NoInfer[F]>): Promise[F], RecipherError>> + decryptField>(record: R, field: F, stored: readonly NoInfer[F]>[]): Promise[F][], RecipherError>> /** Returns the type's name. */ toString(): string } @@ -169,18 +195,48 @@ 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`. + * + * With a record declaration as the first argument, encrypts a row of + * that record, or an array of rows in one key request. Each field is + * encrypted under its field path: the record's name, then the field's + * name. For each encrypted field, the stored row has the field's + * ciphertext and its index terms. + * * The promise does not reject. */ encrypt(value: V): Promise>, RecipherError>> encrypt(values: readonly V[]): Promise>[], RecipherError>> + encrypt(record: R, row: Plaintext): Promise, RecipherError>> + encrypt(record: R, rows: readonly Plaintext[]): Promise[], RecipherError>> /** * 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. + * `stack_encrypt::foreign_keyset`, before any key is requested. + * + * With a record declaration as the first argument, decrypts a stored + * row of that record, or an array of stored rows. + * + * The promise does not reject. */ decrypt(ciphertext: Ciphertext): Promise> decrypt(ciphertexts: readonly Ciphertext[]): Promise> + decrypt(record: R, row: Stored): Promise, RecipherError>> + decrypt(record: R, rows: readonly Stored[]): Promise[], RecipherError>> + /** + * Encrypts one field of a record, to update that field alone. The + * result is the field's stored form, the same form as in a whole stored + * row. An array of values returns an array of stored fields, in one key + * request. The promise does not reject. + */ + encryptField>(record: R, field: F, value: NoInfer[F]>): Promise[F], RecipherError>> + encryptField>(record: R, field: F, values: readonly NoInfer[F]>[]): Promise[F][], RecipherError>> + /** + * Decrypts one field of a record's stored row made under this keyset. + * An array of stored fields decrypts in one key request. The promise + * does not reject. + */ + decryptField>(record: R, field: F, stored: NoInfer[F]>): Promise[F], RecipherError>> + decryptField>(record: R, field: F, stored: readonly NoInfer[F]>[]): Promise[F][], RecipherError>> /** Returns the type's name. */ toString(): string } @@ -192,6 +248,14 @@ export declare class Keyset { */ export declare function bindingInterface(): number +/** + * Checks record declarations with the engine, without credentials and + * without any request. Use it in a test or a continuous integration (CI) + * step. The `Err` is the engine's first refusal. The error names the + * record and, where there is one, the field. Does not throw. + */ +export declare function checkDeclarations(declarations: readonly RecordDeclaration[]): Result + /** * Makes a cipher over the engine's deterministic test keys, from a 32-byte * seed. Every key is derived from the seed and the value's context. So a @@ -275,8 +339,9 @@ export interface RecipherErrorFields { severity: Severity /** * The error's structured fields, keyed by `snake_case` name. For - * example, a ZeroKMS failure has `request_kind`. The map is empty when - * the error has no fields. + * example, a refused plan has `field` and `reason`, and a ZeroKMS + * failure has `request_kind`. A plan is the engine's rules for + * encrypting a record. The map is empty when the error has no fields. */ fields: Record /** The errors that caused this one, outermost first. */ diff --git a/languages/typescript/packages/recipher-js/src/binding.ts b/languages/typescript/packages/recipher-js/src/binding.ts index d885b4f17..3e0994b3e 100644 --- a/languages/typescript/packages/recipher-js/src/binding.ts +++ b/languages/typescript/packages/recipher-js/src/binding.ts @@ -45,6 +45,7 @@ const EXPORTS = [ 'Ciphertext', 'Json', 'bindingInterface', + 'checkDeclarations', 'createTesting', 'installResult', 'json', diff --git a/languages/typescript/packages/recipher-js/src/cipher.ts b/languages/typescript/packages/recipher-js/src/cipher.ts index 559fe9449..556d9d3ec 100644 --- a/languages/typescript/packages/recipher-js/src/cipher.ts +++ b/languages/typescript/packages/recipher-js/src/cipher.ts @@ -18,6 +18,8 @@ import type { RecipherError } from './error' import { err, type Result } from './result' import type { OpenedScalar } from './value-types' +export type { CipherOptions } from './record' + /** * One encrypted value: opaque bytes, encrypted with a data key of its own. * @@ -57,6 +59,7 @@ export interface Classes { Keyset: KeysetClass Ciphertext: CiphertextClass createTesting: Binding['createTesting'] + checkDeclarations: Binding['checkDeclarations'] } /** @@ -77,6 +80,7 @@ function native(loaded: Binding): Classes { Keyset: typed(loaded.Keyset), Ciphertext: typed(loaded.Ciphertext), createTesting: loaded.createTesting, + checkDeclarations: loaded.checkDeclarations, } } @@ -108,6 +112,7 @@ function missing(error: RecipherError): Classes { }, ), createTesting: () => Promise.resolve(err(error)), + checkDeclarations: () => err(error), } } @@ -128,3 +133,13 @@ export const Cipher: CipherClass = classes.Cipher export const Keyset: KeysetClass = classes.Keyset /** The `Ciphertext` class: the native addon's class. */ export const Ciphertext: CiphertextClass = classes.Ciphertext + +/** + * Check record declarations with the engine, with no credentials and no + * network request. Use it in a test or a continuous integration (CI) step. + * + * The `Err` is the first refusal. The error names the record and, where + * there is one, the field. + */ +export const checkDeclarations: Binding['checkDeclarations'] = + classes.checkDeclarations diff --git a/languages/typescript/packages/recipher-js/src/error.ts b/languages/typescript/packages/recipher-js/src/error.ts index 4ba76d069..a05087401 100644 --- a/languages/typescript/packages/recipher-js/src/error.ts +++ b/languages/typescript/packages/recipher-js/src/error.ts @@ -29,8 +29,9 @@ export type { ErrorCause, RecipherErrorFields, Severity } * - `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. + * Examples are a refused declaration's `reason` and 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. diff --git a/languages/typescript/packages/recipher-js/src/index.ts b/languages/typescript/packages/recipher-js/src/index.ts index 6ce14d743..1c6b28c7e 100644 --- a/languages/typescript/packages/recipher-js/src/index.ts +++ b/languages/typescript/packages/recipher-js/src/index.ts @@ -27,8 +27,10 @@ export { Cipher, type CipherClass, + type CipherOptions, Ciphertext, type CiphertextClass, + checkDeclarations, Keyset, type KeysetClass, } from './cipher' @@ -39,6 +41,22 @@ export { type Severity, } from './error' export { type Kind, kinds, type ValueOf } from './kinds' +export { + encrypt, + type Field, + type Index, + type NullMode, + type PassthroughField, + type Plaintext, + passthrough, + type RecordDeclaration, + record, + type SealedField, + type SealedFieldName, + type SealedOptions, + type Stored, + type StoredField, +} from './record' export { Err, err, Ok, ok, type Result } from './result' export { type Json, diff --git a/languages/typescript/packages/recipher-js/src/record.ts b/languages/typescript/packages/recipher-js/src/record.ts new file mode 100644 index 000000000..4e10d685f --- /dev/null +++ b/languages/typescript/packages/recipher-js/src/record.ts @@ -0,0 +1,214 @@ +/** + * Records: declarations of a row's fields. Each field is encrypted, + * encrypted with indexes, or passed through unencrypted. + * + * ```ts + * import { encrypt, kinds, passthrough, record } from '@cipherstash/recipher' + * + * export const user = record('users', { + * id: passthrough(), + * email: encrypt(kinds.string, { index: ['equality'] }), + * name: encrypt(kinds.string, { index: ['match'] }), + * age: encrypt(kinds.int32, { index: ['equality'], null: 'sealed' }), + * notes: encrypt(kinds.string, { null: 'sql' }), + * }) + * ``` + * + * A declaration is a plain, frozen object: `{ type: 'record', name, fields }`, + * with a declaration for each field. The native addon reads the declaration + * and builds the engine's plan from it, once. The engine checks the + * declaration at that time. That happens when a cipher first uses the + * declaration, or when `Cipher.create({ records })` or + * `checkDeclarations(..)` is called. + * + * TypeScript checks a row against the types below. + * + * This module never loads the native addon. The addon's generated + * declarations (`native.d.ts`) name its types, so a module here that loaded + * the addon would make the declarations import themselves. + */ +import type { Kind, ValueOf } from './kinds' + +/** + * An index that an encrypted field stores beside its ciphertext. An index + * stores index terms: bytes that a search can compare without decrypting the + * field. + */ +export type Index = 'equality' | 'match' | 'ore' | 'ope' + +/** + * How a field stores a missing value. + * + * - `sealed`: the null is encrypted like a value, to the same length as a + * value. The stored row does not show which rows have no value. Only for + * a field of fixed width whose only index is `equality`. The fixed-width + * fields are a boolean, a number, a date, a timestamp, and a decimal. + * - `sql`: the stored row has `null` for the field, as SQL `NULL` does. + */ +export type NullMode = 'sealed' | 'sql' + +/** + * A field that is encrypted, and indexed if it names indexes. The code calls + * an encrypted field a sealed field. + */ +export interface SealedField< + K extends Kind = Kind, + I extends readonly Index[] = readonly Index[], + N extends NullMode | undefined = NullMode | undefined, +> { + readonly type: 'sealed' + readonly kind: K + readonly index: I + readonly null?: N +} + +/** + * A field stored as it is: **not encrypted and not authenticated.** Anyone + * with the stored row can read the field, change it, or remove it. The + * encrypted fields still decrypt after that. Use a passthrough field only + * for values that are not secret. Treat the value read back as untrusted. + */ +export interface PassthroughField { + readonly type: 'passthrough' + /** Carries `T` for the type checker. The property never exists at run time. */ + readonly __value?: T +} + +/** A field of a record. */ +export type Field = SealedField | PassthroughField + +/** Options for an encrypted field. */ +export interface SealedOptions< + I extends readonly Index[], + N extends NullMode | undefined, +> { + /** The indexes the field stores. */ + index?: I + /** + * How the field stores a null. Without this option, every row needs a + * value for the field. + */ + null?: N +} + +/** An encrypted field of the kind `kind`. */ +export function encrypt< + K extends Kind, + const I extends readonly Index[] = readonly [], + N extends NullMode | undefined = undefined, +>( + kind: K, + options: SealedOptions = {}, + // `NoInfer`: TypeScript reads what a field declares from `options` only. + // TypeScript never takes it from the type that the caller's code expects. + // That type names every index and every null mode. +): SealedField, NoInfer> { + const index = Object.freeze([...(options.index ?? [])]) + const field = + options.null === undefined + ? { type: 'sealed', kind, index } + : { type: 'sealed', kind, index, null: options.null } + // biome-ignore lint/plugin: an empty array is the default `I`, `readonly []`. + return Object.freeze(field) as unknown as SealedField +} + +/** A field passed through as it is. See `PassthroughField`. */ +export function passthrough(): PassthroughField { + return Object.freeze({ type: 'passthrough' }) +} + +/** A record's declaration: a plain, frozen object. */ +export interface RecordDeclaration< + Name extends string = string, + F extends { readonly [field: string]: Field } = { + readonly [field: string]: Field + }, +> { + /** + * Marks the object as a declaration. Every copy of the package reads this + * marker, including the ESM build and the CommonJS build. + */ + readonly type: 'record' + /** The record's name: the first part of each field's context. */ + readonly name: Name + /** The fields, each with its declaration. */ + readonly fields: F +} + +/** + * A record named `name`, with `fields`. Each field's context is its field + * path: the record's name, then the field's name. A context is data that a + * ciphertext is bound to. The ciphertext decrypts only under the same + * context. + */ +export function record< + const Name extends string, + const F extends { readonly [field: string]: Field }, +>(name: Name, fields: F): RecordDeclaration { + return Object.freeze({ + type: 'record', + name, + fields: Object.freeze({ ...fields }), + }) +} + +/** The plaintext row of a record. A field that takes a null can be `null`. */ +export type Plaintext = + R extends RecordDeclaration + ? { + -readonly [P in keyof F]: F[P] extends SealedField< + infer K, + readonly Index[], + infer N + > + ? ValueOf | (N extends NullMode ? null : never) + : F[P] extends PassthroughField + ? T + : never + } + : never + +/** An encrypted field as it is stored: its ciphertext and its index terms. */ +export type StoredField = { + readonly ciphertext: Uint8Array +} & { readonly [X in I[number]]: Uint8Array } + +/** + * The stored row of a record. Each encrypted field has its ciphertext and + * its index terms, each as opaque bytes. Each passthrough field has its + * value. A field that stores a null as SQL `NULL` is `null` when its value + * is missing. + */ +export type Stored = + R extends RecordDeclaration + ? { + readonly [P in keyof F]: F[P] extends SealedField< + Kind, + infer I, + infer N + > + ? StoredField | (N extends 'sql' ? null : never) + : F[P] extends PassthroughField + ? T + : never + } + : never + +/** The names of a record's encrypted fields. */ +export type SealedFieldName = + R extends RecordDeclaration + ? { + [P in keyof F]: F[P] extends SealedField ? P : never + }[keyof F] & + string + : never + +/** Options for `Cipher.create`. */ +export interface CipherOptions { + /** + * Records to check when the cipher is created, before any credentials are + * looked for. A declaration that the engine refuses then gives an `Err` + * here, not at its first use. + */ + records?: readonly RecordDeclaration[] +} diff --git a/languages/typescript/packages/recipher-js/type-tests/records.ts b/languages/typescript/packages/recipher-js/type-tests/records.ts new file mode 100644 index 000000000..536a4cf67 --- /dev/null +++ b/languages/typescript/packages/recipher-js/type-tests/records.ts @@ -0,0 +1,143 @@ +// 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, + Plaintext, + RecipherError, + Result, + Stored, + VcDate, + VcDecimal, + VcTimestamp, +} from '../src/index' +import { encrypt, kinds, passthrough, record } from '../src/index' + +type Exact = [A] extends [B] ? ([B] extends [A] ? true : false) : false +function check<_ extends true>(): void {} + +const user = record('users', { + id: passthrough(), + email: encrypt(kinds.string, { index: ['equality'] }), + name: encrypt(kinds.string, { index: ['match'] }), + age: encrypt(kinds.int32, { index: ['equality', 'ore'] }), + notes: encrypt(kinds.string), +}) + +// The plaintext row: an integer field is a bigint at every width. +check< + Exact< + Plaintext, + { id: bigint; email: string; name: string; age: bigint; notes: string } + > +>() + +// A field that takes a null may be null; a sealed null is stored like a +// value, a SQL null is a null in the stored row. +const nullable = record('n', { + sealed: encrypt(kinds.int64, { index: ['equality'], null: 'sealed' }), + sql: encrypt(kinds.string, { null: 'sql' }), +}) +check< + Exact< + Plaintext, + { sealed: bigint | null; sql: string | null } + > +>() +declare const storedNullable: Stored +check>() +// @ts-expect-error: a SQL null field may be null in the stored row. +void storedNullable.sql.ciphertext + +// The stored row: a ciphertext and the declared terms, and nothing else. +declare const stored: Stored +check>() +check>() +check>() +check>() +// @ts-expect-error: notes declares no index, so it stores no equality term. +void stored.notes.equality +// @ts-expect-error: name stores a match term, not an equality term. +void stored.name.equality + +// Each kind's type. +const all = record('all', { + flag: encrypt(kinds.boolean), + real: encrypt(kinds.float32), + price: encrypt(kinds.decimal), + day: encrypt(kinds.date), + at: encrypt(kinds.timestamp), + blob: encrypt(kinds.bytes), + small: encrypt(kinds.uint8), +}) +check< + Exact< + Plaintext, + { + flag: boolean + real: number + price: VcDecimal + day: VcDate + at: Date | VcTimestamp + blob: Uint8Array + small: bigint + } + > +>() + +declare const keyset: Keyset +declare const cipher: Cipher +const row: Plaintext = { + id: 1n, + email: 'a', + name: 'b', + age: 3n, + notes: 'c', +} + +// encrypt and decrypt carry the record's types, one row or many. +const one = await keyset.encrypt(user, row) +check, RecipherError>>>() +const many = await keyset.encrypt(user, [row, row]) +check[], RecipherError>>>() +const opened = await cipher.decrypt(user, stored) +check, RecipherError>>>() + +// A row of another shape does not compile. +// @ts-expect-error: age is a bigint, not a number. +void keyset.encrypt(user, { ...row, age: 3 }) +// @ts-expect-error: email is missing. +void keyset.encrypt(user, { id: 1n, name: 'b', age: 3n, notes: 'c' }) +// @ts-expect-error: a field the record does not declare. +void keyset.encrypt(user, { ...row, extra: 1 }) +// @ts-expect-error: email takes no null. +void keyset.encrypt(user, { ...row, email: null }) + +// One field: its stored form and its value. +const email = await keyset.encryptField(user, 'email', 'x') +check< + Exact['email'], RecipherError>> +>() +const age = await cipher.decryptField(user, 'age', stored.age) +check>>() +// @ts-expect-error: a field the record does not declare. +void keyset.encryptField(user, 'missing', 'x') +// @ts-expect-error: id is passed through, not encrypted. +void keyset.encryptField(user, 'id', 1n) +// @ts-expect-error: the value is the field's type. +void keyset.encryptField(user, 'age', 'x') +// @ts-expect-error: the stored form is the field's own. +void cipher.decryptField(user, 'email', stored.name) + +// One field, many values: an array in is an array out. +const emails = await keyset.encryptField(user, 'email', ['x', 'y']) +check< + Exact['email'][], RecipherError>> +>() +const ages = await cipher.decryptField(user, 'age', [stored.age, stored.age]) +check>>() + +// A declaration is plain data, read by any library. +check>() +check>() +check>() From 7c0d0f1592bc1c0d0734be9d95c299cad0a8ba44 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Wed, 25 Nov 2026 23:47:23 +1100 Subject: [PATCH 2/7] fix(recipher-js): name Json and Value in a wrong argument's type error Value was Scalar | JsonMarker in src/value-types.ts, so passing a plain object to encrypt gave an error that named JsonMarker, a brand the package never exports, rather than the Json a caller should reach for. Value is now declared in native-header.d.ts as Scalar | Json, beside the generated Json class, which the header can name without an import, and src/values.ts re-exports it. The marker stays the brand, so a plain object is still not a Json or a Value, and value-types.ts still imports nothing, so the declarations do not import themselves. A type test pins both: the @ts-expect-error lines in type-tests/values.ts keep it as strict, and a unit test compiles a snippet with the TypeScript compiler and checks the messages name Value and Json and never JsonMarker. --- .../__tests__/unit/type-messages.test.ts | 57 +++++++++++++++++++ .../packages/recipher-js/native-header.d.ts | 9 ++- .../packages/recipher-js/native.d.ts | 9 ++- .../packages/recipher-js/src/value-types.ts | 3 - .../packages/recipher-js/src/values.ts | 4 +- .../packages/recipher-js/type-tests/values.ts | 12 ++++ 6 files changed, 88 insertions(+), 6 deletions(-) create mode 100644 languages/typescript/packages/recipher-js/__tests__/unit/type-messages.test.ts diff --git a/languages/typescript/packages/recipher-js/__tests__/unit/type-messages.test.ts b/languages/typescript/packages/recipher-js/__tests__/unit/type-messages.test.ts new file mode 100644 index 000000000..73e2a59d6 --- /dev/null +++ b/languages/typescript/packages/recipher-js/__tests__/unit/type-messages.test.ts @@ -0,0 +1,57 @@ +// The type errors a caller sees. A wrong argument to `encrypt` must name the +// public types, `Value` and `Json`, and never the marker that brands a +// `Json`. `type-tests/` checks that the code does not compile; this suite +// compiles a snippet with the TypeScript compiler and reads the message. +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import ts from 'typescript' +import { afterAll, describe, expect, it } from 'vitest' + +const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..') +const scratch = mkdtempSync(join(tmpdir(), 'recipher-type-messages-')) +afterAll(() => rmSync(scratch, { recursive: true, force: true })) + +/** Compiles `source` against the package, and returns its error messages. */ +function messages(source: string): string[] { + const config = ts.getParsedCommandLineOfConfigFile( + join(root, 'tsconfig.json'), + {}, + { ...ts.sys, onUnRecoverableConfigFileDiagnostic: () => {} }, + ) + if (config === undefined) { + throw new Error('tsconfig.json did not parse') + } + const file = join(scratch, 'snippet.ts') + writeFileSync( + file, + `import type { Json, Keyset, Value } from ${JSON.stringify(join(root, 'src', 'index.ts'))}\n${source}`, + ) + const program = ts.createProgram([file], config.options) + return ts + .getPreEmitDiagnostics(program, program.getSourceFile(file)) + .map((diagnostic) => + ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'), + ) +} + +describe('a value that is not a Value', () => { + it('names Value and Json, not the marker, when passed to encrypt', () => { + const found = messages(` +declare const keyset: Keyset +const document = { a: 1 } +void keyset.encrypt(document) +void keyset.encrypt({ a: 1 }) +const json: Json = document +const value: Value = document +void json +void value +`) + expect(found).toHaveLength(4) + const text = found.join('\n') + expect(text).toContain("parameter of type 'Value'") + expect(text).toContain("required in type 'Json'") + expect(text).not.toContain('JsonMarker') + }) +}) diff --git a/languages/typescript/packages/recipher-js/native-header.d.ts b/languages/typescript/packages/recipher-js/native-header.d.ts index 8a2e0e5c8..bd81e1dd8 100644 --- a/languages/typescript/packages/recipher-js/native-header.d.ts +++ b/languages/typescript/packages/recipher-js/native-header.d.ts @@ -19,7 +19,7 @@ import type { JsonValue, Opened, OpenedScalar, - Value, + Scalar, } from './src/value-types' // biome-ignore-end lint/correctness/noUnusedImports: the generated signatures after this header use these imports. @@ -39,3 +39,10 @@ export interface Ciphertext { /** The marker stops any other object type-checking as a `Json`. */ export interface Json extends JsonMarker {} + +/** + * A value that `encrypt` takes: one scalar, or a `Json` document from + * `json(..)`. It is declared here, beside the `Json` class, so a type error + * names `Json` and `Value`. + */ +export type Value = Scalar | Json diff --git a/languages/typescript/packages/recipher-js/native.d.ts b/languages/typescript/packages/recipher-js/native.d.ts index a46a81cc6..169d2d7fa 100644 --- a/languages/typescript/packages/recipher-js/native.d.ts +++ b/languages/typescript/packages/recipher-js/native.d.ts @@ -19,7 +19,7 @@ import type { JsonValue, Opened, OpenedScalar, - Value, + Scalar, } from './src/value-types' // biome-ignore-end lint/correctness/noUnusedImports: the generated signatures after this header use these imports. @@ -40,6 +40,13 @@ export interface Ciphertext { /** The marker stops any other object type-checking as a `Json`. */ export interface Json extends JsonMarker {} +/** + * A value that `encrypt` takes: one scalar, or a `Json` document from + * `json(..)`. It is declared here, beside the `Json` class, so a type error + * names `Json` and `Value`. + */ +export type Value = Scalar | Json + /** * A cipher: the engine, and the keysets it can use. A keyset is a group * of keys in ZeroKMS, CipherStash's key service. diff --git a/languages/typescript/packages/recipher-js/src/value-types.ts b/languages/typescript/packages/recipher-js/src/value-types.ts index 3bdcae4d3..77cc09f74 100644 --- a/languages/typescript/packages/recipher-js/src/value-types.ts +++ b/languages/typescript/packages/recipher-js/src/value-types.ts @@ -95,9 +95,6 @@ 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 diff --git a/languages/typescript/packages/recipher-js/src/values.ts b/languages/typescript/packages/recipher-js/src/values.ts index 10f2f64ca..0143cbaa2 100644 --- a/languages/typescript/packages/recipher-js/src/values.ts +++ b/languages/typescript/packages/recipher-js/src/values.ts @@ -42,9 +42,11 @@ export type { OpenedJson, OpenedScalar, Scalar, - Value, } from './value-types' +/** A value that `encrypt` takes: one scalar, or a `Json` document. */ +export type Value = Native.Value + /** 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. */ diff --git a/languages/typescript/packages/recipher-js/type-tests/values.ts b/languages/typescript/packages/recipher-js/type-tests/values.ts index 0973100ab..cfeb57813 100644 --- a/languages/typescript/packages/recipher-js/type-tests/values.ts +++ b/languages/typescript/packages/recipher-js/type-tests/values.ts @@ -2,11 +2,13 @@ // runs it. Each `@ts-expect-error` is a line that must not compile. import type { Cipher, + Json, Keyset, OpenedJson, OpenedScalar, RecipherError, Result, + Value, VcDate, VcDecimal, VcTimestamp, @@ -63,6 +65,16 @@ if (many.isOk()) { // A plain object needs json(..). // @ts-expect-error: a plain object is not a value. void keyset.encrypt({ name: 'Ada' }) +// @ts-expect-error: a plain object is not a value. +void keyset.encrypt({ a: 1 }) +const plainObject = { a: 1 } +// @ts-expect-error: a plain object is not a `Json`, though it has a `toString`. +expectType(plainObject) +// @ts-expect-error: a plain object is not a `Value`. +expectType(plainObject) +// What `json(..)` returns is both. +expectType(json({ a: 1 })) +expectType(json({ a: 1 })) // A UUID is not in the engine's value model yet. declare const uuid: VcUuid // @ts-expect-error: a UUID is not a value. From bbfc95c21981d6f0889a63b887294a91e8279916 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Wed, 25 Nov 2026 23:48:02 +1100 Subject: [PATCH 3/7] refactor(recipher-js): record types in record-types.ts, as the value types are The header imported the record types from src/record.ts, so that module could not load the addon, and checkDeclarations had moved to src/cipher.ts, away from the declarations it checks. The values had solved the same problem another way, with an import-free value-types.ts. Records now follow the values: the types the generated signatures name (RecordDeclaration, Plaintext, Stored, SealedFieldName, CipherOptions and the field types) are in an import-free src/record-types.ts, which the header imports. checkDeclarations is back in src/record.ts, beside the declarations it checks, and loads the addon from there, with the same stand-in that returns the load error when the addon did not load. The package's exports are unchanged. AGENTS.md states the rule: one *-types.ts module per topic, imported by the header, never loading the addon. --- AGENTS.md | 2 +- .../__tests__/unit/binding.test.ts | 3 +- .../packages/recipher-js/native-header.d.ts | 2 +- .../packages/recipher-js/native.d.ts | 2 +- .../packages/recipher-js/src/cipher.ts | 15 +- .../packages/recipher-js/src/index.ts | 2 +- .../packages/recipher-js/src/record-types.ts | 151 ++++++++++++++ .../packages/recipher-js/src/record.ts | 188 +++++------------- 8 files changed, 207 insertions(+), 158 deletions(-) create mode 100644 languages/typescript/packages/recipher-js/src/record-types.ts diff --git a/AGENTS.md b/AGENTS.md index f2359ae46..f0b03ca9e 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`, `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, the types the generated signatures name (`src/kinds.ts`, `src/value-types.ts`), and the record declarations (`src/record.ts`), which are plain data the addon reads. `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). 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, the record declarations (`src/record.ts`), which are plain data the addon reads, and the types the generated signatures name. Those types live in one `*-types.ts` module per topic (`src/value-types.ts`, `src/record-types.ts`, and `src/kinds.ts`, which holds plain data), which `native-header.d.ts` imports and which never load the addon: one that did would make the declarations import themselves, and tsup's declaration build fails. A type that names a generated class, such as `Value` (`Scalar | Json`), is declared in the header itself, so a type error names the class. 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/__tests__/unit/binding.test.ts b/languages/typescript/packages/recipher-js/__tests__/unit/binding.test.ts index da9e42bd3..476e084e2 100644 --- a/languages/typescript/packages/recipher-js/__tests__/unit/binding.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/unit/binding.test.ts @@ -6,6 +6,7 @@ import { describe, expect, it } from 'vitest' import { BINDING_INTERFACE, type Binding, load } from '../../src/binding' import { classesOf } from '../../src/cipher' import { RecipherError } from '../../src/error' +import { checkDeclarationsOf } from '../../src/record' import { Err, err, Ok } from '../../src/result' /** A fake native build that exports every name the loader checks. */ @@ -142,7 +143,7 @@ describe('the classes of a build that did not load', () => { expect((await classes.Cipher.create()).err()).toBe(error) expect(classes.Ciphertext.fromBytes(new Uint8Array(4)).err()).toBe(error) expect((await classes.createTesting(new Uint8Array(32))).err()).toBe(error) - expect(classes.checkDeclarations([]).err()).toBe(error) + expect(checkDeclarationsOf(err(error))([]).err()).toBe(error) }) it('recognise no value as one of theirs', () => { diff --git a/languages/typescript/packages/recipher-js/native-header.d.ts b/languages/typescript/packages/recipher-js/native-header.d.ts index bd81e1dd8..0c4de718c 100644 --- a/languages/typescript/packages/recipher-js/native-header.d.ts +++ b/languages/typescript/packages/recipher-js/native-header.d.ts @@ -12,7 +12,7 @@ import type { RecordDeclaration, SealedFieldName, Stored, -} from './src/record' +} from './src/record-types' 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 169d2d7fa..f1f1dcbc5 100644 --- a/languages/typescript/packages/recipher-js/native.d.ts +++ b/languages/typescript/packages/recipher-js/native.d.ts @@ -12,7 +12,7 @@ import type { RecordDeclaration, SealedFieldName, Stored, -} from './src/record' +} from './src/record-types' import type { Err, Ok, Result } from './src/result' import type { JsonMarker, diff --git a/languages/typescript/packages/recipher-js/src/cipher.ts b/languages/typescript/packages/recipher-js/src/cipher.ts index 556d9d3ec..64a26a752 100644 --- a/languages/typescript/packages/recipher-js/src/cipher.ts +++ b/languages/typescript/packages/recipher-js/src/cipher.ts @@ -18,7 +18,7 @@ import type { RecipherError } from './error' import { err, type Result } from './result' import type { OpenedScalar } from './value-types' -export type { CipherOptions } from './record' +export type { CipherOptions } from './record-types' /** * One encrypted value: opaque bytes, encrypted with a data key of its own. @@ -59,7 +59,6 @@ export interface Classes { Keyset: KeysetClass Ciphertext: CiphertextClass createTesting: Binding['createTesting'] - checkDeclarations: Binding['checkDeclarations'] } /** @@ -80,7 +79,6 @@ function native(loaded: Binding): Classes { Keyset: typed(loaded.Keyset), Ciphertext: typed(loaded.Ciphertext), createTesting: loaded.createTesting, - checkDeclarations: loaded.checkDeclarations, } } @@ -112,7 +110,6 @@ function missing(error: RecipherError): Classes { }, ), createTesting: () => Promise.resolve(err(error)), - checkDeclarations: () => err(error), } } @@ -133,13 +130,3 @@ export const Cipher: CipherClass = classes.Cipher export const Keyset: KeysetClass = classes.Keyset /** The `Ciphertext` class: the native addon's class. */ export const Ciphertext: CiphertextClass = classes.Ciphertext - -/** - * Check record declarations with the engine, with no credentials and no - * network request. Use it in a test or a continuous integration (CI) step. - * - * The `Err` is the first refusal. The error names the record and, where - * there is one, the field. - */ -export const checkDeclarations: Binding['checkDeclarations'] = - classes.checkDeclarations diff --git a/languages/typescript/packages/recipher-js/src/index.ts b/languages/typescript/packages/recipher-js/src/index.ts index 1c6b28c7e..f342c59f6 100644 --- a/languages/typescript/packages/recipher-js/src/index.ts +++ b/languages/typescript/packages/recipher-js/src/index.ts @@ -30,7 +30,6 @@ export { type CipherOptions, Ciphertext, type CiphertextClass, - checkDeclarations, Keyset, type KeysetClass, } from './cipher' @@ -42,6 +41,7 @@ export { } from './error' export { type Kind, kinds, type ValueOf } from './kinds' export { + checkDeclarations, encrypt, type Field, type Index, diff --git a/languages/typescript/packages/recipher-js/src/record-types.ts b/languages/typescript/packages/recipher-js/src/record-types.ts new file mode 100644 index 000000000..1814f0ec7 --- /dev/null +++ b/languages/typescript/packages/recipher-js/src/record-types.ts @@ -0,0 +1,151 @@ +/** + * The types of record declarations, rows, stored rows and `Cipher.create`'s + * options. + * + * This module holds types only, and imports types only. 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. + */ +import type { Kind, ValueOf } from './kinds' + +/** + * An index that an encrypted field stores beside its ciphertext. An index + * stores index terms: bytes that a search can compare without decrypting the + * field. + */ +export type Index = 'equality' | 'match' | 'ore' | 'ope' + +/** + * How a field stores a missing value. + * + * - `sealed`: the null is encrypted like a value, to the same length as a + * value. The stored row does not show which rows have no value. Only for + * a field of fixed width whose only index is `equality`. The fixed-width + * fields are a boolean, a number, a date, a timestamp, and a decimal. + * - `sql`: the stored row has `null` for the field, as SQL `NULL` does. + */ +export type NullMode = 'sealed' | 'sql' + +/** + * A field that is encrypted, and indexed if it names indexes. The code calls + * an encrypted field a sealed field. + */ +export interface SealedField< + K extends Kind = Kind, + I extends readonly Index[] = readonly Index[], + N extends NullMode | undefined = NullMode | undefined, +> { + readonly type: 'sealed' + readonly kind: K + readonly index: I + readonly null?: N +} + +/** + * A field stored as it is: **not encrypted and not authenticated.** Anyone + * with the stored row can read the field, change it, or remove it. The + * encrypted fields still decrypt after that. Use a passthrough field only + * for values that are not secret. Treat the value read back as untrusted. + */ +export interface PassthroughField { + readonly type: 'passthrough' + /** Carries `T` for the type checker. The property never exists at run time. */ + readonly __value?: T +} + +/** A field of a record. */ +export type Field = SealedField | PassthroughField + +/** Options for an encrypted field. */ +export interface SealedOptions< + I extends readonly Index[], + N extends NullMode | undefined, +> { + /** The indexes the field stores. */ + index?: I + /** + * How the field stores a null. Without this option, every row needs a + * value for the field. + */ + null?: N +} + +/** A record's declaration: a plain, frozen object. */ +export interface RecordDeclaration< + Name extends string = string, + F extends { readonly [field: string]: Field } = { + readonly [field: string]: Field + }, +> { + /** + * Marks the object as a declaration. Every copy of the package reads this + * marker, including the ESM build and the CommonJS build. + */ + readonly type: 'record' + /** The record's name: the first part of each field's context. */ + readonly name: Name + /** The fields, each with its declaration. */ + readonly fields: F +} + +/** The plaintext row of a record. A field that takes a null can be `null`. */ +export type Plaintext = + R extends RecordDeclaration + ? { + -readonly [P in keyof F]: F[P] extends SealedField< + infer K, + readonly Index[], + infer N + > + ? ValueOf | (N extends NullMode ? null : never) + : F[P] extends PassthroughField + ? T + : never + } + : never + +/** An encrypted field as it is stored: its ciphertext and its index terms. */ +export type StoredField = { + readonly ciphertext: Uint8Array +} & { readonly [X in I[number]]: Uint8Array } + +/** + * The stored row of a record. Each encrypted field has its ciphertext and + * its index terms, each as opaque bytes. Each passthrough field has its + * value. A field that stores a null as SQL `NULL` is `null` when its value + * is missing. + */ +export type Stored = + R extends RecordDeclaration + ? { + readonly [P in keyof F]: F[P] extends SealedField< + Kind, + infer I, + infer N + > + ? StoredField | (N extends 'sql' ? null : never) + : F[P] extends PassthroughField + ? T + : never + } + : never + +/** The names of a record's encrypted fields. */ +export type SealedFieldName = + R extends RecordDeclaration + ? { + [P in keyof F]: F[P] extends SealedField ? P : never + }[keyof F] & + string + : never + +/** Options for `Cipher.create`. */ +export interface CipherOptions { + /** + * Records to check when the cipher is created, before any credentials are + * looked for. A declaration that the engine refuses then gives an `Err` + * here, not at its first use. + */ + records?: readonly RecordDeclaration[] +} diff --git a/languages/typescript/packages/recipher-js/src/record.ts b/languages/typescript/packages/recipher-js/src/record.ts index 4e10d685f..0cd1af5ef 100644 --- a/languages/typescript/packages/recipher-js/src/record.ts +++ b/languages/typescript/packages/recipher-js/src/record.ts @@ -23,73 +23,37 @@ * * TypeScript checks a row against the types below. * - * This module never loads the native addon. The addon's generated - * declarations (`native.d.ts`) name its types, so a module here that loaded - * the addon would make the declarations import themselves. + * The types are in `record-types.ts`, which never loads the addon, because + * the addon's generated declarations (`native.d.ts`) import them. */ -import type { Kind, ValueOf } from './kinds' +import { type Binding, binding } from './binding' +import type { RecipherError } from './error' +import type { Kind } from './kinds' +import type { + Field, + Index, + NullMode, + PassthroughField, + RecordDeclaration, + SealedField, + SealedOptions, +} from './record-types' +import { err, type Result } from './result' -/** - * An index that an encrypted field stores beside its ciphertext. An index - * stores index terms: bytes that a search can compare without decrypting the - * field. - */ -export type Index = 'equality' | 'match' | 'ore' | 'ope' - -/** - * How a field stores a missing value. - * - * - `sealed`: the null is encrypted like a value, to the same length as a - * value. The stored row does not show which rows have no value. Only for - * a field of fixed width whose only index is `equality`. The fixed-width - * fields are a boolean, a number, a date, a timestamp, and a decimal. - * - `sql`: the stored row has `null` for the field, as SQL `NULL` does. - */ -export type NullMode = 'sealed' | 'sql' - -/** - * A field that is encrypted, and indexed if it names indexes. The code calls - * an encrypted field a sealed field. - */ -export interface SealedField< - K extends Kind = Kind, - I extends readonly Index[] = readonly Index[], - N extends NullMode | undefined = NullMode | undefined, -> { - readonly type: 'sealed' - readonly kind: K - readonly index: I - readonly null?: N -} - -/** - * A field stored as it is: **not encrypted and not authenticated.** Anyone - * with the stored row can read the field, change it, or remove it. The - * encrypted fields still decrypt after that. Use a passthrough field only - * for values that are not secret. Treat the value read back as untrusted. - */ -export interface PassthroughField { - readonly type: 'passthrough' - /** Carries `T` for the type checker. The property never exists at run time. */ - readonly __value?: T -} - -/** A field of a record. */ -export type Field = SealedField | PassthroughField - -/** Options for an encrypted field. */ -export interface SealedOptions< - I extends readonly Index[], - N extends NullMode | undefined, -> { - /** The indexes the field stores. */ - index?: I - /** - * How the field stores a null. Without this option, every row needs a - * value for the field. - */ - null?: N -} +export type { + CipherOptions, + Field, + Index, + NullMode, + PassthroughField, + Plaintext, + RecordDeclaration, + SealedField, + SealedFieldName, + SealedOptions, + Stored, + StoredField, +} from './record-types' /** An encrypted field of the kind `kind`. */ export function encrypt< @@ -117,24 +81,6 @@ export function passthrough(): PassthroughField { return Object.freeze({ type: 'passthrough' }) } -/** A record's declaration: a plain, frozen object. */ -export interface RecordDeclaration< - Name extends string = string, - F extends { readonly [field: string]: Field } = { - readonly [field: string]: Field - }, -> { - /** - * Marks the object as a declaration. Every copy of the package reads this - * marker, including the ESM build and the CommonJS build. - */ - readonly type: 'record' - /** The record's name: the first part of each field's context. */ - readonly name: Name - /** The fields, each with its declaration. */ - readonly fields: F -} - /** * A record named `name`, with `fields`. Each field's context is its field * path: the record's name, then the field's name. A context is data that a @@ -152,63 +98,27 @@ export function record< }) } -/** The plaintext row of a record. A field that takes a null can be `null`. */ -export type Plaintext = - R extends RecordDeclaration - ? { - -readonly [P in keyof F]: F[P] extends SealedField< - infer K, - readonly Index[], - infer N - > - ? ValueOf | (N extends NullMode ? null : never) - : F[P] extends PassthroughField - ? T - : never - } - : never - -/** An encrypted field as it is stored: its ciphertext and its index terms. */ -export type StoredField = { - readonly ciphertext: Uint8Array -} & { readonly [X in I[number]]: Uint8Array } - /** - * The stored row of a record. Each encrypted field has its ciphertext and - * its index terms, each as opaque bytes. Each passthrough field has its - * value. A field that stores a null as SQL `NULL` is `null` when its value - * is missing. + * Check declarations with the engine, with no credentials and no network + * request. Use it in a test or a continuous integration (CI) step. + * + * The `Err` is the first refusal. The error names the record and, where + * there is one, the field. When the native addon did not load, the `Err` + * says why. */ -export type Stored = - R extends RecordDeclaration - ? { - readonly [P in keyof F]: F[P] extends SealedField< - Kind, - infer I, - infer N - > - ? StoredField | (N extends 'sql' ? null : never) - : F[P] extends PassthroughField - ? T - : never - } - : never +export const checkDeclarations: Binding['checkDeclarations'] = + checkDeclarationsOf(binding) -/** The names of a record's encrypted fields. */ -export type SealedFieldName = - R extends RecordDeclaration - ? { - [P in keyof F]: F[P] extends SealedField ? P : never - }[keyof F] & - string - : never - -/** Options for `Cipher.create`. */ -export interface CipherOptions { - /** - * Records to check when the cipher is created, before any credentials are - * looked for. A declaration that the engine refuses then gives an `Err` - * here, not at its first use. - */ - records?: readonly RecordDeclaration[] +/** + * The addon's `checkDeclarations` when the addon loaded, or a stand-in that + * returns the load error when it did not. + */ +export function checkDeclarationsOf( + loaded: Result, +): Binding['checkDeclarations'] { + if (loaded.isOk()) { + return loaded.value.checkDeclarations + } + const error = loaded.error + return () => err(error) } From 1591215d3716dd8c4868a192178e4ebfe2aec341 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 19:19:14 +1100 Subject: [PATCH 4/7] docs(recipher-js): plain language for the records prose Rewrite the comments, doc comments and Markdown that the records work added, so that each passes the plain-language checker. No code changes. - One idea in each sentence, and each sentence names its subject. - A doc defines "record declaration", "plan" and "stored row" where it first uses the term. - The user-facing docs say "encrypt" and "decrypt", and "accepts" for what a field or a function allows. - `native.d.ts` is regenerated, because the build copies the doc comments of the `#[napi]` items into it. --- AGENTS.md | 2 +- .../typescript/packages/recipher-js/README.md | 4 +- .../__tests__/addon/records.test.ts | 15 +++-- .../__tests__/unit/type-messages.test.ts | 9 +-- .../packages/recipher-js/crate/Cargo.toml | 14 +++-- .../packages/recipher-js/crate/src/cipher.rs | 56 ++++++++++--------- .../packages/recipher-js/crate/src/error.rs | 6 +- .../packages/recipher-js/crate/src/frames.rs | 16 +++--- .../packages/recipher-js/crate/src/js.rs | 10 ++-- .../packages/recipher-js/crate/src/record.rs | 10 ++-- .../recipher-js/crate/src/record_tests.rs | 6 +- .../packages/recipher-js/native-header.d.ts | 6 +- .../packages/recipher-js/native.d.ts | 56 ++++++++++--------- .../packages/recipher-js/src/record-types.ts | 35 +++++++----- .../packages/recipher-js/src/record.ts | 34 ++++++----- .../packages/recipher-js/src/values.ts | 2 +- .../recipher-js/type-tests/records.ts | 6 +- 17 files changed, 157 insertions(+), 130 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3138da875..58a11e0f7 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, the record declarations, 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 record declarations are in `src/record.ts`, and are plain data that the addon reads. The types are in one `*-types.ts` module for each topic: `src/value-types.ts` and `src/record-types.ts`. `src/kinds.ts` declares types too, and contains plain data. `native-header.d.ts` imports those modules, so none of them may load the addon. If one did, the declarations would import themselves. The declaration build of tsup would then fail. A type that names a generated class, such as `Value` (`Scalar | Json`), is declared in the header itself, so a type error names the class. 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, the stand-ins, the record declarations, and the types that the generated signatures name. The stand-ins are for a build that did not load. The loader is `src/binding.ts`. The loader gives the addon the `Ok`, `Err`, and `RecipherError` classes. The record declarations are in `src/record.ts`. A declaration is plain data that the addon reads. The types are in one `*-types.ts` module for each topic: `src/value-types.ts` and `src/record-types.ts`. `src/kinds.ts` declares types too, and contains plain data. `native-header.d.ts` imports those modules, so none of them may load the addon. If one did, the declarations would import themselves. The declaration build of tsup would then fail. A type that names a generated class, such as `Value` (`Scalar | Json`), is declared in the header itself, so a type error names the class. 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/languages/typescript/packages/recipher-js/README.md b/languages/typescript/packages/recipher-js/README.md index 048add01a..b6aa1c576 100644 --- a/languages/typescript/packages/recipher-js/README.md +++ b/languages/typescript/packages/recipher-js/README.md @@ -186,13 +186,15 @@ const stored = await keyset.encrypt(user, row) const opened = await cipher.decrypt(user, stored.unwrap()) ``` +- `keyset.encrypt(user, row)` returns a stored row. + A stored row is the encrypted form of a row. - A declaration is a plain, frozen object: `{ type: 'record', name, fields }`. A library can read the record's name, its fields, and each field's declaration from it. - The package has an ECMAScript module (ESM) build and a CommonJS build. A declaration made by either build works with a cipher from the other. - Each encrypted field names its kind, by the engine's name for it. The kinds are `kinds.string`, `kinds.boolean`, `kinds.int8` to `kinds.int128`, `kinds.uint8` to `kinds.uint128`, `kinds.float32`, `kinds.float64`, `kinds.decimal`, `kinds.date`, `kinds.timestamp`, and `kinds.bytes`. -- An integer field takes a `bigint` at every width. +- An integer field accepts a `bigint` at every width. The field refuses a `bigint` outside its range. - A context is data that a ciphertext is bound to. The ciphertext decrypts only under the same context. diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/records.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/records.test.ts index 8d7b8b2a7..dd94c3f30 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/records.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/records.test.ts @@ -140,13 +140,14 @@ describe('one field', () => { 'new@example.com', ) - // Its equality term is the term a whole row stores for the value. + // The field's equality term is the term that a whole row stores for the + // value. const row = ( await keyset.encrypt(user, { ...ada, email: 'new@example.com' }) ).unwrap() expect(Buffer.from(email.equality)).toEqual(Buffer.from(row.email.equality)) - // And a whole row takes the field in place of its own. + // A whole row accepts the field in place of its own field. const updated = { ...row, email } expect((await c.decrypt(user, updated)).unwrap().email).toBe( 'new@example.com', @@ -170,13 +171,15 @@ describe('one field', () => { const row = ( await c.defaultKeyset().encrypt(pair, { a: 'x', b: 'y' }) ).unwrap() - // Same shape, so this compiles and the engine reads it; only the context - // differs. The key service refuses the key, which it binds to the - // field path the value was sealed under. + // The two fields have the same shape, so this compiles and the engine + // reads it. Only the context differs. The key service refuses the key. + // The key service binds a key to the field path that the value was + // encrypted under. const result = await c.decryptField(pair, 'a', row.b) expect(result.err()?.code).toBe('stack_kms::retrieve_key_failed') - // A row opened under a record of another name is refused the same way. + // A row decrypted under a record of another name is refused the same + // way. const other = record('other', pair.fields) const moved = await c.decrypt(other, row) expect(moved.err()?.code).toBe('stack_kms::retrieve_key_failed') diff --git a/languages/typescript/packages/recipher-js/__tests__/unit/type-messages.test.ts b/languages/typescript/packages/recipher-js/__tests__/unit/type-messages.test.ts index 73e2a59d6..ed21d5887 100644 --- a/languages/typescript/packages/recipher-js/__tests__/unit/type-messages.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/unit/type-messages.test.ts @@ -1,7 +1,8 @@ -// The type errors a caller sees. A wrong argument to `encrypt` must name the -// public types, `Value` and `Json`, and never the marker that brands a -// `Json`. `type-tests/` checks that the code does not compile; this suite -// compiles a snippet with the TypeScript compiler and reads the message. +// The type errors that a caller reads. A wrong argument to `encrypt` must +// name the public types: `Value` and `Json`. The error must never name the +// marker type of a `Json`. `type-tests/` checks that the code does not +// compile. This suite compiles a snippet with the TypeScript compiler and +// reads the message. import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' diff --git a/languages/typescript/packages/recipher-js/crate/Cargo.toml b/languages/typescript/packages/recipher-js/crate/Cargo.toml index 7bb71b9c6..88a1fa079 100644 --- a/languages/typescript/packages/recipher-js/crate/Cargo.toml +++ b/languages/typescript/packages/recipher-js/crate/Cargo.toml @@ -26,12 +26,14 @@ 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. 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. `Symbol.for` needs `napi9`, and Node 18.17 and later -# provide `napi9`. `Symbol.for` makes the key of a decrypted row's `inspect`. -# `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. +# `Symbol.for` needs `napi9`, and Node 18.17 and later provide `napi9`. +# `Symbol.for` makes the key of a decrypted row's `inspect`. `tokio_rt` runs +# the engine's futures on napi's runtime. napi = { version = "3", features = ["napi9", "tokio_rt", "serde-json"] } napi-derive = "3" # The value bridge: every JavaScript value is read and built through it. diff --git a/languages/typescript/packages/recipher-js/crate/src/cipher.rs b/languages/typescript/packages/recipher-js/crate/src/cipher.rs index 2af1e4731..41edfc6cc 100644 --- a/languages/typescript/packages/recipher-js/crate/src/cipher.rs +++ b/languages/typescript/packages/recipher-js/crate/src/cipher.rs @@ -54,10 +54,10 @@ macro_rules! with_engine { }; } -/// Runs `$body` with `$cipher` bound to what a decrypt call may use, as -/// `$confined` says: the whole cipher, or its default keyset only. Every -/// decrypt goes through this macro, so keyset confinement is decided here -/// alone. +/// Runs `$body` with `$cipher` bound to the cipher that a decrypt call may +/// use. `$confined` selects it: the whole cipher, or its default keyset +/// only. Every decrypt uses this macro, so only this macro decides keyset +/// confinement. macro_rules! confined { ($engine:expr, $confined:expr, |$cipher:ident| $body:expr) => { with_engine!($engine, |whole| match $confined { @@ -118,8 +118,9 @@ impl Cipher { /// - ZeroKMS refuses to load the default keyset. /// /// `options.records` lists record declarations to check now, before the - /// engine looks for credentials. If the engine refuses a declaration, - /// the promise resolves to an `Err` that names the record. + /// engine looks for credentials. A record declaration lists a record's + /// fields and how to store each one. If the engine refuses a + /// declaration, the promise resolves to an `Err` that names the record. /// /// The promise does not reject. #[napi( @@ -164,14 +165,14 @@ impl Cipher { /// ciphertexts were made under. A key request is one request to ZeroKMS /// for data keys. /// - /// With a record declaration as the first argument, decrypts a stored - /// row of that record, or an array of stored rows. A stored row is what - /// `keyset.encrypt` returns for a row. Node's `inspect` shows a - /// decrypted row's field names and hides their values. + /// With a record declaration as the first argument, `decrypt` decrypts + /// a stored row of that record, or an array of stored rows. A stored + /// row is what `keyset.encrypt` returns for a row. Node's `inspect` + /// shows a decrypted row's field names and hides their values. /// - /// Resolves to an `Err` with the code `recipher_js::not_a_ciphertext` - /// when the argument, or an element of the array, is not a - /// `Ciphertext`. The promise does not reject. + /// The promise resolves to an `Err` with the code + /// `recipher_js::not_a_ciphertext` 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> @@ -225,21 +226,22 @@ impl Keyset { /// /// 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. + /// 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. /// - /// 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`. + /// 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`. /// - /// With a record declaration as the first argument, encrypts a row of - /// that record, or an array of rows in one key request. Each field is - /// encrypted under its field path: the record's name, then the field's - /// name. For each encrypted field, the stored row has the field's - /// ciphertext and its index terms. + /// With a record declaration as the first argument, `encrypt` encrypts + /// a row of that record, or an array of rows in one key request. Each + /// field is encrypted under its field path: the record's name, then the + /// field's name. For each encrypted field, the stored row has the + /// field's ciphertext and its index terms. /// /// The promise does not reject. #[napi( @@ -308,8 +310,8 @@ encrypt(record: R, rows: readonly Plaintext[]): /// ciphertext of another keyset fails with the code /// `stack_encrypt::foreign_keyset`, before any key is requested. /// - /// With a record declaration as the first argument, decrypts a stored - /// row of that record, or an array of stored rows. + /// With a record declaration as the first argument, `decrypt` decrypts + /// a stored row of that record, or an array of stored rows. /// /// The promise does not reject. #[napi( @@ -511,8 +513,8 @@ pub(crate) async fn open_in( } /// Decrypts stored rows of the record that `plan` describes, through -/// `engine`: through the whole cipher, or through its default keyset only, -/// as `confined` says. +/// `engine`. `confined` selects the whole cipher, or its default keyset +/// only. pub(crate) async fn open_rows_in( engine: &Engine, plan: Arc, @@ -536,7 +538,7 @@ fn one_value(env: &Env, value: Unknown<'_>) -> Outcome<(OneValue, Option, /// The errors that caused this one, outermost first. diff --git a/languages/typescript/packages/recipher-js/crate/src/frames.rs b/languages/typescript/packages/recipher-js/crate/src/frames.rs index d4d6c7c0c..e437d3fa0 100644 --- a/languages/typescript/packages/recipher-js/crate/src/frames.rs +++ b/languages/typescript/packages/recipher-js/crate/src/frames.rs @@ -2,14 +2,16 @@ //! in a given order. //! //! A frame is an [`OwnedFrame`]: a byte buffer that contains one value, in -//! the engine's frame encoding. A map frame contains a map. A sink receives -//! a value from a frame one part at a time: one scalar, array or map. +//! the engine's frame encoding. A map frame contains a map. A sink receives a +//! value from a frame one part at a time: one scalar, array, or map. //! -//! The addon passes a record's row, and its stored row, between JavaScript -//! and the engine as one map frame each. The engine is the `stack-encrypt` -//! crate. The map has one entry for each of the record's fields. These -//! helpers split such a frame into one frame for each entry. They also -//! write entries back as one map, in the order given. +//! The addon passes a record's row between JavaScript and the engine as one +//! map frame. The addon passes a stored row in the same way. The engine is +//! the `stack-encrypt` crate. The map has one entry for each of the record's +//! fields. +//! +//! These helpers split such a frame into one frame for each entry. The +//! helpers also write entries back as one map, in the order given. use stack_encrypt::dynamic::frame::OwnedFrame; use stack_encrypt::dynamic::plaintext::{ diff --git a/languages/typescript/packages/recipher-js/crate/src/js.rs b/languages/typescript/packages/recipher-js/crate/src/js.rs index ab1d52aef..59774a37f 100644 --- a/languages/typescript/packages/recipher-js/crate/src/js.rs +++ b/languages/typescript/packages/recipher-js/crate/src/js.rs @@ -184,8 +184,8 @@ fn is_uuid(env: &Env, value: &Unknown<'_>) -> bool { .is_ok_and(|wrapper| wrapper == Some(Wrapper::Uuid)) } -/// Returns the property `name` of `value`, when `value` is an object and -/// the property is not `undefined`. +/// Returns the property `name` of `value`. Returns `None` when `value` is not +/// an object, or when the property is `undefined`. /// /// # Errors /// @@ -283,9 +283,9 @@ pub(crate) fn hidden<'e>( .with_name(env, key) .map_err(not_made)? .with_value(&inspect) - // The property is not enumerable, writable or configurable. So a - // copy, spread or comparison of the row does not include it, and - // nothing can replace it. + // The property is not enumerable, writable, or configurable. So a + // copy, a spread, or a comparison of the row does not include the + // property. No code can replace the property. .with_property_attributes(PropertyAttributes::Default); object.define_properties(&[property]).map_err(not_made)?; Ok(row) diff --git a/languages/typescript/packages/recipher-js/crate/src/record.rs b/languages/typescript/packages/recipher-js/crate/src/record.rs index 0611e39f2..7ab6699e5 100644 --- a/languages/typescript/packages/recipher-js/crate/src/record.rs +++ b/languages/typescript/packages/recipher-js/crate/src/record.rs @@ -12,17 +12,17 @@ //! A declaration is the plain object that `record(..)` makes: //! `{ type: "record", name, fields }`. Each field is one of these: //! -//! - `{ type: "sealed", kind: { name }, index: [..], null? }`, a sealed -//! field, which the engine encrypts; -//! - `{ type: "passthrough" }`, a passthrough field, which the engine -//! stores as given, without encryption. +//! - `{ type: "sealed", kind: { name }, index: [..], null? }` is a sealed +//! field. The engine encrypts a sealed field. +//! - `{ type: "passthrough" }` is a passthrough field. The engine stores a +//! passthrough field as given, without encryption. //! //! Each field's context is its field path: the record's name, then the //! field's name. A context is a value that a ciphertext is bound to, and //! decrypting needs the same context. //! //! The addon builds the plan from the declaration with the engine's own -//! types: [`FieldPlan`], [`Output`], [`IndexSpec`], [`NullMode`] and +//! types: [`FieldPlan`], [`Output`], [`IndexSpec`], [`NullMode`], and //! [`ValueKind`]. So the engine checks the plan, and the refusals are the //! engine's. The addon builds a plan once for each declaration, and keeps //! it for the life of the process. diff --git a/languages/typescript/packages/recipher-js/crate/src/record_tests.rs b/languages/typescript/packages/recipher-js/crate/src/record_tests.rs index 555a6d014..27228385c 100644 --- a/languages/typescript/packages/recipher-js/crate/src/record_tests.rs +++ b/languages/typescript/packages/recipher-js/crate/src/record_tests.rs @@ -376,9 +376,9 @@ fn a_plan_is_built_once_for_a_declaration() { )); } -/// `keyset.decrypt` of a stored row is confined to its keyset and -/// `cipher.decrypt` is not, as for a ciphertext. The two differ only in the -/// `Confined` they pass to `open_rows_in`. +/// `keyset.decrypt` of a stored row is confined to its keyset. +/// `cipher.decrypt` is not. A ciphertext has the same rule. The two calls +/// differ only in the `Confined` they pass to `open_rows_in`. #[tokio::test] async fn a_keyset_refuses_another_keysets_row_and_the_cipher_opens_it() { let cipher = engine().await; diff --git a/languages/typescript/packages/recipher-js/native-header.d.ts b/languages/typescript/packages/recipher-js/native-header.d.ts index ee680f05c..97d1c452b 100644 --- a/languages/typescript/packages/recipher-js/native-header.d.ts +++ b/languages/typescript/packages/recipher-js/native-header.d.ts @@ -44,8 +44,8 @@ export interface Ciphertext { export interface Json extends JsonMarker {} /** - * A value that `encrypt` takes: one scalar, or a `Json` document from - * `json(..)`. It is declared here, beside the `Json` class, so a type error - * names `Json` and `Value`. + * A value that `encrypt` accepts: one scalar, or a `Json` document from + * `json(..)`. The type is declared here, beside the `Json` class, so a type + * error names `Json` and `Value`. */ export type Value = Scalar | Json diff --git a/languages/typescript/packages/recipher-js/native.d.ts b/languages/typescript/packages/recipher-js/native.d.ts index cc5512dab..f2525029d 100644 --- a/languages/typescript/packages/recipher-js/native.d.ts +++ b/languages/typescript/packages/recipher-js/native.d.ts @@ -44,9 +44,9 @@ export interface Ciphertext { export interface Json extends JsonMarker {} /** - * A value that `encrypt` takes: one scalar, or a `Json` document from - * `json(..)`. It is declared here, beside the `Json` class, so a type error - * names `Json` and `Value`. + * A value that `encrypt` accepts: one scalar, or a `Json` document from + * `json(..)`. The type is declared here, beside the `Json` class, so a type + * error names `Json` and `Value`. */ export type Value = Scalar | Json @@ -75,8 +75,9 @@ export declare class Cipher { * - ZeroKMS refuses to load the default keyset. * * `options.records` lists record declarations to check now, before the - * engine looks for credentials. If the engine refuses a declaration, - * the promise resolves to an `Err` that names the record. + * engine looks for credentials. A record declaration lists a record's + * fields and how to store each one. If the engine refuses a + * declaration, the promise resolves to an `Err` that names the record. * * The promise does not reject. */ @@ -95,14 +96,14 @@ export declare class Cipher { * ciphertexts were made under. A key request is one request to ZeroKMS * for data keys. * - * With a record declaration as the first argument, decrypts a stored - * row of that record, or an array of stored rows. A stored row is what - * `keyset.encrypt` returns for a row. Node's `inspect` shows a - * decrypted row's field names and hides their values. + * With a record declaration as the first argument, `decrypt` decrypts + * a stored row of that record, or an array of stored rows. A stored + * row is what `keyset.encrypt` returns for a row. Node's `inspect` + * shows a decrypted row's field names and hides their values. * - * Resolves to an `Err` with the code `recipher_js::not_a_ciphertext` - * when the argument, or an element of the array, is not a - * `Ciphertext`. The promise does not reject. + * The promise resolves to an `Err` with the code + * `recipher_js::not_a_ciphertext` 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> @@ -200,21 +201,22 @@ export declare class Keyset { * * 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. + * 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. * - * 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`. + * 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`. * - * With a record declaration as the first argument, encrypts a row of - * that record, or an array of rows in one key request. Each field is - * encrypted under its field path: the record's name, then the field's - * name. For each encrypted field, the stored row has the field's - * ciphertext and its index terms. + * With a record declaration as the first argument, `encrypt` encrypts + * a row of that record, or an array of rows in one key request. Each + * field is encrypted under its field path: the record's name, then the + * field's name. For each encrypted field, the stored row has the + * field's ciphertext and its index terms. * * The promise does not reject. */ @@ -227,8 +229,8 @@ export declare class Keyset { * ciphertext of another keyset fails with the code * `stack_encrypt::foreign_keyset`, before any key is requested. * - * With a record declaration as the first argument, decrypts a stored - * row of that record, or an array of stored rows. + * With a record declaration as the first argument, `decrypt` decrypts + * a stored row of that record, or an array of stored rows. * * The promise does not reject. */ @@ -266,7 +268,7 @@ export declare function bindingInterface(): number * Checks record declarations with the engine, without credentials and * without any request. Use it in a test or a continuous integration (CI) * step. The `Err` is the engine's first refusal. The error names the - * record and, where there is one, the field. Does not throw. + * record and, where there is one, the field. This function does not throw. */ export declare function checkDeclarations(declarations: readonly RecordDeclaration[]): Result @@ -377,9 +379,9 @@ export interface RecipherErrorFields { severity: Severity /** * The error's structured fields, keyed by `snake_case` name. For - * example, a refused plan has `field` and `reason`, and a ZeroKMS - * failure has `request_kind`. A plan is the engine's rules for - * encrypting a record. The map is empty when the error has no fields. + * example, a refused plan has `field` and `reason`. A ZeroKMS failure + * has `request_kind`. A plan is the engine's rules for encrypting a + * record. The map is empty when the error has no fields. */ fields: Record /** The errors that caused this one, outermost first. */ diff --git a/languages/typescript/packages/recipher-js/src/record-types.ts b/languages/typescript/packages/recipher-js/src/record-types.ts index 1814f0ec7..e5f3ec0a3 100644 --- a/languages/typescript/packages/recipher-js/src/record-types.ts +++ b/languages/typescript/packages/recipher-js/src/record-types.ts @@ -1,11 +1,11 @@ /** - * The types of record declarations, rows, stored rows and `Cipher.create`'s - * options. + * The types of record declarations, rows, stored rows, and the options of + * `Cipher.create`. * - * This module holds types only, and imports types only. The addon's + * This module contains types only, and imports types only. 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. + * signatures. If a module here loaded the addon, the declarations would + * import themselves. */ import type { Kind, ValueOf } from './kinds' @@ -19,10 +19,11 @@ export type Index = 'equality' | 'match' | 'ore' | 'ope' /** * How a field stores a missing value. * - * - `sealed`: the null is encrypted like a value, to the same length as a - * value. The stored row does not show which rows have no value. Only for - * a field of fixed width whose only index is `equality`. The fixed-width - * fields are a boolean, a number, a date, a timestamp, and a decimal. + * - `sealed`: the engine encrypts the null like a value, to the same length + * as a value. The stored row does not show which rows have no value. This + * mode is only for a field of fixed width whose only index is `equality`. + * The fixed-width fields are a boolean, a number, a date, a timestamp, and + * a decimal. * - `sql`: the stored row has `null` for the field, as SQL `NULL` does. */ export type NullMode = 'sealed' | 'sql' @@ -50,7 +51,7 @@ export interface SealedField< */ export interface PassthroughField { readonly type: 'passthrough' - /** 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 } @@ -80,7 +81,8 @@ export interface RecordDeclaration< > { /** * Marks the object as a declaration. Every copy of the package reads this - * marker, including the ESM build and the CommonJS build. + * marker, including the ECMAScript module (ESM) build and the CommonJS + * build. */ readonly type: 'record' /** The record's name: the first part of each field's context. */ @@ -89,7 +91,9 @@ export interface RecordDeclaration< readonly fields: F } -/** The plaintext row of a record. A field that takes a null can be `null`. */ +/** + * The plaintext row of a record. A field that accepts a null can be `null`. + */ export type Plaintext = R extends RecordDeclaration ? { @@ -143,9 +147,10 @@ export type SealedFieldName = /** Options for `Cipher.create`. */ export interface CipherOptions { /** - * Records to check when the cipher is created, before any credentials are - * looked for. A declaration that the engine refuses then gives an `Err` - * here, not at its first use. + * Records to check when the cipher is created, before `Cipher.create` + * looks for any credentials. If the engine refuses a declaration, + * `Cipher.create` resolves to the `Err`. Without this option, the `Err` + * comes from the first use of the declaration. */ records?: readonly RecordDeclaration[] } diff --git a/languages/typescript/packages/recipher-js/src/record.ts b/languages/typescript/packages/recipher-js/src/record.ts index 0cd1af5ef..c3f3d4b83 100644 --- a/languages/typescript/packages/recipher-js/src/record.ts +++ b/languages/typescript/packages/recipher-js/src/record.ts @@ -14,17 +14,24 @@ * }) * ``` * - * A declaration is a plain, frozen object: `{ type: 'record', name, fields }`, - * with a declaration for each field. The native addon reads the declaration - * and builds the engine's plan from it, once. The engine checks the - * declaration at that time. That happens when a cipher first uses the - * declaration, or when `Cipher.create({ records })` or - * `checkDeclarations(..)` is called. + * A declaration is a plain, frozen object: + * `{ type: 'record', name, fields }`, with a declaration for each field. + * + * The engine is Stack Encrypt, CipherStash's encryption engine. A plan is + * the engine's description of how to encrypt each field of a row. The native + * addon reads a declaration once, and builds the engine's plan from it. The + * engine checks the declaration when the addon builds the plan. The addon + * builds the plan at the first of these events: + * + * - a cipher uses the declaration; + * - `Cipher.create({ records })` is called with the declaration; + * - `checkDeclarations(..)` is called with the declaration. * * TypeScript checks a row against the types below. * - * The types are in `record-types.ts`, which never loads the addon, because - * the addon's generated declarations (`native.d.ts`) import them. + * The types are in `record-types.ts`. That module never loads the addon, + * because the addon's generated declarations (`native.d.ts`) import the + * types. */ import { type Binding, binding } from './binding' import type { RecipherError } from './error' @@ -82,9 +89,9 @@ export function passthrough(): PassthroughField { } /** - * A record named `name`, with `fields`. Each field's context is its field - * path: the record's name, then the field's name. A context is data that a - * ciphertext is bound to. The ciphertext decrypts only under the same + * Makes a record named `name`, with `fields`. Each field's context is its + * field path: the record's name, then the field's name. A context is data + * that a ciphertext is bound to. The ciphertext decrypts only under the same * context. */ export function record< @@ -99,8 +106,9 @@ export function record< } /** - * Check declarations with the engine, with no credentials and no network - * request. Use it in a test or a continuous integration (CI) step. + * Checks declarations with the engine. The check needs no credentials, and + * makes no network request. Use it in a test or a continuous integration + * (CI) step. * * The `Err` is the first refusal. The error names the record and, where * there is one, the field. When the native addon did not load, the `Err` diff --git a/languages/typescript/packages/recipher-js/src/values.ts b/languages/typescript/packages/recipher-js/src/values.ts index 5d582311e..68a88f843 100644 --- a/languages/typescript/packages/recipher-js/src/values.ts +++ b/languages/typescript/packages/recipher-js/src/values.ts @@ -50,7 +50,7 @@ export type { Scalar, } from './value-types' -/** A value that `encrypt` takes: one scalar, or a `Json` document. */ +/** A value that `encrypt` accepts: one scalar, or a `Json` document. */ export type Value = Native.Value /** The constructor of a wrapper class. */ diff --git a/languages/typescript/packages/recipher-js/type-tests/records.ts b/languages/typescript/packages/recipher-js/type-tests/records.ts index 3b920f548..4dc2cca9e 100644 --- a/languages/typescript/packages/recipher-js/type-tests/records.ts +++ b/languages/typescript/packages/recipher-js/type-tests/records.ts @@ -32,8 +32,8 @@ check< > >() -// A field that takes a null may be null; a sealed null is stored like a -// value, a SQL null is a null in the stored row. +// A field that accepts a null may be null. A sealed null is stored like a +// value. A SQL null is a null in the stored row. const nullable = record('n', { sealed: encrypt(kinds.int64, { index: ['equality'], null: 'sealed' }), sql: encrypt(kinds.string, { null: 'sql' }), @@ -95,7 +95,7 @@ const row: Plaintext = { notes: 'c', } -// encrypt and decrypt carry the record's types, one row or many. +// encrypt and decrypt keep the record's types, for one row or for an array. const one = await keyset.encrypt(user, row) check, RecipherError>>>() const many = await keyset.encrypt(user, [row, row]) From ea69a413724822b44794a3703dcda39d11581aa3 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 20:57:59 +1100 Subject: [PATCH 5/7] fix(recipher-js): error messages for records in the SDK's own words A TypeScript developer reads these messages without knowing the engine. Several messages stated a rule, such as "a row is an object of the record's fields". Each message now says what was wrong with the declaration, the row, or the stored row that was passed. The README says "encrypted field" and "index term", so the messages now use those words in place of "sealed field", "output", and "term". No error code, error field, or refusal changes. Only the text changes. - `not_a_record`, `declaration`, and `not_a_row` say what the value is not. - `record_name` and `context` name the record's name and the field path. The help of `record_name` says "contains". - `no_field` says "encrypted field". - `field_type` puts the field's declared kind in backticks. - Each detail of `not_a_stored_row` is a clause that says what is wrong with the stored row. --- .../packages/recipher-js/crate/src/error.rs | 34 +++++++++---------- .../packages/recipher-js/crate/src/record.rs | 24 ++++++++----- 2 files changed, 33 insertions(+), 25 deletions(-) diff --git a/languages/typescript/packages/recipher-js/crate/src/error.rs b/languages/typescript/packages/recipher-js/crate/src/error.rs index 365b72f7d..a9697a233 100644 --- a/languages/typescript/packages/recipher-js/crate/src/error.rs +++ b/languages/typescript/packages/recipher-js/crate/src/error.rs @@ -114,22 +114,22 @@ pub(crate) enum Error { )] NoTesting, /// A declaration that `record(..)` did not make. - #[error("the value is not a record")] + #[error("the value given as a record is not a record declaration")] #[diagnostic( code(recipher_js::not_a_record), - help("Declare a record with record(..).") + help("Declare a record with `record(..)`.") )] NotARecord, /// A field declared with something other than `encrypt(..)` or /// `passthrough()`. - #[error("a field is declared with encrypt(..) or passthrough()")] + #[error("the field is not declared with `encrypt(..)` or `passthrough()`")] #[diagnostic(code(recipher_js::declaration))] Declaration, /// A field whose name the engine reserves. - #[error("the field's name is one the engine reserves")] + #[error("the field's name is one that the engine reserves")] #[diagnostic( code(recipher_js::reserved_field), - help("Name the field something else.") + help("Give the field another name.") )] ReservedField, /// A field's kind that is not one of `kinds`. @@ -150,32 +150,32 @@ pub(crate) enum Error { /// A context is a value that a ciphertext is bound to, and decrypting /// needs the same context. A field's context is its field path: the /// record's name, then the field's name. - #[error("the field path could not be written")] + #[error("the record's name and the field's name could not be written as a field path")] #[diagnostic(code(recipher_js::context))] Context, /// A record name the engine refuses as a segment of a field path. - #[error("the record name is not a plain segment of a field path")] + #[error("the engine refuses the record name as the first part of a field path")] #[diagnostic( code(recipher_js::record_name), - help("Use a record name that is not empty and holds no character the engine refuses in a field path, such as `/`.") + help("Use a record name that is not empty and contains no character that the engine refuses in a field path, such as `/`.") )] RecordName, /// A field name that the record does not encrypt. The record does not /// declare the name, the name is a passthrough field's, or the name is /// not a string. A passthrough field is stored as given, without /// encryption. - #[error("the record declares no sealed field of that name")] + #[error("the record declares no encrypted field of that name")] #[diagnostic( code(recipher_js::no_field), - help("Name a field the record declares with encrypt(..). A passthrough field has no ciphertext.") + help("Name a field that the record declares with `encrypt(..)`. A passthrough field has no ciphertext.") )] NoField, /// A row that is not an object of the record's fields. - #[error("a row is an object of the record's fields")] + #[error("the row is not an object with the record's fields")] #[diagnostic(code(recipher_js::not_a_row))] NotARow, /// A row's value that is not of its field's kind. - #[error("the value is not of the field's kind, {kind}, or does not fit it")] + #[error("the value is not of the field's kind, `{kind}`, or does not fit that kind")] #[diagnostic(code(recipher_js::field_type))] FieldType { kind: ValueKind }, /// A stored row that does not have the record's shape. A stored row is @@ -184,7 +184,7 @@ pub(crate) enum Error { #[diagnostic(code(recipher_js::not_a_stored_row))] NotAStoredRow { what: &'static str }, /// A stored row from the engine that the SDK cannot read. - #[error("the engine's stored row does not have the shape the SDK reads: {what}")] + #[error("the engine's stored row does not have the shape that the SDK reads: {what}")] #[diagnostic( code(recipher_js::engine_result), help("Report this as a bug in @cipherstash/recipher.") @@ -702,14 +702,14 @@ mod tests { Error::NoTesting => { Some("Build it with `pnpm --filter @cipherstash/recipher build:debug`.") } - Error::NotARecord => Some("Declare a record with record(..)."), - Error::ReservedField => Some("Name the field something else."), + Error::NotARecord => Some("Declare a record with `record(..)`."), + Error::ReservedField => Some("Give the field another name."), Error::Null { .. } => Some("A null mode is `sealed` or `sql`."), Error::RecordName => Some( - "Use a record name that is not empty and holds no character the engine refuses in a field path, such as `/`.", + "Use a record name that is not empty and contains no character that the engine refuses in a field path, such as `/`.", ), Error::NoField => Some( - "Name a field the record declares with encrypt(..). A passthrough field has no ciphertext.", + "Name a field that the record declares with `encrypt(..)`. A passthrough field has no ciphertext.", ), Error::EngineResult { .. } | Error::NoResult | Error::BuildValue => { Some("Report this as a bug in @cipherstash/recipher.") diff --git a/languages/typescript/packages/recipher-js/crate/src/record.rs b/languages/typescript/packages/recipher-js/crate/src/record.rs index 7ab6699e5..94277ceaa 100644 --- a/languages/typescript/packages/recipher-js/crate/src/record.rs +++ b/languages/typescript/packages/recipher-js/crate/src/record.rs @@ -543,15 +543,19 @@ fn stored_tree(plan: &RecordPlan, row: &OwnedFrame) -> Outcome .in_record(&plan.name) .at_field(field) }; - let stored = entries(row) - .ok_or_else(|| misfit(None, "a stored row is an object of the record's fields"))?; + let stored = entries(row).ok_or_else(|| { + misfit( + None, + "the stored row is not an object with the record's fields", + ) + })?; let mut tree = Vec::with_capacity(stored.len()); for (name, value) in stored { let field = plan .fields .iter() .find(|field| field.name == name) - .ok_or_else(|| misfit(Some(&name), "a field the record does not declare"))?; + .ok_or_else(|| misfit(Some(&name), "the record does not declare this field"))?; if field.passthrough { let node = CipherText::Passthrough(PassthroughFrame(value.frame().as_bytes().to_vec())); tree.push(( @@ -567,13 +571,14 @@ fn stored_tree(plan: &RecordPlan, row: &OwnedFrame) -> Outcome let outputs = entries(&value).ok_or_else(|| { misfit( Some(&name), - "a sealed field is an object of its ciphertext and its terms", + "an encrypted field is not an object with its ciphertext and its index terms", ) })?; let mut nodes = Vec::with_capacity(outputs.len()); for (key, output) in outputs { - let bytes = bytes_of(&output) - .ok_or_else(|| misfit(Some(&name), "an output that is not bytes"))?; + let bytes = bytes_of(&output).ok_or_else(|| { + misfit(Some(&name), "a property of an encrypted field is not bytes") + })?; if key == CIPHERTEXT { let ciphertext = stack_encrypt::Ciphertext::from_bytes(&bytes).map_err(|error| { @@ -592,10 +597,13 @@ fn stored_tree(plan: &RecordPlan, row: &OwnedFrame) -> Outcome .iter() .find(|index| index_name(index) == Some(key.as_str())) .ok_or_else(|| { - misfit(Some(&name), "a term of an index the field does not declare") + misfit( + Some(&name), + "an index term is for an index that the field does not declare", + ) })?; let term = vitaminc_aead::to_frame(bytes.as_slice()) - .map_err(|_| misfit(Some(&name), "a term that is not bytes"))?; + .map_err(|_| misfit(Some(&name), "an index term could not be read"))?; nodes.push(( index.key().to_owned(), CipherText::Passthrough(PassthroughFrame(term.risky_ref().to_vec())), From 9aff9246cda83ab50bc12efa19080604490b45f0 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 29 Nov 2026 17:43:32 +1100 Subject: [PATCH 6/7] fix(recipher-js): name a field's unknown null mode recipher_js::null_mode A record field whose null mode is neither "sealed" nor "sql" was refused with recipher_js::null. A lone null value passed to encrypt is refused with recipher_js::null_value. The two codes read as if they were about the same thing. The field's error is now recipher_js::null_mode, which names the setting that is wrong, and a test checks the code and that the error names the record and the field. --- .../packages/recipher-js/crate/src/error.rs | 13 ++++++++----- .../packages/recipher-js/crate/src/record.rs | 2 +- .../packages/recipher-js/crate/src/record_tests.rs | 13 +++++++++++++ 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/languages/typescript/packages/recipher-js/crate/src/error.rs b/languages/typescript/packages/recipher-js/crate/src/error.rs index 82aec141f..820168b5d 100644 --- a/languages/typescript/packages/recipher-js/crate/src/error.rs +++ b/languages/typescript/packages/recipher-js/crate/src/error.rs @@ -163,8 +163,11 @@ pub(crate) enum Error { /// A field's null mode that the engine does not have. A null mode says /// how the engine stores a field's null. #[error("`{mode}` is not a null mode")] - #[diagnostic(code(recipher_js::null), help("A null mode is `sealed` or `sql`."))] - Null { mode: String }, + #[diagnostic( + code(recipher_js::null_mode), + help("A null mode is `sealed` or `sql`.") + )] + NullMode { mode: String }, /// A field path that could not be written as a context. /// /// A context is a value that a ciphertext is bound to, and decrypting @@ -655,7 +658,7 @@ mod tests { Error::ReservedField, Error::Kind { name: name() }, Error::Index { name: name() }, - Error::Null { mode: name() }, + Error::NullMode { mode: name() }, Error::Context, Error::RecordName, Error::NoField, @@ -691,7 +694,7 @@ mod tests { | Error::ReservedField | Error::Kind { .. } | Error::Index { .. } - | Error::Null { .. } + | Error::NullMode { .. } | Error::Context | Error::RecordName | Error::NoField @@ -733,7 +736,7 @@ mod tests { } Error::NotARecord => Some("Declare a record with `record(..)`."), Error::ReservedField => Some("Give the field another name."), - Error::Null { .. } => Some("A null mode is `sealed` or `sql`."), + Error::NullMode { .. } => Some("A null mode is `sealed` or `sql`."), Error::RecordName => Some( "Use a record name that is not empty and contains no character that the engine refuses in a field path, such as `/`.", ), diff --git a/languages/typescript/packages/recipher-js/crate/src/record.rs b/languages/typescript/packages/recipher-js/crate/src/record.rs index 94277ceaa..9fae06b04 100644 --- a/languages/typescript/packages/recipher-js/crate/src/record.rs +++ b/languages/typescript/packages/recipher-js/crate/src/record.rs @@ -306,7 +306,7 @@ fn field_of( [NullMode::Sealed, NullMode::Sql] .into_iter() .find(|known| known.name() == mode) - .ok_or_else(|| at(Error::Null { mode }))?, + .ok_or_else(|| at(Error::NullMode { mode }))?, ), }; let outputs = if passthrough { diff --git a/languages/typescript/packages/recipher-js/crate/src/record_tests.rs b/languages/typescript/packages/recipher-js/crate/src/record_tests.rs index 27228385c..aa3f60d48 100644 --- a/languages/typescript/packages/recipher-js/crate/src/record_tests.rs +++ b/languages/typescript/packages/recipher-js/crate/src/record_tests.rs @@ -248,6 +248,19 @@ fn the_engine_refuses_a_declaration_naming_the_record_and_the_field() { assert_eq!(unknown.code, "recipher_js::kind"); } +#[test] +fn a_null_mode_the_engine_does_not_have_is_refused_naming_the_field() { + let refused = plan(json!({ + "type": "record", + "name": "t", + "fields": { "n": { "type": "sealed", "kind": { "name": "int32" }, "null": "seled" } }, + })) + .unwrap_err(); + assert_eq!(refused.code, "recipher_js::null_mode"); + assert_eq!(refused.field.as_deref(), Some("n")); + assert_eq!(refused.record.as_deref(), Some("t")); +} + #[test] fn a_json_field_needs_the_eql_extension() { let refused = plan(json!({ From 2ce9f4bed4113d80e842dd4ec54a59ea76d7fe4a Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 29 Nov 2026 20:48:34 +1100 Subject: [PATCH 7/7] feat(recipher-js)!: take the row first and the record in the options The record calls now take the thing to encrypt first, or the stored thing to decrypt, and an options object second: - keyset.encrypt(user, { record: UserRecord }) for a row or an array of rows, in one key request; - cipher.decrypt(stored, { record: UserRecord }) to decrypt them; - keyset.encrypt(value, { record: UserRecord, field: 'email' }) and cipher.decrypt(storedField, { record, field }) for one field. encryptField and decryptField are removed. The options are the strict object that `{ kind }` already used. A new options module decides what the call is from the keys alone. Rust tests cover every combination of keys. Four calls are the error recipher_js::options, with a help that says what to pass: - kind and record together; - field without record; - a kind given to decrypt; - a record declaration given as the first argument. A plain object with no record is still recipher_js::plain_object. Its help now names `{ record: UserRecord }`. decrypt now refuses a second argument that is not options, as encrypt does. The overloads stop the same calls compiling. RecordOptions and FieldOptions mark kind as never. EncryptOptions marks record and field as never. The README's Records example now defines everything it uses and runs as written. The binding interface goes to 3. --- .../typescript/packages/recipher-js/README.md | 56 ++- .../__tests__/addon/builds.test.ts | 7 +- .../__tests__/addon/records.test.ts | 344 ++++++++++++++---- .../recipher-js/__tests__/addon/value.test.ts | 9 +- .../packages/recipher-js/crate/src/cipher.rs | 217 +++++------ .../recipher-js/crate/src/ciphertext.rs | 39 +- .../packages/recipher-js/crate/src/error.rs | 45 ++- .../packages/recipher-js/crate/src/js.rs | 23 -- .../packages/recipher-js/crate/src/lib.rs | 3 +- .../packages/recipher-js/crate/src/options.rs | 280 ++++++++++++++ .../recipher-js/crate/src/record_tests.rs | 4 +- .../packages/recipher-js/native-header.d.ts | 2 + .../packages/recipher-js/native.d.ts | 90 +++-- .../packages/recipher-js/src/binding.ts | 2 +- .../packages/recipher-js/src/index.ts | 15 + .../packages/recipher-js/src/kinds.ts | 9 +- .../packages/recipher-js/src/record-types.ts | 35 ++ .../packages/recipher-js/src/record.ts | 9 +- .../recipher-js/type-tests/records.ts | 145 ++++++-- 19 files changed, 978 insertions(+), 356 deletions(-) create mode 100644 languages/typescript/packages/recipher-js/crate/src/options.rs diff --git a/languages/typescript/packages/recipher-js/README.md b/languages/typescript/packages/recipher-js/README.md index 65003a43f..bc700809a 100644 --- a/languages/typescript/packages/recipher-js/README.md +++ b/languages/typescript/packages/recipher-js/README.md @@ -92,6 +92,7 @@ The value bridge converts JavaScript values in both directions: 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. + `{ record }` in the options encrypts the object as a row of a record: see [Records](#records). `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). @@ -139,7 +140,8 @@ const opened = (await cipher.decrypt(age)).unwrap() - 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`. +- For one value, the options take only `kind`. + `record` and `field` are for a row: see [Records](#records). Any other key is an `Err` with the code `recipher_js::options`, so an option that this version does not have is never ignored. `null` as the options is refused with the same code. - A kind from `kinds` takes no `null`, as a Rust type that is not an `Option` takes no `None`. @@ -260,23 +262,42 @@ A record declares each field of a row once. A field is encrypted, encrypted with indexes, or passed through unencrypted. ```ts -import { encrypt, kinds, passthrough, record } from '@cipherstash/recipher' +import { Cipher, encrypt, kinds, passthrough, record } from '@cipherstash/recipher' -export const user = record('users', { +export const UserRecord = record('users', { id: passthrough(), email: encrypt(kinds.string, { index: ['equality'] }), - name: encrypt(kinds.string, { index: ['match'] }), age: encrypt(kinds.int32, { index: ['equality'], null: 'sealed' }), - notes: encrypt(kinds.string, { null: 'sql' }), }) +const cipher = (await Cipher.create({ records: [UserRecord] })).unwrap() +const keyset = cipher.defaultKeyset() + +const user = { id: 1n, email: 'ada@example.com', age: 36n } + // One row, or an array of rows in one key request. -const stored = await keyset.encrypt(user, row) -const opened = await cipher.decrypt(user, stored.unwrap()) +const stored = (await keyset.encrypt(user, { record: UserRecord })).unwrap() +const opened = (await cipher.decrypt(stored, { record: UserRecord })).unwrap() + +// One field of a row. +const email = (await keyset.encrypt('ada@example.com', { record: UserRecord, field: 'email' })).unwrap() +const sameEmail = (await cipher.decrypt(email, { record: UserRecord, field: 'email' })).unwrap() ``` -- `keyset.encrypt(user, row)` returns a stored row. +- The first argument is the thing to encrypt, or the stored thing to decrypt. + The second argument is always an options object. + `{ kind }` is for one value. + `{ record }` is for a row. + `{ record, field }` is for one field of a row. +- `kind` and `record` together do not compile. + `field` without `record` does not compile, and a plain object with no `record` does not compile either. + When the code runs anyway, each is an `Err` whose help says what to pass. + The code is `recipher_js::options`, or `recipher_js::plain_object` for the plain object. + Any other key in the options is refused with `recipher_js::options` too. +- `keyset.encrypt(user, { record: UserRecord })` returns a stored row. A stored row is the encrypted form of a row. +- A declaration is named for what it is, such as `UserRecord`. + A row gets the plain name, such as `user`. - A declaration is a plain, frozen object: `{ type: 'record', name, fields }`. A library can read the record's name, its fields, and each field's declaration from it. - The package has an ECMAScript module (ESM) build and a CommonJS build. @@ -305,11 +326,12 @@ const opened = await cipher.decrypt(user, stored.unwrap()) A field with no null mode takes no `null`, and decrypts as `T`. So the null mode does for a field what `nullable(..)` does for one value. A field's kind is one of `kinds`. - `encrypt(nullable(kinds.int64))` does not compile, and is an `Err` with the code `recipher_js::nullable_field` when the code runs. -- `Plaintext` is the type of a row. - `Stored` is the type of a stored row. + `encrypt(nullable(kinds.int64))` does not compile. + When the code runs anyway, it is an `Err` with the code `recipher_js::nullable_field`. +- `Plaintext` is the type of a row. + `Stored` is the type of a stored row. A row of another shape does not compile. - `stored.notes.equality` does not compile either, because `notes` declares no index. + `stored.email.match` does not compile either, because `email` declares only the `equality` index. - A passthrough field is **not encrypted and not authenticated.** Anyone with the stored row can read it, change it, or remove it. Use a passthrough field only for values that are not secret. @@ -325,17 +347,17 @@ const opened = await cipher.decrypt(user, stored.unwrap()) The values are ordinary properties. `JSON.stringify` or a spread still shows them. -To update one field of a stored row, encrypt that field on its own. +To update one field of a stored row, encrypt that field on its own, with `{ record, field }`. An array of values gives an array of stored fields, with one key request: ```ts -const email = await keyset.encryptField(user, 'email', 'ada@example.com') -const value = await cipher.decryptField(user, 'email', email.unwrap()) - -const emails = await keyset.encryptField(user, 'email', ['a@example.com', 'b@example.com']) +const emails = ( + await keyset.encrypt(['a@example.com', 'b@example.com'], { record: UserRecord, field: 'email' }) +).unwrap() ``` The stored field has the same form as that field in a whole stored row. +A passthrough field has no ciphertext, so its name is refused as a `field`. ## Results, not exceptions 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 3d372aa6c..74e69bfa6 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/builds.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/builds.test.ts @@ -36,10 +36,11 @@ const read = cjs.Ciphertext.fromBytes(sealed.toBytes()).unwrap() const fromCjs_ = cjs.Ciphertext.fromBytes(new Uint8Array(1)) const fromEsm_ = esm.Ciphertext.fromBytes(new Uint8Array(1)) const okCjs = cjs.Ciphertext.fromBytes(sealed.toBytes()) -const people = cjs.record('people', { email: cjs.encrypt(cjs.kinds.string, { index: ['equality'] }) }) -const row = (await fromEsm.defaultKeyset().encrypt(people, { email: 'a@example.com' })).unwrap() +const PersonRecord = cjs.record('people', { email: cjs.encrypt(cjs.kinds.string, { index: ['equality'] }) }) +const person = { email: 'a@example.com' } +const row = (await fromEsm.defaultKeyset().encrypt(person, { record: PersonRecord })).unwrap() const out = { - recordAcrossBuilds: (await fromEsm.decrypt(people, row)).unwrap().email, + recordAcrossBuilds: (await fromEsm.decrypt(row, { record: PersonRecord })).unwrap().email, sameClasses: esm.Cipher === cjs.Cipher && esm.Ciphertext === cjs.Ciphertext, cipherIsCipher: fromCjs instanceof esm.Cipher && fromEsm instanceof cjs.Cipher, ciphertextIsCiphertext: sealed instanceof cjs.Ciphertext, diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/records.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/records.test.ts index 6e0fe9b31..1fe664e3c 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/records.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/records.test.ts @@ -14,7 +14,7 @@ import { } from '../../src/index' import { testCipher } from '../../src/testing' -const user = record('users', { +const UserRecord = record('users', { id: passthrough(), email: encrypt(kinds.string, { index: ['equality'] }), name: encrypt(kinds.string, { index: ['match'] }), @@ -23,7 +23,7 @@ const user = record('users', { notes: encrypt(kinds.string, { null: 'sql' }), }) -const ada: Plaintext = { +const user: Plaintext = { id: 7n, email: 'ada@example.com', name: 'Ada Lovelace', @@ -39,16 +39,24 @@ async function cipher(): Promise { describe('a record', () => { it('round-trips one row', async () => { const c = await cipher() - const stored = (await c.defaultKeyset().encrypt(user, ada)).unwrap() - expect((await c.decrypt(user, stored)).unwrap()).toEqual(ada) - expect((await c.defaultKeyset().decrypt(user, stored)).unwrap()).toEqual( - ada, + const stored = ( + await c.defaultKeyset().encrypt(user, { record: UserRecord }) + ).unwrap() + expect((await c.decrypt(stored, { record: UserRecord })).unwrap()).toEqual( + user, ) + expect( + ( + await c.defaultKeyset().decrypt(stored, { record: UserRecord }) + ).unwrap(), + ).toEqual(user) }) it('stores a ciphertext and the declared terms for each sealed field', async () => { const c = await cipher() - const stored = (await c.defaultKeyset().encrypt(user, ada)).unwrap() + const stored = ( + await c.defaultKeyset().encrypt(user, { record: UserRecord }) + ).unwrap() expect(stored.id).toBe(7n) expect(Object.keys(stored.email).sort()).toEqual(['ciphertext', 'equality']) expect(Object.keys(stored.name).sort()).toEqual(['ciphertext', 'match']) @@ -63,7 +71,9 @@ describe('a record', () => { it('derives the same equality term for the same value', async () => { const c = await cipher() const keyset = c.defaultKeyset() - const [a, b] = (await keyset.encrypt(user, [ada, ada])).unwrap() + const [a, b] = ( + await keyset.encrypt([user, user], { record: UserRecord }) + ).unwrap() expect(Buffer.from(a?.email.equality ?? [])).toEqual( Buffer.from(b?.email.equality ?? []), ) @@ -74,19 +84,30 @@ describe('a record', () => { it('takes a null where the field declares one', async () => { const c = await cipher() - const row = { ...ada, age: null, notes: 'present' } - const stored = (await c.defaultKeyset().encrypt(user, row)).unwrap() + const row = { ...user, age: null, notes: 'present' } + const stored = ( + await c.defaultKeyset().encrypt(row, { record: UserRecord }) + ).unwrap() // A sealed null is stored like a value. expect(stored.age).not.toBeNull() - expect((await c.decrypt(user, stored)).unwrap()).toEqual(row) + expect((await c.decrypt(stored, { record: UserRecord })).unwrap()).toEqual( + row, + ) }) it('round-trips an array of rows, in order', async () => { const c = await cipher() - const rows = [ada, { ...ada, id: 8n, email: 'grace@example.com', age: 45n }] - const stored = (await c.defaultKeyset().encrypt(user, rows)).unwrap() + const rows = [ + user, + { ...user, id: 8n, email: 'grace@example.com', age: 45n }, + ] + const stored = ( + await c.defaultKeyset().encrypt(rows, { record: UserRecord }) + ).unwrap() expect(stored).toHaveLength(2) - expect((await c.decrypt(user, stored)).unwrap()).toEqual(rows) + expect((await c.decrypt(stored, { record: UserRecord })).unwrap()).toEqual( + rows, + ) }) it('holds every kind', async () => { @@ -113,8 +134,10 @@ describe('a record', () => { blob: new Uint8Array([1, 2, 3]), } const c = await cipher() - const stored = (await c.defaultKeyset().encrypt(everything, row)).unwrap() - const opened = (await c.decrypt(everything, stored)).unwrap() + const stored = ( + await c.defaultKeyset().encrypt(row, { record: everything }) + ).unwrap() + const opened = (await c.decrypt(stored, { record: everything })).unwrap() expect(opened.text).toBe('x') expect(opened.flag).toBe(true) expect(opened.small).toBe(255n) @@ -134,32 +157,44 @@ describe('one field', () => { const c = await cipher() const keyset = c.defaultKeyset() const email = ( - await keyset.encryptField(user, 'email', 'new@example.com') + await keyset.encrypt('new@example.com', { + record: UserRecord, + field: 'email', + }) ).unwrap() expect(Object.keys(email).sort()).toEqual(['ciphertext', 'equality']) - expect((await c.decryptField(user, 'email', email)).unwrap()).toBe( - 'new@example.com', - ) + expect( + (await c.decrypt(email, { record: UserRecord, field: 'email' })).unwrap(), + ).toBe('new@example.com') // The field's equality term is the term that a whole row stores for the // value. const row = ( - await keyset.encrypt(user, { ...ada, email: 'new@example.com' }) + await keyset.encrypt( + { ...user, email: 'new@example.com' }, + { record: UserRecord }, + ) ).unwrap() expect(Buffer.from(email.equality)).toEqual(Buffer.from(row.email.equality)) // A whole row accepts the field in place of its own field. const updated = { ...row, email } - expect((await c.decrypt(user, updated)).unwrap().email).toBe( - 'new@example.com', - ) + expect( + (await c.decrypt(updated, { record: UserRecord })).unwrap().email, + ).toBe('new@example.com') }) it("opens alone from a whole row's stored field", async () => { const c = await cipher() - const row = (await c.defaultKeyset().encrypt(user, ada)).unwrap() + const row = ( + await c.defaultKeyset().encrypt(user, { record: UserRecord }) + ).unwrap() expect( - (await c.defaultKeyset().decryptField(user, 'name', row.name)).unwrap(), + ( + await c + .defaultKeyset() + .decrypt(row.name, { record: UserRecord, field: 'name' }) + ).unwrap(), ).toBe('Ada Lovelace') }) @@ -170,19 +205,19 @@ describe('one field', () => { }) const c = await cipher() const row = ( - await c.defaultKeyset().encrypt(pair, { a: 'x', b: 'y' }) + await c.defaultKeyset().encrypt({ a: 'x', b: 'y' }, { record: pair }) ).unwrap() // The two fields have the same shape, so this compiles and the engine // reads it. Only the context differs. The key service refuses the key. // The key service binds a key to the field path that the value was // encrypted under. - const result = await c.decryptField(pair, 'a', row.b) + const result = await c.decrypt(row.b, { record: pair, field: 'a' }) expect(result.err()?.code).toBe('stack_kms::retrieve_key_failed') // A row decrypted under a record of another name is refused the same // way. const other = record('other', pair.fields) - const moved = await c.decrypt(other, row) + const moved = await c.decrypt(row, { record: other }) expect(moved.err()?.code).toBe('stack_kms::retrieve_key_failed') expect(moved.err()?.record).toBe('other') }) @@ -191,36 +226,44 @@ describe('one field', () => { const c = await cipher() const keyset = c.defaultKeyset() const emails = ( - await keyset.encryptField(user, 'email', [ - 'a@example.com', - 'b@example.com', - ]) + await keyset.encrypt(['a@example.com', 'b@example.com'], { + record: UserRecord, + field: 'email', + }) ).unwrap() expect(emails).toHaveLength(2) - expect((await c.decryptField(user, 'email', emails)).unwrap()).toEqual([ - 'a@example.com', - 'b@example.com', - ]) + expect( + ( + await c.decrypt(emails, { record: UserRecord, field: 'email' }) + ).unwrap(), + ).toEqual(['a@example.com', 'b@example.com']) }) it('stores a SQL null field alone as null', async () => { const c = await cipher() const notes = ( - await c.defaultKeyset().encryptField(user, 'notes', null) + await c + .defaultKeyset() + .encrypt(null, { record: UserRecord, field: 'notes' }) ).unwrap() expect(notes).toBeNull() - expect((await c.decryptField(user, 'notes', notes)).unwrap()).toBeNull() + expect( + (await c.decrypt(notes, { record: UserRecord, field: 'notes' })).unwrap(), + ).toBeNull() }) it('refuses a field the record passes through or does not declare, naming it', async () => { const keyset = (await cipher()).defaultKeyset() // @ts-expect-error: id is passed through. - const passed = await keyset.encryptField(user, 'id', 1n) + const passed = await keyset.encrypt(1n, { record: UserRecord, field: 'id' }) expect(passed.err()?.code).toBe('recipher_js::no_field') expect(passed.err()?.field).toBe('id') expect(passed.err()?.record).toBe('users') // @ts-expect-error: no such field. - const missing = await keyset.encryptField(user, 'missing', 'x') + const missing = await keyset.encrypt('x', { + record: UserRecord, + field: 'missing', + }) expect(missing.err()?.field).toBe('missing') }) }) @@ -228,16 +271,18 @@ describe('one field', () => { describe('a decrypted row', () => { it('names its fields and hides their values when inspected', async () => { const c = await cipher() - const stored = (await c.defaultKeyset().encrypt(user, ada)).unwrap() - const opened = (await c.decrypt(user, stored)).unwrap() + const stored = ( + await c.defaultKeyset().encrypt(user, { record: UserRecord }) + ).unwrap() + const opened = (await c.decrypt(stored, { record: UserRecord })).unwrap() const shown = inspect(opened) expect(shown).toContain('email: [hidden]') expect(shown).not.toContain('ada@example.com') expect(shown).not.toContain('Lovelace') // The fields themselves are as they were. expect(opened.email).toBe('ada@example.com') - expect(Object.keys(opened)).toEqual(Object.keys(ada)) - expect({ ...opened }).toEqual(ada) + expect(Object.keys(opened)).toEqual(Object.keys(user)) + expect({ ...opened }).toEqual(user) }) }) @@ -246,7 +291,7 @@ describe('refusals', () => { const c = await cipher() const result = await c .defaultKeyset() - .encrypt(user, { ...ada, age: 2n ** 40n }) + .encrypt({ ...user, age: 2n ** 40n }, { record: UserRecord }) expect(result.err()?.code).toBe('recipher_js::field_type') expect(result.err()?.field).toBe('age') expect(result.err()?.record).toBe('users') @@ -256,25 +301,26 @@ describe('refusals', () => { const c = await cipher() const result = await c .defaultKeyset() - .encrypt(user, { ...ada, age: 2n ** 128n }) + .encrypt({ ...user, age: 2n ** 128n }, { record: UserRecord }) expect(result.err()?.code).toBe('ERR_INTEGER_RANGE') expect(result.err()?.field).toBe('age') }) it('a null where the field takes none', async () => { const keyset = (await cipher()).defaultKeyset() + const row = { ...user, email: null } // @ts-expect-error: email takes no null. - const result = await keyset.encrypt(user, { ...ada, email: null }) + const result = await keyset.encrypt(row, { record: UserRecord }) expect(result.isErr()).toBe(true) }) it('a row with a field the record does not declare', async () => { const c = await cipher() - const row = { ...ada, extra: 'x' } + const row = { ...user, extra: 'x' } // A row widened past the record's type, as untyped input would be. const result = await c .defaultKeyset() - .encrypt(user, row as Plaintext) + .encrypt(row as Plaintext, { record: UserRecord }) expect(result.isErr()).toBe(true) }) @@ -288,7 +334,7 @@ describe('refusals', () => { expect(checked.err()?.record).toBe('bad') const c = await cipher() - const result = await c.defaultKeyset().encrypt(bad, { n: 1n }) + const result = await c.defaultKeyset().encrypt({ n: 1n }, { record: bad }) expect(result.err()?.code).toBe('stack_encrypt::dynamic_plan') }) @@ -296,7 +342,7 @@ describe('refusals', () => { const bad = record('bad', { flag: encrypt(kinds.boolean, { index: ['ore'] }), }) - const result = await Cipher.create({ records: [user, bad] }) + const result = await Cipher.create({ records: [UserRecord, bad] }) expect(result.err()?.code).toBe('stack_encrypt::dynamic_plan') expect(result.err()?.record).toBe('bad') }) @@ -335,33 +381,209 @@ describe('refusals', () => { it('a row with a record that is not a declaration', async () => { const keyset = (await cipher()).defaultKeyset() - // @ts-expect-error: the first argument is not a record. - const result = await keyset.encrypt({ name: 'users' }, ada) + // @ts-expect-error: the record is not a declaration. + const result = await keyset.encrypt(user, { record: { name: 'users' } }) expect(result.err()?.code).toBe('recipher_js::not_a_record') }) it('a stored row with a term of an index the field does not declare, naming the field', async () => { const c = await cipher() - const stored = (await c.defaultKeyset().encrypt(user, ada)).unwrap() + const stored = ( + await c.defaultKeyset().encrypt(user, { record: UserRecord }) + ).unwrap() const stray = { ...stored, email: { ...stored.email, match: new Uint8Array([1, 2, 3]) }, } - const result = await c.decrypt(user, stray) + const result = await c.decrypt(stray, { record: UserRecord }) expect(result.err()?.code).toBe('recipher_js::not_a_stored_row') expect(result.err()?.field).toBe('email') }) it('a stored row altered in storage does not open', async () => { const c = await cipher() - const stored = (await c.defaultKeyset().encrypt(user, ada)).unwrap() + const stored = ( + await c.defaultKeyset().encrypt(user, { record: UserRecord }) + ).unwrap() const ciphertext = Uint8Array.from(stored.email.ciphertext) const last = ciphertext.length - 1 ciphertext[last] = (ciphertext[last] ?? 0) ^ 1 - const result = await c.decrypt(user, { - ...stored, - email: { ...stored.email, ciphertext }, - }) + const result = await c.decrypt( + { + ...stored, + email: { ...stored.email, ciphertext }, + }, + { record: UserRecord }, + ) expect(result.err()?.code).toBe('stack_encrypt::aead') }) }) + +describe('the options name what the first argument is', () => { + // A row and its record, as the README writes them. + const UserRow = record('users', { + id: passthrough(), + email: encrypt(kinds.string, { index: ['equality'] }), + age: encrypt(kinds.int32, { index: ['equality'], null: 'sealed' }), + }) + + it('runs the README example as written', async () => { + const c = await cipher() + const keyset = c.defaultKeyset() + const UserRecord = UserRow + const user = { id: 1n, email: 'ada@example.com', age: 36n } + + const stored = (await keyset.encrypt(user, { record: UserRecord })).unwrap() + const opened = (await c.decrypt(stored, { record: UserRecord })).unwrap() + expect(opened).toEqual(user) + + const email = ( + await keyset.encrypt('ada@example.com', { + record: UserRecord, + field: 'email', + }) + ).unwrap() + expect( + (await c.decrypt(email, { record: UserRecord, field: 'email' })).unwrap(), + ).toBe('ada@example.com') + + const age = (await keyset.encrypt(34n, { kind: kinds.uint64 })).unwrap() + expect((await c.decrypt(age)).unwrap()).toBe(34n) + }) + + it('refuses kind and record together, saying what to pass', async () => { + const c = await cipher() + const keyset = c.defaultKeyset() + const user = { id: 1n, email: 'ada@example.com', age: 36n } + for (const call of [ + // @ts-expect-error: kind and record together. + keyset.encrypt(user, { record: UserRow, kind: kinds.string }), + // @ts-expect-error: kind and record together, for one field. + keyset.encrypt('x', { + record: UserRow, + field: 'email', + kind: kinds.string, + }), + // @ts-expect-error: kind and record together, to decrypt. + c.decrypt(user, { record: UserRow, kind: kinds.string }), + ]) { + const error = (await call).err() + expect(error?.code).toBe('recipher_js::options') + expect(error?.help).toContain('`kind` for one value') + expect(error?.help).toContain('`record` for a row') + } + }) + + it('refuses field without record, saying what to pass', async () => { + const c = await cipher() + const keyset = c.defaultKeyset() + for (const call of [ + // @ts-expect-error: field without record. + keyset.encrypt('x', { field: 'email' }), + // @ts-expect-error: field without record, with a kind. + keyset.encrypt('x', { kind: kinds.string, field: 'email' }), + // @ts-expect-error: field without record, to decrypt. + c.decrypt('x', { field: 'email' }), + ]) { + const error = (await call).err() + expect(error?.code).toBe('recipher_js::options') + expect(error?.help).toContain("{ record: UserRecord, field: 'email' }") + } + }) + + it('refuses a plain object with no record, saying to pass its record', async () => { + const keyset = (await cipher()).defaultKeyset() + const user = { id: 1n, email: 'ada@example.com', age: 36n } + for (const call of [ + // @ts-expect-error: a plain object is not a value. + keyset.encrypt(user), + // @ts-expect-error: a plain object is not a value of a kind. + keyset.encrypt(user, { kind: kinds.string }), + // @ts-expect-error: an array of plain objects is not an array of values. + keyset.encrypt([user]), + ]) { + const error = (await call).err() + expect(error?.code).toBe('recipher_js::plain_object') + expect(error?.help).toContain('{ record: UserRecord }') + expect(error?.help).toContain('json(..)') + // The error does not quote the row. + expect(JSON.stringify(error)).not.toContain('ada@example.com') + } + // Options with none of the keys are refused as options. + // @ts-expect-error: the options have no key. + const empty = await keyset.encrypt(user, {}) + expect(empty.err()?.code).toBe('recipher_js::options') + expect(empty.err()?.help).toContain('{ record: UserRecord }') + }) + + it('refuses a record declaration given first, saying where it goes', async () => { + const c = await cipher() + const keyset = c.defaultKeyset() + const user = { id: 1n, email: 'ada@example.com', age: 36n } + const stored = (await keyset.encrypt(user, { record: UserRow })).unwrap() + for (const call of [ + // @ts-expect-error: the record goes in the options. + keyset.encrypt(UserRow, user), + // @ts-expect-error: the record goes in the options. + c.decrypt(UserRow, stored), + // @ts-expect-error: the record goes in the options. + keyset.decrypt(UserRow, stored), + ]) { + const error = (await call).err() + expect(error?.code).toBe('recipher_js::options') + expect(error?.help).toContain( + 'keyset.encrypt(user, { record: UserRecord })', + ) + expect(JSON.stringify(error)).not.toContain('ada@example.com') + } + }) + + it('refuses a kind given to decrypt, and keys that no call takes', async () => { + const c = await cipher() + const keyset = c.defaultKeyset() + const sealed = (await keyset.encrypt('x')).unwrap() + // @ts-expect-error: decrypt takes no kind. + const kind = await c.decrypt(sealed, { kind: kinds.string }) + expect(kind.err()?.code).toBe('recipher_js::options') + expect(kind.err()?.help).toContain('Ciphertext.fromBytes') + const user = { id: 1n, email: 'ada@example.com', age: 36n } + // A context will be a key of its own later. Today it is refused. + // @ts-expect-error: the options take no context yet. + const context = await keyset.encrypt(user, { + record: UserRow, + context: 'tenant', + }) + expect(context.err()?.code).toBe('recipher_js::options') + for (const options of [null, 'x', 0, [UserRow], { record: null }]) { + // @ts-expect-error: not options. + const result = await c.decrypt(sealed, options) + expect(result.err()?.code).toBe('recipher_js::options') + } + }) + + it('reads a key whose value is undefined as absent', async () => { + const c = await cipher() + const keyset = c.defaultKeyset() + const user = { id: 1n, email: 'ada@example.com', age: 36n } + // The package's types are compiled with `exactOptionalPropertyTypes`, + // so TypeScript refuses these keys. JavaScript can still pass them. + const rowOptions = { record: UserRow, field: undefined } + // @ts-expect-error: an absent key is left out, not set to undefined. + const stored = (await keyset.encrypt(user, rowOptions)).unwrap() + expect( + // @ts-expect-error: an absent key is left out, not set to undefined. + (await c.decrypt(stored, { record: UserRow, kind: undefined })).unwrap(), + ).toEqual(user) + }) + + it('reads no option from a polluted prototype', async () => { + const keyset = (await cipher()).defaultKeyset() + // An object whose `record` is on its prototype, not its own. + const options = Object.create({ record: UserRow }) as never + const result = await keyset.encrypt( + { id: 1n, email: 'ada@example.com', age: 36n }, + options, + ) + expect(result.err()?.code).toBe('recipher_js::options') + }) +}) 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 715313824..cf971971a 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/value.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/value.test.ts @@ -208,13 +208,16 @@ describe('every other call returns or resolves to a Result', () => { expect((await loose.decrypt()).err()?.code).toBe( 'recipher_js::not_a_ciphertext', ) - // The second argument of `encrypt` is its options, so a stray one is - // refused. An argument after the options is ignored. + // The second argument of `encrypt` and `decrypt` 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') + expect((await loose.decrypt(sealed, 'extra')).err()?.code).toBe( + 'recipher_js::options', + ) + expect((await loose.decrypt(sealed, undefined, '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/crate/src/cipher.rs b/languages/typescript/packages/recipher-js/crate/src/cipher.rs index 22d1133bf..bcecd4e22 100644 --- a/languages/typescript/packages/recipher-js/crate/src/cipher.rs +++ b/languages/typescript/packages/recipher-js/crate/src/cipher.rs @@ -28,6 +28,7 @@ use crate::ciphertext::{Ciphertext, Declared}; use crate::error::{Error, RecipherErrorFields}; use crate::js; use crate::json::Json; +use crate::options::{self, Call, Fault, Options}; use crate::outcome::{not_made, refused, spawn, Outcome}; use crate::record::{field_value, one_field_row, open_rows, seal_rows, RecordPlan}; @@ -165,52 +166,35 @@ impl Cipher { /// ciphertexts were made under. A key request is one request to ZeroKMS /// for data keys. /// - /// With a record declaration as the first argument, `decrypt` decrypts - /// a stored row of that record, or an array of stored rows. A stored - /// row is what `keyset.encrypt` returns for a row. Node's `inspect` - /// shows a decrypted row's field names and hides their values. + /// `{ record }` decrypts a stored row of that record, or an array of + /// stored rows. A stored row is what `keyset.encrypt` returns for a row. + /// Node's `inspect` shows a decrypted row's field names and hides their + /// values. `{ record, field }` decrypts one stored field, or an array of + /// them. /// /// The promise resolves to an `Err` with the code /// `recipher_js::not_a_ciphertext` when the argument, or an element of - /// the array, is not a `Ciphertext`. The promise does not reject. + /// the array, is not a `Ciphertext`. Options other than `{ record }` or + /// `{ record, field }` are an `Err` with the code `recipher_js::options`. + /// The promise does not reject. #[napi( ts_type = "(ciphertext: Ciphertext): Promise> decrypt(ciphertexts: readonly Ciphertext[]): Promise> -decrypt(record: R, row: Stored): Promise, RecipherError>> -decrypt(record: R, rows: readonly Stored[]): Promise[], RecipherError>>" +decrypt(stored: NoInfer>, options: RecordOptions): Promise, RecipherError>> +decrypt(stored: readonly NoInfer>[], options: RecordOptions): Promise[], RecipherError>> +decrypt>(stored: NoInfer[F]>, options: FieldOptions): Promise[F], RecipherError>> +decrypt>(stored: readonly NoInfer[F]>[], options: FieldOptions): Promise[F][], RecipherError>>" )] pub fn decrypt<'e>( &self, env: &'e Env, - first: Unknown<'_>, - second: Option>, - ) -> napi::Result>> { - if js::is_record(env, &first) { - return open_rows_of(env, &self.engine, first, second, Confined::No); - } - if let Some(error) = js::second_without_record(env, &first, second.as_ref()) { - return refused(env, error); - } - open(env, &self.engine, first, Confined::No) - } - - /// Decrypts one field of a record's stored row, as `encryptField` or - /// `encrypt` stored it. An array of stored fields decrypts in one key - /// request. The promise does not reject. - #[napi( - ts_type = ">(record: R, field: F, stored: NoInfer[F]>): Promise[F], RecipherError>> -decryptField>(record: R, field: F, stored: readonly NoInfer[F]>[]): Promise[F][], RecipherError>>" - )] - pub fn decrypt_field<'e>( - &self, - env: &'e Env, - record: Unknown<'_>, - field: Unknown<'_>, stored: Unknown<'_>, + // Not an `Option`: napi reads `null` as `None`, and `null` as the + // options must be refused. A missing argument is `undefined`. + options: Unknown<'_>, ) -> napi::Result>> { - open_field(env, &self.engine, record, field, stored, Confined::No) + decrypt_with(env, &self.engine, stored, options, Confined::No) } - /// Returns the type's name. #[napi(js_name = "toString")] pub fn describe(&self) -> &'static str { @@ -242,8 +226,6 @@ impl Keyset { /// safe range is refused with the code `recipher_js::unsafe_integer`. /// The safe range is 2^53 - 1 either side of zero. Pass a `bigint` /// instead. For an array of values, the kind applies to each value. - /// Options that are not `{ kind }`, `null` included, are an `Err` with - /// the code `recipher_js::options`. /// /// `{ kind: nullable(..) }` declares a kind that also takes `null`, such /// as `{ kind: nullable(kinds.int64) }`. A value that is not `null` @@ -252,18 +234,25 @@ impl Keyset { /// not encrypt a typed null as one value yet, so today that `null` is an /// `Err` with the code `recipher_js::null_value`. /// + /// `{ record }` encrypts a row of that record, or an array of rows in + /// one key request. Each field is encrypted under its field path: the + /// record's name, then the field's name. For each encrypted field, the + /// stored row has the field's ciphertext and its index terms. + /// `{ record, field }` encrypts one field of a row, to update that field + /// alone. The result is the field's stored form, the same form as in a + /// whole stored row. An array of values returns an array of stored + /// fields, in one key request. + /// /// A value that cannot be encrypted resolves to an `Err`. For example, a - /// plain object is an `Err` with the code `recipher_js::plain_object`. - /// `null` with no kind, with a kind that is not `nullable(..)`, or with - /// `nullable(..)` of a variable-width kind such as `kinds.string`, is an - /// `Err` with the code `recipher_js::null_value`. Store a value that is - /// not there as a database `NULL`. + /// plain object with no `record` is an `Err` with the code + /// `recipher_js::plain_object`. Today every `null` is an `Err` with the + /// code `recipher_js::null_value`, `nullable(..)` included. Store a value + /// that is not there as a database `NULL`. /// - /// With a record declaration as the first argument, `encrypt` encrypts - /// a row of that record, or an array of rows in one key request. Each - /// field is encrypted under its field path: the record's name, then the - /// field's name. For each encrypted field, the stored row has the - /// field's ciphertext and its index terms. + /// Options other than `{ kind }`, `{ record }`, and `{ record, field }` + /// are an `Err` with the code `recipher_js::options`. So are `kind` and + /// `record` together, `field` without `record`, and `null` as the + /// options. The error's help says what to pass. /// /// The promise does not reject. #[napi( @@ -271,29 +260,31 @@ impl Keyset { encrypt(values: readonly V[]): Promise>[], RecipherError>> encrypt>(value: V, options: EncryptOptions): Promise>, RecipherError>> encrypt>(values: readonly V[], options: EncryptOptions): Promise>[], RecipherError>> -encrypt(record: R, row: Plaintext): Promise, RecipherError>> -encrypt(record: R, rows: readonly Plaintext[]): Promise[], RecipherError>>" +encrypt(row: NoInfer>, options: RecordOptions): Promise, RecipherError>> +encrypt(rows: readonly NoInfer>[], options: RecordOptions): Promise[], RecipherError>> +encrypt>(value: NoInfer[F]>, options: FieldOptions): Promise[F], RecipherError>> +encrypt>(values: readonly NoInfer[F]>[], options: FieldOptions): Promise[F][], RecipherError>>" )] pub fn encrypt<'e>( &self, env: &'e Env, - first: Unknown<'_>, + value: Unknown<'_>, // Not an `Option`: napi reads `null` as `None`, and `null` as the // options must be refused. A missing argument is `undefined`. - second: Unknown<'_>, + options: Unknown<'_>, ) -> napi::Result>> { - if js::is_record(env, &first) { - return seal_rows_of(env, &self.engine, first, Some(second)); - } - if let Some(error) = js::second_without_record(env, &first, Some(&second)) { - return refused(env, error); + if js::is_record(env, &value) { + return refused(env, Error::options(Fault::RecordFirst).into()); } - // With a value as the first argument, the second is its options. - let declared = match crate::ciphertext::declared_kind(env, second) { - Ok(declared) => declared, + let declared = match options::read(env, Call::Encrypt, options) { + Ok(Options::None) => None, + Ok(Options::Kind(declared)) => Some(declared), + Ok(Options::Row { record }) => return seal_rows_of(env, &self.engine, record, value), + Ok(Options::Field { record, field }) => { + return seal_field(env, &self.engine, record, field, value) + } Err(error) => return refused(env, error), }; - let value = first; let (many, values) = match js::elements(env, value) { Some(Ok(elements)) => (true, elements), Some(Err(error)) => return refused(env, error), @@ -341,73 +332,29 @@ encrypt(record: R, rows: readonly Plaintext[]): /// ciphertext of another keyset fails with the code /// `stack_encrypt::foreign_keyset`, before any key is requested. /// - /// With a record declaration as the first argument, `decrypt` decrypts - /// a stored row of that record, or an array of stored rows. + /// `{ record }` decrypts a stored row of that record, or an array of + /// stored rows. `{ record, field }` decrypts one stored field, or an + /// array of them. Options other than those are an `Err` with the code + /// `recipher_js::options`. /// /// The promise does not reject. #[napi( ts_type = "(ciphertext: Ciphertext): Promise> decrypt(ciphertexts: readonly Ciphertext[]): Promise> -decrypt(record: R, row: Stored): Promise, RecipherError>> -decrypt(record: R, rows: readonly Stored[]): Promise[], RecipherError>>" +decrypt(stored: NoInfer>, options: RecordOptions): Promise, RecipherError>> +decrypt(stored: readonly NoInfer>[], options: RecordOptions): Promise[], RecipherError>> +decrypt>(stored: NoInfer[F]>, options: FieldOptions): Promise[F], RecipherError>> +decrypt>(stored: readonly NoInfer[F]>[], options: FieldOptions): Promise[F][], RecipherError>>" )] pub fn decrypt<'e>( &self, env: &'e Env, - first: Unknown<'_>, - second: Option>, - ) -> napi::Result>> { - if js::is_record(env, &first) { - return open_rows_of(env, &self.engine, first, second, Confined::ToDefault); - } - if let Some(error) = js::second_without_record(env, &first, second.as_ref()) { - return refused(env, error); - } - open(env, &self.engine, first, Confined::ToDefault) - } - - /// Encrypts one field of a record, to update that field alone. The - /// result is the field's stored form, the same form as in a whole stored - /// row. An array of values returns an array of stored fields, in one key - /// request. The promise does not reject. - #[napi( - ts_type = ">(record: R, field: F, value: NoInfer[F]>): Promise[F], RecipherError>> -encryptField>(record: R, field: F, values: readonly NoInfer[F]>[]): Promise[F][], RecipherError>>" - )] - pub fn encrypt_field<'e>( - &self, - env: &'e Env, - record: Unknown<'_>, - field: Unknown<'_>, - value: Unknown<'_>, - ) -> napi::Result>> { - seal_field(env, &self.engine, record, field, value) - } - - /// Decrypts one field of a record's stored row made under this keyset. - /// An array of stored fields decrypts in one key request. The promise - /// does not reject. - #[napi( - ts_type = ">(record: R, field: F, stored: NoInfer[F]>): Promise[F], RecipherError>> -decryptField>(record: R, field: F, stored: readonly NoInfer[F]>[]): Promise[F][], RecipherError>>" - )] - pub fn decrypt_field<'e>( - &self, - env: &'e Env, - record: Unknown<'_>, - field: Unknown<'_>, stored: Unknown<'_>, + // Not an `Option`, as for `encrypt`. + options: Unknown<'_>, ) -> napi::Result>> { - open_field( - env, - &self.engine, - record, - field, - stored, - Confined::ToDefault, - ) + decrypt_with(env, &self.engine, stored, options, Confined::ToDefault) } - /// Returns the type's name. #[napi(js_name = "toString")] pub fn describe(&self) -> &'static str { @@ -485,8 +432,33 @@ pub(crate) enum Confined { ToDefault, } +/// Runs `cipher.decrypt` and `keyset.decrypt`: reads the options, then +/// decrypts a ciphertext, a stored row, or a stored field, or an array of +/// one of them. +fn decrypt_with<'e>( + env: &'e Env, + engine: &Arc, + stored: Unknown<'_>, + options: Unknown<'_>, + confined: Confined, +) -> napi::Result>> { + if js::is_record(env, &stored) { + return refused(env, Error::options(Fault::RecordFirst).into()); + } + match options::read(env, Call::Decrypt, options) { + Ok(Options::None) => open(env, engine, stored, confined), + Ok(Options::Row { record }) => open_rows_of(env, engine, record, stored, confined), + Ok(Options::Field { record, field }) => { + open_field(env, engine, record, field, stored, confined) + } + // `options::read` never gives `decrypt` a kind. + Ok(Options::Kind(_)) => refused(env, Error::options(Fault::DecryptKind).into()), + Err(error) => refused(env, error), + } +} + /// Decrypts a ciphertext, or an array of them, for `cipher.decrypt` and -/// `keyset.decrypt`. +/// `keyset.decrypt` with no options. fn open<'e>( env: &'e Env, engine: &Arc, @@ -659,16 +631,15 @@ fn read_row(env: &Env, plan: &RecordPlan, row: Unknown<'_>) -> Outcome( env: &'e Env, engine: &Arc, record: Unknown<'_>, - rows: Option>, + rows: Unknown<'_>, ) -> napi::Result>> { let read = || -> Outcome<(Arc, bool, Vec)> { let plan = plan_of(env, record)?; - let rows = rows.unwrap_or(().into_unknown(env).map_err(not_made)?); let (many, rows) = one_or_many(env, rows)?; let rows = rows .into_iter() @@ -698,17 +669,17 @@ fn seal_rows_of<'e>( ) } -/// Runs `cipher.decrypt(record, stored | stored[])` and `keyset.decrypt`. +/// Runs `cipher.decrypt(stored | stored[], { record })` and +/// `keyset.decrypt`. fn open_rows_of<'e>( env: &'e Env, engine: &Arc, record: Unknown<'_>, - stored: Option>, + stored: Unknown<'_>, confined: Confined, ) -> napi::Result>> { let read = || -> Outcome<(Arc, bool, Vec)> { let plan = plan_of(env, record)?; - let stored = stored.unwrap_or(().into_unknown(env).map_err(not_made)?); let (many, rows) = one_or_many(env, stored)?; let rows = rows .into_iter() @@ -749,7 +720,7 @@ fn field_plan_of( Ok((plan.field(&name)?, name)) } -/// Runs `keyset.encryptField(record, field, value | values)`. +/// Runs `keyset.encrypt(value | values, { record, field })`. fn seal_field<'e>( env: &'e Env, engine: &Arc, @@ -792,8 +763,8 @@ fn seal_field<'e>( ) } -/// Runs `cipher.decryptField(record, field, stored | stored[])` and -/// `keyset.decryptField`. +/// Runs `cipher.decrypt(stored | stored[], { record, field })` and +/// `keyset.decrypt`. fn open_field<'e>( env: &'e Env, engine: &Arc, diff --git a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs index c6d16dbef..24694a0b8 100644 --- a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs +++ b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs @@ -202,19 +202,8 @@ impl<'de> Deserialize<'de> for Nullable { } } -/// 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. +/// The kind in the options of `keyset.encrypt`, read once the options +/// module has checked their keys. #[derive(Deserialize)] struct OptionsKind { kind: KindArgument, @@ -238,28 +227,18 @@ fn kind_of(env: &Env, value: Option>) -> Outcome> { named(&argument).map(Some) } -/// Returns the kind that the options of `keyset.encrypt` declare, or -/// `None` when there are no options. +/// Returns the kind that the options of `keyset.encrypt` declare. `bytes` +/// is the frame of the options, which have the key `kind` and no key that +/// `encrypt` does not take. /// /// # Errors /// -/// - `recipher_js::options`, when the options are not an object whose only -/// key is `kind`, `null` included; -/// - `recipher_js::not_a_kind`, when the kind is not one of `kinds`, or -/// `nullable(..)` of one. -pub(crate) fn declared_kind(env: &Env, value: Unknown<'_>) -> Outcome> { - // A missing argument reaches the addon as `undefined`. `null` is read, - // and refused like any other value that is not `{ kind }`. - let Some(value) = given(Some(value)) else { - return Ok(None); - }; - let frame = js::read(env, value).map_err(|_| Error::Options)?; - let bytes = frame.frame().as_bytes(); - stack_encrypt::dynamic::frame::serde::from_slice::(bytes) - .map_err(|_| Error::Options)?; +/// Returns `recipher_js::not_a_kind` when the kind is not one of `kinds`, +/// or `nullable(..)` of one. +pub(crate) fn kind_in_options(bytes: &[u8]) -> Outcome { let options: OptionsKind = stack_encrypt::dynamic::frame::serde::from_slice(bytes).map_err(|_| Error::NotAKind)?; - named(&options.kind).map(Some) + named(&options.kind) } /// Returns the kind that `argument` names, when it is one of `kinds`, or diff --git a/languages/typescript/packages/recipher-js/crate/src/error.rs b/languages/typescript/packages/recipher-js/crate/src/error.rs index 51e20a29d..79e8aa98a 100644 --- a/languages/typescript/packages/recipher-js/crate/src/error.rs +++ b/languages/typescript/packages/recipher-js/crate/src/error.rs @@ -30,6 +30,7 @@ use stack_encrypt::dynamic::ValueKind; use stack_encrypt::ErrorPayload; use crate::ciphertext::Declared; +use crate::options::Fault; /// 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. @@ -69,7 +70,7 @@ pub(crate) enum Error { #[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(..)`.") + help("To encrypt a row, pass its record, as in `keyset.encrypt(user, {{ record: UserRecord }})`. To encrypt the object as a JSON document, wrap it in `json(..)`.") )] PlainObject, /// `null` given as one value. A ciphertext contains one value, and @@ -103,14 +104,19 @@ 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, + /// Options of `encrypt` or `decrypt` that the call does not take, or a + /// record declaration given where the value goes. Make it with + /// [`Error::options`]. That function picks the message and the help for + /// the fault. + #[error("{message}")] + #[diagnostic(code(recipher_js::options))] + Options { + /// What went wrong: [`Fault::message`]. + message: &'static str, + /// What to pass instead: [`Fault::help`]. + #[help] + help: &'static str, + }, /// 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`")] @@ -280,6 +286,14 @@ pub(crate) const NULL_HELP_NULLABLE: &str = "Store a value that is not there as 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 `recipher_js::options` for `fault`. + pub(crate) fn options(fault: Fault) -> Self { + Self::Options { + message: fault.message(), + help: fault.help(), + } + } + /// 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 { @@ -516,6 +530,7 @@ mod tests { NULL_HELP_TYPED, UNDESCRIBED_CAUSE, }; use crate::ciphertext::Declared; + use crate::options::Fault; use stack_encrypt::dynamic::ValueKind; #[test] @@ -712,7 +727,7 @@ mod tests { Error::UnsafeInteger, Error::NotACiphertext, Error::NotBytes, - Error::Options, + Error::options(Fault::NotOptions), Error::JsonKind, Error::NotAKind, Error::OpenedNull, @@ -753,7 +768,7 @@ mod tests { | Error::UnsafeInteger | Error::NotACiphertext | Error::NotBytes - | Error::Options + | Error::Options { .. } | Error::JsonKind | Error::NotAKind | Error::OpenedNull @@ -792,14 +807,14 @@ mod tests { 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::PlainObject => Some( + "To encrypt a row, pass its record, as in `keyset.encrypt(user, { record: UserRecord })`. To encrypt the object as a JSON document, wrap it in `json(..)`.", + ), Error::NullValue { .. } => Some(NULL_HELP_NULLABLE), Error::UnsafeInteger => Some( "The safe range is 2^53 - 1 either side of zero. Pass the integer as a `bigint` instead.", ), - Error::Options => Some("Pass a kind from `kinds`, as in `{ kind: kinds.int64 }`."), + Error::Options { .. } => Some(Fault::NotOptions.help()), Error::JsonKind => { Some("Wrap a JSON document in `json(..)`, and declare `kinds.json` or no kind.") } diff --git a/languages/typescript/packages/recipher-js/crate/src/js.rs b/languages/typescript/packages/recipher-js/crate/src/js.rs index 3b6666299..49b4fa8c9 100644 --- a/languages/typescript/packages/recipher-js/crate/src/js.rs +++ b/languages/typescript/packages/recipher-js/crate/src/js.rs @@ -255,29 +255,6 @@ pub(crate) fn is_record(env: &Env, value: &Unknown<'_>) -> bool { ) } -/// Returns the failure for a call that has a second argument, when the -/// first argument is a plain object but not a record declaration. Such a -/// call passes a row with a record argument that is not a record. Returns -/// `None` for any other call. For example, `Array.prototype.map` passes a -/// value with its index, and that call gets `None`. -pub(crate) fn second_without_record( - env: &Env, - first: &Unknown<'_>, - second: Option<&Unknown<'_>>, -) -> Option { - let second = second?; - if second.get_type().ok() == Some(ValueType::Undefined) - || first.get_type().ok() != Some(ValueType::Object) - || first.is_array().unwrap_or(true) - { - return None; - } - let plain = Wrappers::get(env) - .and_then(|wrappers| wrappers.is_plain(*first)) - .unwrap_or(false); - plain.then(|| Error::NotARecord.into()) -} - /// Returns the text of a JavaScript string, or `None` for any other value. pub(crate) fn string(value: Unknown<'_>) -> Option { if value.get_type().ok() != Some(ValueType::String) { diff --git a/languages/typescript/packages/recipher-js/crate/src/lib.rs b/languages/typescript/packages/recipher-js/crate/src/lib.rs index 681fba887..b14afd66e 100644 --- a/languages/typescript/packages/recipher-js/crate/src/lib.rs +++ b/languages/typescript/packages/recipher-js/crate/src/lib.rs @@ -68,6 +68,7 @@ mod error; mod frames; mod js; mod json; +mod options; mod outcome; mod record; @@ -88,7 +89,7 @@ use napi_derive::napi; /// The version of the interface between the package's TypeScript and this /// addon build. -pub const BINDING_INTERFACE: u32 = 2; +pub const BINDING_INTERFACE: u32 = 3; /// 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/crate/src/options.rs b/languages/typescript/packages/recipher-js/crate/src/options.rs new file mode 100644 index 000000000..45ec0bd9d --- /dev/null +++ b/languages/typescript/packages/recipher-js/crate/src/options.rs @@ -0,0 +1,280 @@ +//! The options of `encrypt` and `decrypt`: the object that each call takes +//! as its second argument. +//! +//! The first argument of a call is the thing to encrypt, or the stored thing +//! to decrypt. The options say what that thing is: +//! +//! - no options: one value, or an array of values; +//! - `{ kind }`: one value of a declared kind, or an array of them. Only +//! `encrypt` takes a kind; +//! - `{ record }`: a row of the record, or an array of rows; +//! - `{ record, field }`: one field of a row, or an array of values of that +//! field. +//! +//! Any other key is refused, so an option that this version does not have is +//! never ignored. A key whose value is `undefined` or `null` counts as +//! absent. + +use napi::bindgen_prelude::{JsValue, Unknown}; +use napi::{Env, ValueType}; +use serde::de::IgnoredAny; +use serde::Deserialize; + +use crate::ciphertext::{kind_in_options, Declared}; +use crate::error::Error; +use crate::js; +use crate::outcome::Outcome; + +/// The call that the options are given to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Call { + /// `keyset.encrypt`. + Encrypt, + /// `cipher.decrypt` and `keyset.decrypt`. + Decrypt, +} + +/// Which of the keys `kind`, `record`, and `field` an options object has. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Keys { + pub(crate) kind: bool, + pub(crate) record: bool, + pub(crate) field: bool, +} + +/// What the options ask a call to encrypt or decrypt, decided from their +/// keys alone. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Target { + /// One value of a declared kind, or an array of them. + Kind, + /// A row of a record, or an array of rows. + Row, + /// One field of a row, or an array of values of that field. + Field, +} + +/// What is wrong with the options of a call, or with where its arguments +/// are. Each fault is the error `recipher_js::options`, with a help that +/// says what to pass instead. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Fault { + /// Options that are not an object, or an object with a key that the + /// call does not take. `null` and an array are not objects here. + NotOptions, + /// An object with none of the keys the call takes. + NoKey, + /// `kind` and `record` together. + KindAndRecord, + /// `field` without `record`. + FieldWithoutRecord, + /// `kind` given to `decrypt`. + DecryptKind, + /// A record declaration given as the first argument, where the value + /// goes. + RecordFirst, +} + +/// Every [`Fault`]. The match in the test that reads this list has no +/// wildcard, so a new fault needs an entry here. +#[cfg(test)] +pub(crate) const FAULTS: [Fault; 6] = [ + Fault::NotOptions, + Fault::NoKey, + Fault::KindAndRecord, + Fault::FieldWithoutRecord, + Fault::DecryptKind, + Fault::RecordFirst, +]; + +impl Fault { + /// What went wrong, in one line. + pub(crate) fn message(self) -> &'static str { + match self { + Self::NotOptions => { + "the options are an object with `kind`, or with `record` and an optional `field`" + } + Self::NoKey => "the options have none of `kind`, `record`, and `field`", + Self::KindAndRecord => "the options have both `kind` and `record`", + Self::FieldWithoutRecord => "the options have `field` without `record`", + Self::DecryptKind => "the options of `decrypt` have no `kind`", + Self::RecordFirst => "a record declaration is the first argument, where the value goes", + } + } + + /// What to pass instead. + pub(crate) fn help(self) -> &'static str { + match self { + Self::NotOptions | Self::NoKey => { + "Pass `{ kind: kinds.int64 }` for one value, `{ record: UserRecord }` for a row, or `{ record: UserRecord, field: 'email' }` for one field of a row. Leave the options out to encrypt a value as its type." + } + Self::KindAndRecord => { + "Pass `kind` for one value, or `record` for a row. A record's fields declare their own kinds." + } + Self::FieldWithoutRecord => { + "Pass the field's record with it, as in `{ record: UserRecord, field: 'email' }`." + } + Self::DecryptKind => { + "A ciphertext's kind is given to `Ciphertext.fromBytes(bytes, kind)`. `decrypt` takes `{ record }`, or `{ record, field }`, or no options." + } + Self::RecordFirst => { + "Pass the row first and its record in the options, as in `keyset.encrypt(user, { record: UserRecord })` and `cipher.decrypt(stored, { record: UserRecord })`." + } + } + } +} + +/// Returns what options with `keys` ask `call` to encrypt or decrypt. +/// +/// # Errors +/// +/// Returns the [`Fault`] of a combination of keys that the call does not +/// take. +pub(crate) fn target(call: Call, keys: Keys) -> Result { + match (keys.kind, keys.record, keys.field) { + (true, true, _) => Err(Fault::KindAndRecord), + (_, false, true) => Err(Fault::FieldWithoutRecord), + (true, false, false) => match call { + Call::Encrypt => Ok(Target::Kind), + Call::Decrypt => Err(Fault::DecryptKind), + }, + (false, true, false) => Ok(Target::Row), + (false, true, true) => Ok(Target::Field), + (false, false, false) => Err(Fault::NoKey), + } +} + +/// The options of a call, read. +pub(crate) enum Options<'e> { + /// No options. + None, + /// `{ kind }`, with the kind it declares. + Kind(Declared), + /// `{ record }`, with the record declaration as given. + Row { record: Unknown<'e> }, + /// `{ record, field }`, with the declaration and the field name as + /// given. + Field { + record: Unknown<'e>, + field: Unknown<'e>, + }, +} + +/// The keys an options object may have. Any other key is refused. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Shape { + #[serde(default)] + kind: Option, + #[serde(default)] + record: Option, + #[serde(default)] + field: Option, +} + +/// Reads the options of `call`. A missing argument reaches the addon as +/// `undefined`. `undefined` is no options. +/// +/// # Errors +/// +/// - `recipher_js::options`, for each [`Fault`] of the options; +/// - `recipher_js::not_a_kind`, when `kind` is not one of `kinds`, or +/// `nullable(..)` of one. +pub(crate) fn read<'e>(env: &Env, call: Call, options: Unknown<'e>) -> Outcome> { + let refused = |fault: Fault| Err(Error::options(fault).into()); + match options.get_type().ok() { + Some(ValueType::Undefined) => return Ok(Options::None), + Some(ValueType::Object) if !options.is_array().unwrap_or(true) => {} + _ => return refused(Fault::NotOptions), + } + // The bridge reads the object's own keys, as it reads a value. So a key + // on a polluted prototype is never read as an option. + let frame = js::read(env, options).map_err(|_| Error::options(Fault::NotOptions))?; + let bytes = frame.frame().as_bytes(); + let shape: Shape = stack_encrypt::dynamic::frame::serde::from_slice(bytes) + .map_err(|_| Error::options(Fault::NotOptions))?; + let keys = Keys { + kind: shape.kind.is_some(), + record: shape.record.is_some(), + field: shape.field.is_some(), + }; + match target(call, keys) { + Err(fault) => refused(fault), + Ok(Target::Kind) => kind_in_options(bytes).map(Options::Kind), + Ok(Target::Row) => Ok(Options::Row { + record: own(env, options, "record")?, + }), + Ok(Target::Field) => Ok(Options::Field { + record: own(env, options, "record")?, + field: own(env, options, "field")?, + }), + } +} + +/// Returns the property `name` of `options`. The bridge has already read +/// `name` as one of the object's own keys. +fn own<'e>(env: &Env, options: Unknown<'e>, name: &str) -> Outcome> { + js::property(env, options, name)?.ok_or_else(|| Error::options(Fault::NotOptions).into()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::error::RecipherErrorFields; + + fn keys(kind: bool, record: bool, field: bool) -> Keys { + Keys { + kind, + record, + field, + } + } + + #[test] + fn encrypt_takes_kind_or_record_or_record_and_field() { + let encrypt = |k, r, f| target(Call::Encrypt, keys(k, r, f)); + assert_eq!(encrypt(true, false, false), Ok(Target::Kind)); + assert_eq!(encrypt(false, true, false), Ok(Target::Row)); + assert_eq!(encrypt(false, true, true), Ok(Target::Field)); + assert_eq!(encrypt(false, false, false), Err(Fault::NoKey)); + assert_eq!(encrypt(true, true, false), Err(Fault::KindAndRecord)); + assert_eq!(encrypt(true, true, true), Err(Fault::KindAndRecord)); + assert_eq!(encrypt(false, false, true), Err(Fault::FieldWithoutRecord)); + assert_eq!(encrypt(true, false, true), Err(Fault::FieldWithoutRecord)); + } + + #[test] + fn decrypt_takes_record_or_record_and_field_and_no_kind() { + let decrypt = |k, r, f| target(Call::Decrypt, keys(k, r, f)); + assert_eq!(decrypt(true, false, false), Err(Fault::DecryptKind)); + assert_eq!(decrypt(false, true, false), Ok(Target::Row)); + assert_eq!(decrypt(false, true, true), Ok(Target::Field)); + assert_eq!(decrypt(false, false, false), Err(Fault::NoKey)); + assert_eq!(decrypt(true, true, false), Err(Fault::KindAndRecord)); + assert_eq!(decrypt(true, true, true), Err(Fault::KindAndRecord)); + assert_eq!(decrypt(false, false, true), Err(Fault::FieldWithoutRecord)); + assert_eq!(decrypt(true, false, true), Err(Fault::FieldWithoutRecord)); + } + + #[test] + fn every_fault_is_the_options_error_with_a_help_that_says_what_to_pass() { + for fault in FAULTS { + // No wildcard: a new fault needs a check of its help here. + let names = match fault { + Fault::NotOptions | Fault::NoKey => &["kind", "record", "field"][..], + Fault::KindAndRecord => &["kind", "record"], + Fault::FieldWithoutRecord => &["record", "field"], + Fault::DecryptKind => &["Ciphertext.fromBytes", "record"], + Fault::RecordFirst => &["{ record: UserRecord }"], + }; + let error = RecipherErrorFields::from(Error::options(fault)); + assert_eq!(error.code, "recipher_js::options"); + assert_eq!(error.message, fault.message()); + let help = error.help.expect("every fault has a help"); + assert_eq!(help, fault.help()); + for name in names { + assert!(help.contains(name), "{fault:?}: {help}"); + } + } + } +} diff --git a/languages/typescript/packages/recipher-js/crate/src/record_tests.rs b/languages/typescript/packages/recipher-js/crate/src/record_tests.rs index 00d928e4c..af2023069 100644 --- a/languages/typescript/packages/recipher-js/crate/src/record_tests.rs +++ b/languages/typescript/packages/recipher-js/crate/src/record_tests.rs @@ -379,8 +379,8 @@ async fn many_rows_and_many_fields_alone_are_one_key_request_each_way() { let _ = open_rows(&cipher, users(), stored).await.unwrap(); assert_eq!(cipher.kms().retrieves.load(Ordering::SeqCst), 1); - // Three values of one field, as `encryptField` encrypts an array of - // them. + // Three values of one field, as `keyset.encrypt(values, { record, + // field })` encrypts them. let email = users().field("email").unwrap(); let rows = ["a", "b", "c"] .into_iter() diff --git a/languages/typescript/packages/recipher-js/native-header.d.ts b/languages/typescript/packages/recipher-js/native-header.d.ts index 0f762f15d..af96eb95f 100644 --- a/languages/typescript/packages/recipher-js/native-header.d.ts +++ b/languages/typescript/packages/recipher-js/native-header.d.ts @@ -14,8 +14,10 @@ import type { } from './src/kinds' import type { CipherOptions, + FieldOptions, Plaintext, RecordDeclaration, + RecordOptions, SealedFieldName, Stored, } from './src/record-types' diff --git a/languages/typescript/packages/recipher-js/native.d.ts b/languages/typescript/packages/recipher-js/native.d.ts index 3fff8a597..dc8371bdb 100644 --- a/languages/typescript/packages/recipher-js/native.d.ts +++ b/languages/typescript/packages/recipher-js/native.d.ts @@ -14,8 +14,10 @@ import type { } from './src/kinds' import type { CipherOptions, + FieldOptions, Plaintext, RecordDeclaration, + RecordOptions, SealedFieldName, Stored, } from './src/record-types' @@ -103,26 +105,24 @@ export declare class Cipher { * ciphertexts were made under. A key request is one request to ZeroKMS * for data keys. * - * With a record declaration as the first argument, `decrypt` decrypts - * a stored row of that record, or an array of stored rows. A stored - * row is what `keyset.encrypt` returns for a row. Node's `inspect` - * shows a decrypted row's field names and hides their values. + * `{ record }` decrypts a stored row of that record, or an array of + * stored rows. A stored row is what `keyset.encrypt` returns for a row. + * Node's `inspect` shows a decrypted row's field names and hides their + * values. `{ record, field }` decrypts one stored field, or an array of + * them. * * The promise resolves to an `Err` with the code * `recipher_js::not_a_ciphertext` when the argument, or an element of - * the array, is not a `Ciphertext`. The promise does not reject. + * the array, is not a `Ciphertext`. Options other than `{ record }` or + * `{ record, field }` are an `Err` with the code `recipher_js::options`. + * The promise does not reject. */ decrypt(ciphertext: Ciphertext): Promise> decrypt(ciphertexts: readonly Ciphertext[]): Promise> - decrypt(record: R, row: Stored): Promise, RecipherError>> - decrypt(record: R, rows: readonly Stored[]): Promise[], RecipherError>> - /** - * Decrypts one field of a record's stored row, as `encryptField` or - * `encrypt` stored it. An array of stored fields decrypts in one key - * request. The promise does not reject. - */ - decryptField>(record: R, field: F, stored: NoInfer[F]>): Promise[F], RecipherError>> - decryptField>(record: R, field: F, stored: readonly NoInfer[F]>[]): Promise[F][], RecipherError>> + decrypt(stored: NoInfer>, options: RecordOptions): Promise, RecipherError>> + decrypt(stored: readonly NoInfer>[], options: RecordOptions): Promise[], RecipherError>> + decrypt>(stored: NoInfer[F]>, options: FieldOptions): Promise[F], RecipherError>> + decrypt>(stored: readonly NoInfer[F]>[], options: FieldOptions): Promise[F][], RecipherError>> /** Returns the type's name. */ toString(): string } @@ -228,8 +228,6 @@ export declare class Keyset { * safe range is refused with the code `recipher_js::unsafe_integer`. * The safe range is 2^53 - 1 either side of zero. Pass a `bigint` * instead. For an array of values, the kind applies to each value. - * Options that are not `{ kind }`, `null` included, are an `Err` with - * the code `recipher_js::options`. * * `{ kind: nullable(..) }` declares a kind that also takes `null`, such * as `{ kind: nullable(kinds.int64) }`. A value that is not `null` @@ -238,18 +236,25 @@ export declare class Keyset { * not encrypt a typed null as one value yet, so today that `null` is an * `Err` with the code `recipher_js::null_value`. * + * `{ record }` encrypts a row of that record, or an array of rows in + * one key request. Each field is encrypted under its field path: the + * record's name, then the field's name. For each encrypted field, the + * stored row has the field's ciphertext and its index terms. + * `{ record, field }` encrypts one field of a row, to update that field + * alone. The result is the field's stored form, the same form as in a + * whole stored row. An array of values returns an array of stored + * fields, in one key request. + * * A value that cannot be encrypted resolves to an `Err`. For example, a - * plain object is an `Err` with the code `recipher_js::plain_object`. - * `null` with no kind, with a kind that is not `nullable(..)`, or with - * `nullable(..)` of a variable-width kind such as `kinds.string`, is an - * `Err` with the code `recipher_js::null_value`. Store a value that is - * not there as a database `NULL`. + * plain object with no `record` is an `Err` with the code + * `recipher_js::plain_object`. Today every `null` is an `Err` with the + * code `recipher_js::null_value`, `nullable(..)` included. Store a value + * that is not there as a database `NULL`. * - * With a record declaration as the first argument, `encrypt` encrypts - * a row of that record, or an array of rows in one key request. Each - * field is encrypted under its field path: the record's name, then the - * field's name. For each encrypted field, the stored row has the - * field's ciphertext and its index terms. + * Options other than `{ kind }`, `{ record }`, and `{ record, field }` + * are an `Err` with the code `recipher_js::options`. So are `kind` and + * `record` together, `field` without `record`, and `null` as the + * options. The error's help says what to pass. * * The promise does not reject. */ @@ -257,37 +262,28 @@ export declare class Keyset { encrypt(values: readonly V[]): Promise>[], RecipherError>> encrypt>(value: V, options: EncryptOptions): Promise>, RecipherError>> encrypt>(values: readonly V[], options: EncryptOptions): Promise>[], RecipherError>> - encrypt(record: R, row: Plaintext): Promise, RecipherError>> - encrypt(record: R, rows: readonly Plaintext[]): Promise[], RecipherError>> + encrypt(row: NoInfer>, options: RecordOptions): Promise, RecipherError>> + encrypt(rows: readonly NoInfer>[], options: RecordOptions): Promise[], RecipherError>> + encrypt>(value: NoInfer[F]>, options: FieldOptions): Promise[F], RecipherError>> + encrypt>(values: readonly NoInfer[F]>[], options: FieldOptions): Promise[F][], RecipherError>> /** * 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. * - * With a record declaration as the first argument, `decrypt` decrypts - * a stored row of that record, or an array of stored rows. + * `{ record }` decrypts a stored row of that record, or an array of + * stored rows. `{ record, field }` decrypts one stored field, or an + * array of them. Options other than those are an `Err` with the code + * `recipher_js::options`. * * The promise does not reject. */ decrypt(ciphertext: Ciphertext): Promise> decrypt(ciphertexts: readonly Ciphertext[]): Promise> - decrypt(record: R, row: Stored): Promise, RecipherError>> - decrypt(record: R, rows: readonly Stored[]): Promise[], RecipherError>> - /** - * Encrypts one field of a record, to update that field alone. The - * result is the field's stored form, the same form as in a whole stored - * row. An array of values returns an array of stored fields, in one key - * request. The promise does not reject. - */ - encryptField>(record: R, field: F, value: NoInfer[F]>): Promise[F], RecipherError>> - encryptField>(record: R, field: F, values: readonly NoInfer[F]>[]): Promise[F][], RecipherError>> - /** - * Decrypts one field of a record's stored row made under this keyset. - * An array of stored fields decrypts in one key request. The promise - * does not reject. - */ - decryptField>(record: R, field: F, stored: NoInfer[F]>): Promise[F], RecipherError>> - decryptField>(record: R, field: F, stored: readonly NoInfer[F]>[]): Promise[F][], RecipherError>> + decrypt(stored: NoInfer>, options: RecordOptions): Promise, RecipherError>> + decrypt(stored: readonly NoInfer>[], options: RecordOptions): Promise[], RecipherError>> + decrypt>(stored: NoInfer[F]>, options: FieldOptions): Promise[F], RecipherError>> + decrypt>(stored: readonly NoInfer[F]>[], options: FieldOptions): Promise[F][], RecipherError>> /** Returns the type's name. */ toString(): string } diff --git a/languages/typescript/packages/recipher-js/src/binding.ts b/languages/typescript/packages/recipher-js/src/binding.ts index 6743f60ac..d617a4907 100644 --- a/languages/typescript/packages/recipher-js/src/binding.ts +++ b/languages/typescript/packages/recipher-js/src/binding.ts @@ -37,7 +37,7 @@ import { Err, err, Ok, ok, type Result } from './result' * and in the crate whenever a class, a method, or a returned value of the * addon changes shape. */ -export const BINDING_INTERFACE = 2 +export const BINDING_INTERFACE = 3 /** 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/index.ts b/languages/typescript/packages/recipher-js/src/index.ts index bed45cb6b..edb57c621 100644 --- a/languages/typescript/packages/recipher-js/src/index.ts +++ b/languages/typescript/packages/recipher-js/src/index.ts @@ -16,6 +16,19 @@ * const opened = await cipher.decrypt(sealed.value) * ``` * + * The first argument of `encrypt` is the thing to encrypt, and the first + * argument of `decrypt` is the stored thing to decrypt. The second argument + * is always an options object: + * + * - `{ kind }` declares one value's kind, as in `{ kind: kinds.uint64 }`; + * - `{ record }` encrypts or decrypts a row of a record that `record(..)` + * declares, or an array of rows in one key request; + * - `{ record, field }` encrypts or decrypts one field of a row. + * + * `kind` and `record` together, `field` without `record`, and a plain + * object with no `record` do not compile. When the code runs anyway, each + * is an `Err` whose help says what to pass. + * * 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. * @@ -63,12 +76,14 @@ export { checkDeclarations, encrypt, type Field, + type FieldOptions, type Index, type NullMode, type PassthroughField, type Plaintext, passthrough, type RecordDeclaration, + type RecordOptions, record, type SealedField, type SealedFieldName, diff --git a/languages/typescript/packages/recipher-js/src/kinds.ts b/languages/typescript/packages/recipher-js/src/kinds.ts index 5bfc81b0e..75bbbfb63 100644 --- a/languages/typescript/packages/recipher-js/src/kinds.ts +++ b/languages/typescript/packages/recipher-js/src/kinds.ts @@ -163,13 +163,20 @@ export type Declared = K extends Kind */ export type OpenedAs = V extends null ? null : ValueOf -/** The options of `encrypt`: the kind declared for the value. */ +/** + * The options of `encrypt` for one value, or an array of values: the kind + * declared for the value. A row takes `RecordOptions` instead. + */ export interface EncryptOptions { /** * The kind of the value, from `kinds`, such as `kinds.uint64`, or * `nullable(..)` of one. */ readonly kind: K + /** A value with a kind is not a row, so it has no record. */ + readonly record?: never + /** A field is named only with its record. */ + readonly field?: never } /** diff --git a/languages/typescript/packages/recipher-js/src/record-types.ts b/languages/typescript/packages/recipher-js/src/record-types.ts index e5f3ec0a3..0dfba5dcd 100644 --- a/languages/typescript/packages/recipher-js/src/record-types.ts +++ b/languages/typescript/packages/recipher-js/src/record-types.ts @@ -144,6 +144,41 @@ export type SealedFieldName = string : never +/** + * The options of `encrypt` and `decrypt` for a row of a record, or an array + * of rows: `{ record: UserRecord }`. + * + * `kind` and `field` do not compile here. A record's fields declare their + * own kinds. One field of a row takes `FieldOptions`. + */ +export interface RecordOptions { + /** The row's record declaration, from `record(..)`. */ + readonly record: R + /** A row has no kind of its own: each field declares one. */ + readonly kind?: never + /** A whole row names no field. */ + readonly field?: never +} + +/** + * The options of `encrypt` and `decrypt` for one field of a row, or an + * array of values of that field: `{ record: UserRecord, field: 'email' }`. + * + * The field is one of the record's encrypted fields. A passthrough field + * has no ciphertext, so its name does not compile here. + */ +export interface FieldOptions< + R extends RecordDeclaration, + F extends SealedFieldName, +> { + /** The record declaration that declares the field, from `record(..)`. */ + readonly record: R + /** The name of one of the record's encrypted fields. */ + readonly field: F + /** The field declares its own kind. */ + readonly kind?: never +} + /** Options for `Cipher.create`. */ export interface CipherOptions { /** diff --git a/languages/typescript/packages/recipher-js/src/record.ts b/languages/typescript/packages/recipher-js/src/record.ts index c62fb6820..f93d6f09c 100644 --- a/languages/typescript/packages/recipher-js/src/record.ts +++ b/languages/typescript/packages/recipher-js/src/record.ts @@ -5,7 +5,7 @@ * ```ts * import { encrypt, kinds, passthrough, record } from '@cipherstash/recipher' * - * export const user = record('users', { + * export const UserRecord = record('users', { * id: passthrough(), * email: encrypt(kinds.string, { index: ['equality'] }), * name: encrypt(kinds.string, { index: ['match'] }), @@ -14,6 +14,11 @@ * }) * ``` * + * A call takes the row first, and the declaration in its options: + * `keyset.encrypt(user, { record: UserRecord })` and + * `cipher.decrypt(stored, { record: UserRecord })`. One field of a row adds + * its name: `{ record: UserRecord, field: 'email' }`. + * * A declaration is a plain, frozen object: * `{ type: 'record', name, fields }`, with a declaration for each field. * @@ -50,11 +55,13 @@ import { err, type Result } from './result' export type { CipherOptions, Field, + FieldOptions, Index, NullMode, PassthroughField, Plaintext, RecordDeclaration, + RecordOptions, SealedField, SealedFieldName, SealedOptions, diff --git a/languages/typescript/packages/recipher-js/type-tests/records.ts b/languages/typescript/packages/recipher-js/type-tests/records.ts index 93dad337a..601572a5a 100644 --- a/languages/typescript/packages/recipher-js/type-tests/records.ts +++ b/languages/typescript/packages/recipher-js/type-tests/records.ts @@ -16,7 +16,7 @@ import { encrypt, kinds, nullable, passthrough, record } from '../src/index' type Exact = [A] extends [B] ? ([B] extends [A] ? true : false) : false function check<_ extends true>(): void {} -const user = record('users', { +const UserRecord = record('users', { id: passthrough(), email: encrypt(kinds.string, { index: ['equality'] }), name: encrypt(kinds.string, { index: ['match'] }), @@ -27,7 +27,7 @@ const user = record('users', { // The plaintext row: an integer field is a bigint at every width. check< Exact< - Plaintext, + Plaintext, { id: bigint; email: string; name: string; age: bigint; notes: string } > >() @@ -56,7 +56,7 @@ check>() void storedNullable.sql.ciphertext // The stored row: a ciphertext and the declared terms, and nothing else. -declare const stored: Stored +declare const stored: Stored check>() check>() check>() @@ -93,7 +93,7 @@ check< declare const keyset: Keyset declare const cipher: Cipher -const row: Plaintext = { +const user: Plaintext = { id: 1n, email: 'a', name: 'b', @@ -101,49 +101,138 @@ const row: Plaintext = { notes: 'c', } -// encrypt and decrypt keep the record's types, for one row or for an array. -const one = await keyset.encrypt(user, row) -check, RecipherError>>>() -const many = await keyset.encrypt(user, [row, row]) -check[], RecipherError>>>() -const opened = await cipher.decrypt(user, stored) -check, RecipherError>>>() +// encrypt and decrypt take the row first and the record in the options. +// They keep the record's types, for one row or for an array. +const one = await keyset.encrypt(user, { record: UserRecord }) +check, RecipherError>>>() +const many = await keyset.encrypt([user, user], { record: UserRecord }) +check[], RecipherError>>>() +const opened = await cipher.decrypt(stored, { record: UserRecord }) +check< + Exact, RecipherError>> +>() +const openedMany = await keyset.decrypt([stored, stored], { + record: UserRecord, +}) +check< + Exact< + typeof openedMany, + Result[], RecipherError> + > +>() // A row of another shape does not compile. // @ts-expect-error: age is a bigint, not a number. -void keyset.encrypt(user, { ...row, age: 3 }) +void keyset.encrypt({ ...user, age: 3 }, { record: UserRecord }) +const noEmail = { id: 1n, name: 'b', age: 3n, notes: 'c' } // @ts-expect-error: email is missing. -void keyset.encrypt(user, { id: 1n, name: 'b', age: 3n, notes: 'c' }) +void keyset.encrypt(noEmail, { record: UserRecord }) // @ts-expect-error: a field the record does not declare. -void keyset.encrypt(user, { ...row, extra: 1 }) +void keyset.encrypt({ ...user, extra: 1 }, { record: UserRecord }) // @ts-expect-error: email takes no null. -void keyset.encrypt(user, { ...row, email: null }) +void keyset.encrypt({ ...user, email: null }, { record: UserRecord }) +// @ts-expect-error: a stored row of another record. +void cipher.decrypt(storedNullable, { record: UserRecord }) + +// The options decide what the first argument is, and only these +// combinations compile. +// @ts-expect-error: a plain object with no record is not a value. +void keyset.encrypt(user) +// @ts-expect-error: a plain object with no record, with a kind. +void keyset.encrypt(user, { kind: kinds.string }) +// @ts-expect-error: a plain object with no record or kind. +void keyset.encrypt(user, {}) +// @ts-expect-error: `kind` and `record` together. +void keyset.encrypt(user, { record: UserRecord, kind: kinds.string }) +// @ts-expect-error: `kind` and `record` together, for one field. +void keyset.encrypt('x', { + record: UserRecord, + field: 'email', + kind: kinds.string, +}) +// @ts-expect-error: `kind` and `record` together, for one value. +void keyset.encrypt('x', { kind: kinds.string, record: UserRecord }) +// @ts-expect-error: `field` without `record`. +void keyset.encrypt('x', { field: 'email' }) +// @ts-expect-error: `field` without `record`, with a kind. +void keyset.encrypt('x', { kind: kinds.string, field: 'email' }) +// @ts-expect-error: `field` without `record`, to decrypt. +void cipher.decrypt(stored.email, { field: 'email' }) +// @ts-expect-error: `decrypt` takes no kind. +void cipher.decrypt(stored.email, { kind: kinds.string }) +// @ts-expect-error: the record goes in the options, not first. +void keyset.encrypt(UserRecord, user) +// @ts-expect-error: the record goes in the options, not first. +void cipher.decrypt(UserRecord, stored) +// @ts-expect-error: the options take no `context` yet. +void keyset.encrypt(user, { record: UserRecord, context: 'tenant' }) // One field: its stored form and its value. -const email = await keyset.encryptField(user, 'email', 'x') +const email = await keyset.encrypt('x', { record: UserRecord, field: 'email' }) check< - Exact['email'], RecipherError>> + Exact['email'], RecipherError>> >() -const age = await cipher.decryptField(user, 'age', stored.age) +const age = await cipher.decrypt(stored.age, { + record: UserRecord, + field: 'age', +}) check>>() // @ts-expect-error: a field the record does not declare. -void keyset.encryptField(user, 'missing', 'x') +void keyset.encrypt('x', { record: UserRecord, field: 'missing' }) // @ts-expect-error: id is passed through, not encrypted. -void keyset.encryptField(user, 'id', 1n) +void keyset.encrypt(1n, { record: UserRecord, field: 'id' }) // @ts-expect-error: the value is the field's type. -void keyset.encryptField(user, 'age', 'x') +void keyset.encrypt('x', { record: UserRecord, field: 'age' }) // @ts-expect-error: the stored form is the field's own. -void cipher.decryptField(user, 'email', stored.name) +void cipher.decrypt(stored.name, { record: UserRecord, field: 'email' }) +// @ts-expect-error: a whole row is not one field. +void keyset.encrypt(user, { record: UserRecord, field: 'email' }) // One field, many values: an array in is an array out. -const emails = await keyset.encryptField(user, 'email', ['x', 'y']) +const emails = await keyset.encrypt(['x', 'y'], { + record: UserRecord, + field: 'email', +}) check< - Exact['email'][], RecipherError>> + Exact< + typeof emails, + Result['email'][], RecipherError> + > >() -const ages = await cipher.decryptField(user, 'age', [stored.age, stored.age]) +const ages = await cipher.decrypt([stored.age, stored.age], { + record: UserRecord, + field: 'age', +}) check>>() +// The README's Records example, as written there. +{ + const UserRecord = record('users', { + id: passthrough(), + email: encrypt(kinds.string, { index: ['equality'] }), + age: encrypt(kinds.int32, { index: ['equality'], null: 'sealed' }), + }) + const user = { id: 1n, email: 'ada@example.com', age: 36n } + const stored = await keyset.encrypt(user, { record: UserRecord }) + if (stored.isOk()) { + const opened = await cipher.decrypt(stored.value, { record: UserRecord }) + check< + Exact, RecipherError>> + >() + } + const email = await keyset.encrypt('ada@example.com', { + record: UserRecord, + field: 'email', + }) + check< + Exact< + typeof email, + Result['email'], RecipherError> + > + >() +} + // A declaration is plain data, read by any library. -check>() -check>() -check>() +check>() +check>() +check>()