Skip to content

feat(recipher-js): records through the engine's Planned - #1776

Draft
coderdan wants to merge 1 commit into
feat/recipher-js-valuesfrom
feat/recipher-js-records
Draft

coderdan wants to merge 1 commit into
feat/recipher-js-valuesfrom
feat/recipher-js-records

Conversation

@coderdan

@coderdan coderdan commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Step 3 of phase 1 of the TypeScript SDK plan (#1747), on top of #1775. A program declares a record once (each field encrypted, encrypted and indexed, or passed through) and encrypts and decrypts whole rows of it, or one field at a time. Rows go through the engine's dynamic::Planned, so the stored bytes are the engine's, and many rows make one key request.

A record is a declaration like a table's: a name, and for each field what is stored. An index is a search term stored beside a field's ciphertext (an equality term, a match term, an order term). Querying with those terms is step 4.

The package is still private and takes no changeset.

Changes

Declaring. record(name, fields), encrypt(kinds.x, { index, null }) and passthrough<T>() make plain, frozen data: { type: 'record', name, fields }. The type: 'record' property is how the native build recognises a declaration, so a declaration from the CommonJS build works with a cipher from the ESM build. A library reads user.name, user.fields and each field's type, kind, index and null.

The plan, from the engine's types. crate/src/record.rs reads the declaration with vitaminc's frame serde and builds the plan with the engine's own types: FieldPlan::new(name, context, outputs), .with_type(ValueKind), .with_null(NullMode), Plan::new. Outputs are Output::Ciphertext, Output::Term(IndexSpec) and Output::Passthrough; the stored row is read with Output::parse and Output::key(). The only table of the SDK's own maps its index names (equality, match, ore, ope) to IndexSpec. Each field's context is its field path, [record, field], read by the engine's context reader. A plan, and the plan of each sealed field alone, is built once per declaration and kept for the life of the process.

Rows. keyset.encrypt(user, row | rows), cipher.decrypt(user, stored | stored[]) and keyset.decrypt. Each value is read as its field's kind by the engine's dynamic::read before the engine sees it: vitaminc reads a bigint at its narrowest width, and the engine checks by exact kind.

One field. keyset.encryptField(user, 'email', value | values) and cipher.decryptField / keyset.decryptField(user, 'email', stored | stored[]) run the plan of that field alone, under the same field path. An array is one key request. A field encrypted alone has the bytes it has in a whole row, and a row's field opens alone.

Refusals name the record and the field. RecipherError has a record property beside field. A declaration refusal, from checkDeclarations, Cipher.create({ records }) or the first use, names the record; a record name the engine refuses is blamed on the record, not on a field; the engine's reserved names bind and context_field are refused as recipher::reserved_field, naming the field; a value out of its field's range names the field, also when vitaminc refuses it first (a bigint past 128 bits); a stored row's misfit names the field, and a term of an index the field does not declare is refused.

A decrypted row hides its values when inspected. Each opened row has a non-enumerable Symbol.for('nodejs.util.inspect.custom') method, so console.log(row) prints users { email: [hidden], .. }. The fields themselves are ordinary properties. This needs Node-API 9, so the crate turns on napi's napi9 feature.

The binding interface number is now 3.

What the tests prove

Rust (crate/src/record_tests.rs):

  • A row round-trips; the field stored as SQL NULL opens as a null; an integer opens at its field's width.
  • The stored row has exactly the outputs declared.
  • A field's ciphertext is sealed under its field path: the engine's typed decrypt_with_context::<String>(ct, ("users", "email")) opens it, and ("users", "name") refuses it.
  • One field opens alone, and a field sealed alone opens through the engine's typed API under its field path.
  • Three rows, and three values of one field, are one key request each way (a counting key source).
  • An integer is read at its field's width and refused outside it, naming the record and the field; the engine refuses a bad declaration naming both; a json field is refused (it needs the EQL extension); a bad record name is the record's fault and a bad field name the field's; a plan is built once.

TypeScript (__tests__/addon/records.test.ts): round trips of one row and many; the stored shape; nulls; every kind; encryptField giving the same equality term as a whole row and a whole row taking the updated field; arrays of one field; a SQL-null field alone; a field opened as another field of the same shape (two string fields with equality) refused, asserting the kind and the code, and a row opened under a record of another name refused the same way; inspect of a decrypted row; and each refusal above with its record and field. The two-format suite now also declares a record in the CommonJS build and uses it with an ESM cipher. type-tests/records.ts pins the row, stored and field types, arrays of one field, and that a declaration is plain data.

Verification

Run locally on macOS (arm64), Rust 1.94.1, Node 24.1, pnpm 10.33.2, at a0479fca0:

  • cargo fmt --all --check: passed.
  • cargo clippy --locked --all-targets --all-features -- -D warnings: passed. Default features: passed.
  • cargo test --locked --all-features: 41 passed (37 unit, 4 boundary), six runs in a row. CI's first run of this branch caught a race in the plan cache (two threads building one declaration's plan, the second replacing the first); the cache now keeps the first plan built.
  • pnpm run build:debug, then git status: clean. pnpm run build:native (release): built, native.d.ts unchanged, createTesting resolves to Err(recipher::no_testing).
  • pnpm run test:addon: 76 passed.
  • pnpm run test: 27 passed, tsc clean.
  • pnpm run code:check: no errors. pnpm run test:scripts: 96 files passed. pnpm run lint:typecheck-scope: passed.

Not run: anything against a live ZeroKMS, and the conformance profiles (see below). CI results are in the checks.

Deviations from the plan

  • No json record field. The engine refuses a plan field of type json unless it names an EQL target. It comes with the EQL extension (step 7). A test pins the refusal.
  • Values are read as the field's kind by the engine's dynamic::read. It converts a value only when the conversion is exact, so it also takes an exact float in an integer field or an integer in a decimal field; TypeScript's types refuse both at compile time.
  • The conformance profiles are not run (record-declarations-v1, the runtime and read profiles). There is no TypeScript conformance runner yet (stack-encrypt conformance: add TypeScript runner and public SDK mapping tests #1479).
  • Plaintext<R> is also the opened row's type, and Cipher.create({ records }) builds plans into a process-wide cache rather than one per cipher: a plan does not depend on the cipher.
  • RecipherError gains record, which the plan does not name, so a refusal can name the record it is about.
  • The engine's TargetResolver is not passed yet. The crate runs Planned::new, which uses NoTargets. The eql cargo feature (step 7) passes the resolver.

Needs from the engine

  • A refusal that says a value was sealed under another context. Opening a field as another field, or a row under another record's name, fails when the key service refuses the data key, so the engine reports it as a key-retrieval failure (stack_kms::retrieve_key_failed), and the SDK reports kind zerokms. The engine cannot tell this from any other refusal by the key service before it asks, so the SDK cannot either without guessing; a caller who switches on kind may treat it as an outage. A check of the stored context before any key is requested, as the engine already does for a plan with a context field (Error::ContextMismatch), would let the SDK report context_mismatch.

Changed since the first review

The whole step is rebuilt on #1774's new shape. The TypeScript RecordDeclaration class, its WeakMap of plans and its hand-written declaration frame are gone: a declaration is plain data, and the plan, its cache and the field plans are in Rust. The hand-written conversion of a value to its field's width (about 200 lines) is replaced by the engine's dynamic::read. Line counts (old 82b94834b, new a0479fca0): Rust source 2,496 lines in two crates (2,323 without test modules) became 4,020 in one (3,133 without test modules); TypeScript src/ 1,729 became 1,420.

Review findings:

  • Declaration refusals never name the record, and a bad record name is blamed on a field: fixed: record on every declaration refusal; a bad record name is asked of the engine alone to tell which name is at fault; bind and context_field are refused before the engine, naming the field.
  • instanceof RecordDeclaration across CJS and ESM: fixed: no instanceof; a declaration is recognised by its type: 'record' property. A plain object given with a second argument is recipher::not_a_record, not a value refusal. Tested in a two-format process.
  • The "field opened as another field" test was weak: fixed: two fields of the same shape, asserting kind and code, and a row under a record of another name.
  • encryptField/decryptField took one value and rebuilt the plan each call: fixed: one value or an array (one key request, tested by count in Rust), and each field's plan is built with the record's, once.
  • Wire strings hand-written: fixed: Output, IndexSpec, NullMode::name() and ValueKind throughout. The crate no longer spells an engine output key (c, eq, ...) or a null mode; the words sealed and passthrough remain only as the tags of the TypeScript declaration's own fields.
  • A decrypted row's util.inspect printed plaintext: fixed, tested.
  • Wrong-context open reported as zerokms: not fixed; see "Needs from the engine". The test pins today's kind and code.
  • Refusals that did not name the field (stored_tree, unknown field in field(..)): fixed.
  • A stray index term accepted: fixed: a stored row's term must be one of the field's own indexes.
  • A bigint past 128 bits refused with no field: fixed: when vitaminc refuses a row, the crate reads each field again to name the one it refused.
  • The Rust test that checked keys and not the value: fixed: one_field_opens_alone_... checks the opened value.

Related

Refs #1747 (the plan). Based on #1775.

@changeset-bot

changeset-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: a0479fc

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai

coderabbitai Bot commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true

@coderdan coderdan left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an automated code review, run at the PR author's request. It covers only this PR's own diff (base feat/recipher-js-values).

Summary. The core of this PR is sound. Each field's context is exactly [record name, field name]. Every row goes through dynamic::Planned, so the bytes are the engine's. A forged c node cannot be slipped in: ciphertext must be bytes that parse as a ciphertext, and a term can never land under c. Integer range checks are right at every width and sign, and the errors name the field, never the value. encryptField and a whole row's field are interchangeable in both directions, and every index kind round-trips. I found nothing blocking. The findings below are about error reporting, one spec deviation, a dual-package dispatch problem, and one test that does not prove what its name says.

What I ran. I built the debug addon. cargo test --locked --all-features passed (40 tests), and so did test:addon (50 tests). I wrote throwaway vitest probes (not committed) for about 60 cases: wrong field, wrong record, null and missing and extra and undefined fields, every integer width boundary, float32 narrowing, bad and reserved names, altered stored rows, and every index on every kind it allows. I also ran a CJS-plus-ESM script against a tsup build. To check the @ts-expect-error lines, I loosened StoredField and Plaintext and confirmed tsc fails (the type tests are real).

Should fix

  1. A declaration refusal does not name the record. See the inline comment on crates/core/src/record.rs:177. The spec says the refusal names the record, the field and the reason.
  2. Record calls dispatch on instanceof RecordDeclaration. With the dual CJS/ESM build, a declaration from the other copy falls through to the value path, and the row is ignored. Inline on src/cipher.ts:244.
  3. The "a field opened as another field" test does not test the context. It also shows that a wrong-context open comes back as kind zerokms. Inline on __tests__/addon/records.test.ts:167.
  4. encryptField/decryptField take one value only, and rebuild the field plan on every call. Inline on src/cipher.ts:254.
  5. The plan's output keys are hand-written strings. Inline on crates/core/src/record.rs:45.

Question / design

  1. A decrypted row prints its plaintext. util.inspect(opened) prints { n: 5n }, and console.log(opened) shows every decrypted field. The plan's "Results and errors" section says "a decrypted row's inspect output names its fields and hides their values, as Go's Redacted does." This PR returns a plain object. If the plan still holds, the record decrypt path is where that wrapper (or a non-enumerable util.inspect.custom) belongs. If it is deferred, please list it under "Deviations from the plan".
  2. Wrong-context opens report zerokms. Opening a field under another field's plan, or a row under another record's name, returns kind: 'zerokms', code: 'stack_kms::retrieve_key_failed' ("Forbidden: the data key is bound to another context"). A caller who switches on kind treats that as an outage or a credential problem, and may retry. kind_of comes from #1775, but this PR makes the case easy to reach. Should the SDK map it to context_mismatch (or open)?

Nits

  1. A bigint outside 128 bits gets no field name. 2n ** 128n in a uint128 field, or -(2n ** 127n) - 1n in an int128 field, is refused by vitaminc's reader in read_all, as ERR_INTEGER_RANGE with no field. Inside 128 bits the refusal is recipher::out_of_range with the field. Inline on crates/node/src/lib.rs:347.
  2. Refusals in stored_tree and RecordPlan::field do not name the field. A stored index is also checked against all four index names, not the field's own. Inline on crates/core/src/record.rs:687.
  3. one_field_opens_alone_and_a_field_alone_opens_in_a_row checks keys, not the value. It asserts the opened row's keys only (crates/core/tests/records.rs:272), not that the field opens to "ada@example.com". The TypeScript test covers the value, but the Rust test reads stronger than it is.

Not reported, because the ADR lists them as known non-findings: altered or removed index terms and passthrough values are not authenticated, and an SQL-null field removed in storage opens as null. My probes confirmed both still decrypt (equality replaced with garbage still opens), which is the documented behaviour.

)
})?;
let plan = record::plan(frame.as_protected_ref())
.map_err(|error| Refusal::of(Kind::Declaration, &error, Some(error.payload())))?;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should fix: a declaration refusal does not name the record, and a bad record name is blamed on a field.

The plan's "A record" section says a refusal "names the record, the field and the reason". Here the engine's refusal is passed on as it is, and the record name is lost. From Cipher.create({ records: [a, b, c] }) a caller cannot tell which record failed. What I saw from checkDeclarations:

  • record('a/b', { x }), record('', { x }), record('1x', { x }) and a record name with a control character all give field: 'x', reason: 'context_not_label'. The fault is the record's name, but the error blames field x.
  • A field named bind or context_field is refused, but with no field at all (reason: 'bind' / 'context_field'). The context_field message ("the context field is not a string passthrough…") also reads as nonsense to someone who only named a field.

Fix: add the record's name to every Kind::Declaration refusal from build (a record property on Refusal/RecipherError, or at least in the message). Check the two reserved names in the SDK before the engine sees them, with field set. For context_not_label, saying "the record name or the field name is not a plain segment" would point at both.

first: unknown,
second?: unknown,
): Promise<Result<unknown, RecipherError>> {
if (first instanceof RecordDeclaration) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should fix: dispatching on instanceof RecordDeclaration breaks across the CJS and ESM builds, and the row is silently ignored.

The package ships both dist/index.cjs and dist/index.js, and each has its own RecordDeclaration class. Suppose a library declares its records through require and the app uses import (the plan's "a library reads a record's name, its fields…" case). Then first instanceof RecordDeclaration is false, and encrypt(user, row) goes to #encryptValues(user): it tries to encrypt the declaration as a value and drops row. I ran this against a tsup build:

encrypt with CJS declaration via ESM cipher: {"kind":"value","code":"recipher::plain_object","message":"an object is not a value: wrap it in json(..)"}
decrypt: {"kind":"value","code":"recipher::not_a_ciphertext","message":"decrypt takes a Ciphertext"}
checkDeclarations: "recipher::not_a_record"

It fails closed, but the error points the user the wrong way. Fix: brand declarations with Symbol.for('@cipherstash/recipher.record') and check the brand here, in decryptAny (line 415) and in planOf (record.ts:247). Also, when a second argument is given and the first is not a declaration, return recipher::not_a_record rather than falling through to the value path.

const c = await cipher()
const row = (await c.defaultKeyset().encrypt(user, ada)).unwrap()
// @ts-expect-error: a match field's stored form has no equality term.
const result = await c.decryptField(user, 'email', row.name)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should fix: this test does not show that each field is sealed under its own path.

email stores equality and name stores match. The @ts-expect-error is about that shape difference, and the test asserts only isErr(). At run time stored_tree accepts the match output, and the refusal comes from key retrieval:

{"kind":"zerokms","code":"stack_kms::retrieve_key_failed","message":"Failed to send request: Forbidden: the data key is bound to another context"}

So the claim in the name holds, but nothing pins it. If the context binding broke, a refusal for some other reason would still pass. Fix: declare two fields with the same shape (two string fields with equality), open one's stored form as the other, and assert the kind and code. Add the same check for a row opened under a record with another name: record('people', user.fields) refuses today with the same error.

Separately, see the review body: zerokms is a misleading kind for "this value was sealed under another context". A caller who switches on kind would treat it as an outage.

* 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.
*/
async encryptField<

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should fix: encryptField/decryptField have no array form, and the field plan is rebuilt on every call.

  1. The plan's "The shape of a call" section says "Every call takes one value or an array of them … and makes at most one key request however long it is". Here an update of one field across N rows is N calls and N key requests. An array does not compile (value: Plaintext<R>[F]), and at run time it is refused as a wrong-type value. Please either take readonly Plaintext<R>[F][] (and readonly Stored<R>[F][]) and send them as N one-field rows through runRecords/openRows, which is already one request, or list this under "Deviations from the plan".
  2. fieldPlanOf calls plan.field(field) each time. That writes a plan frame and runs the engine's record::plan on every encryptField and decryptField. The PR says "a plan is built once per declaration and cached", but that is true of whole-record plans only. Cache the field plans too, for example a Map<string, NativePlan> held in a second WeakMap keyed by the declaration.


/// An index a sealed field stores: the SDK's name for it, and the engine's
/// output key.
const INDEXES: [(&str, &str); 4] = [

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should fix (low): the plan's output keys are hand-written strings, where the engine offers types.

INDEXES maps SDK names to "eq", "match", "ore", "ope", and "c" and "passthrough" are literals here (lines 266, 270, 599, 609, 657, 681). The null mode is copied through as an unchecked string. The engine already has these spellings as frozen wire format: dynamic::record::Output (Output::Ciphertext.key(), Output::Passthrough.key(), Output::parse) and NullMode::name(). The bytes are right today. But the brief for this step is that the plan is "written from the declaration … through the engine's types". Using Output/IndexSpec and NullMode would make a typo here a compile error rather than a refused plan. It would also let stored_row/stored_tree match on Output::Ciphertext.key() instead of "c". Only the SDK-name side (equality → eq) needs a table of its own.

fn read_all(values: Vec<Unknown<'_>>) -> Result<Vec<vitaminc_protected::Buffer>> {
values
.into_iter()
.map(|value| JsRef::new(value).to_frame())

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: a bigint outside 128 bits is refused here, with no field name.

2n ** 128n in a uint128 field, or -(2n ** 127n) - 1n in an int128 field, never reaches conform. vitaminc's reader throws, and the result is { kind: 'value', code: 'ERR_INTEGER_RANGE', message: 'BigInt is outside the signed/unsigned 128-bit range' }, with no field. One bit inside that range, the same mistake gives recipher::out_of_range with field set. The value is not leaked, so this is only about consistency. You could check bigint ranges per field in TypeScript before the call, or map the reader's error onto the field it was reading, if JsRef can report the path.

.iter()
.find(|(index, _)| *index == key)
.map(|(_, output)| *output)
.ok_or_else(|| misfit("an output the record does not declare"))?;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: several refusals in stored_tree and RecordPlan::field do not name the field.

  • misfit(..) never sets field. "a field the record does not declare", "an output that is not bytes" and "an output the record does not declare" all come back with field: undefined. The same goes for the Ciphertext::from_bytes refusal at line 680.
  • RecordPlan::field (line 200) refuses an unknown name with field: None. The message names the record but not the field that was asked for.
  • This lookup checks the key against all four index names, not against the field's own indexes. So { email: { ciphertext, equality, match } } is accepted and opens, even though email declares no match index. That is harmless, because terms are not read to decrypt. But the message "the record does not declare" suggests a per-field check that is not there. Either check field.indexes or reword the message.

record(..), encrypt(..) and passthrough() declare a record as plain data.
The crate builds the engine's plan from it with the engine's own types,
once for each declaration, and encrypts and decrypts rows, and one field
or an array of one field, through dynamic::Planned. A refusal names the
record and the field. A decrypted row's inspect hides its values. The
binding interface is 3.
@coderdan
coderdan force-pushed the feat/recipher-js-records branch from 6937e90 to a0479fc Compare November 24, 2026 01:56

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant