From 5df27759b4bd93587214cac68b43a7409b091a78 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Tue, 24 Nov 2026 21:45:39 +1100 Subject: [PATCH 1/3] chore(recipher-js): drop the check that the addon never names Label The check was added while the engine planned to replace `Label` and `IntoLabel` with field paths, so that a crate that never named them would need no change. The context design is settled now, and the check guards against nothing. The two other boundary checks stay: the addon does not link `eql-bindings`, and a default build cannot reach the test keys. Refs #1803. --- AGENTS.md | 2 +- .../recipher-js/crate/tests/boundaries.rs | 48 +------------------ 2 files changed, 2 insertions(+), 48 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b9a471485..91f63e19f 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 **one crate** in a **detached Cargo workspace** with its own `Cargo.lock`, excluded from the root: `crate/` (crate `recipher-js`, napi-rs 3), which defines the `Cipher`, `Keyset` and `Ciphertext` classes the package exports, runs every operation through the engine, and reads and builds JavaScript values only through the value bridge beside it, `value-napi/` (crate `recipher-value-napi`, a copy of vitaminc's `vitaminc-aead-napi` 0.10.0, unpublished, with a detached test addon workspace of its own at `value-napi/tests/addon` and vitaminc's value conformance corpus at `value-napi/tests/testdata`; Biome does not check that directory). A test fails if it names `Label`/`IntoLabel`, 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. The TypeScript (`src/`) holds only `Result`, `RecipherError`, the typed signatures over the native methods and the adapter that turns each native outcome into 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, and run in `.github/workflows/tests-recipher-js.yml`. +- `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 **one crate** in a **detached Cargo workspace** with its own `Cargo.lock`, excluded from the root: `crate/` (crate `recipher-js`, napi-rs 3), which defines the `Cipher`, `Keyset` and `Ciphertext` classes the package exports, runs every operation through the engine, and reads and builds JavaScript values only through the value bridge beside it, `value-napi/` (crate `recipher-value-napi`, a copy of vitaminc's `vitaminc-aead-napi` 0.10.0, unpublished, with a detached test addon workspace of its own at `value-napi/tests/addon` and vitaminc's value conformance corpus at `value-napi/tests/testdata`; Biome does not check that directory). A test fails if it links `eql-bindings` or reaches the engine's `test-support` with its default features. `@napi-rs/cli` v3 builds it (`build:debug`, `build:native`) and writes its generated TypeScript declarations to the committed `native.d.ts`; CI fails when the build changes that file. The TypeScript (`src/`) holds only `Result`, `RecipherError`, the typed signatures over the native methods and the adapter that turns each native outcome into 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, and run in `.github/workflows/tests-recipher-js.yml`. - `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/crate/tests/boundaries.rs b/languages/typescript/packages/recipher-js/crate/tests/boundaries.rs index e46e6b8ee..2726ea8c7 100644 --- a/languages/typescript/packages/recipher-js/crate/tests/boundaries.rs +++ b/languages/typescript/packages/recipher-js/crate/tests/boundaries.rs @@ -1,8 +1,5 @@ //! What the crate must not reach. //! -//! - It names no `Label` and no `IntoLabel`. The engine is to replace both -//! (the label becomes a field path), and a crate that never named them -//! needs no change when it does. //! - It does not link `eql-bindings`. The EQL types are an extension to the //! core; a build of the core holds none of them. //! - A build with its default features has no test cipher: neither the @@ -12,56 +9,13 @@ //! `testing` on, so this is the check that the release build cannot reach //! the test keys. -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use std::process::Command; fn crate_dir() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")) } -/// Every `.rs` file under `dir`. -fn rust_files(dir: &Path, found: &mut Vec) { - for entry in std::fs::read_dir(dir).unwrap() { - let path = entry.unwrap().path(); - if path.is_dir() { - rust_files(&path, found); - } else if path.extension().is_some_and(|ext| ext == "rs") { - found.push(path); - } - } -} - -/// Whether `source` holds `word` as a whole identifier. -fn names(source: &str, word: &str) -> bool { - source.match_indices(word).any(|(at, _)| { - let before = source[..at].chars().next_back(); - let after = source[at + word.len()..].chars().next(); - let ident = |c: Option| c.is_some_and(|c| c.is_alphanumeric() || c == '_'); - !ident(before) && !ident(after) - }) -} - -#[test] -fn the_crate_names_no_label() { - let mut files = Vec::new(); - rust_files(&crate_dir().join("src"), &mut files); - assert!(!files.is_empty(), "no source files found"); - for file in files { - let source = std::fs::read_to_string(&file).unwrap(); - for word in ["Label", "IntoLabel"] { - assert!(!names(&source, word), "{} names `{word}`", file.display()); - } - } -} - -#[test] -fn the_word_check_matches_whole_identifiers_only() { - assert!(names("use stack_encrypt::Label;", "Label")); - assert!(names("fn f(x: IntoLabel)", "IntoLabel")); - assert!(!names("LabelError", "Label")); - assert!(!names("MyLabel", "Label")); -} - /// `cargo tree --locked` for the crate with its default features, from the /// committed lock: no build is needed. fn tree(edges: &str, format: Option<&str>) -> String { From 559faebee0ebf1fe5534dd0474f9eb40cc2fcb37 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Tue, 24 Nov 2026 21:45:49 +1100 Subject: [PATCH 2/3] refactor(recipher-js): derive Debug on a record's plan `RecordPlan` had a hand-written `Debug` that printed only the record's name. The repository's rule is to derive vitaminc's `OpaqueDebug` for a type whose contents must not print, and `Debug` otherwise. A plan holds only declaration data (names, kinds, indexes and the engine's `Plan`), which is not secret, so it derives `Debug`, as its `Field` does now. No other hand-written `Debug` is left in the addon or the value bridge. Refs #1803. --- .../packages/recipher-js/crate/src/record.rs | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/languages/typescript/packages/recipher-js/crate/src/record.rs b/languages/typescript/packages/recipher-js/crate/src/record.rs index 76eb8bafa..3b64caee8 100644 --- a/languages/typescript/packages/recipher-js/crate/src/record.rs +++ b/languages/typescript/packages/recipher-js/crate/src/record.rs @@ -69,7 +69,9 @@ fn index_name(index: &IndexSpec) -> Option<&'static str> { } } -/// A record's plan, built once from its declaration. +/// A record's plan, built once from its declaration. A declaration holds no +/// secret, so the whole plan prints. +#[derive(Debug)] pub(crate) struct RecordPlan { name: String, plan: Plan, @@ -80,7 +82,7 @@ pub(crate) struct RecordPlan { } /// A field as the rows read it. -#[derive(Clone)] +#[derive(Clone, Debug)] struct Field { name: String, kind: Option, @@ -88,16 +90,6 @@ struct Field { passthrough: bool, } -impl std::fmt::Debug for RecordPlan { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - // A declaration is not secret, but a plan's debug form is the - // engine's, which nothing here needs to show. - f.debug_struct("RecordPlan") - .field("name", &self.name) - .finish_non_exhaustive() - } -} - /// A declaration, as `record(..)` writes it. #[derive(Deserialize)] struct Declaration { From 0df27f1169cb6ced1d39cfb144ef062eb27f2598 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Tue, 24 Nov 2026 21:45:57 +1100 Subject: [PATCH 3/3] docs(recipher-js): write the addon's and the package's docs in plain language The doc comments were dense: long sentences, several ideas each, and terms such as frame, sink, plan, passthrough and outcome used before anyone said what they are. They now use short sentences with one idea each and plain verbs, and define each term where it first appears. Napi copies the addon's doc comments into `native.d.ts`, so the generated declarations change with them. Only comments and the README's prose change. No code, name, message or code example does. Refs #1803. --- .../typescript/packages/recipher-js/README.md | 312 +++++++++++------- .../packages/recipher-js/crate/src/cipher.rs | 223 ++++++++----- .../recipher-js/crate/src/ciphertext.rs | 91 ++--- .../recipher-js/crate/src/engine_tests.rs | 27 +- .../packages/recipher-js/crate/src/error.rs | 174 ++++++---- .../packages/recipher-js/crate/src/frames.rs | 54 +-- .../packages/recipher-js/crate/src/js.rs | 118 ++++--- .../packages/recipher-js/crate/src/json.rs | 161 +++++---- .../packages/recipher-js/crate/src/lib.rs | 60 ++-- .../packages/recipher-js/crate/src/outcome.rs | 37 ++- .../packages/recipher-js/crate/src/record.rs | 184 +++++++---- .../recipher-js/crate/src/record_tests.rs | 21 +- .../packages/recipher-js/crate/src/value.rs | 50 ++- .../recipher-js/crate/tests/boundaries.rs | 23 +- .../packages/recipher-js/native.d.ts | 246 ++++++++------ .../packages/recipher-js/src/binding.ts | 112 ++++--- .../packages/recipher-js/src/cipher.ts | 177 +++++----- .../packages/recipher-js/src/error.ts | 66 ++-- .../packages/recipher-js/src/index.ts | 7 +- .../packages/recipher-js/src/kinds.ts | 20 +- .../packages/recipher-js/src/record.ts | 92 ++++-- .../packages/recipher-js/src/result.ts | 60 ++-- .../packages/recipher-js/src/testing.ts | 30 +- .../packages/recipher-js/src/values.ts | 85 ++--- 24 files changed, 1441 insertions(+), 989 deletions(-) diff --git a/languages/typescript/packages/recipher-js/README.md b/languages/typescript/packages/recipher-js/README.md index 3670ec2e1..2f347e943 100644 --- a/languages/typescript/packages/recipher-js/README.md +++ b/languages/typescript/packages/recipher-js/README.md @@ -1,13 +1,22 @@ # @cipherstash/recipher -The TypeScript SDK on the Stack Encrypt engine. It encrypts values with -per-value ZeroKMS data keys, and knows nothing about a database. +`@cipherstash/recipher` is the TypeScript SDK for the Stack Encrypt engine. +Stack Encrypt is CipherStash's encryption engine, written in Rust. +The package encrypts each value with a data key of its own. +The data keys come from ZeroKMS, CipherStash's key service. +The package contains no database code. -> **Not released.** This package is private and is not published to npm. -> No build of it promises that a later build opens the values it stored. +> **Not released.** This package is private. The package is not published to npm. +> No build of this package promises that a later build can decrypt the values it stored. ## Encrypt and decrypt one value +A `Cipher` uses ZeroKMS to get data keys. +`Cipher.create()` looks for credentials in the `CS_*` environment variables, then in the profile that `stash auth login` writes. +A keyset is a group of keys in ZeroKMS. +Every data key is made under one keyset. +`cipher.defaultKeyset()` returns the keyset that a ZeroKMS administrator set as the default for your client. + ```ts import { Cipher } from '@cipherstash/recipher' @@ -24,18 +33,23 @@ const stored = sealed.value.toBytes() // a Uint8Array to keep const opened = await cipher.decrypt(sealed.value) ``` -- Encrypting needs a keyset; decrypting does not. `cipher.decrypt` opens a - value from any of the cipher's keysets, and `keyset.decrypt` refuses a - value from another keyset. -- `Ciphertext.fromBytes(bytes)` reads stored bytes back. Each ciphertext - has its own data key. -- The bytes are the engine's: Rust's `keyset.decrypt::` opens what - this package seals, and this package opens what Rust sealed. +- Encrypting needs a keyset. Decrypting does not. +- `cipher.decrypt` decrypts a value from any of the cipher's keysets. + `keyset.decrypt` refuses a value from another keyset. +- `Ciphertext.fromBytes(bytes)` reads stored bytes back as a ciphertext. + Each ciphertext has its own data key. +- The stored bytes use the engine's format. + Rust code that calls `keyset.decrypt::` decrypts what this package encrypts. + This package decrypts what Rust encrypted. +- You cannot make a `Cipher`, a `Keyset`, or a `Ciphertext` with a constructor. + Get a cipher from `Cipher.create()`, a keyset from `cipher.defaultKeyset()`, and a ciphertext from `encrypt` or `Ciphertext.fromBytes`. ## Values -A value's type picks how it is encrypted. The mapping is the one vitaminc -defines, read and built by the `recipher-value-napi` crate (`value-napi/`): +A value's type decides how it is encrypted. +vitaminc defines the mapping. +vitaminc is the CipherStash Rust library that the engine's plaintext types come from. +The `recipher-value-napi` crate, in `value-napi/`, converts JavaScript values by that mapping, in both directions: | Value | Encrypted as | Decrypts as | |---|---|---| @@ -51,18 +65,24 @@ defines, read and built by the `recipher-value-napi` crate (`value-napi/`): | `null` | null | `null` | | `json(value)` | a JSON document, as its JSON text | the document, from the `Ciphertext` that `encrypt` returned or one read with `kinds.json` | -- Integers are a `bigint`. A `number` is a float, and `5` does not equal - the integer `5n`. -- A plain object is refused. Wrap it in `json(..)`. -- `VcUuid` is exported, but the engine's value model does not hold a UUID - yet, so encrypting one is an `Err` with the code `recipher::uuid`. -- vitaminc's rules apply: a `Map`, a `Set`, a class instance, a sparse - array, a typed array other than a `Uint8Array`, a string with an - unpaired surrogate, and a property named `__proto__`, `constructor` or - `prototype` are refused, each with a code of its own. - -An array in is an array out, in the same order, with one key request -however long it is: +- Integers are a `bigint`. + A `number` is a float. + The `number` `5` does not equal the integer `5n`. +- A plain object is refused. + Wrap it in `json(..)`. +- The package exports `VcUuid`, for a universally unique identifier (UUID). + The engine has no plaintext type for a UUID yet. + Encrypting a `VcUuid` is an `Err` with the code `recipher::uuid`. +- vitaminc's rules refuse each of these values, with an error code for each: + - a `Map` or a `Set`; + - a class instance; + - a sparse array; + - a typed array other than a `Uint8Array`; + - a string with an unpaired surrogate; + - a property named `__proto__`, `constructor`, or `prototype`. + +If you encrypt an array, you get back an array of ciphertexts in the same order. +The whole array needs one key request to ZeroKMS, however long it is: ```ts const sealed = await keyset.encrypt(['first secret', 'second secret']) @@ -71,37 +91,45 @@ const opened = await cipher.decrypt(sealed.unwrap()) ### JSON documents -`json(value)` encrypts a document as one ciphertext, as the engine's -`JsonPlaintext` does: as its JSON text. - -- An integer outside a `number`'s safe range is a `bigint`, in the 64-bit - range the engine's parser reads (`-(2n ** 63n)` to `2n ** 64n - 1n`); a - `bigint` outside it is refused. -- A whole `number` between 2^53 and 2^64 from zero is refused: an integer - was likely meant, and its digits are not the ones written. Use a - `bigint`. Any other finite `number`, such as `1e20`, is a float. -- Bytes, a `Date`, the wrapper classes and `undefined` have no JSON form - and are refused. So is a document nested deeper than 127 levels. -- A property named `__proto__`, `constructor` or `prototype` cannot be - encrypted, and a document another SDK wrote with one opens as an `Err` - with the code `recipher::reserved_key`: vitaminc does not build those - properties in JavaScript. -- **Read a stored document back with `kinds.json`.** The bytes do not say - a value is JSON. `Ciphertext.fromBytes(bytes, kinds.json)` opens it as - the document. With no kind it opens as its JSON text, and `JSON.parse` - of that text loses the digits of a large integer. +`json(value)` encrypts a whole document as one ciphertext. +The document is encrypted as its JSON text, as the engine's `JsonPlaintext` type does. + +- An integer outside a `number`'s safe range is a `bigint`. + The `bigint` must be in the 64-bit range that the engine's parser reads: `-(2n ** 63n)` to `2n ** 64n - 1n`. + A `bigint` outside that range is refused. +- A whole `number` is refused when its absolute value is at least 2^53 but less than 2^64. + An integer was likely meant. + The `number` does not keep the digits that were written. + Use a `bigint` instead. + Any other finite `number`, such as `1e20`, is a float. +- Bytes, a `Date`, the wrapper classes, and `undefined` have no JSON form. + The package refuses them. + The package also refuses a document nested deeper than 127 levels. +- A property named `__proto__`, `constructor`, or `prototype` cannot be encrypted. + Another SDK can write a document with one of these properties. + Decrypting that document here gives an `Err` with the code `recipher::reserved_key`. + The reason is that vitaminc does not build those properties in JavaScript. +- **Read a stored document back with `kinds.json`.** + The bytes do not record that a value is JSON. + `Ciphertext.fromBytes(bytes, kinds.json)` decrypts to the document. + With no kind, the document decrypts to its JSON text. + `JSON.parse` of that text loses the digits of a large integer. ### Stored bytes -`Ciphertext.fromBytes(bytes)` opens as whatever was sealed, typed as any -scalar. `Ciphertext.fromBytes(bytes, kinds.string)` is typed by the kind, -and decrypting refuses a value sealed as another type. An integer kind -takes an integer of any width that fits it. +A kind names the type a stored ciphertext decrypts to, such as `kinds.string`. + +`Ciphertext.fromBytes(bytes)` decrypts to whatever type was encrypted. +The ciphertext's TypeScript type allows any scalar: any type in the table above except a JSON document. + +`Ciphertext.fromBytes(bytes, kinds.string)` has the kind's type. +Decrypting it refuses a value that was encrypted as another type. +An integer kind accepts an integer encrypted at any width, if the value fits the kind. ## Records -A record declares each field once: encrypted, encrypted and indexed, or -passed through. +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' @@ -119,39 +147,51 @@ const stored = await keyset.encrypt(user, row) const opened = await cipher.decrypt(user, stored.unwrap()) ``` -- A declaration is plain, frozen data: `{ type: 'record', name, fields }`. - A library reads the record's name, its fields and each field's - declaration from it, and a declaration made by either the ESM or the - CommonJS build works with a cipher from the other. -- A field names its kind, in the engine's words: `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, and refuses one outside its range. -- A field's context is its field path: the record's name, then the - field's name. The engine's typed Rust API opens a stored field's - ciphertext under `("users", "email")`. -- The stored row has one object for each sealed field: `ciphertext`, and - `equality`, `match`, `ore` or `ope` for each index it declares, each - opaque bytes. A passthrough field keeps its value. A field with - `null: 'sql'` is `null` in the stored row when the value is absent. -- `Plaintext` is the row's type and `Stored` the - stored row's. A row of another shape does not compile, and neither does - `stored.notes.equality`. -- A passthrough field is **not encrypted and not authenticated.** Use it - only for values that are not secret, and treat the value read back as - untrusted. -- The engine checks a declaration the first time a cipher uses it, and the - plan it builds is kept. `Cipher.create({ records })` checks them before - it looks for credentials, and `checkDeclarations(records)` checks them - with no credentials. A refusal names the record (`error.record`) and, - where there is one, the field (`error.field`). -- A decrypted row's `inspect` (and so `console.log`) names its fields and - hides their values. The values are ordinary properties, so +- 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. -One field of a record, for an update of that field. An array of values is -an array of stored fields, in one key request: +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') @@ -160,20 +200,30 @@ const value = await cipher.decryptField(user, 'email', email.unwrap()) const emails = await keyset.encryptField(user, 'email', ['a@example.com', 'b@example.com']) ``` -The field's stored form is the one it has in a whole row. +The stored field has the same form as that field in a whole stored row. ## Results, not exceptions -No call throws and no promise rejects. Every call resolves to a `Result`, -with Rust's `Result` methods in camelCase: `isOk`, `isErr`, `ok`, `err`, -`map`, `mapErr`, `mapOr`, `and`, `andThen`, `or`, `orElse`, `unwrapOr`, -`unwrapOrElse`, `unwrap` and `expect`. Only `unwrap` and `expect` throw. -This holds for a method passed on its own (`ciphertexts.map(cipher.decrypt)` -keeps its cipher), for an argument of the wrong type, and when the native -build is missing. +No call throws, and no promise rejects. +Every call resolves to a `Result`. +A `Result` has the methods of Rust's `Result`, in camelCase: + +- `isOk`, `isErr`, `ok`, and `err`; +- `map`, `mapErr`, and `mapOr`; +- `and`, `andThen`, `or`, and `orElse`; +- `unwrapOr`, `unwrapOrElse`, `unwrap`, and `expect`. + +Only `unwrap` and `expect` throw. +The other calls do not throw in these cases either: -A `RecipherError` is a diagnostic, as a value. Most come from the engine. -The SDK's own have a `recipher::` code. Switch on `code`: +- a method passed on its own: `ciphertexts.map(cipher.decrypt)` keeps its cipher; +- an argument of the wrong type; +- a native addon that did not load. + +A `RecipherError` is an error report that a call returns as a value. +Most errors come from the engine. +The SDK's own errors have a code that starts with `recipher::`. +Switch on `code`: ```ts const opened = await cipher.decrypt(damaged) @@ -184,23 +234,19 @@ if (opened.isErr()) { } ``` -| Property | What it holds | +| Property | What it contains | | --- | --- | -| `code` | Stable, and what to switch on: the engine's code (`stack_encrypt::aead`), vitaminc's for a value it refused (`ERR_INTEGER_RANGE`), or the SDK's own (`recipher::not_a_ciphertext`). | +| `code` | The code to switch on. It is stable. It is the engine's code (`stack_encrypt::aead`), vitaminc's code for a value it refused (`ERR_INTEGER_RANGE`), or the SDK's own (`recipher::not_a_ciphertext`). | | `message` | What went wrong, in one line. | | `help` | What to do about it, where the error knows. | | `url` | A documentation page for the error, where it has one. | -| `severity` | `error`, unless the diagnostic states `warning` or `advice`. | -| `fields` | The error's structured fields, by `snake_case` name: a refused declaration's `reason`, a ZeroKMS failure's `request_kind`. | +| `severity` | `error`, unless the engine's report states `warning` or `advice`. | +| `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 one is. | -| `causes` | The errors behind this one, outermost first, each a `message` and, for an engine error, a `code`. A cause from another library has a fixed message, never that library's own text. | - -No error holds a plaintext, a key, a token or a ciphertext. +| `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. | -`Cipher`, `Keyset` and `Ciphertext` have no constructor: get a cipher from -`Cipher.create()`, a keyset from `cipher.defaultKeyset()` and a ciphertext -from `encrypt` or `Ciphertext.fromBytes`. +No error contains a plaintext, a key, a token, or a ciphertext. ## Tests without ZeroKMS @@ -210,40 +256,54 @@ import { testCipher } from '@cipherstash/recipher/testing' const cipher = (await testCipher()).unwrap() ``` -A test cipher needs no credentials and makes no request. Its keys are a -function of a public seed, so never use it for data you keep. Only the -debug build of the addon (`build:debug`) has it. +A test cipher needs no credentials and makes no network requests. +The test cipher derives its keys from a public seed. +Never use a test cipher for data you keep. +Only the debug build of the addon has the test cipher. +The `build:debug` script makes that build. ## How it is built -The classes are written in Rust, in one crate (`crate/`, crate -`recipher-js`): a napi-rs 3 addon over the engine. It reads and builds -JavaScript values only through the value bridge beside it (`value-napi/`, -crate `recipher-value-napi`). napi-rs's -CLI builds it, and writes its TypeScript declarations to `native.d.ts`, -which is committed. The package's TypeScript holds what Rust cannot: -`Result`, `RecipherError`, and typed signatures over the native methods. +The native addon is compiled Rust code that Node loads. +The classes are written in Rust, in the `recipher-js` crate in `crate/`. +The crate is a napi-rs 3 addon that calls the engine. +napi-rs is a Rust framework for writing Node addons. + +The addon reads and builds JavaScript values only through the value bridge beside it. +The value bridge is the `recipher-value-napi` crate in `value-napi/`. + +napi-rs's command-line tool builds the addon. +The tool also writes the addon's TypeScript declarations to `native.d.ts`. +`native.d.ts` is committed. +The package's TypeScript contains what Rust cannot provide: `Result`, `RecipherError`, and typed signatures over the native methods. The package's `build` and `test` scripts never run cargo. | Script | What it does | |---|---| -| `build` | The TypeScript, with tsup. | -| `test` | The suites that need no addon, and the typecheck with the type tests. | -| `build:debug` | The addon, with the test cipher, as `recipher.node`, and `native.d.ts`. Needs Rust. | -| `build:native` | The release addon, without the test cipher. Needs Rust. | -| `test:addon` | `build`, then the suites that load the addon. Run `build:debug` first. | -| `test:cargo` | `cargo test`, `cargo fmt --check` and clippy over the crate. | +| `build` | Builds the TypeScript, with tsup. | +| `test` | Runs the suites that need no addon, and the typecheck with the type tests. | +| `build:debug` | Builds the addon, with the test cipher, as `recipher.node`, and writes `native.d.ts`. Needs Rust. | +| `build:native` | Builds the release addon, without the test cipher. Needs Rust. | +| `test:addon` | Runs `build`, then the suites that load the addon. Run `build:debug` first. | +| `test:cargo` | Runs `cargo test`, `cargo fmt --check`, and clippy over the crate. | -The addon is loaded when the package is imported. The ESM and the CommonJS -builds load the same addon, so they share its classes. +The addon is loaded when the package is imported. +The ESM build and the CommonJS build load the same addon, so the two builds share its classes. ## What is not here yet -`opaque(..)` for a whole object, a `json` record field (it needs the EQL -extension's `JsonSearch`), search terms, credentials passed in code, named -keysets, audit metadata, cancellation, the wasm build and the platform -packages. +These features are not built yet: + +- `opaque(..)`, for a whole object; +- 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; +- audit metadata; +- cancellation; +- the WebAssembly (wasm) build; +- the platform packages. -The JavaScript engine holds the plaintext strings it is given, and no test -can check what it does with them. +The JavaScript engine keeps the plaintext strings it is given in memory. +No test can check what the JavaScript engine does with them. diff --git a/languages/typescript/packages/recipher-js/crate/src/cipher.rs b/languages/typescript/packages/recipher-js/crate/src/cipher.rs index 994c2ef26..34d679d15 100644 --- a/languages/typescript/packages/recipher-js/crate/src/cipher.rs +++ b/languages/typescript/packages/recipher-js/crate/src/cipher.rs @@ -1,10 +1,15 @@ -//! [`Cipher`] and [`Keyset`]: the engine, and the calls that run on it. +//! The [`Cipher`] and [`Keyset`] classes, and the calls that run on the +//! engine. The engine is the Stack Encrypt engine, the `stack-encrypt` +//! crate. //! -//! Each call reads its arguments on the JavaScript thread, then runs the -//! engine's future on napi's runtime, holding only what it owns: the -//! engine (shared by every handle of one cipher) and the values read. The -//! future is `Send` and `'static`, which `spawn_future_with_callback` -//! requires, so this compiles only because the engine's pending calls are. +//! Each call reads its arguments on the JavaScript thread. The call then +//! runs the engine's future on napi's runtime. The future owns everything +//! it uses: the engine and the values read. Every `Cipher` and `Keyset` +//! object of one cipher shares the same engine. +//! +//! `spawn_future_with_callback` requires the future to be `Send` and +//! `'static`. So this module compiles only because the engine's pending +//! calls are `Send` and `'static` too. use std::sync::Arc; @@ -25,18 +30,18 @@ use crate::record::{field_value, one_field_row, open_rows, seal_rows, RecordPlan use crate::value::OneValue; use napi::bindgen_prelude::ToNapiValue; -/// The engine cipher, over the key source it was built with. A napi class -/// cannot be generic, so the two key sources are the two variants. +/// The engine's cipher, with the key source it was built with. A napi class +/// cannot be generic, so each key source is one variant. #[derive(OpaqueDebug)] enum Engine { - /// Over ZeroKMS, with the credentials the engine detected. + /// Keys from ZeroKMS, with the credentials the engine found. Detected(Box>>), - /// Over the engine's deterministic test key source. + /// Keys from the engine's deterministic test key source. #[cfg(feature = "testing")] Testing(Box>), } -/// Run `$body` with `$cipher` bound to the engine cipher, whatever its key +/// Runs `$body` with `$cipher` bound to the engine's cipher, for either key /// source. macro_rules! with_engine { ($engine:expr, |$cipher:ident| $body:expr) => { @@ -48,20 +53,24 @@ macro_rules! with_engine { }; } -/// A cipher: the engine, and the keysets it reaches. +/// A cipher: the engine, and the keysets it can use. A keyset is a group +/// of keys in ZeroKMS, CipherStash's key service. /// -/// Build one with `Cipher.create()`, or, in a test, with `testCipher()` -/// from `@cipherstash/recipher/testing`. It has no constructor. +/// Make a cipher with `Cipher.create()`. In a test, make one with +/// `testCipher()` from `@cipherstash/recipher/testing`. The class has no +/// constructor. #[napi] #[derive(OpaqueDebug)] pub struct Cipher { engine: Arc, } -/// One keyset of a cipher. Every data key is made under one keyset, and a -/// ciphertext names the keyset it was made under. +/// One keyset of a cipher. A data key is the key that encrypts one value. +/// Each data key is made under one keyset. A ciphertext names the keyset it +/// was made under. /// -/// Get one from `cipher.defaultKeyset()`. It has no constructor. +/// Get a keyset from `cipher.defaultKeyset()`. The class has no +/// constructor. #[napi] #[derive(OpaqueDebug)] pub struct Keyset { @@ -70,17 +79,21 @@ pub struct Keyset { #[napi] impl Cipher { - /// A cipher over ZeroKMS, with the credentials the engine finds: the - /// `CS_*` variables, then the profile `stash auth login` writes. + /// Makes a cipher that gets its keys from ZeroKMS. The engine looks for + /// credentials in the `CS_*` environment variables first, then in the + /// profile that `stash auth login` writes. + /// + /// The promise resolves to the engine's error in these cases: /// - /// Resolves to the engine's error when there are no credentials, when - /// they are refused, or when ZeroKMS refuses to load the default keyset. + /// - there are no credentials; + /// - the credentials are refused; + /// - ZeroKMS refuses to load the default keyset. /// - /// `options.records` are declarations to check now, before any - /// credential is looked for: a declaration the engine refuses is a - /// failure naming the record. - // Configurable, as an instance method is, so the package's TypeScript - // can wrap it (`adapt`). + /// `options.records` lists record declarations to check now, before the + /// engine looks for credentials. If the engine refuses a declaration, + /// the result is a failure that names the record. + // An instance method is configurable. This static method is made + // configurable too, so the package's TypeScript can wrap it (`adapt`). #[napi(configurable = true, ts_return_type = "Promise>")] pub fn create<'e>( env: &'e Env, @@ -103,8 +116,8 @@ impl Cipher { ) } - /// The client's default keyset: the one a ZeroKMS administrator set for - /// it. Encrypting needs a keyset. + /// Returns the client's default keyset: the keyset that a ZeroKMS + /// administrator set for this client. Encrypting needs a keyset. #[napi] pub fn default_keyset(&self) -> Keyset { Keyset { @@ -112,10 +125,15 @@ impl Cipher { } } - /// Open a ciphertext from any of this cipher's keysets, as the value it - /// was sealed as, or an array of them. With a record first, open its - /// stored row, or an array of them, in one key request for each keyset - /// they were sealed under. + /// Decrypts a ciphertext, or an array of ciphertexts, made under any of + /// this cipher's keysets. Each value decrypts as the type it was + /// encrypted as. + /// + /// 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. The cipher makes one key request + /// for each keyset the rows were encrypted under. A key request is one + /// request to ZeroKMS for data keys. #[napi(ts_return_type = "Promise>")] pub fn decrypt<'e>( &self, @@ -132,8 +150,9 @@ impl Cipher { open(env, &self.engine, first, Confined::No) } - /// Open one field of a record's stored row, as `encryptField` or - /// `encrypt` stored it, or an array of them in one key request. + /// 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. #[napi(ts_return_type = "Promise>")] pub fn decrypt_field<'e>( &self, @@ -145,7 +164,7 @@ impl Cipher { open_field(env, &self.engine, record, field, stored, Confined::No) } - /// Names the type. + /// Returns the type's name. #[napi(js_name = "toString")] pub fn describe(&self) -> &'static str { "Cipher" @@ -154,17 +173,23 @@ impl Cipher { #[napi] impl Keyset { - /// Encrypt a value, with no context, as one ciphertext with its own data - /// key. An array of values is an array of ciphertexts, in the same - /// order, made with one key request however long it is. All or nothing: - /// one value refused is a failure for the whole array, before any - /// request. + /// Encrypts a value as one ciphertext with its own data key, with no + /// context. A context is a value that a ciphertext is bound to, and + /// decrypting needs the same context. /// - /// A value's type picks how it is encrypted, by vitaminc's mapping for - /// JavaScript. A `Json` from `json(..)` is encrypted as a JSON document. + /// An array of values returns an array of ciphertexts, in the same + /// order. The keyset makes one key request for the whole array, however + /// long it is. A key request is one request to ZeroKMS for data keys. If + /// any value is refused, the whole array fails, before any request. /// - /// With a record first, encrypt its row, or an array of them in one key - /// request: each field under its field path. + /// A value's type sets how it is encrypted. The mapping of JavaScript + /// types comes from vitaminc, CipherStash's cryptography library. A + /// `Json` from `json(..)` is encrypted as a JSON document. + /// + /// 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. #[napi(ts_return_type = "Promise>")] pub fn encrypt<'e>( &self, @@ -222,10 +247,12 @@ impl Keyset { ) } - /// Open a ciphertext sealed under this keyset, or an array of them. A - /// ciphertext of another keyset is a failure with the code - /// `stack_encrypt::foreign_keyset`, before any key is requested. With a - /// record first, open its stored row, or an array of them. + /// 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, decrypts a stored + /// row of that record, or an array of stored rows. #[napi(ts_return_type = "Promise>")] pub fn decrypt<'e>( &self, @@ -242,9 +269,10 @@ impl Keyset { open(env, &self.engine, first, Confined::ToDefault) } - /// Encrypt one field of a record, for an update of that field: its - /// stored form, as the field has it in a whole stored row. An array of - /// values is an array of stored fields, in one key request. + /// 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. #[napi(ts_return_type = "Promise>")] pub fn encrypt_field<'e>( &self, @@ -256,8 +284,8 @@ impl Keyset { seal_field(env, &self.engine, record, field, value) } - /// Open one field of a record's stored row sealed under this keyset, or - /// an array of them in one key request. + /// Decrypts one field of a record's stored row made under this keyset. + /// An array of stored fields decrypts in one key request. #[napi(ts_return_type = "Promise>")] pub fn decrypt_field<'e>( &self, @@ -276,21 +304,24 @@ impl Keyset { ) } - /// Names the type. + /// Returns the type's name. #[napi(js_name = "toString")] pub fn describe(&self) -> &'static str { "Keyset" } } -/// A cipher over the engine's deterministic test keys, from a 32-byte seed: -/// every key is a function of the seed and the value's context, so a value -/// sealed by one test cipher opens in another with the same seed. It needs -/// no credentials and makes no request. Its keys are no secret from anyone -/// who knows the seed. +/// 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 +/// value encrypted by one test cipher decrypts in another with the same +/// seed. +/// +/// The test cipher needs no credentials and makes no request. Anyone who +/// knows the seed can derive its keys. /// -/// Only a build with the `testing` feature has one; any other resolves to -/// a failure with the code `recipher::no_testing`. +/// Only a build with the `testing` feature has the test cipher. In any +/// other build, the promise resolves to a failure with the code +/// `recipher::no_testing`. #[napi(ts_return_type = "Promise>")] pub fn create_testing<'e>( env: &'e Env, @@ -324,7 +355,7 @@ fn testing(env: &Env, _seed: [u8; 32]) -> napi::Result refused(env, Error::NoTesting.into()) } -/// A new cipher's JavaScript value. +/// Returns the JavaScript value of a new cipher. fn cipher_value(env: &Env, engine: Engine) -> Outcome> { Ok(Cipher { engine: Arc::new(engine), @@ -334,17 +365,17 @@ fn cipher_value(env: &Env, engine: Engine) -> Outcome> { .to_unknown()) } -/// Which keysets a decrypt opens a value of. +/// The keysets whose values a decrypt call accepts. #[derive(Clone, Copy)] enum Confined { - /// Any of the cipher's. + /// Any of the cipher's keysets. No, - /// The default keyset's alone. + /// Only the default keyset. ToDefault, } -/// Open a ciphertext, or an array of them, as `cipher.decrypt` and -/// `keyset.decrypt` do. +/// Decrypts a ciphertext, or an array of them, for `cipher.decrypt` and +/// `keyset.decrypt`. fn open<'e>( env: &'e Env, engine: &Arc, @@ -394,9 +425,9 @@ fn open<'e>( ) } -/// One value to seal, and the kind its ciphertext opens as: a `Json`'s -/// document, which opens as JSON, or any other value, which opens as what -/// it was sealed as. +/// Returns one value to encrypt, and the kind its ciphertext decrypts as. A +/// `Json`'s document decrypts as JSON. Any other value decrypts as the type +/// it was encrypted as. fn one_value(env: &Env, value: Unknown<'_>) -> Outcome<(OneValue, Option)> { if let Some(document) = Json::of(env, value) { return Ok((OneValue::json(document?), Some(ValueKind::Json))); @@ -404,9 +435,10 @@ fn one_value(env: &Env, value: Unknown<'_>) -> Outcome<(OneValue, Option(env: &'e Env, records: Unknown<'_>) -> napi::Result> { let checked = check(env, records); @@ -415,7 +447,8 @@ pub fn check_declarations<'e>(env: &'e Env, records: Unknown<'_>) -> napi::Resul }) } -/// Build the plan of each declaration in `records`, an array of them. +/// 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?, @@ -427,7 +460,8 @@ fn check(env: &Env, records: Unknown<'_>) -> Outcome<()> { Ok(()) } -/// The `records` of `Cipher.create`'s options, if it names any. +/// 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), @@ -435,7 +469,8 @@ fn records_of_options<'e>(env: &Env, options: Option>) -> Outcome) -> Outcome> { if !js::is_record(env, &record) { return Err(Error::NotARecord.into()); @@ -443,8 +478,8 @@ fn plan_of(env: &Env, record: Unknown<'_>) -> Outcome> { RecordPlan::of(&js::read(env, record)?) } -/// The values of `value`: its elements when it is an array, and whether it -/// was one. +/// 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?)), @@ -452,7 +487,8 @@ fn one_or_many<'e>(env: &Env, value: Unknown<'e>) -> Outcome<(bool, Vec( env: &'e Env, many: bool, @@ -464,8 +500,9 @@ fn one_or_array<'e>( values.pop().ok_or_else(|| Error::NoResult.into()) } -/// A row of `plan`'s record, read and each field read as its kind. A value -/// vitaminc refuses is named by the field it was read from. +/// 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) { @@ -482,7 +519,7 @@ fn read_row(env: &Env, plan: &RecordPlan, row: Unknown<'_>) -> Outcome( env: &'e Env, engine: &Arc, @@ -521,7 +558,7 @@ fn seal_rows_of<'e>( ) } -/// `cipher.decrypt(record, stored | stored[])` and `keyset.decrypt`. +/// Runs `cipher.decrypt(record, stored | stored[])` and `keyset.decrypt`. fn open_rows_of<'e>( env: &'e Env, engine: &Arc, @@ -564,7 +601,8 @@ fn open_rows_of<'e>( ) } -/// The plan of `field` of `record` alone, and the field's name. +/// 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<'_>, @@ -576,7 +614,7 @@ fn field_plan_of( Ok((plan.field(&name)?, name)) } -/// `keyset.encryptField(record, field, value | values)`. +/// Runs `keyset.encryptField(record, field, value | values)`. fn seal_field<'e>( env: &'e Env, engine: &Arc, @@ -619,7 +657,7 @@ fn seal_field<'e>( ) } -/// `cipher.decryptField(record, field, stored | stored[])` and +/// Runs `cipher.decryptField(record, field, stored | stored[])` and /// `keyset.decryptField`. fn open_field<'e>( env: &'e Env, @@ -669,8 +707,9 @@ fn open_field<'e>( ) } -/// Seal values under `keyset`, each as one ciphertext with its own data -/// key, in one key request however many there are. +/// 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. pub(crate) async fn seal( keyset: &KeysetCipher<'_, K>, values: Vec, @@ -682,14 +721,16 @@ where .encrypt_into::, K>(keyset) .await .map_err(|error| match error { - // No ciphertext exists yet, so this is the value, not damage. + // No ciphertext exists yet, so the value caused this failure, + // not a damaged ciphertext. stack_encrypt::Error::Aead => Error::NotSealed.into(), error => RecipherErrorFields::engine(&error), }) } -/// Open ciphertexts through `cipher` (a cipher, or one keyset of it), in -/// one key request for each keyset they were sealed under. +/// Decrypts ciphertexts through `cipher`: a cipher, or one keyset of it. +/// The function makes one key request for each keyset the ciphertexts +/// were made under. pub(crate) async fn unseal<'c, K>( cipher: impl Into>, sealed: Vec, diff --git a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs index d52aca1d9..d964effd9 100644 --- a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs +++ b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs @@ -1,4 +1,7 @@ -//! [`Ciphertext`]: one sealed value, as JavaScript holds it. +//! The [`Ciphertext`] class: one encrypted value, as a JavaScript object. +//! +//! The engine that encrypts it is the Stack Encrypt engine, the +//! `stack-encrypt` crate. use napi::bindgen_prelude::{ ClassInstance, FromNapiValue, JavaScriptClassExt, JsValue, Object, Uint8Array, Uint8ArraySlice, @@ -15,16 +18,18 @@ use crate::error::{Error, RecipherErrorFields}; use crate::js; use crate::outcome::{failed, not_made, settle, Outcome}; -/// One sealed value: the engine's opaque ciphertext, with its own data key. +/// One encrypted value: the engine's opaque ciphertext of the whole value, +/// with its own data key. A data key is the key that encrypts one value. /// -/// Its bytes are the engine's sealed-value envelope, the bytes Rust's -/// `Ciphertext::to_bytes` and the Go SDK write. `Debug` hides them, and so -/// do `toString()` and Node's `inspect`: the class has no own properties. +/// The ciphertext's bytes are the engine's envelope for an encrypted value. +/// Rust's `Ciphertext::to_bytes` and the Go SDK write the same bytes. +/// `Debug` hides the bytes. So do `toString()` and Node's `inspect`, +/// because the class has no own properties. /// -/// It exists as a class, rather than as the bytes, so that `decrypt` can -/// tell a ciphertext from any other value, and so that it carries the type -/// it opens as: a JSON document is sealed as its JSON text, and nothing in -/// the bytes says it is JSON. +/// The SDK uses a class rather than plain bytes for two reasons. First, +/// `decrypt` can tell a ciphertext from any other value. Second, the class +/// records the type the value decrypts as. A JSON document is encrypted as +/// its JSON text, and nothing in the bytes says that it is JSON. #[napi] #[derive(Clone, OpaqueDebug)] pub struct Ciphertext { @@ -33,17 +38,19 @@ pub struct Ciphertext { } impl Ciphertext { - /// `sealed`, opening as what it was sealed as (`None`), or as `kind`. + /// Wraps `sealed`. When `opens_as` is `None`, the ciphertext decrypts as + /// the type it was encrypted as. Otherwise it decrypts as that kind. pub(crate) fn new(sealed: stack_encrypt::Ciphertext, opens_as: Option) -> Self { Self { sealed, opens_as } } - /// The engine's ciphertext. + /// Returns the engine's ciphertext. pub(crate) fn sealed(&self) -> &stack_encrypt::Ciphertext { &self.sealed } - /// The ciphertext `value` is, or `None` when it is not a `Ciphertext`. + /// Returns a copy of `value` when it is a `Ciphertext`, or `None` when + /// it is not. pub(crate) fn of(env: &Env, value: Unknown<'_>) -> Option { if !Self::instance_of(env, &value).unwrap_or(false) { return None; @@ -53,13 +60,13 @@ impl Ciphertext { .map(|instance| Ciphertext::clone(&instance)) } - /// An opened value, as the kind this ciphertext opens as. + /// Returns a decrypted value as the kind this ciphertext decrypts as. /// /// # Errors /// - /// `recipher::opened_type` for a value sealed as another type, and - /// `recipher::not_a_document` for one named JSON that is not a JSON - /// document. + /// Returns `recipher::opened_type` for a value encrypted as another + /// type. Returns `recipher::not_a_document` when the kind is JSON but + /// the value is not a JSON document. pub(crate) fn opened(&self, value: ValueFrame) -> Outcome { match self.opens_as { None => Ok(value), @@ -71,16 +78,18 @@ impl Ciphertext { #[napi] impl Ciphertext { - /// Read a ciphertext from stored bytes, a `Uint8Array` or a `Buffer`. - /// This checks the bytes' shape only; decrypting is what authenticates - /// them. A failure does not quote the bytes. + /// Reads a ciphertext from stored bytes, a `Uint8Array` or a `Buffer`. + /// This method checks only the shape of the bytes. Decrypting is what + /// checks that they are authentic. A failure does not quote the bytes. /// - /// With a kind, such as `kinds.string`, it opens as that kind, and - /// decrypting refuses a value sealed as another type. `kinds.json` opens - /// a JSON document. With none, it opens as whatever it was sealed as, - /// and a JSON document opens as its JSON text. - // Configurable, as an instance method is, so the package's TypeScript - // can wrap it (`adapt`). + /// Give a kind, such as `kinds.string`, to decrypt the value as that + /// kind. Decrypting then refuses a value encrypted as another type. + /// `kinds.json` decrypts a JSON document. + /// + /// With no kind, the value decrypts as the type it was encrypted as. A + /// JSON document then decrypts as its JSON text. + // An instance method is configurable. This static method is made + // configurable too, so the package's TypeScript can wrap it (`adapt`). #[napi(configurable = true, ts_return_type = "Outcome")] pub fn from_bytes<'e>( env: &'e Env, @@ -103,26 +112,29 @@ impl Ciphertext { }) } - /// The bytes to store: a copy, so changing it changes no ciphertext. + /// Returns the bytes to store. They are a copy, so changing them does + /// not change any ciphertext. #[napi] pub fn to_bytes(&self) -> Uint8Array { Uint8Array::from(self.sealed.to_bytes()) } - /// Names the type and hides the bytes. + /// Returns the type's name, and hides the bytes. #[napi(js_name = "toString")] pub fn describe(&self) -> &'static str { "Ciphertext(***)" } } -/// A kind, as the package's `kinds` spells it: `{ name: "string" }`. +/// A kind, in the form the package's `kinds` object writes it: +/// `{ name: "string" }`. #[derive(Deserialize)] struct KindArgument { name: String, } -/// The kind `value` names, or `None` for `undefined`. +/// Returns the kind that `value` names, or `None` when `value` is absent or +/// `undefined`. fn kind_of(env: &Env, value: Option>) -> Outcome> { let Some(value) = value.filter(|value| value.get_type().ok() != Some(ValueType::Undefined)) else { @@ -141,7 +153,7 @@ fn kind_of(env: &Env, value: Option>) -> Outcome> Ok(Some(kind)) } -/// Whether `kind` is an integer kind. +/// Returns whether `kind` is an integer kind. fn integer(kind: ValueKind) -> bool { matches!( kind, @@ -158,9 +170,11 @@ fn integer(kind: ValueKind) -> bool { ) } -/// `value` as `kind`: itself when it is of that kind; an integer of another -/// width, or a float of another width, converted by the engine's `read` -/// when the conversion is exact; anything else refused. +/// Returns `value` as `kind`. +/// +/// A value of that kind is returned unchanged. The engine's `read` converts +/// an integer to another integer width, or a float to another float width, +/// when the conversion is exact. Any other value is refused. fn as_kind(kind: ValueKind, value: ValueFrame) -> Outcome { let refused = || RecipherErrorFields::from(Error::OpenedType { kind }); let opened = value.kind(); @@ -176,10 +190,13 @@ fn as_kind(kind: ValueKind, value: ValueFrame) -> Outcome { read(kind, &value).map_err(|_| refused()) } -/// The bytes of a `Uint8Array` (a `Buffer` is one), copied, or `None` for -/// any other value. Read as a borrowed slice, as vitaminc reads bytes: -/// napi's owned `Uint8Array` keeps a reference to a typed array of another -/// element type it refuses. +/// Returns a copy of the bytes of a `Uint8Array`, or `None` for any other +/// value. A `Buffer` is a `Uint8Array`. +/// +/// The function reads the bytes as a borrowed slice. That is how vitaminc, +/// CipherStash's cryptography library, reads bytes. napi's owned +/// `Uint8Array` is not used. When it refuses a typed array of another +/// element type, it still keeps a reference to that array. pub(crate) fn bytes_of(value: Unknown<'_>) -> Option> { if !value.is_typedarray().unwrap_or(false) { return None; diff --git a/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs b/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs index deb24d5bf..e91a1f2c3 100644 --- a/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs +++ b/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs @@ -1,5 +1,6 @@ -//! The crate's seal and open against the engine's typed API: each reads the -//! other's ciphertexts, so the bytes are the engine's, for every type. +//! Tests of the crate's encrypt and decrypt against the engine's typed +//! Rust API. Each side decrypts the other's ciphertexts. So the tests show +//! that the crate writes the engine's bytes, for every type. use std::borrow::Cow; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -33,14 +34,14 @@ fn one(value: P) -> OneValue { OneValue::scalar(ValueFrame::of(value).unwrap()).unwrap() } -/// Seal `values` through the crate, under the test keys. +/// Encrypts `values` through the crate, with the test keys. async fn sdk_seal(values: Vec) -> Vec { seal(&engine().await.default_keyset(), values) .await .unwrap() } -/// Open `sealed` through the crate, under the test keys. +/// Decrypts `sealed` through the crate, with the test keys. async fn sdk_open(sealed: stack_encrypt::Ciphertext) -> ValueFrame { unseal(&engine().await, vec![sealed]) .await @@ -55,8 +56,8 @@ async fn the_engine_opens_what_the_sdk_sealed() { let sealed = sdk_seal(vec![one("from the sdk"), one(42i8), one(1.5f64)]).await; let mut sealed = sealed.into_iter(); let text: String = keyset.decrypt(sealed.next().unwrap()).await.unwrap(); - // vitaminc reads a `bigint` at its narrowest width; the engine opens it - // at any width that holds it. + // vitaminc reads a `bigint` at its narrowest width. The engine decrypts + // it at any width that fits it. let int: i64 = keyset.decrypt(sealed.next().unwrap()).await.unwrap(); let float: f64 = keyset.decrypt(sealed.next().unwrap()).await.unwrap(); assert_eq!((text.as_str(), int, float), ("from the sdk", 42, 1.5)); @@ -112,8 +113,9 @@ async fn a_json_document_the_engine_sealed_opens_as_json_with_its_big_integer() .unwrap(); let ciphertext = Ciphertext::new(sealed.clone(), Some(ValueKind::Json)); let opened = ciphertext.opened(sdk_open(sealed).await).unwrap(); - // A safe integer opens as a float, as a JavaScript `number`; one outside - // the safe range as an integer, a `bigint`. + // A safe integer decrypts as a float, for a JavaScript `number`. An + // integer outside the safe range decrypts as an integer, for a + // JavaScript `bigint`. let expected = crate::json::document(&opened).unwrap(); assert_eq!( expected.value(), @@ -126,7 +128,7 @@ async fn a_json_document_the_engine_sealed_opens_as_json_with_its_big_integer() ); } -/// `{"id": u64::MAX, "n": 5.0}`, as the crate opens the document above. +/// `{"id": u64::MAX, "n": 5.0}`, as the crate decrypts the document above. struct OpenedDocument; impl Encrypt for &OpenedDocument { @@ -156,8 +158,9 @@ async fn a_json_document_the_sdk_sealed_is_the_engines_json_plaintext() { ); } -/// `{"name": "Ada", "age": 36.0, "big": u64::MAX}` as a JavaScript caller -/// hands it over: a number is a float, a `bigint` an integer. +/// `{"name": "Ada", "age": 36.0, "big": u64::MAX}`, in the form a +/// JavaScript caller passes it: a number is a float, and a `bigint` is an +/// integer. struct Document; impl Encrypt for &Document { @@ -193,7 +196,7 @@ async fn a_ciphertext_of_another_seed_does_not_open() { assert!(unseal(&other, sealed).await.is_err()); } -/// A deterministic key source that counts the key requests it is sent. +/// A deterministic key source that counts the key requests it receives. struct Counting { inner: DeterministicSource, generates: AtomicUsize, diff --git a/languages/typescript/packages/recipher-js/crate/src/error.rs b/languages/typescript/packages/recipher-js/crate/src/error.rs index 79fcd1457..8ec6c5a02 100644 --- a/languages/typescript/packages/recipher-js/crate/src/error.rs +++ b/languages/typescript/packages/recipher-js/crate/src/error.rs @@ -1,16 +1,24 @@ -//! Every failure the addon reports, as the object JavaScript receives. +//! Every failure the addon reports, in the form of the object JavaScript +//! receives. //! -//! An error is a miette diagnostic: the engine's, the value bridge's -//! [`Refusal`](recipher_value_napi::Refusal), or one of the SDK's own in -//! [`Error`]. [`RecipherErrorFields::diagnostic`] turns any of them into a -//! [`RecipherErrorFields`]: its code, message, help, documentation URL, -//! severity, structured fields and causes. No error here holds a plaintext, -//! a key, a token or a ciphertext. +//! Each error is a miette diagnostic: an error with a code, a message and +//! optional help. An error comes from one of three places: //! -//! A cause that is one of the engine's own diagnostics gives its code and -//! message. A cause from another library gives [`UNDESCRIBED_CAUSE`] and -//! nothing else: its message is text the engine does not vouch for, and is -//! never copied. +//! - the engine: the Stack Encrypt engine, the `stack-encrypt` crate; +//! - the value bridge, the `recipher-value-napi` crate that converts +//! JavaScript values, as a [`Refusal`](recipher_value_napi::Refusal); +//! - the SDK itself, as an [`Error`]. +//! +//! [`RecipherErrorFields::diagnostic`] turns any of them into a +//! [`RecipherErrorFields`]. That object has the error's code, message, +//! help, documentation URL, severity, structured fields and causes. No +//! error here contains a plaintext, a key, a token or a ciphertext. +//! +//! A cause is an error that led to another error. For a cause that is one +//! of the engine's own diagnostics, the failure includes its code and +//! message. A cause from another library is reported as +//! [`UNDESCRIBED_CAUSE`] and nothing else. Its message is text that the +//! engine does not control, so the addon never copies it. use std::error::Error as StdError; @@ -19,8 +27,8 @@ use napi_derive::napi; use stack_encrypt::dynamic::ValueKind; use stack_encrypt::ErrorPayload; -/// The SDK's own errors: what the addon refuses before the engine sees it, -/// and what goes wrong between the engine and JavaScript. +/// The SDK's own errors. They cover what the addon refuses before the +/// engine reads it, and what goes wrong between the engine and JavaScript. #[derive(Debug, thiserror::Error, Diagnostic)] pub(crate) enum Error { /// `undefined` given as a value. @@ -30,16 +38,17 @@ pub(crate) enum Error { help("Use `null` for a value that is not there.") )] Undefined, - /// A `VcUuid`, which the engine's value model does not hold. + /// A `VcUuid`. The engine's value model, the set of value types the + /// engine reads, has no UUID type. #[error("a UUID cannot be encrypted yet: the engine's value model does not hold one")] #[diagnostic(code(recipher::uuid), help("Encrypt its text instead."))] Uuid, - /// A value outside the engine's value model, or one Node-API failed to - /// read. + /// A value outside the engine's value model, or a value that Node-API + /// failed to read. #[error("the value cannot be encrypted: it is not one the engine reads")] #[diagnostic(code(recipher::value))] Value, - /// A getter of the application's threw while the value was read. + /// A getter in the application threw while the addon read the value. #[error( "reading the value threw. The thrown error is not kept, because its message may hold the value" )] @@ -53,17 +62,17 @@ pub(crate) enum Error { #[error("an object is not a value")] #[diagnostic(code(recipher::plain_object), help("Wrap it in json(..)."))] PlainObject, - /// A value that is not a JSON document the engine seals. + /// A value that the engine cannot encrypt as a JSON document. #[error("the value is not a JSON document the engine seals: {what}")] #[diagnostic(code(recipher::not_json))] NotJson { what: &'static str }, - /// A JSON document nested deeper than the engine's parser reads. + /// A JSON document nested deeper than the engine's JSON parser reads. #[error( "the value is not a JSON document the engine seals: it is nested deeper than 127 levels of arrays and objects" )] #[diagnostic(code(recipher::too_deep))] JsonTooDeep, - /// The engine refused to seal a value as it was given. + /// The engine refused to encrypt a value in the form it was given. #[error("the engine could not seal the value as given")] #[diagnostic(code(recipher::not_sealed))] NotSealed, @@ -82,11 +91,11 @@ pub(crate) enum Error { #[error("a ciphertext opens as one of `kinds`, such as `kinds.string`")] #[diagnostic(code(recipher::not_a_kind))] NotAKind, - /// A ciphertext that opened as another kind than the one named. + /// A ciphertext that decrypted to another kind than the one named. #[error("the value opened, but it was not sealed as the kind named, {kind}")] #[diagnostic(code(recipher::opened_type))] OpenedType { kind: ValueKind }, - /// A ciphertext named JSON that opened as text that is not JSON. + /// A ciphertext named as JSON that decrypted to text that is not JSON. #[error("the value opened, but it is not a JSON document")] #[diagnostic(code(recipher::not_a_document))] NotADocument, @@ -94,8 +103,8 @@ pub(crate) enum Error { #[error("a test cipher's seed is a Uint8Array of 32 bytes")] #[diagnostic(code(recipher::testing_seed))] TestingSeed, - /// `createTesting` in a build without the test cipher. - // A build with the test cipher never raises it. + /// `createTesting`, called in a build without the test cipher. + // A build with the test cipher never returns this error. #[cfg_attr(feature = "testing", allow(dead_code))] #[error("this native build has no test cipher")] #[diagnostic( @@ -115,7 +124,7 @@ pub(crate) enum Error { #[error("a field is declared with encrypt(..) or passthrough()")] #[diagnostic(code(recipher::declaration))] Declaration, - /// A field named with a name the engine reserves. + /// A field whose name the engine reserves. #[error("the field's name is one the engine reserves")] #[diagnostic(code(recipher::reserved_field), help("Name the field something else."))] ReservedField, @@ -123,15 +132,20 @@ pub(crate) enum Error { #[error("`{name}` is not one of `kinds`")] #[diagnostic(code(recipher::kind))] Kind { name: String }, - /// A field's index that is not one the SDK names. + /// A field's index that is not one of the indexes the SDK names. #[error("`{name}` is not an index")] #[diagnostic(code(recipher::index))] Index { name: String }, - /// A field's null mode that is not one the engine has. + /// 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::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::context))] Context, @@ -142,8 +156,10 @@ pub(crate) enum Error { 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 named that the record does not seal: no such field, a - /// passthrough field, or a name that is not a string. + /// 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::no_field), @@ -158,7 +174,8 @@ pub(crate) enum Error { #[error("the value is not of the field's kind, {kind}, or does not fit it")] #[diagnostic(code(recipher::field_type))] FieldType { kind: ValueKind }, - /// A stored row that does not have the record's shape. + /// 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::not_a_stored_row))] NotAStoredRow { what: &'static str }, @@ -211,28 +228,34 @@ impl From for Severity { #[napi(object)] #[derive(Clone, Debug, PartialEq, Eq)] pub struct RecipherErrorFields { - /// Stable: the diagnostic's code, such as `stack_encrypt::aead`, - /// vitaminc's code for a value it refused, such as `ERR_INTEGER_RANGE`, - /// or the SDK's own, such as `recipher::not_a_ciphertext`. + /// The error's code. A code is stable, so a caller can match on it. + /// The code is one of three kinds: + /// + /// - a diagnostic's code, such as the engine's `stack_encrypt::aead`; + /// - the code of vitaminc, CipherStash's cryptography library, for a + /// value it refused, such as `ERR_INTEGER_RANGE`; + /// - the SDK's own code, such as `recipher::not_a_ciphertext`. pub code: String, /// What went wrong, in one line. pub message: String, - /// What to do about it, where the error knows. + /// What to do about the error, when the error says. pub help: Option, - /// A documentation page for the error, where it has one. + /// A documentation page for the error, when it has one. pub url: Option, - /// How serious it is: `error` unless the diagnostic says otherwise. + /// How serious the failure is. The severity is `error` unless the + /// diagnostic states another one. pub severity: Severity, - /// The error's structured fields, by `snake_case` name: a refused - /// plan's `field` and `reason`, a ZeroKMS failure's `request_kind`. - /// Empty where the error has none. + /// 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. pub fields: serde_json::Map, - /// The errors behind this one, outermost first. + /// The errors that caused this one, outermost first. pub causes: Vec, - /// The field at fault, where one is known. + /// The field at fault, when it is known. pub field: Option, - /// The record at fault, where one is known: a declaration, a row or a - /// stored row of it. + /// The record at fault, when it is known. The fault is in the record's + /// declaration, in a row of it, or in a stored row of it. pub record: Option, } @@ -240,30 +263,32 @@ pub struct RecipherErrorFields { #[napi(object)] #[derive(Clone, Debug, PartialEq, Eq)] pub struct ErrorCause { - /// The cause's code, where it is one of the engine's own errors. + /// The cause's code, when the cause is one of the engine's own errors. pub code: Option, - /// The engine error's message. For an error from another library, the - /// fixed text `an error from another library`. + /// The message of the engine's error. For an error from another + /// library, the message is this fixed text: + /// `an error from another library`. pub message: String, } -/// What a cause from another library is reported as. +/// The message reported for a cause from another library. pub const UNDESCRIBED_CAUSE: &str = "an error from another library"; -/// How deep the cause chain is followed. A chain this long is a loop or a -/// bug, and a bounded walk cannot be made to spin. +/// The most causes the addon reads from a cause chain. A chain this long +/// is a loop or a bug. The limit means a looping chain cannot make the walk +/// run forever. const MAX_CAUSES: usize = 16; -/// One link of a cause chain. +/// One cause in a cause chain. enum Cause<'a> { - /// One of the engine's errors, reached as a diagnostic source. + /// One of the engine's errors, found as a diagnostic source. Ours(&'a dyn Diagnostic), - /// Anything reached as a plain source. + /// Any error found as a plain source. Foreign(&'a (dyn StdError + 'static)), } -/// The cause after a diagnostic: its diagnostic source, or else its plain -/// source. +/// Returns the cause of a diagnostic: its diagnostic source if it has one, +/// or else its plain source. fn next_of(diagnostic: &dyn Diagnostic) -> Option> { diagnostic .diagnostic_source() @@ -271,8 +296,9 @@ fn next_of(diagnostic: &dyn Diagnostic) -> Option> { .or_else(|| diagnostic.source().map(Cause::Foreign)) } -/// The error's causes, in order. Once the chain leaves the diagnostics it -/// follows plain sources to the end. +/// Returns the error's causes, in order. After the first cause that is not +/// a diagnostic, the walk follows only plain sources, to the end of the +/// chain. fn causes_of(error: &dyn Diagnostic) -> Vec { let mut out = Vec::new(); let mut next = next_of(error); @@ -301,16 +327,17 @@ fn causes_of(error: &dyn Diagnostic) -> Vec { } impl RecipherErrorFields { - /// The failure for any diagnostic, with the structured fields of - /// `payload` where there is one. `field` is the payload's `field`, where - /// it names one. + /// Returns the failure for any diagnostic. The structured fields come + /// from `payload`, when there is one. The failure's `field` is the + /// payload's `field`, when the payload has one. pub(crate) fn diagnostic( error: &dyn Diagnostic, payload: Option>, ) -> Self { let fields = payload.unwrap_or_default(); Self { - // Every error the addon reports has a code; this is never seen. + // Every error the addon reports has a code, so JavaScript never + // receives this fallback. code: error .code() .map_or_else(|| "recipher::unknown".to_owned(), |code| code.to_string()), @@ -328,25 +355,26 @@ impl RecipherErrorFields { } } - /// The failure for an engine error, with its structured fields. + /// Returns the failure for an engine error, with its structured fields. pub(crate) fn engine(error: &E) -> Self { Self::diagnostic(error, Some(error.payload())) } - /// This failure, naming the record at fault. + /// 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 } - /// This failure, naming the field at fault, or none. + /// 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 } - /// The engine's reason token, such as `no_fields`, where the error's - /// fields hold one. + /// 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") @@ -369,8 +397,8 @@ mod tests { fn an_aead_failure_keeps_the_engine_code_message_and_help() { let error = RecipherErrorFields::engine(&stack_encrypt::Error::Aead); assert_eq!(error.code, "stack_encrypt::aead"); - // The message is the engine's one line. Its help is a field of - // its own, never appended. + // The message is the engine's one-line message. The help is a + // separate field, and is never appended to the message. assert_eq!(error.message, stack_encrypt::Error::Aead.to_string()); assert!(error .help @@ -417,11 +445,13 @@ mod tests { assert_eq!(error.help.as_deref(), Some("try again")); assert_eq!(error.url.as_deref(), Some("https://example.com/outer")); assert_eq!(error.severity, Severity::Warning); - // Every payload field crosses, and `field` is also the typed one. + // Every payload field reaches the failure, and the payload's + // `field` also sets the typed `field`. assert_eq!(error.fields["count"], 3); assert_eq!(error.field.as_deref(), Some("age")); - // The engine's own cause keeps its code. The other library's is - // named as one and its message is not copied. + // The engine's own cause keeps its code. The other library's cause + // is reported as one from another library, and its message is not + // copied. assert_eq!( error.causes, [ @@ -451,8 +481,8 @@ mod tests { assert!(error.fields.is_empty() && error.causes.is_empty()); } - /// One of every variant of [`Error`]. The match has no wildcard, so a - /// variant added without a row here does not compile. + /// 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![ diff --git a/languages/typescript/packages/recipher-js/crate/src/frames.rs b/languages/typescript/packages/recipher-js/crate/src/frames.rs index d110bce88..5a763a8c5 100644 --- a/languages/typescript/packages/recipher-js/crate/src/frames.rs +++ b/languages/typescript/packages/recipher-js/crate/src/frames.rs @@ -1,8 +1,16 @@ -//! Reading a map frame entry by entry, and writing one in a given order. +//! Helpers that read a map frame one entry at a time, and write a map frame +//! in a given order. //! -//! A record's row and its stored row cross the binding as one frame each: a -//! map of the record's fields. These helpers split such a frame into one -//! frame per entry, and write entries back as one map, in the order given. +//! 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, @@ -12,8 +20,8 @@ use stack_encrypt::{AsProtectedRef, Buffer, Encrypt, EncryptRef}; use vitaminc_aead::frame::{FrameError, FrameWriteError}; use vitaminc_aead::{Frame, FrameWriter}; -/// The entries of a map frame, each as its own frame, in the frame's order, -/// or `None` when the frame is not a map. +/// 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 @@ -26,26 +34,30 @@ pub(crate) fn entries(frame: &ValueFrame) -> Option> { .collect() } -/// The bytes of a frame that is one bytes leaf, or `None`. +/// 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 written by [`Map`]. +/// One entry of a map that [`Map`] writes. pub(crate) enum Entry<'a> { - /// A value, walked as it is. + /// A value, written as it is. Value(&'a ValueFrame), - /// Bytes, as a bytes leaf. + /// Bytes, written as a bytes value. Bytes(Vec), - /// A frame held as bytes, such as a passthrough node's, walked in place. + /// 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 map of its own. + /// A nested map. Map(Map<'a>), /// A null. Null, } -/// A map, its entries written in the order given. +/// 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<'_> { @@ -77,13 +89,13 @@ impl Encrypt for &Map<'_> { } } -/// A walk that writes each entry of a map into a buffer of its own. +/// A sink that writes each entry of a map into its own buffer. struct Split; -/// The entries written so far. +/// The entries that [`Split`] has written so far. struct Collect(Vec<(String, Buffer)>); -/// What [`Split`] refuses anything but a map with. +/// 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")) } @@ -132,7 +144,8 @@ impl MapSink for Collect { } } -/// Never made: [`Split`] refuses a sequence before it would be. +/// A type that is never created, because [`Split`] refuses a sequence +/// before it would create one. struct NotAMap; impl SeqSink for NotAMap { @@ -151,10 +164,10 @@ impl SeqSink for NotAMap { } } -/// A walk that reads one bytes leaf. +/// A sink that reads one bytes value. struct BytesOf; -/// A refusal with no text: the caller writes its own. +/// An error with no text. The caller writes its own message. struct NotBytes; impl SinkError for NotBytes { @@ -189,7 +202,8 @@ impl Sink for BytesOf { } } -/// Never made: [`BytesOf`] refuses a container before it would be. +/// 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 { diff --git a/languages/typescript/packages/recipher-js/crate/src/js.rs b/languages/typescript/packages/recipher-js/crate/src/js.rs index 450d8fcdc..78e366b30 100644 --- a/languages/typescript/packages/recipher-js/crate/src/js.rs +++ b/languages/typescript/packages/recipher-js/crate/src/js.rs @@ -1,17 +1,25 @@ -//! JavaScript values in and out, through `recipher-value-napi`. +//! Converts JavaScript values to and from the engine's values, through the +//! value bridge, the `recipher-value-napi` crate. //! -//! A value is read with `JsRef::to_frame`, on the JavaScript thread, into -//! the engine's [`ValueFrame`]: a buffer wiped when it drops, which a worker -//! thread then seals with no access to JavaScript. An opened frame is built -//! back into a JavaScript value with `JsBuilder::build`. Nothing here -//! converts a value itself. +//! The engine is the Stack Encrypt engine, the `stack-encrypt` crate. The +//! engine's value model is the set of value types it reads. //! -//! When the bridge refuses a value it says which rule the value broke, and -//! for a scalar it also throws into JavaScript. [`read`] turns either into a -//! [`RecipherErrorFields`], so a call that reads a value returns an outcome -//! rather than throwing. What a -//! getter of the application's threw is caught and dropped, never copied: -//! its message may hold the value. +//! `JsRef::to_frame` reads a JavaScript value, on the JavaScript thread, +//! into the engine's [`ValueFrame`]. A frame is a byte buffer that contains +//! one value. The buffer is wiped when it drops. A worker thread then +//! encrypts the frame, with no access to JavaScript. `JsBuilder::build` +//! builds a decrypted frame back into a JavaScript value. This module does +//! not convert any value itself. +//! +//! When the bridge refuses a value, it says which rule the value broke. A +//! scalar is a value that is not an array or an object. For a scalar, the +//! bridge also throws a JavaScript exception. [`read`] turns either into a +//! [`RecipherErrorFields`]. So a call that reads a value returns a failed +//! outcome object, `{ ok: false, error }`, instead of throwing. +//! +//! When an application's getter throws, the addon catches the exception +//! and drops it without copying it. The exception's message may contain +//! the value. use napi::bindgen_prelude::{FromNapiValue, JsObjectValue, JsValue, Object, Unknown}; use napi::{Env, Status, ValueType}; @@ -25,13 +33,17 @@ use vitaminc_protected::Controlled; use crate::error::{Error, RecipherErrorFields}; use crate::outcome::not_made; -/// Read a JavaScript value into the engine's value model. +/// Reads a JavaScript value into a frame of the engine's value model. /// /// # Errors /// -/// `recipher::undefined`, `recipher::uuid` for a `VcUuid`, `recipher::value` -/// for another value outside the engine's value model, `recipher::threw` -/// when reading it threw, or the bridge's code for a value it refused. +/// Returns one of these errors: +/// +/// - `recipher::undefined` for `undefined`; +/// - `recipher::uuid` for a `VcUuid`; +/// - `recipher::value` for another value outside the engine's value model; +/// - `recipher::threw` when reading the value threw; +/// - the bridge's code, for a value the bridge refused. pub fn read(env: &Env, value: Unknown<'_>) -> Result { if value.get_type().ok() == Some(ValueType::Undefined) { return Err(Error::Undefined.into()); @@ -44,12 +56,14 @@ pub fn read(env: &Env, value: Unknown<'_>) -> Result( env: &Env, value: Unknown<'e>, @@ -67,20 +81,21 @@ pub fn elements<'e>( Some(read().map_err(|error| refused(env, &error.into()))) } -/// Build the JavaScript value of an opened frame. +/// Builds the JavaScript value of a decrypted frame. /// /// # Errors /// -/// `recipher::reserved_key` for a value JavaScript cannot hold as it was -/// sealed (a map key vitaminc does not build), and `recipher::build_value` -/// for any other failure. +/// Returns `recipher::reserved_key` for a value that JavaScript cannot +/// represent in the form it was encrypted. That is a value with a map key +/// that vitaminc, CipherStash's cryptography library, does not build. +/// Returns `recipher::build_value` for any other failure. pub fn build(env: &Env, value: ValueFrame) -> Result, RecipherErrorFields> { let bytes = value.into_inner(); let frame = Frame::parse(bytes.risky_ref()).map_err(|_| Error::BuildValue)?; JsBuilder::build(env, frame).map_err(|error| not_built(env, &error)) } -/// The failure for a value `JsBuilder` did not build. +/// Returns the failure for a value that `JsBuilder` did not build. fn not_built(env: &Env, fault: &JsFault) -> RecipherErrorFields { if fault.status() == Status::PendingException { let _ = take_exception(env); @@ -91,19 +106,20 @@ fn not_built(env: &Env, fault: &JsFault) -> RecipherErrorFields { } } -/// Whether `value` is one of vitaminc's `VcUuid`s. +/// Returns whether `value` is a vitaminc `VcUuid`. fn is_uuid(env: &Env, value: &Unknown<'_>) -> bool { Wrappers::get(env) .and_then(|wrappers| wrappers.classify(value)) .is_ok_and(|wrapper| wrapper == Some(Wrapper::Uuid)) } -/// The property `name` of `value`, when `value` is an object and has it. +/// Returns the property `name` of `value`, when `value` is an object and +/// the property is not `undefined`. /// /// # Errors /// -/// `recipher::threw` when reading it throws, as a getter may; what it threw -/// is dropped. +/// Returns `recipher::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>, @@ -119,9 +135,11 @@ pub(crate) fn property<'e>( Ok((property.get_type().ok() != Some(ValueType::Undefined)).then_some(property)) } -/// Whether `value` is a record's declaration, as `record(..)` makes it: an -/// object whose `type` is `"record"`. The check reads only that property, -/// so it holds for a declaration from any copy of the package. +/// 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; @@ -132,10 +150,11 @@ pub(crate) fn is_record(env: &Env, value: &Unknown<'_>) -> bool { ) } -/// The failure for a call given a second argument whose first is a plain -/// object that is not a declaration: a row with a record that is not one. -/// `None` for anything else, such as a value passed with an index by -/// `Array.prototype.map`. +/// 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<'_>, @@ -154,7 +173,7 @@ pub(crate) fn second_without_record( plain.then(|| Error::NotARecord.into()) } -/// The text of a JavaScript string, or `None` for any other value. +/// 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; @@ -162,11 +181,12 @@ pub(crate) fn string(value: Unknown<'_>) -> Option { String::from_unknown(value).ok() } -/// `row`, an opened row of `record`, with an `inspect` that names its -/// fields and hides their values: Node's `util.inspect` and `console.log` -/// print `users { email: [hidden], .. }`. The method is a property keyed -/// by `Symbol.for('nodejs.util.inspect.custom')` that is not enumerable, -/// so the row's own fields are as they were. +/// 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>, @@ -192,17 +212,19 @@ pub(crate) fn hidden<'e>( .with_name(env, key) .map_err(not_made)? .with_value(&inspect) - // Not enumerable, writable or configurable: no copy, spread or - // comparison of the row sees it, and nothing replaces it. + // 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) } -/// The failure for a value the bridge refused. The bridge says which rule -/// the value broke; nothing here reads its text. An exception may still be -/// pending in JavaScript, and is cleared: what the application threw is -/// never kept, because its message may hold the value. +/// 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 +/// function clears it. What the application threw is never kept, because +/// its message may contain the value. fn refused(env: &Env, fault: &JsFault) -> RecipherErrorFields { if fault.status() == Status::PendingException { let _ = take_exception(env); @@ -214,7 +236,7 @@ fn refused(env: &Env, fault: &JsFault) -> RecipherErrorFields { } } -/// The exception pending in `env`, cleared, if there is one. +/// Clears and returns the exception pending in `env`, if there is one. #[allow(unsafe_code)] fn take_exception(env: &Env) -> Option> { let mut raw = std::ptr::null_mut(); diff --git a/languages/typescript/packages/recipher-js/crate/src/json.rs b/languages/typescript/packages/recipher-js/crate/src/json.rs index cd03d964c..95425092e 100644 --- a/languages/typescript/packages/recipher-js/crate/src/json.rs +++ b/languages/typescript/packages/recipher-js/crate/src/json.rs @@ -1,28 +1,41 @@ -//! A JSON document: [`Json`], made by `json(..)`, and the conversion between -//! a frame and the engine's [`JsonPlaintext`]. +//! JSON documents: the [`Json`] class that `json(..)` makes, and the +//! conversion between a frame and the engine's [`JsonPlaintext`]. //! -//! JavaScript has one number type, and a `number` cannot hold every integer -//! a JSON document can. So on the way in: +//! The engine is the Stack Encrypt engine, the `stack-encrypt` crate. The +//! engine's value model is the set of value types it reads. A frame is a +//! byte buffer that contains one value of the model. A sink receives a +//! value from a frame one part at a time: one scalar, array or map. //! -//! - an object, an array, text, a boolean and null are themselves; -//! - a `number` that is a safe integer (at most 2^53 - 1 from zero) is -//! written as that integer, as `JSON.stringify` writes it, and any other -//! finite `number` as a float, except one that is a whole number between -//! 2^53 and 2^64 from zero: that is refused, because an integer was likely -//! meant and its digits are not the number the caller wrote; -//! - a `bigint` is written as its digits, and is refused outside the 64-bit -//! range the engine's parser reads; -//! - anything else (bytes, a date, a timestamp, a decimal, a UUID, -//! `undefined`) is refused: it has no JSON form; -//! - a document nested deeper than 127 levels is refused, as the engine's -//! parser would refuse it on the way out. +//! # Encrypting //! -//! On the way out, an integer in the safe range is a `number`, and one -//! outside it a `bigint`, so no digit is lost. A float is a `number`. +//! JavaScript has one number type, and a `number` cannot represent every +//! integer that a JSON document can. So a document's values become JSON +//! values by these rules: //! -//! The document is sealed by the engine's [`JsonPlaintext`], as its JSON -//! text, and read back by the engine's parser. Everything built on the way, -//! map keys included, is wiped when it is dropped. +//! - An object, an array, text, a boolean and null stay as they are. +//! - A `number` that is a safe integer is written as that integer, as +//! `JSON.stringify` writes it. A safe integer is at most 2^53 - 1 from +//! zero. +//! - A whole `number` between 2^53 and 2^64 from zero is refused. The +//! caller probably meant an integer, and the `number`'s digits are not the +//! ones the caller wrote. +//! - Any other finite `number` is written as a float. +//! - A `bigint` is written as its digits. A `bigint` outside the 64-bit +//! range that the engine's parser reads is refused. +//! - Any other value is refused, because it has no JSON form. Examples are +//! bytes, a date, a timestamp, a decimal, a UUID and `undefined`. +//! - A document nested deeper than 127 levels is refused, because the +//! engine's parser would refuse it when the document is decrypted. +//! +//! # Decrypting +//! +//! An integer in the safe range becomes a `number`, and an integer outside +//! it becomes a `bigint`, so no digit is lost. A float becomes a `number`. +//! +//! The engine encrypts the document as its JSON text, through +//! [`JsonPlaintext`], and reads it back with the engine's JSON parser. +//! Everything built along the way, including map keys, is wiped when it is +//! dropped. use napi::bindgen_prelude::{ClassInstance, FromNapiValue, JavaScriptClassExt, Unknown}; use napi::Env; @@ -41,23 +54,25 @@ use zeroize::Zeroizing; use crate::error::{Error, RecipherErrorFields}; use crate::js; -/// The deepest a document nests: the engine's parser reads 127 levels of -/// arrays and objects. +/// The deepest a document can nest. The engine's JSON parser reads 127 +/// levels of arrays and objects. const MAX_DEPTH: usize = 127; -/// The largest integer a JavaScript `number` holds exactly: 2^53 - 1. +/// The largest integer that a JavaScript `number` represents exactly: +/// 2^53 - 1. const MAX_SAFE: u64 = (1 << 53) - 1; -/// 2^64, the first magnitude past every 64-bit integer. +/// 2^64: the smallest magnitude larger than every 64-bit integer. const TWO_TO_64: f64 = 18_446_744_073_709_551_616.0; /// A JSON document to encrypt as one ciphertext, as its JSON text. Nothing -/// inside it can be searched. Make one with `json(..)`. +/// inside the document can be searched. Make one with `json(..)`. /// -/// The document is read when it is made, so a later change to the object -/// does not change what is encrypted. A document that cannot be encrypted -/// is held as its failure, which `encrypt` returns. `Debug`, `toString()` -/// and Node's `inspect` hide the document. +/// `json(..)` reads the document when it makes the `Json`. So a later +/// change to the object does not change what is encrypted. If the document +/// cannot be encrypted, the `Json` keeps the failure, and `encrypt` returns +/// that failure. `Debug`, `toString()` and Node's `inspect` hide the +/// document. #[napi] #[derive(OpaqueDebug)] pub struct Json { @@ -66,7 +81,7 @@ pub struct Json { #[napi] impl Json { - /// Names the type and hides the document. + /// Returns the type's name, and hides the document. #[napi(js_name = "toString")] pub fn describe(&self) -> &'static str { "Json(***)" @@ -74,8 +89,9 @@ impl Json { } impl Json { - /// The document of `value` when it is a `Json`, as a value to seal, or - /// why it cannot be one; `None` when `value` is not a `Json`. + /// Returns the document of `value` as a value to encrypt, when `value` + /// is a `Json`. Returns the failure instead when the document cannot be + /// encrypted. Returns `None` when `value` is not a `Json`. pub(crate) fn of( env: &Env, value: Unknown<'_>, @@ -88,22 +104,29 @@ impl Json { .map(|json| json.document()) } - /// The document, as a value to seal, or why it cannot be one. + /// Returns the document as a value to encrypt, or the failure that + /// stops it being encrypted. pub(crate) fn document(&self) -> Result { match &self.document { - // The copy is wiped when the `JsonPlaintext` holding it drops. + // The copy is wiped when the `JsonPlaintext` that contains it + // drops. Ok(document) => Ok(JsonPlaintext::from(document.value().clone())), Err(error) => Err(error.clone()), } } } -/// A JSON document, to encrypt as one ciphertext: a plain object, an array, -/// text, a number, a `bigint`, a boolean or `null`, nested at most 127 -/// levels. An integer outside a `number`'s safe range is a `bigint`, within -/// 64 bits; a whole `number` between 2^53 and 2^64 from zero is refused, -/// since an integer was likely meant. The document is read now. Never -/// throws: a document that cannot be encrypted is an `Err` from `encrypt`. +/// Makes a JSON document to encrypt as one ciphertext. The document is a +/// plain object, an array, text, a number, a `bigint`, a boolean or `null`, +/// nested at most 127 levels. +/// +/// Give an integer outside a `number`'s safe range as a `bigint`, within 64 +/// bits. The safe range is at most 2^53 - 1 from zero. A whole `number` +/// between 2^53 and 2^64 from zero is refused, because the caller probably +/// meant an integer. +/// +/// `json(..)` reads the document now. `json(..)` never throws: `encrypt` +/// returns an `Err` for a document that cannot be encrypted. #[napi(js_name = "json")] pub fn json_document(env: &Env, document: Unknown<'_>) -> Json { Json { @@ -111,8 +134,9 @@ pub fn json_document(env: &Env, document: Unknown<'_>) -> Json { } } -/// The JSON sink's error is the SDK's: [`Error::NotJson`] or -/// [`Error::JsonTooDeep`], each fixed text with no part of the value in it. +/// The JSON sink returns the SDK's own errors: [`Error::NotJson`] or +/// [`Error::JsonTooDeep`]. Each has fixed text that includes no part of the +/// value. impl SinkError for Error { fn source(_: SourceError) -> Self { Self::NotJson { @@ -121,7 +145,7 @@ impl SinkError for Error { } } -/// The document a frame holds, as the engine's [`JsonPlaintext`]. +/// Returns the document in a frame, as the engine's [`JsonPlaintext`]. pub(crate) fn document(frame: &ValueFrame) -> Result { frame .visit(ToJson { @@ -132,20 +156,20 @@ pub(crate) fn document(frame: &ValueFrame) -> Result Result { let document = read_json(frame).map_err(|_| Error::NotADocument)?; ValueFrame::of(&FromJson(document.value())).map_err(|_| Error::BuildValue.into()) } -/// Where a built value goes. +/// The place a built JSON value goes. trait Out { type Ok; fn put(self, value: Value) -> Result; } -/// The value is the result. +/// The built value is the result. struct Root; impl Out for Root { @@ -155,7 +179,7 @@ impl Out for Root { } } -/// The value is the next element of an array. +/// The built value is the next element of an array. struct Element<'s>(&'s mut Vec); impl Out for Element<'_> { @@ -166,9 +190,9 @@ impl Out for Element<'_> { } } -/// The value is the member `key` of an object. The key is held wiped on -/// drop until it is in the object, so a member refused or dropped -/// unfinished leaves no copy of its key behind. +/// The built value is the member `key` of an object. Until the key is in +/// the object, it is kept in a buffer that is wiped when dropped. So a +/// member that is refused, or dropped unfinished, leaves no copy of its key. struct Member<'s> { object: &'s mut Map, key: Zeroizing, @@ -183,14 +207,14 @@ impl Out for Member<'_> { } } -/// A sink that builds a JSON value at `depth` levels of nesting, and hands +/// A sink that builds a JSON value at `depth` levels of nesting, and passes /// it to `O`. struct ToJson { out: O, depth: usize, } -/// A JSON number for a float, by the rules in the module docs. +/// Returns the JSON number for a float, by the rules in the module docs. fn float(value: f64) -> Result { if !value.is_finite() { return Err(Error::NotJson { @@ -199,7 +223,7 @@ fn float(value: f64) -> Result { } let magnitude = value.abs(); if value.fract() == 0.0 && magnitude <= MAX_SAFE as f64 { - // A safe integer, so the conversion is exact. + // The value is a safe integer, so the conversion is exact. #[allow(clippy::cast_possible_truncation)] return Ok(Value::Number(Number::from(value as i64))); } @@ -216,7 +240,8 @@ fn float(value: f64) -> Result { }) } -/// A JSON number for an integer, refused outside the 64-bit range. +/// Returns the JSON number for an integer. An integer outside the 64-bit +/// range is refused. fn integer(value: Int) -> Result { let wide = match value { Int::I8(n) => i128::from(n), @@ -242,7 +267,8 @@ fn integer(value: Int) -> Result { } impl ToJson { - /// The depth of a container opened here, refused past the limit. + /// Returns the depth of an array or object that starts here. A depth + /// past the limit is refused. fn nested(&self) -> Result { let depth = self.depth + 1; if depth > MAX_DEPTH { @@ -306,7 +332,7 @@ impl Sink for ToJson { } } -/// An array being built. What it holds is wiped if it is dropped unfinished. +/// An array being built. Its items are wiped if it is dropped unfinished. struct JsonArray { out: Option, depth: usize, @@ -347,7 +373,7 @@ impl SeqSink for JsonArray { } } -/// An object being built. What it holds is wiped if it is dropped +/// An object being built. Its members are wiped if it is dropped /// unfinished. struct JsonObject { out: Option, @@ -391,7 +417,7 @@ impl MapSink for JsonObject { } } -/// A JSON value walked into a sink, by the rules in the module docs. +/// A JSON value, written into a sink by the rules in the module docs. struct FromJson<'v>(&'v Value); impl Encrypt for &FromJson<'_> { @@ -423,12 +449,12 @@ fn walk(value: &Value, sink: S) -> Result { } } -/// A number as JavaScript reads it: a `number` for a float or a safe -/// integer, a `bigint` for any other integer. +/// Returns a number in the form JavaScript reads it: a `number` for a float +/// or a safe integer, and a `bigint` for any other integer. fn number_of(number: &Number) -> Physical<'static> { if let Some(n) = number.as_i64() { if n.unsigned_abs() <= MAX_SAFE { - // In range, so the conversion is exact. + // The integer is in the safe range, so the conversion is exact. #[allow(clippy::cast_precision_loss)] return Physical::Float(Float::F64(n as f64)); } @@ -451,7 +477,7 @@ mod tests { ValueFrame::of(text).unwrap() } - /// Arrays nested `.0` deep, the innermost empty. + /// Arrays nested `.0` levels deep. The innermost array is empty. struct Nested(usize); impl stack_encrypt::Encrypt for &Nested { @@ -468,7 +494,7 @@ mod tests { } } - /// `depth` arrays, each holding the next, as a frame. + /// Returns a frame of `depth` nested arrays, each inside the one before. fn nested(depth: usize) -> ValueFrame { ValueFrame::of(&Nested(depth)).unwrap() } @@ -529,8 +555,9 @@ mod tests { r#"{"small": 5, "big": 18446744073709551615, "f": 1.5}"#, )) .unwrap(); - // Read back as a document: the small integer is a float now, the - // big one is still an integer. + // In the decrypted frame, the small integer is now a float, and the + // big one is still an integer. The frame reads back as the same + // document. let read = document(&opened).unwrap(); assert_eq!( read.value(), diff --git a/languages/typescript/packages/recipher-js/crate/src/lib.rs b/languages/typescript/packages/recipher-js/crate/src/lib.rs index d80bd5c64..d8a239c29 100644 --- a/languages/typescript/packages/recipher-js/crate/src/lib.rs +++ b/languages/typescript/packages/recipher-js/crate/src/lib.rs @@ -1,33 +1,40 @@ //! The Node addon of `@cipherstash/recipher`. //! -//! It defines the classes the package exports, [`Cipher`], [`Keyset`] and -//! [`Ciphertext`], and runs every operation through the Stack Encrypt engine. -//! napi-rs generates their TypeScript declarations (`native.d.ts`) from this -//! crate. It reads and builds JavaScript values only through -//! `recipher-value-napi` (see [`js`]). +//! The addon defines the classes the package exports: [`Cipher`], +//! [`Keyset`], [`Ciphertext`] and [`Json`]. Every operation runs through the +//! Stack Encrypt engine, the `stack-encrypt` crate. The engine encrypts and +//! decrypts values with keys from ZeroKMS, CipherStash's key service. +//! +//! napi-rs generates the classes' TypeScript declarations (`native.d.ts`) +//! from this crate. The crate reads and builds JavaScript values only +//! through the `recipher-value-napi` crate (see [`js`]). //! //! # Outcomes //! -//! A call that can fail returns an outcome object, `{ ok: true, value }` or -//! `{ ok: false, error }`, where `error` is a [`RecipherErrorFields`]; an -//! asynchronous call resolves to one and never rejects for a failure it can -//! report. Every argument is taken as an untyped JavaScript value and -//! checked here, so a value of the wrong type is an outcome too, never an -//! exception. The package's TypeScript turns an outcome into its `Result`. +//! A call that can fail returns an outcome object instead of throwing. An +//! outcome object is `{ ok: true, value }` on success, or +//! `{ ok: false, error }` on failure. The `error` is a +//! [`RecipherErrorFields`]. An asynchronous call resolves to an outcome +//! object, and does not reject for a failure it can report. +//! +//! Every argument arrives as an untyped JavaScript value, and the addon +//! checks it. So a value of the wrong type gives a failed outcome object, +//! not an exception. The package's TypeScript turns each outcome object +//! into its `Result` type. //! //! # The interface number //! -//! [`binding_interface`] reports [`BINDING_INTERFACE`], the version of what -//! the TypeScript calls. It changes whenever a class, a method or an -//! outcome changes shape, and the TypeScript refuses a build that reports -//! another number. +//! [`binding_interface`] returns [`BINDING_INTERFACE`]. That number is the +//! version of the interface that the package's TypeScript calls. The number +//! changes whenever a class, a method or an outcome object changes shape. +//! The TypeScript refuses an addon build that returns another number. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic)] #![warn(clippy::mem_forget)] #![warn(clippy::print_stdout)] #![warn(clippy::print_stderr)] #![warn(clippy::dbg_macro)] -// A failure is the object JavaScript receives, field for field, and it is -// built on a cold path; boxing it would buy nothing. +// A failure is built field for field as the object JavaScript receives. +// It is built only when a call fails, so boxing it would gain nothing. #![allow(clippy::result_large_err)] #![cfg_attr(test, allow(clippy::unwrap_used))] #![cfg_attr(test, allow(clippy::expect_used))] @@ -58,21 +65,24 @@ use napi::Env; use napi_derive::napi; /// The version of the interface between the package's TypeScript and this -/// build. +/// addon build. pub const BINDING_INTERFACE: u32 = 4; -/// The version of the interface between the package's TypeScript and this -/// build. The TypeScript refuses a build that reports another. +/// Returns the version of the interface between the package's TypeScript +/// and this addon build. The TypeScript refuses a build that returns +/// another version. #[napi] pub fn binding_interface() -> u32 { BINDING_INTERFACE } -/// vitaminc's wrapper classes, `VcDate`, `VcTimestamp`, `VcDecimal` and -/// `VcUuid`, for the types JavaScript lacks: exported so JavaScript can -/// construct them, and so the values it decrypts are instances of them. -// napi's module registration calls it; `clippy --all-targets` also builds -// the crate as a test, where nothing does. +/// Exports the wrapper classes of vitaminc, CipherStash's cryptography +/// library: `VcDate`, `VcTimestamp`, `VcDecimal` and `VcUuid`. Each class +/// stands for a type that JavaScript does not have. The addon exports them +/// so JavaScript can construct them, and so decrypted values are instances +/// of them. +// napi's module registration calls this function. `clippy --all-targets` +// also builds the crate as a test, where nothing calls it. #[cfg_attr(test, allow(dead_code))] #[napi(module_exports)] fn wrappers(mut exports: Object<'_>, env: Env) -> napi::Result<()> { diff --git a/languages/typescript/packages/recipher-js/crate/src/outcome.rs b/languages/typescript/packages/recipher-js/crate/src/outcome.rs index 1091a7e2b..8c87c240b 100644 --- a/languages/typescript/packages/recipher-js/crate/src/outcome.rs +++ b/languages/typescript/packages/recipher-js/crate/src/outcome.rs @@ -1,4 +1,8 @@ -//! The outcome object every call that can fail returns. +//! Outcome objects: what every call that can fail returns to JavaScript. +//! +//! An outcome object is `{ ok: true, value }` on success, or +//! `{ ok: false, error }` on failure. A call returns one instead of +//! throwing. use std::future::Future; @@ -7,14 +11,17 @@ use napi::Env; use crate::error::{Error, RecipherErrorFields}; -/// What a call's work comes to before JavaScript sees it. +/// The result of a call's work, before the addon builds it into an outcome +/// object for JavaScript. pub(crate) type Outcome = Result; -/// The outcome object for `outcome`: `{ ok: true, value }`, with `value` -/// building the success's JavaScript value, or `{ ok: false, error }`. A -/// failure to build the value is a failure too, so the call still returns -/// an outcome. The `napi::Result` is an error only when napi cannot make the -/// object itself. +/// Builds the outcome object for `outcome`. +/// +/// A success becomes `{ ok: true, value }`, and the `value` function builds +/// its JavaScript value. A failure becomes `{ ok: false, error }`. If the +/// `value` function fails, the outcome object is a failure too, so the call +/// still returns an outcome object. The returned `napi::Result` is an error +/// only when napi cannot make the object itself. pub(crate) fn settle<'e, T>( env: &'e Env, outcome: Outcome, @@ -35,21 +42,22 @@ pub(crate) fn settle<'e, T>( Ok(object) } -/// The failure for a value napi could not make, which is never the -/// caller's to fix. +/// Returns the failure for a JavaScript value that napi could not make. +/// The caller did not cause this failure and cannot fix it. pub(crate) fn not_made(_: napi::Error) -> RecipherErrorFields { Error::BuildValue.into() } -/// A failure, as an outcome object. +/// Builds a failed outcome object for `error`. pub(crate) fn failed(env: &Env, error: RecipherErrorFields) -> napi::Result> { settle(env, Err::<(), _>(error), |env, ()| { ().into_unknown(env).map_err(not_made) }) } -/// Run `work` on napi's runtime and resolve the promise to its outcome -/// object, built on the JavaScript thread by `value`. +/// Runs `work` on napi's asynchronous runtime, and returns a promise of its +/// outcome object. The `value` function builds the success's JavaScript +/// value on the JavaScript thread. pub(crate) fn spawn<'e, T, F, V>( env: &'e Env, work: F, @@ -65,8 +73,9 @@ where }) } -/// A promise of `error`'s outcome, for a call refused before any work -/// starts, so the call still returns a promise and never throws. +/// Returns a promise of a failed outcome object for `error`. A call uses it +/// when it refuses its arguments before any work starts. The call then +/// still returns a promise, and does not throw. pub(crate) fn refused( env: &Env, error: RecipherErrorFields, diff --git a/languages/typescript/packages/recipher-js/crate/src/record.rs b/languages/typescript/packages/recipher-js/crate/src/record.rs index 3b64caee8..ccf2ddd7f 100644 --- a/languages/typescript/packages/recipher-js/crate/src/record.rs +++ b/languages/typescript/packages/recipher-js/crate/src/record.rs @@ -1,24 +1,52 @@ -//! A record: a declaration of fields, turned into the engine's [`Plan`] once, -//! and the rows encrypted and decrypted through `dynamic::Planned`. +//! Records: declarations of fields, and the rows encrypted and decrypted +//! under them. //! -//! A declaration is the plain object `record(..)` makes: -//! `{ type: "record", name, fields }`, each field -//! `{ type: "sealed", kind: { name }, index: [..], null? }` or -//! `{ type: "passthrough" }`. Each field's context is its field path: the -//! record's name, then the field's name. The plan is built from the -//! declaration with the engine's own types ([`FieldPlan`], [`Output`], -//! [`IndexSpec`], [`NullMode`], [`ValueKind`]), so the engine checks it -//! and its refusals are the engine's. A plan is built once for each -//! declaration and kept for the life of the process. +//! 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`. //! -//! A row crosses as one frame, a map of the record's fields. A value is -//! read as its field's kind by the engine's [`read`] before the engine -//! sees it, because vitaminc reads a JavaScript `bigint` at the narrowest -//! width that holds it. +//! # Declarations //! -//! A stored row crosses as one frame too: for each 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. +//! 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}; @@ -39,18 +67,18 @@ use crate::error::{Error, RecipherErrorFields}; use crate::frames::{bytes_of, entries, Entry, Map}; use crate::outcome::Outcome; -/// The stored row's name for a field's ciphertext. +/// The key of a field's ciphertext in a stored row. const CIPHERTEXT: &str = "ciphertext"; -/// Field names the engine reserves at the top of a plan. +/// Field names that the engine reserves for the top level of a plan. const RESERVED: [&str; 2] = ["bind", "context_field"]; -/// An index a declaration names, by the SDK's name for it. +/// 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 under its default options, as the engine reads - // its key in a plan. + // 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), @@ -58,7 +86,7 @@ fn index_named(name: &str) -> Option { } } -/// The SDK's name for an index, as a stored row spells it. +/// 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"), @@ -69,19 +97,19 @@ fn index_name(index: &IndexSpec) -> Option<&'static str> { } } -/// A record's plan, built once from its declaration. A declaration holds no -/// secret, so the whole plan prints. +/// 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, - /// The plan of each sealed field alone, by its name. + /// A plan for each sealed field on its own, keyed by the field's name. alone: HashMap>, } -/// A field as the rows read it. +/// A field, as the addon uses it to read rows. #[derive(Clone, Debug)] struct Field { name: String, @@ -135,25 +163,25 @@ struct FieldDeclaration { null: Option, } -/// A field's kind, as `kinds` spells it. +/// A field's kind, as the package's `kinds` object writes it. #[derive(Deserialize)] struct KindDeclaration { name: String, } -/// The plans built so far, by the declaration's frame bytes. A declaration -/// holds no secret. +/// 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 { - /// The plan of the declaration a binding read into `frame`, built the - /// first time it is seen. + /// Returns the plan of the declaration that the addon read into + /// `frame`. The plan is built the first time the declaration is seen. /// /// # Errors /// - /// `recipher::not_a_record`, or a refusal of the declaration naming the - /// record and, where there is one, the field. + /// Returns `recipher::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 @@ -170,8 +198,8 @@ impl RecordPlan { return Err(Error::NotARecord.into()); } let plan = Arc::new(Self::build(declaration.name, declaration.fields.0)?); - // Another call may have built the same plan meanwhile: the first one - // kept is the one every call uses. + // 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) @@ -215,23 +243,24 @@ impl RecordPlan { }) } - /// The record's name. + /// Returns the record's name. pub(crate) fn name(&self) -> &str { &self.name } - /// The names of the fields, in declaration order. + /// 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()) } - /// The plan of the sealed field `name` alone: the same field path, so - /// the field's bytes are the bytes it has in a whole row. + /// 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 /// - /// `recipher::no_field` for a name the record does not declare, or that - /// it passes through. + /// Returns `recipher::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) @@ -241,7 +270,7 @@ impl RecordPlan { } } -/// A field, and the engine's plan of it. +/// Returns a field, and the engine's plan for it. fn field_of( record: &str, name: String, @@ -310,8 +339,8 @@ fn field_of( )) } -/// A field's context: its field path, `[record, field]`, read by the -/// engine's own context reader. +/// 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, @@ -320,10 +349,12 @@ fn field_path( context(frame.as_protected_ref()).ok() } -/// The engine's refusal of a declaration of `record`. When the engine says -/// a context is not a label, the record's name or the field's is at fault. -/// The record's is tried alone to say which: the engine names the field -/// either way. +/// 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) { @@ -332,20 +363,22 @@ fn engine_refused(record: &str, error: &stack_encrypt::dynamic::Error) -> Reciph refused } -/// Whether `record` is a name the engine takes as the first segment of a -/// field path, asked of the engine with a field it takes. +/// 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()) } -/// A row's fields, each read as its field's kind, in the row's order. +/// Returns a row with each value read as its field's kind, in the row's +/// order. /// /// # Errors /// -/// `recipher::not_a_row` for a row that is not an object, and -/// `recipher::field_type` for a value that is not of its field's kind or -/// does not fit it, naming the field. +/// Returns `recipher::not_a_row` for a row that is not an object. Returns +/// `recipher::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)?; @@ -357,7 +390,7 @@ pub(crate) fn conform_row(plan: &RecordPlan, row: &ValueFrame) -> Outcome read(kind, &value).map_err(|_| { RecipherErrorFields::from(Error::FieldType { kind }) .in_record(&plan.name) @@ -374,12 +407,14 @@ pub(crate) fn conform_row(plan: &RecordPlan, row: &ValueFrame) -> Outcome( keyset: &KeysetCipher<'_, K>, plan: Arc, @@ -402,14 +437,18 @@ where .collect() } -/// Open stored rows under a record's plan, in one key request for each -/// keyset they were sealed under. Each stored row is a frame as -/// [`seal_rows`] returns it; each result a row. +/// 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 /// -/// `recipher::not_a_stored_row` for a stored row of another shape, naming -/// the field, and the engine's refusal of one that does not open. +/// Returns `recipher::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, @@ -431,7 +470,8 @@ where .map_err(|error| RecipherErrorFields::engine(&error).in_record(&plan.name)) } -/// The stored row the engine returned, as the frame the SDK hands back. +/// 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 { @@ -496,7 +536,8 @@ fn stored_row(plan: &RecordPlan, tree: StackCipherText) -> Outcome { }) } -/// The engine's stored record for a stored row the SDK handed back. +/// 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 }) @@ -521,7 +562,7 @@ fn stored_tree(plan: &RecordPlan, row: &ValueFrame) -> Outcome continue; } if value.kind().is_none() { - // A null: the field is absent, as SQL `NULL` stores it. + // A null means the field is absent, as SQL `NULL` stores it. continue; } let outputs = entries(&value).ok_or_else(|| { @@ -566,8 +607,9 @@ fn stored_tree(plan: &RecordPlan, row: &ValueFrame) -> Outcome Ok(CipherText::Map(tree)) } -/// The value of the field `name` in a one-field row, or a null when the -/// row has none (a null stored as SQL `NULL`). +/// 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", @@ -592,7 +634,7 @@ impl stack_encrypt::Encrypt for &Null { } } -/// A one-field row: `{ name: value }`. +/// 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 { 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 3f602a9c4..7ee80fc1d 100644 --- a/languages/typescript/packages/recipher-js/crate/src/record_tests.rs +++ b/languages/typescript/packages/recipher-js/crate/src/record_tests.rs @@ -1,6 +1,7 @@ -//! Records through the crate against the engine: the plan built from a -//! declaration, rows in and stored rows out, and what the engine's typed -//! API reads of them. +//! 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}; @@ -42,7 +43,8 @@ fn users() -> Arc { .unwrap() } -/// A row as JavaScript hands it over: an integer at its narrowest width. +/// 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(); @@ -161,7 +163,7 @@ 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 opens through the field's own plan. + // 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() @@ -176,8 +178,8 @@ async fn one_field_opens_alone_and_a_field_alone_opens_through_the_engine() { ValueFrame::of("ada@example.com").unwrap() ); - // A field sealed alone opens through the engine's typed API under its - // field path. + // 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]) @@ -280,7 +282,7 @@ fn a_bad_record_name_is_the_records_fault_and_a_bad_field_name_the_fields() { assert_eq!(bad_field.record.as_deref(), Some("users")); } -/// A deterministic key source that counts the key requests it is sent. +/// A deterministic key source that counts the key requests it receives. struct Counting { inner: DeterministicSource, generates: AtomicUsize, @@ -345,7 +347,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` seals an array of them. + // 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() diff --git a/languages/typescript/packages/recipher-js/crate/src/value.rs b/languages/typescript/packages/recipher-js/crate/src/value.rs index 9f5e8a304..efe0132aa 100644 --- a/languages/typescript/packages/recipher-js/crate/src/value.rs +++ b/languages/typescript/packages/recipher-js/crate/src/value.rs @@ -1,4 +1,7 @@ -//! A value the engine seals as one leaf. +//! A value that the engine encrypts as one leaf. +//! +//! The engine is the Stack Encrypt engine, the `stack-encrypt` crate. A +//! leaf is one value that the engine encrypts as a single ciphertext. use stack_encrypt::dynamic::plaintext::{depth, Error as _, Scalar, Sink, SourceError}; use stack_encrypt::dynamic::{ValueFrame, ValueKind}; @@ -8,21 +11,32 @@ use vitaminc_protected::OpaqueDebug; use crate::error::{Error, RecipherErrorFields}; -/// A value checked to be one leaf: one scalar of the value model, or a JSON -/// document. The engine seals it through its opaque scalar path, as Rust's -/// `keyset.encrypt(value)` does, so each ciphertext is the one Rust and Go -/// write for the same value. +/// A value checked to be one leaf: one scalar of the engine's value model, +/// or one JSON document. /// -/// The engine seals a value as one opaque leaf only when its type is one of -/// vitaminc's scalars (`Scalar`). A [`ValueFrame`] can hold any value of the -/// model, an array or a map too, so it is not one; this type is the check -/// that it holds one scalar, made once, before the engine sees it. The -/// engine's opaque path also needs a value it can wipe (`Zeroize`): wiping -/// drops the value, which wipes its own buffer. `Debug` hides the value. +/// The value model is the set of value types the engine reads. A scalar is +/// a value of the model that is not an array or a map, such as text, a +/// number or bytes. +/// +/// The engine encrypts the value through its opaque scalar path. That path +/// encrypts a whole value as one leaf. Rust's `keyset.encrypt(value)` uses +/// the same path. So each ciphertext has the form that Rust and Go write +/// for the same value. +/// +/// The engine encrypts a value as one opaque leaf only when its type +/// implements `Scalar`, a trait of vitaminc, CipherStash's cryptography +/// library. A [`ValueFrame`] can contain any value of the model, including +/// an array or a map. So a [`ValueFrame`] is not a `Scalar`. This type +/// checks that the frame contains one scalar. The check runs once, before +/// the engine reads the value. +/// +/// The opaque path also needs a value it can wipe (`Zeroize`). Wiping drops +/// the value, and the value wipes its own buffer when it drops. `Debug` +/// hides the value. #[derive(OpaqueDebug)] pub(crate) struct OneValue(Option); -/// What a [`OneValue`] holds. +/// The value inside a [`OneValue`]: a scalar, or a JSON document. #[derive(OpaqueDebug)] enum Leaf { Scalar(ValueFrame), @@ -30,12 +44,12 @@ enum Leaf { } impl OneValue { - /// `value`, if it is one scalar. + /// Returns `value` as a [`OneValue`], if it is one scalar. /// /// # Errors /// - /// `recipher::not_a_scalar` for an array, `recipher::plain_object` for an - /// object. + /// Returns `recipher::not_a_scalar` for an array, and + /// `recipher::plain_object` for an object. pub(crate) fn scalar(value: ValueFrame) -> Result { match value.kind() { Some(ValueKind::Array) => Err(Error::NotAScalar.into()), @@ -44,8 +58,8 @@ impl OneValue { } } - /// A JSON document, sealed as the engine's `JsonPlaintext` is: as its - /// JSON text. + /// Returns a JSON document as a [`OneValue`]. The engine encrypts it as + /// it encrypts any `JsonPlaintext`: as its JSON text. pub(crate) fn json(document: JsonPlaintext) -> Self { Self(Some(Leaf::Json(document))) } @@ -53,7 +67,7 @@ impl OneValue { impl zeroize::Zeroize for OneValue { fn zeroize(&mut self) { - // Each leaf wipes its buffer when it is dropped. + // Dropping the leaf wipes its buffer. self.0 = None; } } diff --git a/languages/typescript/packages/recipher-js/crate/tests/boundaries.rs b/languages/typescript/packages/recipher-js/crate/tests/boundaries.rs index 2726ea8c7..7d374f881 100644 --- a/languages/typescript/packages/recipher-js/crate/tests/boundaries.rs +++ b/languages/typescript/packages/recipher-js/crate/tests/boundaries.rs @@ -1,13 +1,14 @@ -//! What the crate must not reach. +//! Checks of what the crate must not depend on. //! -//! - It does not link `eql-bindings`. The EQL types are an extension to the -//! core; a build of the core holds none of them. -//! - A build with its default features has no test cipher: neither the -//! crate's `testing` feature nor the engine's `test-support`, whose key -//! source derives every key from a public seed. `build:native` makes the -//! release addon with the default features, and every CI build turns -//! `testing` on, so this is the check that the release build cannot reach -//! the test keys. +//! - The crate does not link `eql-bindings`. The EQL (Encrypt Query +//! Language) types are an extension to the core. A build of the core +//! contains none of them. +//! - A build with the default features has no test cipher. That build turns +//! on neither the crate's `testing` feature nor the engine's +//! `test-support` feature. The `test-support` key source derives every +//! key from a public seed. `build:native` makes the release addon with +//! the default features, and every CI build turns `testing` on. So this +//! test is what checks that the release build cannot reach the test keys. use std::path::PathBuf; use std::process::Command; @@ -16,8 +17,8 @@ fn crate_dir() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")) } -/// `cargo tree --locked` for the crate with its default features, from the -/// committed lock: no build is needed. +/// Runs `cargo tree --locked` for the crate with its default features. +/// The command reads the committed lock file, so no build is needed. fn tree(edges: &str, format: Option<&str>) -> String { let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_owned()); let mut args = vec![ diff --git a/languages/typescript/packages/recipher-js/native.d.ts b/languages/typescript/packages/recipher-js/native.d.ts index c950b881a..e61270492 100644 --- a/languages/typescript/packages/recipher-js/native.d.ts +++ b/languages/typescript/packages/recipher-js/native.d.ts @@ -7,207 +7,257 @@ export type Outcome = | { ok: false; error: RecipherErrorFields } /** - * A cipher: the engine, and the keysets it reaches. + * A cipher: the engine, and the keysets it can use. A keyset is a group + * of keys in ZeroKMS, CipherStash's key service. * - * Build one with `Cipher.create()`, or, in a test, with `testCipher()` - * from `@cipherstash/recipher/testing`. It has no constructor. + * Make a cipher with `Cipher.create()`. In a test, make one with + * `testCipher()` from `@cipherstash/recipher/testing`. The class has no + * constructor. */ export declare class Cipher { /** - * A cipher over ZeroKMS, with the credentials the engine finds: the - * `CS_*` variables, then the profile `stash auth login` writes. + * Makes a cipher that gets its keys from ZeroKMS. The engine looks for + * credentials in the `CS_*` environment variables first, then in the + * profile that `stash auth login` writes. * - * Resolves to the engine's error when there are no credentials, when - * they are refused, or when ZeroKMS refuses to load the default keyset. + * The promise resolves to the engine's error in these cases: * - * `options.records` are declarations to check now, before any - * credential is looked for: a declaration the engine refuses is a - * failure naming the record. + * - there are no credentials; + * - 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 result is a failure that names the record. */ static create(options?: unknown | undefined | null): Promise> /** - * The client's default keyset: the one a ZeroKMS administrator set for - * it. Encrypting needs a keyset. + * Returns the client's default keyset: the keyset that a ZeroKMS + * administrator set for this client. Encrypting needs a keyset. */ defaultKeyset(): Keyset /** - * Open a ciphertext from any of this cipher's keysets, as the value it - * was sealed as, or an array of them. With a record first, open its - * stored row, or an array of them, in one key request for each keyset - * they were sealed under. + * Decrypts a ciphertext, or an array of ciphertexts, made under any of + * this cipher's keysets. Each value decrypts as the type it was + * encrypted as. + * + * 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. The cipher makes one key request + * for each keyset the rows were encrypted under. A key request is one + * request to ZeroKMS for data keys. */ decrypt(first: unknown, second?: unknown | undefined | null): Promise> /** - * Open one field of a record's stored row, as `encryptField` or - * `encrypt` stored it, or an array of them in one key request. + * 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. */ decryptField(record: unknown, field: unknown, stored: unknown): Promise> - /** Names the type. */ + /** Returns the type's name. */ toString(): string } /** - * One sealed value: the engine's opaque ciphertext, with its own data key. + * One encrypted value: the engine's opaque ciphertext of the whole value, + * with its own data key. A data key is the key that encrypts one value. * - * Its bytes are the engine's sealed-value envelope, the bytes Rust's - * `Ciphertext::to_bytes` and the Go SDK write. `Debug` hides them, and so - * do `toString()` and Node's `inspect`: the class has no own properties. + * The ciphertext's bytes are the engine's envelope for an encrypted value. + * Rust's `Ciphertext::to_bytes` and the Go SDK write the same bytes. + * `Debug` hides the bytes. So do `toString()` and Node's `inspect`, + * because the class has no own properties. * - * It exists as a class, rather than as the bytes, so that `decrypt` can - * tell a ciphertext from any other value, and so that it carries the type - * it opens as: a JSON document is sealed as its JSON text, and nothing in - * the bytes says it is JSON. + * The SDK uses a class rather than plain bytes for two reasons. First, + * `decrypt` can tell a ciphertext from any other value. Second, the class + * records the type the value decrypts as. A JSON document is encrypted as + * its JSON text, and nothing in the bytes says that it is JSON. */ export declare class Ciphertext { /** - * Read a ciphertext from stored bytes, a `Uint8Array` or a `Buffer`. - * This checks the bytes' shape only; decrypting is what authenticates - * them. A failure does not quote the bytes. + * Reads a ciphertext from stored bytes, a `Uint8Array` or a `Buffer`. + * This method checks only the shape of the bytes. Decrypting is what + * checks that they are authentic. A failure does not quote the bytes. + * + * Give a kind, such as `kinds.string`, to decrypt the value as that + * kind. Decrypting then refuses a value encrypted as another type. + * `kinds.json` decrypts a JSON document. * - * With a kind, such as `kinds.string`, it opens as that kind, and - * decrypting refuses a value sealed as another type. `kinds.json` opens - * a JSON document. With none, it opens as whatever it was sealed as, - * and a JSON document opens as its JSON text. + * With no kind, the value decrypts as the type it was encrypted as. A + * JSON document then decrypts as its JSON text. */ static fromBytes(bytes: unknown, kind?: unknown | undefined | null): Outcome - /** The bytes to store: a copy, so changing it changes no ciphertext. */ + /** + * Returns the bytes to store. They are a copy, so changing them does + * not change any ciphertext. + */ toBytes(): Uint8Array - /** Names the type and hides the bytes. */ + /** Returns the type's name, and hides the bytes. */ toString(): string } /** * A JSON document to encrypt as one ciphertext, as its JSON text. Nothing - * inside it can be searched. Make one with `json(..)`. + * inside the document can be searched. Make one with `json(..)`. * - * The document is read when it is made, so a later change to the object - * does not change what is encrypted. A document that cannot be encrypted - * is held as its failure, which `encrypt` returns. `Debug`, `toString()` - * and Node's `inspect` hide the document. + * `json(..)` reads the document when it makes the `Json`. So a later + * change to the object does not change what is encrypted. If the document + * cannot be encrypted, the `Json` keeps the failure, and `encrypt` returns + * that failure. `Debug`, `toString()` and Node's `inspect` hide the + * document. */ export declare class Json { - /** Names the type and hides the document. */ + /** Returns the type's name, and hides the document. */ toString(): string } /** - * One keyset of a cipher. Every data key is made under one keyset, and a - * ciphertext names the keyset it was made under. + * One keyset of a cipher. A data key is the key that encrypts one value. + * Each data key is made under one keyset. A ciphertext names the keyset it + * was made under. * - * Get one from `cipher.defaultKeyset()`. It has no constructor. + * Get a keyset from `cipher.defaultKeyset()`. The class has no + * constructor. */ export declare class Keyset { /** - * Encrypt a value, with no context, as one ciphertext with its own data - * key. An array of values is an array of ciphertexts, in the same - * order, made with one key request however long it is. All or nothing: - * one value refused is a failure for the whole array, before any - * request. + * Encrypts a value as one ciphertext with its own data key, with no + * context. A context is a value that a ciphertext is bound to, and + * decrypting needs the same context. + * + * An array of values returns an array of ciphertexts, in the same + * order. The keyset makes one key request for the whole array, however + * long it is. A key request is one request to ZeroKMS for data keys. If + * any value is refused, the whole array fails, before any request. * - * A value's type picks how it is encrypted, by vitaminc's mapping for - * JavaScript. A `Json` from `json(..)` is encrypted as a JSON document. + * A value's type sets how it is encrypted. The mapping of JavaScript + * types comes from vitaminc, CipherStash's cryptography library. A + * `Json` from `json(..)` is encrypted as a JSON document. * - * With a record first, encrypt its row, or an array of them in one key - * request: each field under its field path. + * 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. */ encrypt(first: unknown, second?: unknown | undefined | null): Promise> /** - * Open a ciphertext sealed under this keyset, or an array of them. A - * ciphertext of another keyset is a failure with the code - * `stack_encrypt::foreign_keyset`, before any key is requested. With a - * record first, open its stored row, or an array of them. + * 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, decrypts a stored + * row of that record, or an array of stored rows. */ decrypt(first: unknown, second?: unknown | undefined | null): Promise> /** - * Encrypt one field of a record, for an update of that field: its - * stored form, as the field has it in a whole stored row. An array of - * values is an array of stored fields, in one key request. + * 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. */ encryptField(record: unknown, field: unknown, value: unknown): Promise> /** - * Open one field of a record's stored row sealed under this keyset, or - * an array of them in one key request. + * Decrypts one field of a record's stored row made under this keyset. + * An array of stored fields decrypts in one key request. */ decryptField(record: unknown, field: unknown, stored: unknown): Promise> - /** Names the type. */ + /** Returns the type's name. */ toString(): string } /** - * The version of the interface between the package's TypeScript and this - * build. The TypeScript refuses a build that reports another. + * Returns the version of the interface between the package's TypeScript + * and this addon build. The TypeScript refuses a build that returns + * another version. */ export declare function bindingInterface(): number /** - * Check declarations with the engine, with no credentials and no - * request: for a test or a CI step. The first refusal is the failure, - * naming the record and, where there is one, the field. + * Checks record declarations with the engine, without credentials and + * without any request. Use it in a test or a CI step. The failure is the + * engine's first refusal. The failure names the record and, where there is + * one, the field. */ export declare function checkDeclarations(records: unknown): Outcome /** - * A cipher over the engine's deterministic test keys, from a 32-byte seed: - * every key is a function of the seed and the value's context, so a value - * sealed by one test cipher opens in another with the same seed. It needs - * no credentials and makes no request. Its keys are no secret from anyone - * who knows the seed. + * 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 + * value encrypted by one test cipher decrypts in another with the same + * seed. * - * Only a build with the `testing` feature has one; any other resolves to - * a failure with the code `recipher::no_testing`. + * The test cipher needs no credentials and makes no request. Anyone who + * knows the seed can derive its keys. + * + * Only a build with the `testing` feature has the test cipher. In any + * other build, the promise resolves to a failure with the code + * `recipher::no_testing`. */ export declare function createTesting(seed: unknown): Promise> /** One error in a failure's cause chain. */ export interface ErrorCause { - /** The cause's code, where it is one of the engine's own errors. */ + /** The cause's code, when the cause is one of the engine's own errors. */ code?: string /** - * The engine error's message. For an error from another library, the - * fixed text `an error from another library`. + * The message of the engine's error. For an error from another + * library, the message is this fixed text: + * `an error from another library`. */ message: string } /** - * A JSON document, to encrypt as one ciphertext: a plain object, an array, - * text, a number, a `bigint`, a boolean or `null`, nested at most 127 - * levels. An integer outside a `number`'s safe range is a `bigint`, within - * 64 bits; a whole `number` between 2^53 and 2^64 from zero is refused, - * since an integer was likely meant. The document is read now. Never - * throws: a document that cannot be encrypted is an `Err` from `encrypt`. + * Makes a JSON document to encrypt as one ciphertext. The document is a + * plain object, an array, text, a number, a `bigint`, a boolean or `null`, + * nested at most 127 levels. + * + * Give an integer outside a `number`'s safe range as a `bigint`, within 64 + * bits. The safe range is at most 2^53 - 1 from zero. A whole `number` + * between 2^53 and 2^64 from zero is refused, because the caller probably + * meant an integer. + * + * `json(..)` reads the document now. `json(..)` never throws: `encrypt` + * returns an `Err` for a document that cannot be encrypted. */ export declare function json(document: unknown): Json /** A failure, as JavaScript receives it. */ export interface RecipherErrorFields { /** - * Stable: the diagnostic's code, such as `stack_encrypt::aead`, - * vitaminc's code for a value it refused, such as `ERR_INTEGER_RANGE`, - * or the SDK's own, such as `recipher::not_a_ciphertext`. + * The error's code. A code is stable, so a caller can match on it. + * The code is one of three kinds: + * + * - a diagnostic's code, such as the engine's `stack_encrypt::aead`; + * - the code of vitaminc, CipherStash's cryptography library, for a + * value it refused, such as `ERR_INTEGER_RANGE`; + * - the SDK's own code, such as `recipher::not_a_ciphertext`. */ code: string /** What went wrong, in one line. */ message: string - /** What to do about it, where the error knows. */ + /** What to do about the error, when the error says. */ help?: string - /** A documentation page for the error, where it has one. */ + /** A documentation page for the error, when it has one. */ url?: string - /** How serious it is: `error` unless the diagnostic says otherwise. */ + /** + * How serious the failure is. The severity is `error` unless the + * diagnostic states another one. + */ severity: Severity /** - * The error's structured fields, by `snake_case` name: a refused - * plan's `field` and `reason`, a ZeroKMS failure's `request_kind`. - * Empty where the error has none. + * 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. */ fields: Record - /** The errors behind this one, outermost first. */ + /** The errors that caused this one, outermost first. */ causes: Array - /** The field at fault, where one is known. */ + /** The field at fault, when it is known. */ field?: string /** - * The record at fault, where one is known: a declaration, a row or a - * stored row of it. + * The record at fault, when it is known. The fault is in the record's + * declaration, in a row of it, or in a stored row of it. */ record?: string } diff --git a/languages/typescript/packages/recipher-js/src/binding.ts b/languages/typescript/packages/recipher-js/src/binding.ts index 7e92526a7..10e2a3b9a 100644 --- a/languages/typescript/packages/recipher-js/src/binding.ts +++ b/languages/typescript/packages/recipher-js/src/binding.ts @@ -1,30 +1,40 @@ /** - * The native build, and the one job the TypeScript does over it: make each - * native call a `Result`. + * Loads the native addon, and makes each native call return a `Result`. * - * The classes the package exports (`Cipher`, `Keyset`, `Ciphertext`) are the - * native build's own, written in Rust, and `native.d.ts` is what napi-rs - * generates for them. A native method takes untyped arguments and checks - * them itself, and returns an outcome object, `{ ok, value }` or - * `{ ok, error }`, rather than throwing. What is left for TypeScript: + * The native addon is the compiled Rust code that Node loads from + * `recipher.node`. The classes this package exports (`Cipher`, `Keyset`, + * and `Ciphertext`) are defined in the addon, in Rust. napi-rs, the Rust + * framework the addon is written with, generates their declarations in + * `native.d.ts`. * - * - turning an outcome into a `Result`, which Rust cannot build because - * `Result` is a TypeScript class; - * - turning what napi itself throws (a method called on something that is - * not its class) into an `Err`, so no call throws; - * - binding each method to its instance, so a method passed on its own, - * as in `stored.map(cipher.decrypt)`, still has its cipher; - * - stand-ins that resolve to an `Err` when the native build did not load, - * since then there are no classes to export. + * A native method takes untyped arguments and checks them itself. A native + * method does not throw. It returns an outcome object instead: `{ ok, value }` + * when the call worked, or `{ ok, error }` when it failed. * - * `adapt` does the first three by replacing each method on a class with a - * getter that returns the method, bound and wrapped. It runs once per class, - * however many copies of this module load it: the ESM and the CommonJS build - * share the addon, which Node loads once per process, and its classes. + * This module does four jobs that the Rust cannot do: * - * The addon is loaded when this module is imported. A build that does not - * load, or that implements another binding interface than this TypeScript, - * is an `Err` from every call, never an exception. + * - Turn an outcome into a `Result`. Rust cannot build a `Result`, because + * `Result` is a TypeScript class. + * - Turn an exception that napi itself throws into an `Err`, so that no call + * throws. napi throws when a method is called on an object that is not an + * instance of the method's class. + * - Bind each method to its instance. A method passed on its own, as in + * `stored.map(cipher.decrypt)`, then still has its cipher. + * - Provide stand-ins that resolve to an `Err` when the addon did not load. + * Without the addon, there are no classes to export. + * + * `adapt` does the first three jobs. `adapt` replaces each method on a class + * with a getter. The getter returns the method, bound to its instance, with + * its outcome turned into a `Result`. `adapt` changes each class once, + * however many copies of this module load. The ECMAScript module (ESM) build + * and the CommonJS build share the addon and its classes, because Node loads + * the addon once per process. + * + * The addon is loaded when this module is imported. If the addon does not + * load, every call returns an `Err` and none throws. The same happens when + * the addon reports a binding interface version other than this + * TypeScript's. The binding interface version is a number that the addon and + * this TypeScript both state, and the two numbers must match. */ import { createRequire } from 'node:module' import { dirname, join } from 'node:path' @@ -34,13 +44,16 @@ import type { Outcome } from '../native' import { fromNative, type RecipherError, sdkError } from './error' import { err, ok, type Result } from './result' -/** The binding interface this TypeScript speaks. */ +/** + * The binding interface version of this TypeScript. The addon must report + * the same number. + */ export const BINDING_INTERFACE = 4 -/** What the native build exports. */ +/** The native addon's exports, as `native.d.ts` declares them. */ export type Binding = typeof Native -/** The exports `load` checks for. */ +/** The exports that `load` checks the addon has. */ const EXPORTS = [ 'Cipher', 'Keyset', @@ -57,8 +70,9 @@ const EXPORTS = [ ] as const /** - * Load the native build at `path` with `require`, and check that it is one - * this TypeScript can call. + * Load the native addon at `path` with `require`. Then check that this + * TypeScript can call it: the addon must export every name in `EXPORTS`, and + * report the binding interface version `BINDING_INTERFACE`. */ export function load( require: (path: string) => unknown, @@ -90,7 +104,8 @@ export function load( ), ) } - // Every export `EXPORTS` names is a function, as `Binding` says. + // The check above found a function for every name in `EXPORTS`, as + // `Binding` declares. const binding = exported as Binding let version: unknown try { @@ -110,13 +125,16 @@ export function load( return ok(binding) } -/** The native build of this package, loaded once, when it is imported. */ +/** This package's native addon, loaded once, when this module is imported. */ export const binding: Result = load( createRequire(import.meta.url), join(dirname(fileURLToPath(import.meta.url)), '..', 'recipher.node'), ) -/** The error of a native call that threw or rejected, which it never should. */ +/** + * The error for a native call that threw or rejected. A native call should + * never do either. + */ function threw(): RecipherError { return sdkError( 'recipher::native_threw', @@ -125,7 +143,7 @@ function threw(): RecipherError { ) } -/** The `Result` of a native outcome. */ +/** Turn a native outcome into a `Result`. */ function fromOutcome(outcome: Outcome): Result { if (typeof outcome !== 'object' || outcome === null) { return err( @@ -135,12 +153,12 @@ function fromOutcome(outcome: Outcome): Result { ), ) } - // The native build's declarations type `value` for each method; the - // typed signature over the method names `T`. + // `native.d.ts` gives `value` a type for each method. Here the type comes + // from the typed signature over the method, which names `T`. return outcome.ok ? ok(outcome.value as T) : err(fromNative(outcome.error)) } -/** A synchronous native call as a `Result`. Never throws. */ +/** Run a synchronous native call, and return its `Result`. Never throws. */ export function settle( call: () => Outcome, ): Result { @@ -151,7 +169,7 @@ export function settle( } } -/** An asynchronous native call as a `Result`. Never rejects. */ +/** Run an asynchronous native call, and return its `Result`. Never rejects. */ export async function settleAsync( call: () => Promise>, ): Promise> { @@ -162,23 +180,29 @@ export async function settleAsync( } } -/** How a method's return value reaches the caller. */ +/** How `adapt` changes what a method returns to the caller. */ export type Adaptation = - /** A promise of an outcome, as a promise of a `Result`. */ + /** A promise of an outcome becomes a promise of a `Result`. */ | 'async' - /** An outcome, as a `Result`. */ + /** An outcome becomes a `Result`. */ | 'sync' - /** As it is: the method does not fail. Only bound. */ + /** + * The return value is unchanged, because the method does not fail. The + * method is only bound to its instance. + */ | 'plain' -/** Set on a class or a prototype `adapt` has run on. */ +/** The marker that `adapt` sets on a class or a prototype it has changed. */ const ADAPTED = Symbol.for('@cipherstash/recipher.adapted') /** - * Replace each method named in `methods` on `target` (a class, for its - * static methods, or its prototype) with a getter that gives the method - * bound to the object it is read from, its outcome a `Result`. Then freeze - * `target`. A target already adapted is left as it is. + * Replace each method named in `methods` on `target` with a getter. Then + * freeze `target`. + * + * `target` is a class, for its static methods, or a class's prototype. The + * getter returns the method bound to the object it is read from. The bound + * method returns a `Result` in place of an outcome, as `methods` says. If + * `adapt` has already changed `target`, `adapt` leaves it as it is. */ export function adapt( target: object, diff --git a/languages/typescript/packages/recipher-js/src/cipher.ts b/languages/typescript/packages/recipher-js/src/cipher.ts index 4d326f320..81205ce15 100644 --- a/languages/typescript/packages/recipher-js/src/cipher.ts +++ b/languages/typescript/packages/recipher-js/src/cipher.ts @@ -1,14 +1,18 @@ /** - * `Cipher`, `Keyset` and `Ciphertext`: the native build's classes, with the - * typed signatures TypeScript callers see. + * The `Cipher`, `Keyset`, and `Ciphertext` classes of the native addon, with + * the typed signatures that TypeScript callers see. * - * The classes are written in Rust (`crate/src/cipher.rs` and - * `crate/src/ciphertext.rs`), and `native.d.ts` declares them as napi-rs - * generates them: untyped arguments, outcome objects. This module exports - * the same classes, adapted by `adapt` so each method returns a `Result`, - * under the signatures below, which say what a call takes and gives: one - * value in and one ciphertext out, an array in and an array out, and the - * type a ciphertext opens as. + * The classes are written in Rust, in `crate/src/cipher.rs` and + * `crate/src/ciphertext.rs`. `native.d.ts` declares them as napi-rs + * generates them: with untyped arguments, and returning outcome objects + * (`{ ok, value }` or `{ ok, error }`). This module exports the same classes + * after `adapt` has changed each method to return a `Result`. + * + * The signatures below say what each call takes and returns: + * + * - one value in gives one ciphertext out; + * - an array in gives an array out; + * - a ciphertext's type parameter is the type it decrypts to. */ import { adapt, type Binding, binding, settleAsync } from './binding' import type { RecipherError } from './error' @@ -25,36 +29,44 @@ import type { Opened, OpenedScalar, Value } from './values' declare const opens: unique symbol /** - * One sealed value: opaque bytes, with its own data key. + * One encrypted value: opaque bytes, encrypted with a data key of its own. + * + * `T` is the type the ciphertext decrypts to. For example, + * `keyset.encrypt('..')` returns a `Ciphertext`. A ciphertext read + * from stored bytes with no kind named decrypts to whatever type was + * encrypted. The type of such a ciphertext allows any scalar. * - * `T` is the type it decrypts to: `keyset.encrypt('..')` returns a - * `Ciphertext`. A ciphertext read from stored bytes with no kind - * named opens as whatever it was sealed as, typed as any scalar. * `toString()` and Node's `inspect` hide the bytes. */ export interface Ciphertext { - /** The bytes to store. A copy: changing it changes no ciphertext. */ + /** + * The bytes to store. The array is a copy, so changing it does not change + * any ciphertext. + */ toBytes(): Uint8Array - /** Names the type and hides the bytes. */ + /** Text that names the type and hides the bytes. */ toString(): string - /** Records `T`, which nothing at run time holds. */ + /** Carries `T` for the type checker. The property never exists at run time. */ readonly [opens]?: T } /** The `Ciphertext` class. */ export interface CiphertextClass { readonly prototype: Ciphertext - /** `value instanceof Ciphertext`. */ + /** Whether `value` is a `Ciphertext`, for `value instanceof Ciphertext`. */ [Symbol.hasInstance](value: unknown): value is Ciphertext /** - * Read a ciphertext from stored bytes. This checks the bytes' shape only; - * decrypting is what authenticates them. + * Read a ciphertext from stored bytes. This method checks only the shape + * of the bytes. Decrypting checks that the bytes are genuine and + * unchanged. * - * With a kind, such as `kinds.string`, it opens as that kind, and - * decrypting refuses a value sealed as another type. Read a JSON - * document back with `kinds.json`: with no kind, it opens as its JSON - * text, and `JSON.parse` of that text loses the digits of an integer - * outside a `number`'s safe range. + * With a kind, such as `kinds.string`, the ciphertext decrypts to that + * kind. Decrypting then refuses a value that was encrypted as another + * type. + * + * Read a JSON document back with `kinds.json`. With no kind, the document + * decrypts to its JSON text. `JSON.parse` of that text loses the digits of + * an integer outside a `number`'s safe range. */ fromBytes( bytes: Uint8Array, @@ -64,16 +76,20 @@ export interface CiphertextClass { } /** - * One keyset of a cipher. Every data key is made under one keyset, and a + * One keyset of a cipher. A keyset is a group of keys in ZeroKMS, + * CipherStash's key service. Every data key is made under one keyset. A * ciphertext names the keyset it was made under. */ export interface Keyset { /** - * Encrypt a value, with no context, as one ciphertext with its own data - * key. The value's type picks how it is encrypted. An array of values is - * an array of ciphertexts, in the same order, made with one key request - * however long it is. All or nothing: one value refused is an `Err` for - * the whole array. + * Encrypt a value as one ciphertext, with a data key of its own and no + * context. A context is data that a ciphertext is bound to. The ciphertext + * decrypts only under the same context. The value's type decides how it is + * encrypted. + * + * An array of values gives an array of ciphertexts, in the same order. The + * whole array takes one key request to ZeroKMS, however long it is. If one + * value is refused, the whole array is an `Err`. */ encrypt( value: V, @@ -82,9 +98,10 @@ export interface Keyset { values: readonly V[], ): Promise>[], RecipherError>> /** - * Encrypt a row of a record, each field under its field path, or an - * array of rows in one key request. The stored row has, for each sealed - * field, its ciphertext and its index terms. + * Encrypt a row of a record, or an array of rows with 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. */ encrypt( record: R, @@ -95,15 +112,16 @@ export interface Keyset { rows: readonly Plaintext[], ): Promise[], RecipherError>> /** - * Open a ciphertext sealed under this keyset, or an array of them in one - * key request. A ciphertext from another keyset is an `Err` with the code - * `stack_encrypt::foreign_keyset`, refused before any key is requested. + * Decrypt a ciphertext made under this keyset, or an array of them with + * one key request. A ciphertext from another keyset is an `Err` with the + * code `stack_encrypt::foreign_keyset`. The keyset refuses it before any + * key is requested. */ decrypt(ciphertext: Ciphertext): Promise> decrypt( ciphertexts: readonly Ciphertext[], ): Promise> - /** Open a stored row of a record sealed under this keyset, or an array of them. */ + /** Decrypt a stored row of a record made under this keyset, or an array of rows. */ decrypt( record: R, row: Stored, @@ -113,9 +131,9 @@ export interface Keyset { rows: readonly Stored[], ): Promise[], RecipherError>> /** - * Encrypt one field of a record, for an update of that field: its stored - * form, as the field has it in a whole stored row. An array of values is - * an array of stored fields, in one key request. + * Encrypt one field of a record, to update that field. The stored field + * has the same form as that field in a whole stored row. An array of + * values gives an array of stored fields, with one key request. */ encryptField>( record: R, @@ -127,7 +145,7 @@ export interface Keyset { field: F, values: readonly NoInfer[F]>[], ): Promise[F][], RecipherError>> - /** Open one field of a stored row sealed under this keyset, or an array of them. */ + /** Decrypt one field of a stored row made under this keyset, or an array of them. */ decryptField>( record: R, field: F, @@ -138,41 +156,43 @@ export interface Keyset { field: F, stored: readonly NoInfer[F]>[], ): Promise[F][], RecipherError>> - /** Names the type. */ + /** Text that names the type. */ toString(): string } /** The `Keyset` class. Get a keyset from `cipher.defaultKeyset()`. */ export interface KeysetClass { readonly prototype: Keyset - /** `value instanceof Keyset`. */ + /** Whether `value` is a `Keyset`, for `value instanceof Keyset`. */ [Symbol.hasInstance](value: unknown): value is Keyset } /** - * A cipher: the engine, and the keysets it reaches. + * A cipher: the Stack Encrypt engine, and the keysets it can use. * - * Build one with `Cipher.create()`, or, in a test, with `testCipher()` from - * `@cipherstash/recipher/testing`. + * Make one with `Cipher.create()`. In a test, make one with `testCipher()` + * from `@cipherstash/recipher/testing`. */ export interface Cipher { /** - * The client's default keyset: the one a ZeroKMS administrator set for - * it. Encrypting needs a keyset. + * The client's default keyset: the keyset that a ZeroKMS administrator set + * for the client. The client is the ZeroKMS client whose credentials the + * cipher uses. Encrypting needs a keyset. */ defaultKeyset(): Keyset /** - * Open a ciphertext from any of this cipher's keysets, as the type it - * opens as. An array opens as an array, in the same order, with one key - * request for each keyset its ciphertexts were sealed under. + * Decrypt a ciphertext from any of this cipher's keysets, to the type it + * was encrypted as. An array gives an array, in the same order. Decrypting + * an array takes one key request for each keyset that its ciphertexts were + * made under. */ decrypt(ciphertext: Ciphertext): Promise> decrypt( ciphertexts: readonly Ciphertext[], ): Promise> /** - * Open a stored row of a record, or an array of them. The opened row's - * `inspect` names its fields and hides their values. + * Decrypt a stored row of a record, or an array of rows. Node's `inspect` + * shows the decrypted row's field names and hides their values. */ decrypt( record: R, @@ -182,7 +202,7 @@ export interface Cipher { record: R, rows: readonly Stored[], ): Promise[], RecipherError>> - /** Open one field of a stored row, or an array of them, in one key request. */ + /** Decrypt one field of a stored row, or an array of them with one key request. */ decryptField>( record: R, field: F, @@ -193,16 +213,16 @@ export interface Cipher { field: F, stored: readonly NoInfer[F]>[], ): Promise[F][], RecipherError>> - /** Names the type. */ + /** Text that names the type. */ toString(): string } /** Options for `Cipher.create`. */ export interface CipherOptions { /** - * Records to check now, before any credential is looked for, so a - * declaration the engine refuses is an `Err` here rather than at its - * first use. + * 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[] } @@ -210,13 +230,16 @@ export interface CipherOptions { /** The `Cipher` class. */ export interface CipherClass { readonly prototype: Cipher - /** `value instanceof Cipher`. */ + /** Whether `value` is a `Cipher`, for `value instanceof Cipher`. */ [Symbol.hasInstance](value: unknown): value is Cipher /** - * A cipher over ZeroKMS, with the credentials it finds: the `CS_*` - * variables, then the profile that `stash auth login` writes. Resolves - * to an `Err` with the code `stack_encrypt::config` when there are none, - * and to the engine's refusal when it refuses one of `options.records`. + * Create a cipher that uses ZeroKMS. The cipher looks for credentials in + * the `CS_*` environment variables, then in the profile that + * `stash auth login` writes. + * + * Resolves to an `Err` with the code `stack_encrypt::config` when there + * are no credentials. Resolves to the engine's error when the engine + * refuses one of `options.records`. */ create(options?: CipherOptions): Promise> } @@ -230,11 +253,12 @@ export interface Classes { } /** - * A class, frozen, under the type this module gives it. For a native class, - * `adapt` has replaced each method the type names with its form that - * returns a `Result`; `type-tests/native.ts` checks that each is a method - * the class has. A stand-in has the static methods its type names, and no - * instances. + * Freeze a class, and give it the type that this module declares for it. + * + * For a native class, `adapt` has already replaced each method that the type + * names with a version that returns a `Result`. `type-tests/native.ts` + * checks that the class has each of those methods. A stand-in class has the + * static methods that its type names, and no instances. */ function retyped(cls: object): T { Object.freeze(cls) @@ -242,7 +266,7 @@ function retyped(cls: object): T { return cls as unknown as T } -/** The native classes, adapted so each method returns a `Result`. */ +/** The native classes, after `adapt` has changed each method to return a `Result`. */ function adapted(native: Binding): Classes { adapt(native.Cipher, { create: 'async' }) adapt(native.Cipher.prototype, { @@ -268,8 +292,9 @@ function adapted(native: Binding): Classes { } /** - * Stand-ins for a native build that did not load: every call resolves to - * the `Err` that says why, and `instanceof` is false for every value. + * Stand-in classes for when the native addon did not load. Every call + * resolves to the `Err` that says why the addon did not load. `instanceof` + * is false for every value. */ function missing(error: RecipherError): Classes { return { @@ -295,8 +320,8 @@ function missing(error: RecipherError): Classes { } /** - * The classes for a native build, or the stand-ins for one that did not - * load. + * The changed native classes when the addon loaded, or the stand-ins when + * it did not. */ export function classesOf(loaded: Result): Classes { return loaded.isOk() ? adapted(loaded.value) : missing(loaded.error) @@ -305,9 +330,9 @@ export function classesOf(loaded: Result): Classes { /** The classes this package exports. */ export const classes: Classes = classesOf(binding) -/** The `Cipher` class: the native build's, adapted. */ +/** The `Cipher` class: the native addon's class, with each method returning a `Result`. */ export const Cipher: CipherClass = classes.Cipher -/** The `Keyset` class: the native build's, adapted. */ +/** The `Keyset` class: the native addon's class, with each method returning a `Result`. */ export const Keyset: KeysetClass = classes.Keyset -/** The `Ciphertext` class: the native build's, adapted. */ +/** The `Ciphertext` class: the native addon's class, with each method returning a `Result`. */ export const Ciphertext: CiphertextClass = classes.Ciphertext diff --git a/languages/typescript/packages/recipher-js/src/error.ts b/languages/typescript/packages/recipher-js/src/error.ts index c88b4e79a..18ee30581 100644 --- a/languages/typescript/packages/recipher-js/src/error.ts +++ b/languages/typescript/packages/recipher-js/src/error.ts @@ -1,9 +1,10 @@ /** - * `RecipherError`: every failure, as a value. + * `RecipherError`: the error that a failed call returns, as a value. * - * The native build defines the error's fields (`RecipherErrorFields`, in the - * generated `native.d.ts`) and every error it reports. This class exists in - * TypeScript because an error has to exist when the native build did not + * The native addon is the compiled Rust code that this package loads. The + * addon defines the error's fields (`RecipherErrorFields`, in the generated + * `native.d.ts`), and every error the addon reports. This class is written + * in TypeScript because an error must still exist when the addon did not * load. */ import type { ErrorCause, RecipherErrorFields, Severity } from '../native' @@ -11,28 +12,32 @@ import type { ErrorCause, RecipherErrorFields, Severity } from '../native' export type { ErrorCause, RecipherErrorFields, Severity } /** - * A failure, as a value. Every call that fails resolves to an `Err` holding - * one; none throws. + * A failure, as a value. Every call that fails resolves to an `Err` that + * contains a `RecipherError`. No call throws. * - * - `code` is stable, and is what to switch on: the engine's diagnostic - * code, such as `stack_encrypt::aead`, vitaminc's code for a value it - * refused, such as `ERR_INTEGER_RANGE`, or the SDK's own, such as - * `recipher::not_a_ciphertext`. + * - `code` is the code to switch on. It is stable. It is one of these: + * - the engine's error code, such as `stack_encrypt::aead`; + * - vitaminc's code for a value it refused, such as `ERR_INTEGER_RANGE`. + * vitaminc is the CipherStash Rust library that the engine's plaintext + * types come from; + * - the SDK's own code, such as `recipher::not_a_ciphertext`. * - `message` says what went wrong, in one line. - * - `help` says what to do about it, and `url` is a documentation page for - * the error, where the error has them. - * - `severity` is `error`, unless the engine's diagnostic states `warning` - * or `advice`. - * - `fields` holds the error's structured fields by `snake_case` name, and - * is empty where it has none: a refused declaration's `reason`, a - * ZeroKMS failure's `request_kind`. + * - `help` says what to do about it, where the error knows. + * - `url` is a documentation page for the error, where it has one. + * - `severity` is `error`, unless the engine's error report states + * `warning` or `advice`. + * - `fields` contains the error's structured fields, by `snake_case` name. + * 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 a declaration, a row or a stored row is of. + * - `record` names the record that the failed declaration, row, or stored + * row belongs to. * - `causes` lists the errors behind this one, outermost first. A cause - * from another library has no code and a fixed message. + * from another library has no code, and a fixed message. * - * No property, and no text it gives, holds a plaintext, a key, a token or a - * ciphertext. + * No property, and no text that the error gives, contains a plaintext, a + * key, a token, or a ciphertext. */ export class RecipherError { readonly code: string @@ -63,7 +68,7 @@ export class RecipherError { Object.freeze(this) } - /** The code and message, then the help where there is one. */ + /** Text with the code and the message, then the help where there is one. */ toString(): string { const text = `RecipherError(${this.code}): ${this.message}` return this.help === undefined ? text : `${text}\nhelp: ${this.help}` @@ -71,8 +76,10 @@ export class RecipherError { } /** - * The error of a native outcome. The native build writes it, so this only - * checks that it has the shape. + * Make a `RecipherError` from the error in a native outcome. A native + * outcome is the object a native method returns: `{ ok, value }` or + * `{ ok, error }`. The addon writes the error, so this function only checks + * the error's shape. */ export function fromNative(error: unknown): RecipherError { const { code, message, help, url, severity, fields, causes, field, record } = @@ -101,7 +108,10 @@ export function fromNative(error: unknown): RecipherError { }) } -/** A cause of the shape the native build writes, or nothing. */ +/** + * The cause, in a one-item array, when it has the shape that the addon + * writes. Otherwise, an empty array. + */ function causeOf(cause: unknown): ErrorCause[] { if (typeof cause !== 'object' || cause === null) { return [] @@ -114,9 +124,9 @@ function causeOf(cause: unknown): ErrorCause[] { } /** - * An error the TypeScript raises itself, for a native build that did not - * load or did not answer as it should. Every other error is the native - * build's. + * An error that the TypeScript makes itself. The TypeScript makes one when + * the addon did not load, or when the addon did not return what it should. + * The addon makes every other error. */ export function sdkError(code: string, message: string): RecipherError { return new RecipherError({ code, message }) diff --git a/languages/typescript/packages/recipher-js/src/index.ts b/languages/typescript/packages/recipher-js/src/index.ts index 84a737a10..ac841147d 100644 --- a/languages/typescript/packages/recipher-js/src/index.ts +++ b/languages/typescript/packages/recipher-js/src/index.ts @@ -1,6 +1,7 @@ /** - * `@cipherstash/recipher`: encrypt values with per-value ZeroKMS data keys, - * through the Stack Encrypt engine. + * `@cipherstash/recipher` encrypts values through the Stack Encrypt engine, + * CipherStash's encryption engine. Each value gets a data key of its own + * from ZeroKMS, CipherStash's key service. * * ```ts * import { Cipher } from '@cipherstash/recipher' @@ -15,7 +16,7 @@ * const opened = await cipher.decrypt(sealed.value) * ``` * - * No call throws and no promise rejects: every call resolves to a `Result`. + * No call throws, and no promise rejects. Every call resolves to a `Result`. */ export { Cipher, diff --git a/languages/typescript/packages/recipher-js/src/kinds.ts b/languages/typescript/packages/recipher-js/src/kinds.ts index 75a5a2f7a..0b367270f 100644 --- a/languages/typescript/packages/recipher-js/src/kinds.ts +++ b/languages/typescript/packages/recipher-js/src/kinds.ts @@ -1,10 +1,11 @@ /** - * The kinds of value, in the engine's words: what a stored ciphertext is - * read back as (`Ciphertext.fromBytes(bytes, kinds.string)`). + * Kinds: the types of value, by the engine's names for them. A kind says + * what type a stored ciphertext decrypts to, as in + * `Ciphertext.fromBytes(bytes, kinds.string)`. * - * A kind is plain data, `{ name }`, with the engine's name for it. Its type - * records the TypeScript type a value of the kind is: an integer kind's - * values are a `bigint` at every width. + * A kind is plain data, `{ name }`, that contains the engine's name for the + * type. The kind's TypeScript type records the type of the kind's values. + * An integer kind's values are a `bigint` at every width. */ import type { OpenedJson, VcDate, VcDecimal, VcTimestamp } from './values' @@ -12,7 +13,7 @@ import type { OpenedJson, VcDate, VcDecimal, VcTimestamp } from './values' export interface Kind { /** The engine's name for the kind, such as `int32`. */ readonly name: Name - /** Records `T`, which nothing at run time holds. */ + /** Carries `T` for the type checker. The property never exists at run time. */ readonly __value?: T } @@ -20,12 +21,13 @@ function kind(name: Name): Kind { return Object.freeze({ name }) } -/** The type a value of kind `K` is. */ +/** The TypeScript type of a value of kind `K`. */ export type ValueOf = K extends Kind ? T : never /** - * The kinds, in the engine's words. An integer kind's values are a `bigint` - * at every width. `json` is a JSON document, sealed as its JSON text. + * The kinds, by the engine's names for them. An integer kind's values are a + * `bigint` at every width. `json` is a JSON document, encrypted as its JSON + * text. */ export const kinds = Object.freeze({ string: kind<'string', string>('string'), diff --git a/languages/typescript/packages/recipher-js/src/record.ts b/languages/typescript/packages/recipher-js/src/record.ts index 2b000bda2..f2f91b403 100644 --- a/languages/typescript/packages/recipher-js/src/record.ts +++ b/languages/typescript/packages/recipher-js/src/record.ts @@ -1,6 +1,6 @@ /** - * Records: a declaration of fields, each encrypted, encrypted and indexed, - * or passed through. + * 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' @@ -14,32 +14,42 @@ * }) * ``` * - * A declaration is plain, frozen data: `{ type: 'record', name, fields }`, - * each field with its own declaration. The native build reads it, builds - * the engine's plan from it once, and checks it then: when a cipher first - * uses it, or when `Cipher.create({ records })` or `checkDeclarations(..)` - * is called. The types below are what TypeScript checks a row against. + * 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. */ import { binding, settle } from './binding' import type { RecipherError } from './error' import type { Kind, ValueOf } from './kinds' import { err, type Result } from './result' -/** An index a sealed field stores beside its ciphertext. */ +/** + * 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 value that is not there. + * How a field stores a missing value. * - * - `sealed`: the null is sealed like a value, as long as one, so the - * stored row does not show which rows have none. For a field of fixed - * width (a boolean, a number, a date, a timestamp or a decimal) whose - * only index is `equality`. + * - `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. */ +/** + * 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[], @@ -52,14 +62,14 @@ export interface SealedField< } /** - * A field passed through as it is: **not encrypted and not - * authenticated.** Anyone with the stored row can read it, change it or - * remove it, and the sealed fields still decrypt. Use it only for values - * that are not secret, and treat the value read back as untrusted. + * 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' - /** Records `T`, which nothing at run time holds. */ + /** Carries `T` for the type checker. The property never exists at run time. */ readonly __value?: T } @@ -73,11 +83,14 @@ export interface SealedOptions< > { /** The indexes the field stores. */ index?: I - /** How the field stores a null. With none, every row needs a value. */ + /** + * How the field stores a null. Without this option, every row needs a + * value for the field. + */ null?: N } -/** An encrypted field of `kind`. */ +/** An encrypted field of the kind `kind`. */ export function encrypt< K extends Kind, const I extends readonly Index[] = readonly [], @@ -85,8 +98,9 @@ export function encrypt< >( kind: K, options: SealedOptions = {}, - // `NoInfer`: what a field declares is read from `options` alone, never from - // the type a caller's context expects, which names every index and mode. + // `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 = @@ -102,14 +116,17 @@ export function passthrough(): PassthroughField { return Object.freeze({ type: 'passthrough' }) } -/** A record's declaration: plain, frozen data. */ +/** 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 a declaration, for every copy of the package. */ + /** + * 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 @@ -119,7 +136,9 @@ export interface RecordDeclaration< /** * A record named `name`, with `fields`. Each field's context is its field - * path: the record's name, then the field's name. + * 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, @@ -132,7 +151,7 @@ export function record< }) } -/** The plaintext row of a record. A field that takes a null may be `null`. */ +/** The plaintext row of a record. A field that takes a null can be `null`. */ export type Plaintext = R extends RecordDeclaration ? { @@ -148,15 +167,16 @@ export type Plaintext = } : never -/** A sealed field as it is stored: its ciphertext and its index terms. */ +/** 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: for each sealed field its ciphertext and - * terms, each opaque bytes; for each passthrough field its value. A field - * that stores a null as SQL `NULL` is `null` for an absent value. + * 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 @@ -173,7 +193,7 @@ export type Stored = } : never -/** The field names of a record whose fields are sealed. */ +/** The names of a record's encrypted fields. */ export type SealedFieldName = R extends RecordDeclaration ? { @@ -183,9 +203,11 @@ export type SealedFieldName = : never /** - * Check declarations with the engine, with no credentials and no request: - * for a test or a CI step. The first refusal is the `Err`, naming the - * record and, where there is one, the field. + * 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. */ export function checkDeclarations( declarations: readonly RecordDeclaration[], diff --git a/languages/typescript/packages/recipher-js/src/result.ts b/languages/typescript/packages/recipher-js/src/result.ts index 06dc1fdda..c425b8245 100644 --- a/languages/typescript/packages/recipher-js/src/result.ts +++ b/languages/typescript/packages/recipher-js/src/result.ts @@ -1,12 +1,12 @@ /** - * A `Result`: the value of a call that worked, or the error of one that did - * not. It has Rust's `Result` methods, in camelCase, and each does what - * Rust's does. + * A `Result`: the value of a call that worked, or the error of a call that + * failed. A `Result` has the methods of Rust's `Result`, named in camelCase. + * Each method does what the Rust method does. * - * `unwrap()` and `expect(..)` are the only methods that throw, as they are - * the only ones that panic in Rust. Use them in a script, a test or a - * startup path. Everywhere else, narrow with `isOk()` or `isErr()`, or - * combine with `map`, `andThen` and `unwrapOr`. + * Only `unwrap()` and `expect(..)` throw. In Rust, they are also the only + * `Result` methods that panic. Use them in a script, a test, or code that + * runs at startup. Everywhere else, narrow the type with `isOk()` or + * `isErr()`, or combine results with `map`, `andThen`, and `unwrapOr`. * * ```ts * const sealed = await keyset.encrypt('a secret message') @@ -19,40 +19,46 @@ export type Result = Ok | Err interface Methods { - /** Whether this is an `Ok`. Narrows the type, as a Rust `match` does. */ + /** Whether this is an `Ok`. Narrows the type, as a `match` does in Rust. */ isOk(): this is Ok - /** Whether this is an `Err`. Narrows the type, as a Rust `match` does. */ + /** Whether this is an `Err`. Narrows the type, as a `match` does in Rust. */ isErr(): this is Err - /** The value, or `undefined` for an `Err`. */ + /** Returns the value, or `undefined` for an `Err`. */ ok(): T | undefined - /** The error, or `undefined` for an `Ok`. */ + /** Returns the error, or `undefined` for an `Ok`. */ err(): E | undefined - /** An `Ok` with `f` applied to its value; an `Err` as it is. */ + /** + * For an `Ok`, returns an `Ok` of `f` applied to the value. Returns an + * `Err` unchanged. + */ map(f: (value: T) => U): Result - /** An `Err` with `f` applied to its error; an `Ok` as it is. */ + /** + * For an `Err`, returns an `Err` of `f` applied to the error. Returns an + * `Ok` unchanged. + */ mapErr(f: (error: E) => F): Result - /** `f` applied to the value, or `fallback` for an `Err`. */ + /** Returns `f` applied to the value, or `fallback` for an `Err`. */ mapOr(fallback: U, f: (value: T) => U): U - /** `other` for an `Ok`; this `Err` as it is. */ + /** For an `Ok`, returns `other`. Returns this `Err` unchanged. */ and(other: Result): Result - /** `f` applied to the value for an `Ok`; this `Err` as it is. */ + /** For an `Ok`, returns `f` applied to the value. Returns this `Err` unchanged. */ andThen(f: (value: T) => Result): Result - /** This `Ok` as it is; `other` for an `Err`. */ + /** Returns this `Ok` unchanged. For an `Err`, returns `other`. */ or(other: Result): Result - /** This `Ok` as it is; `f` applied to the error for an `Err`. */ + /** Returns this `Ok` unchanged. For an `Err`, returns `f` applied to the error. */ orElse(f: (error: E) => Result): Result - /** The value, or `fallback` for an `Err`. */ + /** Returns the value, or `fallback` for an `Err`. */ unwrapOr(fallback: U): T | U - /** The value, or `f` applied to the error for an `Err`. */ + /** Returns the value, or `f` applied to the error for an `Err`. */ unwrapOrElse(f: (error: E) => U): T | U /** - * The value. Throws for an `Err`, with the error as the thrown error's - * `cause`. + * Returns the value. For an `Err`, throws an `Error` whose `cause` is the + * error. */ unwrap(): T /** - * The value. Throws for an `Err`, with `message` and the error as the - * thrown error's `cause`. + * Returns the value. For an `Err`, throws an `Error` whose message starts + * with `message`, and whose `cause` is the error. */ expect(message: string): T } @@ -113,7 +119,7 @@ export class Ok implements Methods { } } -/** The result of a call that did not work. */ +/** The result of a call that failed. */ export class Err implements Methods { readonly error: E @@ -173,12 +179,12 @@ export class Err implements Methods { } } -/** An `Ok` holding `value`. */ +/** Make an `Ok` that contains `value`. */ export function ok(value: T): Result { return new Ok(value) } -/** An `Err` holding `error`. */ +/** Make an `Err` that contains `error`. */ export function err(error: E): Result { return new Err(error) } diff --git a/languages/typescript/packages/recipher-js/src/testing.ts b/languages/typescript/packages/recipher-js/src/testing.ts index 5705629fc..01b16679d 100644 --- a/languages/typescript/packages/recipher-js/src/testing.ts +++ b/languages/typescript/packages/recipher-js/src/testing.ts @@ -1,5 +1,6 @@ /** - * A cipher for tests: no credentials, no network. + * A cipher for tests. A test cipher needs no credentials and makes no + * network requests. * * ```ts * import { testCipher } from '@cipherstash/recipher/testing' @@ -7,16 +8,19 @@ * const cipher = (await testCipher()).unwrap() * ``` * - * Every key is a function of a seed and the value's context, so a value - * sealed by one test cipher opens in another with the same seed, in the same - * process or a later one. The keys are no secret from anyone who knows the - * seed: never use a test cipher for data you keep. + * Every key is derived from a seed and the value's context. The context is + * data that a ciphertext is bound to. A value encrypted by one test cipher + * decrypts with another test cipher that has the same seed. That works in + * the same process or in a later one. + * + * Anyone who knows the seed can derive the keys. Never use a test cipher for + * data you keep. */ import { type Cipher, classes } from './cipher' import type { RecipherError } from './error' import type { Result } from './result' -/** The byte the seed of a test cipher is filled with when none is given. */ +/** The byte that fills a test cipher's seed when no seed is given. */ const DEFAULT_SEED_BYTE = 0x2a /** Options for `testCipher`. */ @@ -26,10 +30,13 @@ export interface TestCipherOptions { } /** - * A cipher over the engine's deterministic test keys. Resolves to an `Err` - * with the code `recipher::testing_seed` for a seed that is not 32 bytes, - * or one whose getter throws, and `recipher::no_testing` when the native - * build has no test cipher: only the debug build (`build:debug`) has one. + * A cipher that uses the engine's deterministic test keys. The same seed + * always gives the same keys. + * + * Resolves to an `Err` with the code `recipher::testing_seed` when the seed + * is not 32 bytes, or when reading `options.seed` throws. Resolves to an + * `Err` with the code `recipher::no_testing` when the native addon has no + * test cipher. Only the debug build of the addon (`build:debug`) has one. */ export async function testCipher( options?: TestCipherOptions | null, @@ -38,7 +45,8 @@ export async function testCipher( try { seed = options?.seed ?? new Uint8Array(32).fill(DEFAULT_SEED_BYTE) } catch { - // Not a seed, so the native build refuses it as one. + // `undefined` is not a seed, so the addon refuses it with + // `recipher::testing_seed`. seed = undefined } return classes.createTesting(seed) diff --git a/languages/typescript/packages/recipher-js/src/values.ts b/languages/typescript/packages/recipher-js/src/values.ts index ac8d1f565..bcc1b01d8 100644 --- a/languages/typescript/packages/recipher-js/src/values.ts +++ b/languages/typescript/packages/recipher-js/src/values.ts @@ -1,8 +1,9 @@ /** - * The values the SDK encrypts, and the types they open as. + * The values the SDK encrypts, and the types they decrypt to. * - * A value's type picks how it is encrypted, by vitaminc's mapping for - * JavaScript: + * A value's type decides how it is encrypted. The mapping is vitaminc's + * mapping for JavaScript. vitaminc is the CipherStash Rust library that the + * engine's plaintext types come from. * * | Value | Encrypted as | Decrypts as | * |---|---|---| @@ -18,19 +19,19 @@ * | `null` | null | `null` | * | `json(value)` | a JSON document, as its text | the document | * - * Integers are a `bigint`: a `number` is a float, and `5` does not equal - * the integer `5n`. A plain object is refused: wrap it in `json(..)`. + * Integers are a `bigint`. A `number` is a float. The `number` `5` does not + * equal the integer `5n`. A plain object is refused. Wrap it in `json(..)`. * - * The wrapper classes (`VcDate`, `VcTimestamp`, `VcDecimal`, `VcUuid`) and - * `json` are the native build's. Without a build, stand-ins take their - * place: each constructs as the class does, and `encrypt` then resolves to - * the `Err` that says why the build did not load. + * The wrapper classes (`VcDate`, `VcTimestamp`, `VcDecimal`, and `VcUuid`) + * and `json` come from the native addon. When the addon did not load, + * stand-ins take their place. Each stand-in constructs as the class does. + * `encrypt` then resolves to the `Err` that says why the addon did not load. */ import { binding } from './binding' declare const wrapper: unique symbol -/** A calendar date, such as `new VcDate('2026-11-23')`. vitaminc's class. */ +/** A calendar date, such as `new VcDate('2026-11-23')`. The class comes from vitaminc. */ export interface VcDate { /** The date as `YYYY-MM-DD`. */ readonly value: string @@ -38,15 +39,15 @@ export interface VcDate { readonly [wrapper]: 'VcDate' } -/** A UTC instant to the nanosecond. vitaminc's class. */ +/** A UTC instant, to the nanosecond. The class comes from vitaminc. */ export interface VcTimestamp { - /** The instant as RFC 3339 text with nanoseconds. */ + /** The instant as RFC 3339 text, with nanoseconds. */ readonly value: string toJSON(): string readonly [wrapper]: 'VcTimestamp' } -/** A decimal with its scale, such as `new VcDecimal('1.50')`. vitaminc's class. */ +/** A decimal with its scale, such as `new VcDecimal('1.50')`. The class comes from vitaminc. */ export interface VcDecimal { /** The decimal as text, with its scale. */ readonly value: string @@ -55,9 +56,9 @@ export interface VcDecimal { } /** - * A UUID. vitaminc's class. The engine's value model does not hold a UUID - * yet, so encrypting one is an `Err` with the code `recipher::uuid`, and it - * is not a `Scalar`. + * A universally unique identifier (UUID). The class comes from vitaminc. + * The engine has no plaintext type for a UUID yet. Encrypting a `VcUuid` is + * an `Err` with the code `recipher::uuid`. `VcUuid` is not a `Scalar`. */ export interface VcUuid { /** The UUID as hyphenated hex. */ @@ -75,13 +76,14 @@ export interface WrapperConstructor { type WrapperName = 'VcDate' | 'VcTimestamp' | 'VcDecimal' | 'VcUuid' /** - * The class the native build defines, or a stand-in that holds its text, is - * frozen, and serialises as vitaminc's does. + * The class that the native addon defines. When the addon did not load, a + * stand-in class instead. The stand-in keeps its text, is frozen, and + * serialises to JSON as vitaminc's class does. */ function wrapperClass(name: WrapperName): WrapperConstructor { if (binding.isOk()) { - // The build exports each class under its name (`crate/src/lib.rs`); - // napi-rs does not declare them, so they are typed here. + // The addon exports each class under its name (`crate/src/lib.rs`). + // napi-rs does not declare these classes, so this code gives them types. return Reflect.get(binding.value, name) as WrapperConstructor } const StandIn = class { @@ -110,7 +112,7 @@ export const VcDecimal: WrapperConstructor = /** A UUID. */ export const VcUuid: WrapperConstructor = wrapperClass('VcUuid') -/** A value that is one scalar. */ +/** A value that is one scalar: a single value, not a JSON document. */ export type Scalar = | string | boolean @@ -125,9 +127,10 @@ export type Scalar = /** * A JSON value. An integer outside the safe range of a `number` is a - * `bigint`, within the 64-bit range (`-(2n ** 63n)` to `2n ** 64n - 1n`); - * on encrypt, a whole `number` between 2^53 and 2^64 from zero is refused, - * because an integer was likely meant. + * `bigint`, within the 64-bit range (`-(2n ** 63n)` to `2n ** 64n - 1n`). + * + * `encrypt` refuses a whole `number` whose absolute value is at least 2^53 + * but less than 2^64. An integer was likely meant. */ export type JsonValue = | null @@ -138,7 +141,7 @@ export type JsonValue = | readonly JsonValue[] | { readonly [key: string]: JsonValue } -/** A JSON document as it opens. */ +/** A JSON document as it decrypts. */ export type OpenedJson = | null | boolean @@ -157,41 +160,49 @@ declare const document: unique symbol export interface Json { toString(): string /** - * Marks a `Json`, so no other object is one. Nothing at run time holds - * it: a `Json` is the native build's class. + * Marks a `Json`, so that no other object type-checks as one. The marker + * never exists at run time, because a `Json` is an instance of the native + * addon's class. */ readonly [document]: true } -/** A JSON document, to encrypt as one ciphertext. */ +/** The type of `json`, which makes a JSON document to encrypt as one ciphertext. */ export type JsonFunction = (document: JsonValue) => Json /** - * A JSON document, to encrypt as one ciphertext. The document is read now, - * so a later change to the object does not change what is encrypted. Never - * throws: a document that cannot be encrypted (bytes or a `Date` in it, - * nesting deeper than 127 levels) is an `Err` from `encrypt`. + * A JSON document, to encrypt as one ciphertext. `json` reads the document + * immediately, so a later change to the object does not change what is + * encrypted. + * + * `json` never throws. A document that cannot be encrypted is an `Err` from + * `encrypt`. Examples are a document that contains bytes or a `Date`, and a + * document nested deeper than 127 levels. */ export const json: JsonFunction = binding.isOk() ? nativeJson(binding.value.json) : standInJson -/** The native `json`, which returns its `Json` class, as `Json` types it. */ +/** + * The native addon's `json` function, with the type `JsonFunction`. The + * function returns an instance of the addon's `Json` class, which the `Json` + * type describes. + */ function nativeJson(native: (document: unknown) => unknown): JsonFunction { // biome-ignore lint/plugin: the native class carries no TypeScript brand; `Json` describes it. return native as unknown as JsonFunction } -/** The stand-in for `json` when the native build did not load. */ +/** The stand-in for `json` when the native addon did not load. */ function standInJson(): Json { // biome-ignore lint/plugin: a stand-in `Json`, which `encrypt` refuses with the load error. return Object.freeze({ toString: () => 'Json(***)' }) as unknown as Json } -/** A value `encrypt` takes. */ +/** A value that `encrypt` takes. */ export type Value = Scalar | Json -/** The type a value of type `V` decrypts as. */ +/** The type that a value of type `V` decrypts to. */ export type Opened = V extends string ? string : V extends boolean @@ -216,5 +227,5 @@ export type Opened = V extends string ? OpenedJson : never -/** Any scalar a stored ciphertext can open as. */ +/** Any scalar type that a stored ciphertext can decrypt to. */ export type OpenedScalar = Opened