Skip to content

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

Open
coderdan wants to merge 17 commits into
nextfrom
feat/recipher-js-records
Open

coderdan wants to merge 17 commits into
nextfrom
feat/recipher-js-records

Conversation

@coderdan

@coderdan coderdan commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #1813
Closes #1803

This PR adds records to @cipherstash/recipher. A record is a declaration like a table's: a name, and for each field whether it is encrypted, encrypted with search indexes, or passed through unencrypted. A program declares a record once, then encrypts and decrypts whole rows, 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.

An index is a search term stored beside a field's ciphertext. Querying with those terms comes later.

It follows #1774's design: every native method builds its Result in Rust, and the record signatures are written on the Rust methods, so the generated native.d.ts is the public type.

The package is private and not published, so there is no changeset.

Changes

Declaring. record(name, fields), encrypt(kinds.x, { index, null }) and passthrough<T>() make plain, frozen data: { type: 'record', name, fields }. The addon recognises a declaration by its type: 'record' property, so a declaration from the CommonJS build works with a cipher from the ESM build.

The plan. crate/src/record.rs reads a declaration through vitaminc's frame serde and builds the engine's plan with the engine's own types (FieldPlan, Plan, Output, IndexSpec, NullMode, ValueKind). The only table of the SDK's own maps the index names (equality, match, ore, ope) to IndexSpec. Each field is encrypted under its field path: the record's name, then the field's name. A plan is built once per declaration and kept. RecordPlan derives Debug, because it holds only declaration data.

The calls. The first argument is the thing to encrypt, or the stored thing to decrypt. The second argument is always an options object, the strict one #1775 added for { kind }:

export const UserRecord = record('users', {
  id: passthrough<bigint>(),
  email: encrypt(kinds.string, { index: ['equality'] }),
  age: encrypt(kinds.int32, { index: ['equality'], null: 'sealed' }),
})

const user = { id: 1n, email: '[email protected]', age: 36n }

// One row, or an array of rows in one key request.
const stored = await keyset.encrypt(user, { record: UserRecord })
const opened = await cipher.decrypt(stored.unwrap(), { record: UserRecord })

// One field of a row.
const email = await keyset.encrypt('[email protected]', { record: UserRecord, field: 'email' })

// One value, as #1775 has it.
const age = await keyset.encrypt(34n, { kind: kinds.uint64 })

Rows. keyset.encrypt(row | rows, { record }), cipher.decrypt(stored | stored[], { record }), and keyset.decrypt. The engine's dynamic::read reads each value as its field's kind before the engine sees it.

One field. keyset.encrypt(value | values, { record, field }) and cipher.decrypt(storedField | storedField[], { record, field }) run the plan of that field alone, under the same field path. A field encrypted alone has the same bytes as in a whole row. There is no encryptField or decryptField.

The options. crate/src/options.rs reads the options and decides what the call is from its keys alone. A Rust test covers every combination of keys for both calls. These are compile errors, through the overloads, and at run time an Err with the code recipher_js::options and a help that says what to pass:

  • kind and record together;
  • field without record;
  • a kind given to decrypt;
  • a record declaration given as the first argument, the old order;
  • any key other than kind, record, and field. A later context key has room beside either.

A plain object with no record is a compile error too. At run time it is recipher_js::plain_object, whose help now names { record: UserRecord } as well as json(..). decrypt now refuses a second argument that is not options, as encrypt does.

Checking declarations. checkDeclarations(records) checks declarations with no credentials, and returns a Result. Cipher.create({ records }) checks them before it looks for credentials.

Signatures. The Rust methods carry the TypeScript signatures as ts_type, ts_args_type, and ts_return_type strings. That covers the record overloads of encrypt and decrypt, Cipher.create(options?: CipherOptions), and checkDeclarations. Each returns its Result from Rust.

The record overloads take RecordOptions<R> or FieldOptions<R, F>. Both mark kind as never. EncryptOptions<K> marks record and field as never. The row argument is NoInfer<Plaintext<R>>, so TypeScript takes R from record only. The return types follow the declaration: Stored<typeof UserRecord>, Plaintext<typeof UserRecord>, and a field's own type.

Record types, as the value types are. The types those signatures name (RecordDeclaration, Plaintext, Stored, SealedFieldName, RecordOptions, FieldOptions, CipherOptions and the field types) are in an import-free src/record-types.ts, which native-header.d.ts imports. src/record.ts holds the declaration builders and checkDeclarations, which loads the addon from there, with a stand-in that returns the load error when the addon did not load. The package's exports are unchanged. AGENTS.md states the rule: one *-types.ts module per topic, imported by the header, never loading the addon, because a module that did would make the declarations import themselves.

Type errors name Json and Value. Value is now declared in native-header.d.ts as Scalar | Json, beside the generated Json class, instead of as Scalar | JsonMarker in src/value-types.ts. Passing a plain object to encrypt now gives an error that names Value and Json, never JsonMarker. The marker is still the brand, so a plain object is still not a Json or a Value.

Keyset confinement. A decrypted row goes through open_rows_in, beside #1774's open_in. Both run one confined! match, so whether a decrypt is confined to the default keyset is decided in one place for ciphertexts and rows. A Rust test checks that a keyset refuses another keyset's row with stack_encrypt::foreign_keyset, and that the cipher opens it.

AGENTS.md. The recipher-js entry now lists the record declarations in src/record.ts.

Errors. A refusal names the record in error.record and, where there is one, the field in error.field. New codes include recipher_js::not_a_record, declaration, reserved_field, record_name, no_field, not_a_row, field_type, not_a_stored_row and engine_result.

A decrypted row hides its values when inspected. console.log(row) prints users { email: [hidden], .. }. The crate turns on napi's napi9 feature for Symbol.for.

The binding interface number goes to 3. The arguments of both encrypt and decrypt changed shape.

Verification

Run locally on macOS (arm64), Rust 1.94.1, Node 24, pnpm 10.33.2, at this PR's head:

  • cargo fmt --all --check: clean.
  • cargo test --locked --all-features across the recipher-js workspace: recipher-js 56 unit tests and 2 boundary tests passed, the options tests among them. The recipher-value-napi tests passed.
  • cargo clippy --locked --all-targets --all-features -- -D warnings: clean.
  • build:debug: native.d.ts regenerated and committed; the build leaves no other change.
  • test:addon: 129 passed. Unit vitest: 31 passed. tsc --noEmit with the type tests: clean.
  • Biome on the package: clean.

Not run: anything against a live ZeroKMS, and the conformance profiles (there is no TypeScript conformance runner yet, #1479). CI results are in the checks.

Review notes

  • Type tests for the options. type-tests/records.ts has an @ts-expect-error line for each combination that must not compile, and a copy of the README's Records example. __tests__/addon/records.test.ts runs the same example and each refusal.

  • New type tests. type-tests/values.ts adds @ts-expect-error lines: keyset.encrypt({ a: 1 }), and a plain object as a Json and as a Value. It also checks that json(..) returns both. __tests__/unit/type-messages.test.ts compiles a snippet with the TypeScript compiler and checks that the messages name Value and Json and never JsonMarker.

  • 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.

  • Opening a field as another field fails at the key service, so the engine reports a key-retrieval failure, not a context mismatch. A check of the stored context before any key request would let the SDK say so.

  • The engine's TargetResolver is not passed yet. The crate runs Planned::new, which uses NoTargets.

Related

@changeset-bot

changeset-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 2ce9f4b

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

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI; Enforced overrides: Organization
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 087a80b3-827d-40fd-a50d-e5196078b4de

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review

@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 "[email protected]". 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.

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.

Fixed in the rewrite (ce0079f). Every refusal of a declaration now names the record (crate/src/record.rs:278-282 and :357-363).

A record name that is not a plain segment is recipher_js::record_name, with no field. The names bind and context_field are refused before the addon builds the engine's plan. The code is recipher_js::reserved_field, with field set (record.rs:72-73 and :283-285). Tests: __tests__/addon/records.test.ts:303-322.

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.

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.

Fixed in the rewrite (ce0079f). The test now declares the fields a and b with the same shape: a string with equality. The test opens the stored form of b as a, and asserts the code. The test also opens a row under a record of another name, and asserts the code and the record (__tests__/addon/records.test.ts:165-187).

The code is stack_kms::retrieve_key_failed in both cases. Whether the SDK should give this case a code of its own is still open: see the comment on the review.


/// 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.

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.

Fixed in the rewrite (ce0079f). The plan is built with the engine's types Output, IndexSpec, and NullMode (crate/src/record.rs:55-59 and :303-318). The code for stored rows matches on Output::parse, Output::Ciphertext, Output::Term, and Output::Passthrough.key() (record.rs:497-608). The null mode is read through NullMode::name().

Only the SDK's own names are written out. The index names equality, match, ore, and ope are at record.rs:76-97. The ciphertext key of a stored field is at record.rs:70.

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.

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.

Fixed in the rewrite (ce0079f). The refusal now names the field: 2n ** 128n in age gives ERR_INTEGER_RANGE with field: 'age' (__tests__/addon/records.test.ts:254-261). When the bridge refuses a row, read_row reads each field again to find the one at fault (crate/src/cipher.rs:609-623). From the code, a getter on a field of a refused row therefore runs a second time.

.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.

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.

Fixed in the rewrite (ce0079f). The messages were reworded in ea69a41.

  • Each refusal in stored_tree names its field, except the one for a stored row that is not an object (crate/src/record.rs:541-604). The Ciphertext::from_bytes refusal names the field too (record.rs:583-588).
  • RecordPlan::field names the field that was asked for (record.rs:263-268).
  • An index term is checked against the field's own indexes (record.rs:595-604). Test: __tests__/addon/records.test.ts:332-342.

@coderdan

Copy link
Copy Markdown
Contributor Author

Rewritten to fold in #1791, #1805, #1807, #1808. Previous head: a0479fc.

Encrypting one value at a time does not fit how applications store data:
in rows, with some fields encrypted and searchable and some not.

record(..), encrypt(..) and passthrough() declare a record as plain,
frozen data, recognised by its type property, so a declaration from the
CommonJS build works with a cipher from the ESM build. The addon builds
the engine's plan from a declaration with the engine's own types, once
for each declaration, and encrypts and decrypts whole rows, one field, or
an array of one field through dynamic::Planned, so the stored bytes are
the engine's and many rows make one key request. Each field is sealed
under its field path, the record's name and then the field's name.

A decrypted row goes through open_rows_in, beside the skeleton's
open_in: both run the one confined! match, so whether a decrypt is
confined to the default keyset is decided in one place for ciphertexts
and rows alike, and a test pins it for rows.

A refusal names the record and, where there is one, the field, with a
recipher_js:: code. A decrypted row's inspect shows its field names and
hides their values. RecordPlan derives Debug: it holds only declaration
data.

The record overloads of encrypt and decrypt, encryptField, decryptField,
Cipher.create(options) and checkDeclarations are written on the Rust
methods as ts_type strings, so native.d.ts stays the public type, and
each returns its Result from Rust. src/record.ts never loads the addon,
because the generated declarations import its types; checkDeclarations
therefore lives with the other native entry points in src/cipher.ts,
with a stand-in for an addon that did not load.

Nothing is released, so the binding interface stays 1.

Closes #1813
Closes #1803
@coderdan
coderdan force-pushed the feat/recipher-js-values branch from a5555b7 to fc5c851 Compare November 25, 2026 12:40
@coderdan
coderdan force-pushed the feat/recipher-js-records branch from 68dd83e to ce0079f Compare November 25, 2026 12:40
Value was Scalar | JsonMarker in src/value-types.ts, so passing a plain
object to encrypt gave an error that named JsonMarker, a brand the
package never exports, rather than the Json a caller should reach for.

Value is now declared in native-header.d.ts as Scalar | Json, beside the
generated Json class, which the header can name without an import, and
src/values.ts re-exports it. The marker stays the brand, so a plain
object is still not a Json or a Value, and value-types.ts still imports
nothing, so the declarations do not import themselves.

A type test pins both: the @ts-expect-error lines in type-tests/values.ts
keep it as strict, and a unit test compiles a snippet with the TypeScript
compiler and checks the messages name Value and Json and never
JsonMarker.
…types are

The header imported the record types from src/record.ts, so that module
could not load the addon, and checkDeclarations had moved to
src/cipher.ts, away from the declarations it checks. The values had
solved the same problem another way, with an import-free value-types.ts.

Records now follow the values: the types the generated signatures name
(RecordDeclaration, Plaintext, Stored, SealedFieldName, CipherOptions and
the field types) are in an import-free src/record-types.ts, which the
header imports. checkDeclarations is back in src/record.ts, beside the
declarations it checks, and loads the addon from there, with the same
stand-in that returns the load error when the addon did not load. The
package's exports are unchanged.

AGENTS.md states the rule: one *-types.ts module per topic, imported by
the header, never loading the addon.
@coderdan

Copy link
Copy Markdown
Contributor Author

This replies to review 6030323967.

Status of the automated review of 23 November, at ea69a41. Errors no longer have a kind, so a caller switches on the code.

Findings 1 to 5, 8, and 9 are fixed. Each inline comment has the details. Two more are fixed:

    1. A decrypted row hides its values. The addon adds a util.inspect hook that is not enumerable, and prints each field as [hidden] (crate/src/js.rs:255-292). Test: __tests__/addon/records.test.ts:228-241.
    1. The Rust test now checks the opened value (crate/src/record_tests.rs:163-198).

Finding 7 is not resolved. A field opened under another field's path still gives stack_kms::retrieve_key_failed. So does a row opened under another record's name. A test pins that code (__tests__/addon/records.test.ts:179 and :185).

By the code alone, a caller cannot tell this case from a failure of the key service. Whether the SDK maps the case to a code of its own needs your decision. Nobody has checked whether the key service's error says which case it is.

…and interface 2

This merge brings two fixes from the values branch. The docs and the error
message now say that this version of the SDK does not encrypt a UUID yet.
The text no longer says that the engine has no UUID type. The binding interface
number is now 2, so the TypeScript refuses an older addon build when it
loads.

One file conflicted. In `type-tests/values.ts`, this branch adds checks for
plain objects before the UUID check. The resolution keeps those checks and
takes the new comment on the UUID check.
coderdan added a commit that referenced this pull request Nov 29, 2026
The second review of #2019 found the plan out of step with the code.

- The wrapper classes are RcDate, RcTimestamp, RcDecimal, and RcUuid in
  #1775, #1776, and #1996. The plan used vitaminc's Vc names. The plan
  now uses the Rc names, and says once that #1775 renamed them.
- The JSON number rules are now one table, with a row for each range of
  whole numbers. Each range includes both ends. The table shows the new
  refusal below -2^63. That refusal says the integer has no exact form.
  The plan also says that NaN and the infinities are refused.
- The round trip of 2^64 - 1 is tested on the native build only. The
  plan now names that test, and says the wasm build is planned.
- The UUID cell no longer repeats the refusal before #1996.
- The header now gives the status. Step 1 is built. The next steps are
  in open pull requests.
This brings in two commits from #1775. The first gives the bigint range
in the json() docs. The second refuses a whole number below -2^63 and
above -2^64 with its own message, instead of asking for a bigint. The
merge had no conflicts.
coderdan added a commit that referenced this pull request Nov 29, 2026
This brings in the fix from #1775 through #1776. A whole number below
-2^63 and above -2^64 is now refused with its own message, instead of a
message that asks for a bigint. The merge had no conflicts, and the
UUID changes on this branch are unchanged.
The values branch now has next, encrypts one value through the engine's
dynamic::value::encrypt, and takes a declared kind as encrypt's second
argument. On this branch encrypt's second argument is already the row of
a record. The merge keeps both: when the first argument is a record
declaration, the second is its row, or its array of rows. Otherwise the
second is the options of the value, { kind }. A plain object with a
second argument is still refused with recipher_js::not_a_record.

The value module is gone, since nothing on this branch used OneValue
outside the single-value path. native.d.ts is the build:debug output.
…mode

A record field whose null mode is neither "sealed" nor "sql" was refused
with recipher_js::null. A lone null value passed to encrypt is refused
with recipher_js::null_value. The two codes read as if they were about
the same thing. The field's error is now recipher_js::null_mode, which
names the setting that is wrong, and a test checks the code and that the
error names the record and the field.
encrypt keeps its second argument as an Unknown, so null as the options is refused. A record's rows and the not-a-record check read it as before.
@coderdan
coderdan marked this pull request as ready for review November 29, 2026 07:54
@coderdan
coderdan requested a review from a team as a code owner November 29, 2026 07:54
This merge brings in `nullable(kind)` and the wrapper classes' `from(text)`.

Records already type a field by its null mode. A field with
`null: 'sealed'` or `null: 'sql'` decrypts as `T | null`, and a field with
no null mode decrypts as `T`. That is the rule `nullable(..)` now gives one
value, so the types needed no change.

A field's kind cannot be `nullable(..)`, because the null mode says whether
a field takes a null. `encrypt(nullable(kinds.int64))` does not compile.
When the code runs, the declaration is refused with the new code
`recipher_js::nullable_field`. The error names the field. Before this change,
the addon read the kind's name and dropped `nullable`, so the field took no
null and nothing said why.

The records tests make wrappers with `from(text)`. `native.d.ts` is
regenerated.
Base automatically changed from feat/recipher-js-values to next November 29, 2026 08:29
const opened = await cipher.decrypt(user, stored.unwrap())
```

- `keyset.encrypt(user, row)` returns a stored row.

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.

Row is a database specific term - refer to this as a record

@coderdan

coderdan commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor Author

Decided: the record API takes the plaintext first, and the declaration in the options object. This replaces keyset.encrypt(user, row), cipher.decrypt(user, stored), and encryptField(user, 'email', value).

export const UserRecord = record('users', {
  id: passthrough<bigint>(),
  email: encrypt(kinds.string, { index: ['equality'] }),
  age: encrypt(kinds.int32, { index: ['equality'], null: 'sealed' }),
})

const user = { id: 1n, email: '[email protected]', age: 36n }

// One row, or an array of rows in one key request.
const stored = await keyset.encrypt(user, { record: UserRecord })
const opened = await cipher.decrypt(stored, { record: UserRecord })

// One field of a row.
const email = await keyset.encrypt('[email protected]', { record: UserRecord, field: 'email' })

// One value, as #1775 has it.
const age = await keyset.encrypt(34n, { kind: kinds.uint64 })

The rules:

  1. The first argument is the thing being encrypted, or the stored thing being decrypted.
  2. The second argument is always an options object. kind is for one value. record, and optionally field, are for a row or one of its fields. A context will be added later as context, beside either, so no call takes a third argument.
  3. The types enforce the combinations. kind and record together do not compile. field without record does not compile either. A plain object with no record does not compile. At run time each of these is an Err, with a help that says what to pass.
  4. Names. A declaration is named for what it is (UserRecord), and a row gets the plain name (user). The README's example defines everything it uses, so it runs as written.

The record calls now take the thing to encrypt first, or the stored
thing to decrypt, and an options object second:

- keyset.encrypt(user, { record: UserRecord }) for a row or an array of
  rows, in one key request;
- cipher.decrypt(stored, { record: UserRecord }) to decrypt them;
- keyset.encrypt(value, { record: UserRecord, field: 'email' }) and
  cipher.decrypt(storedField, { record, field }) for one field.

encryptField and decryptField are removed.

The options are the strict object that `{ kind }` already used. A new
options module decides what the call is from the keys alone. Rust tests
cover every combination of keys. Four calls are the error
recipher_js::options, with a help that says what to pass:

- kind and record together;
- field without record;
- a kind given to decrypt;
- a record declaration given as the first argument.

A plain object with no record is still recipher_js::plain_object. Its
help now names `{ record: UserRecord }`. decrypt now refuses a second
argument that is not options, as encrypt does.

The overloads stop the same calls compiling. RecordOptions and
FieldOptions mark kind as never. EncryptOptions marks record and field
as never.

The README's Records example now defines everything it uses and runs
as written. The binding interface goes to 3.
@coderdan

Copy link
Copy Markdown
Contributor Author

2ce9f4b implements the record API decision in #1776 (comment). keyset.encrypt(user, { record: UserRecord }), cipher.decrypt(stored, { record: UserRecord }), and { record, field } for one field replace the old calls. encryptField and decryptField are gone.

The combinations the decision rules out do not compile. At run time each is recipher_js::options with a help that says what to pass. A plain object with no record stays recipher_js::plain_object. The README's Records example now runs as written. #1996 merges this in 961617e.

coderdan added a commit that referenced this pull request Nov 29, 2026
#1776 changed the record API. Every encrypt now takes the value first
and an options object second: { kind } for one value, { record } for a
row, and { record, field } for one field. encryptField and decryptField
are gone. The plan's examples and its mentions of those calls now match,
and the record example defines the row it encrypts.
const user = { id: 1n, email: '[email protected]', age: 36n }

// One row, or an array of rows in one key request.
const stored = (await keyset.encrypt(user, { record: UserRecord })).unwrap()

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.

What is the type of stored? It'd be good to show what the returned encrypted value looks like in this example.

//! the engine's frame encoding. A map frame contains a map. A sink receives a
//! value from a frame one part at a time: one scalar, array, or map.
//!
//! The addon passes a record's row between JavaScript and the engine as one

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.

Don't use the term "add-on." It's the language adapter.

/// The version of the interface between the package's TypeScript and this
/// addon build.
pub const BINDING_INTERFACE: u32 = 2;
pub const BINDING_INTERFACE: u32 = 3;

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 should be 1.

use crate::outcome::Outcome;

/// The key of a field's ciphertext in a stored row.
const CIPHERTEXT: &str = "ciphertext";

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.

There is no such field - what is this referring to? EQL has the c field but this code has nothing to do with EQL.

@coderdan

Copy link
Copy Markdown
Contributor Author

The rework of this pull request needs two additions to Stack Encrypt, so that the binding does not work around them:

@coderdan

Copy link
Copy Markdown
Contributor Author

This pull request waits for two changes to Stack Encrypt. The rework starts when both have merged:

The rework then follows the record design in the plan on #2019. record() writes Stack Encrypt's plan, and the binding reads it with dynamic::record::plan and calls dynamic. The binding keeps none of its own declaration format, value conversion, or renaming. #1996 and #2026 wait for this pull request.

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

1 participant