Skip to content

feat(recipher-js): every value type, arrays and JSON documents - #1775

Draft
coderdan wants to merge 1 commit into
feat/recipher-js-skeletonfrom
feat/recipher-js-values
Draft

coderdan wants to merge 1 commit into
feat/recipher-js-skeletonfrom
feat/recipher-js-values

Conversation

@coderdan

@coderdan coderdan commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Step 2 of phase 1 of the TypeScript SDK plan (#1747), on top of #1774. @cipherstash/recipher now encrypts every value in vitaminc's JavaScript mapping, an array of values in one key request, and a JSON document made with json(..). A value's type picks how it is encrypted; no call names a kind. A ciphertext read back from stored bytes can be typed by naming a kind, kinds.json among them, so a stored JSON document opens as the document and not as its text.

The package is still private and takes no changeset.

Changes

Values. keyset.encrypt(value) takes a string, boolean, number (a float), bigint (an integer at the narrowest width that holds it), Uint8Array or Buffer, Date, VcTimestamp, VcDate, VcDecimal, null, or a Json, and returns a Ciphertext<T> typed by what it opens as. vitaminc's four wrapper classes are exported by the addon (Wrappers::exports) and re-exported by the package. Each value is sealed through the engine's opaque scalar path, so each ciphertext is exactly what Rust's keyset.encrypt and Go write.

Arrays. keyset.encrypt([a, b, c]) returns an array of ciphertexts, and decrypt of an array an array, in order, through the engine's collection path (Vec<_>::encrypt_into, Vec<ValueFrame>::decrypt_from): one key request each way. All or nothing: one refused element is an Err for the array, before any request.

JSON documents. json(document) is a native function returning a native Json class. It reads the document when it is called (a later change to the object does not change what is encrypted), and holds either the engine's JsonPlaintext or the reason it cannot be one; it never throws. The conversion between a frame and a document is in crate/src/json.rs:

  • an integer outside a number's safe range is a bigint, within the 64-bit range the engine's parser reads;
  • a whole number between 2^53 and 2^64 from zero is refused (an integer was likely meant); any other finite number, such as 1e20 or Number.MAX_VALUE, is written as a float, so a document another SDK wrote with one encrypts again;
  • a document nested deeper than 127 levels is refused as recipher::too_deep, the engine parser's limit, before the engine sees it;
  • a map key is held in Zeroizing until it is in the object, so a member refused half-built leaves no unwiped copy.

Reading stored bytes as a kind. Ciphertext.fromBytes(bytes, kinds.string) is typed Ciphertext<string>, and decrypting it refuses a value sealed as another type (recipher::opened_type, kind open); an integer kind takes an integer of any width that fits it, through the engine's dynamic::read. kinds.json opens the text as a JSON document. With no kind, the ciphertext opens as whatever was sealed. kinds (the engine's names, { name } plain data) arrives in this step for that reason; records reuse it in #1776.

Refusals, each an Err with a code of its own: recipher::plain_object (wrap it in json(..)), recipher::not_plain (a Map, a Set, a class instance), recipher::not_bytes (a typed array other than Uint8Array), recipher::uuid, recipher::undefined, recipher::reserved_key (__proto__, constructor, prototype: value on encrypt, open on decrypt), vitaminc's ERR_INTEGER_RANGE and the other five ERR_* codes.

Missing build. Without the addon, the wrapper classes and json are stand-ins that construct normally (frozen, holding their text), and encrypt resolves to the load error. Nothing throws at import.

The binding interface number is now 2, in Rust and in TypeScript.

What the tests prove

Rust (crate/src/engine_tests.rs, crate/src/json.rs, crate/src/ciphertext.rs, crate/src/value.rs):

  • The engine seals, the SDK opens, for every type: a String, an i64, u64::MAX, bytes, a nanosecond Timestamp and a Decimal sealed by the engine's typed API open through the crate as those values, byte for byte.
  • The SDK seals, the engine opens: text, an i8 (opened by the engine as an i64) and a float.
  • JSON both ways: a JsonPlaintext holding u64::MAX sealed by the engine opens through the crate as a document, with the big integer as an integer and the safe one as a float; a document the crate seals opens through the engine's typed decrypt::<JsonPlaintext>.
  • One key request each way for an array of three (a counting key source), none for an empty array.
  • Depth 127 is a document and 128 is recipher::too_deep; 1e20, f64::MAX and -6.02e23 are written as floats and read back the same by the engine's parser; a document another SDK wrote with 1e20 encrypts again.

TypeScript (__tests__/addon/values.test.ts): every row of the mapping round-trips through stored bytes; arrays; JSON documents, including kinds.json read-back of 18446744073709551615n, depth 127/128 (the 128 refusal is kind value, not open), large floats re-encrypted, the reserved keys both ways, and the document read at json(..) time; typed fromBytes (an int8 opened as int64, text refused as int64); and each refusal's code, with no plaintext in any message. A suite runs the built package with no addon and checks the stand-ins. type-tests/values.ts pins the types, including fromBytes typed by a kind.

Verification

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

  • cargo fmt --all --check: passed.
  • cargo clippy --locked --all-targets --all-features -- -D warnings: passed. Default features: passed.
  • cargo test --locked --all-features: 29 passed (25 unit, 4 boundary).
  • pnpm run build:debug, then git status: the tree was clean.
  • pnpm run test:addon: 52 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. CI results are in the checks.

Deviations from the plan

  • opaque(..) is not here. See "Needs from the engine".
  • A VcUuid is refused, now with recipher::uuid and a message that names a UUID. The engine's value model refuses one.
  • A JSON document read back with no kind opens as its JSON text. The bytes do not say a value is JSON. kinds.json reads it as a document; the README and the fromBytes docs say not to JSON.parse the text.
  • The JSON number rule is narrower than the plan's. The plan refuses every number that is an unsafe integer. This refuses only whole numbers between 2^53 and 2^64; larger ones (1e20) are floats, so a document another SDK wrote with one encrypts again. A Rust-written float between 2^53 and 2^64 (such as 1e19) still opens as a number and is then refused if encrypted again.
  • kinds arrives in this step, for fromBytes; the plan introduces it with records.
  • Not done in this step: the value profile of the conformance suite (record-values-v1, a record profile; there is no TypeScript conformance runner yet, stack-encrypt conformance: add TypeScript runner and public SDK mapping tests #1479), running vitaminc's value-conformance.cjs against this addon (written against vitaminc's test addon's exports), and the fuzz target.

Needs from the engine

  • opaque(..) (the engine's OpaqueBlob format) for a value whose type is known only at run time. OpaqueBlob<T> writes vitaminc's storage profile through serde::Serialize, so it needs a Rust type; a binding holds a frame, and the engine has no entry point from a frame to the storage-profile bytes and back.
  • A UUID in the value model. ValueFrame refuses vitaminc's Uuid logical type, so no binding can encrypt one through dynamic.

Changed since the first review

The whole step is rebuilt on #1774's new shape: one crate, the engine's types, and the classes defined in Rust. Plaintext, Encoding, the TypeScript Json class and the wrapper-class lookup are gone; json(..) and Json are native, and a Ciphertext carries the kind it opens as. Line counts (old 44064c7f8, new a94a1a7fc): Rust source 1,367 lines in two crates (1,223 without test modules) became 2,206 in one (1,719 without test modules); TypeScript src/ 1,124 became 1,104.

Review findings:

  • JSON depth 128 failed on encrypt as open / stack_encrypt::aead: fixed twice over. The crate refuses past 127 levels as recipher::too_deep, kind value; and any engine Aead error on the seal path is now recipher::not_sealed, kind value, since no ciphertext exists yet. Tested at 127 and 128 in Rust and in TypeScript.
  • A JSON ciphertext read back untyped opens as text and loses big integers; README misdescribed it: fixed with Ciphertext.fromBytes(bytes, kinds.json), tested with 18446744073709551615n; the README row and the doc comments are corrected.
  • Floats of 2^53 and more refused in a document: fixed for 2^64 and more (written as floats; the decrypt-then-encrypt case is tested in both languages). Whole numbers between 2^53 and 2^64 are still refused, deliberately; see "Deviations".
  • Prototype-named JSON keys gave generic or internal errors: fixed as far as the SDK can: recipher::reserved_key, kind value on encrypt and kind open on decrypt, and the README lists the three keys. The rule itself is vitaminc's, in both directions; carrying such a key in a document needs a change in vitaminc, not here.
  • Binding interface not bumped: fixed, it is 2 here (and 3 in feat(recipher-js): records through the engine's Planned #1776).
  • VcUuid refusal never says UUID: fixed, recipher::uuid, asserted.
  • Test gaps: fixed: the engine-seals/SDK-opens direction is tested for each type the review listed, and the "vitaminc's code" test asserts ERR_INTEGER_RANGE.
  • Wrapper classes throw when the addon is missing, and the addon loads on import: the throw is fixed (stand-ins construct normally; tested against the built package with no addon). Loading on import is kept and documented: the package exports the native classes themselves.
  • Un-wiped copied map key on a refusal: fixed (Zeroizing until it is inserted).
  • Docs did not mention the 64-bit bigint limit: fixed.
  • A top-level Uint16Array was refused with "wrap it in json(..)": fixed, it is recipher::not_bytes at the top and inside an array.

Related

Refs #1747 (the plan). Based on #1774; #1776 is based on this branch.

@changeset-bot

changeset-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: a94a1a7

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.

Summary. The scalar mapping is vitaminc's from end to end. The addon reads each value with JsRef::to_frame and builds each result with JsBuilder. Every value is sealed by the engine through one Vec<_>::encrypt_into, and the counting key source really checks one generate and one retrieve for three values. I found no lossy scalar conversion. -0, NaN, Infinity, the i128 bounds, year 0001, and a JS 42n (sealed as i8) all round-trip, and Rust's decrypt::<i64> and decrypt::<Timestamp> open what the SDK seals. The problems are in the JSON path, in some error kinds, and in one interface check. Nothing is blocking.

Blocking

None.

Should fix

  1. A JSON document nested 128 levels deep fails on encrypt with kind open, code stack_encrypt::aead, and a message saying the ciphertext is damaged or was altered (crates/core/src/json.rs:70).
  2. A stored JSON document read back with fromBytes opens as its JSON text. The obvious next step, JSON.parse, silently loses the digits the bigint rule protects (src/cipher.ts:48, README.md:52).
  3. Every float of 2^53 or more is refused in a JSON document, because such a float has no fraction. A document Rust wrote with 1e20 opens in JS, and encrypting it again is refused (crates/core/src/json.rs:146).
  4. A JSON document with a constructor, prototype or __proto__ key cannot be encrypted, and one written by another SDK opens as an internal error (crates/core/src/json.rs:79).
  5. The native encrypt and decrypt changed shape, but BINDING_INTERFACE is still 1, so a stale step-1 recipher.node is accepted (src/native.ts:25).
  6. A VcUuid is refused with a message that does not mention a UUID (src/cipher.ts:291).
  7. Tests. The engine-seals, SDK-opens direction is tested only for a string (crates/core/tests/round_trip.rs). Add cases where the engine seals an i64, u64::MAX, a Timestamp, a Decimal, bytes and a JsonPlaintext holding u64::MAX, and the SDK opens each one. Without them, the claim that both sides read each other holds for text only. Separately, the "with vitaminc's code" test does not check the code (__tests__/addon/values.test.ts:217).

Question / design

  1. When the addon is missing, constructing a wrapper class throws. The classes are also built at import time, so the addon now loads when the package is imported (src/values.ts:85).

Nit

  1. A JSON map key copied in Rust is not wiped when its value is refused (crates/core/src/json.rs:285).
  2. The docs say a bigint in a document "is written as its digits". They do not say that one outside the 64-bit range is refused (src/values.ts:119).
  3. A top-level typed array other than Uint8Array, such as a Uint16Array, is refused as recipher::plain_object with "wrap it in json(..)". json(..) refuses it too. Only the message is wrong (src/cipher.ts, refuse).

What I ran. I built the debug addon (build:debug) and ran test:addon: 35 passed. I also ran throwaway probes, deleted afterwards. In Rust (cargo test --all-features), the SDK sealed an i8 and a millisecond timestamp, and the engine opened them as i64 and Timestamp. I checked JSON depths 126 to 129, re-encrypted an engine-sealed {"x": 1e20}, and round-tripped NaN, Infinity and -0. In vitest I checked each refusal's kind and code, json(..) with large floats, sparse arrays, lone surrogates and the prototype keys, Dates at the range ends, and fromBytes of a JSON ciphertext. CI is green.

}

/// The document a frame holds, as the engine's [`JsonPlaintext`].
pub(crate) fn document(frame: &ValueFrame) -> Result<JsonPlaintext, Refusal> {

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 document that is too deep fails on encrypt as open / stack_encrypt::aead.

vitaminc lets a frame nest 128 levels. The engine's JSON parser reads 127. So keyset.encrypt(json(deep)) with 128 nested arrays passes document(). Then JsonPlaintext's visit refuses it as Error::Aead, and Refusal::engine maps that to kind open. What comes back is:

{ kind: 'open', code: 'stack_encrypt::aead',
  message: 'AEAD operation failed (wrong key, AAD mismatch, or malformed ciphertext). ... the ciphertext is damaged or was altered.' }

That is wrong on an encrypt. A caller switching on kind would treat it as tampering. I reproduced this from vitest and from Rust: depths 126 and 127 seal, 128 fails as above, and 129 is refused by vitaminc.

Fix: check the depth here, at most 127 as the engine's parser reads, and refuse with recipher::not_json ("nested deeper than 127 levels"). You could also make encrypt_with map an engine Aead to Kind::Value, since no ciphertext exists yet. Add a test at 127 and 128.

* decrypting is what authenticates them.
*
* A JSON document is sealed as its JSON text, so one read back here
* opens as that text.

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: the untyped fromBytes gap is a trap for JSON.

The real path is store, then read back, so in practice every json(..) value goes through fromBytes and opens as a string. The natural next step loses data silently. I ran:

const sealed = (await k.encrypt(json({ id: 18446744073709551615n }))).unwrap()
const opened = (await c.decrypt(Ciphertext.fromBytes(sealed.toBytes()).unwrap())).unwrap()
// opened === '{"id":18446744073709551615}'
JSON.parse(opened) // { id: 18446744073709552000 }

This is the precision loss the bigint rule exists to prevent. The type is honest (OpenedScalar includes string), but nothing pushes the caller to the right reader, because none exists yet.

Fix: add a way to read stored bytes as a JSON document in this PR, for example Ciphertext.fromBytes(bytes, { json: true }), to become kinds.json in step 3. Or keep json(..) back until typed fromBytes lands. At the very least, say in this doc comment and the README not to JSON.parse the text.

| `new VcDate('2026-11-23')` | a calendar date | `VcDate` |
| `new VcDecimal('1.50')` | a decimal, with its scale | `VcDecimal` |
| `null` | null | `null` |
| `json(value)` | a JSON document, as its JSON text | the document |

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.

"Decrypts as: the document" is true only for a Ciphertext that never left memory. Read back with Ciphertext.fromBytes, which is how stored data is read, it decrypts as the JSON text, and JSON.parse of that text loses bigint digits. See the comment on src/cipher.ts:48. Please make this row say so, or fix the gap.

return Ok(Value::Number(Number::from(value as i64)));
}
return Err(NotJson::Kind(
"an integer outside the safe range held as a number; use a bigint",

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: every large float is refused, and decrypt then encrypt fails.

Every f64 of magnitude 2^53 or more has no fraction. So this branch refuses every large float, not only integers that lost digits. json({ x: 1e21 }), json({ x: Number.MAX_VALUE }) and json(JSON.parse('{"x":6.02e23}')) are all recipher::not_json.

Worse, the read and write rules disagree. A document Rust or Go wrote as {"x": 1e20} opens in JS as { x: 1e20 }, a number (number_of returns F64). Encrypting that same value again is refused. I checked this in Rust: the engine sealed JsonPlaintext::from(json!({"x": 1e20})), the SDK opened it with Encoding::Json, and re-sealing it gave Err(Value, "recipher::not_json", "...an integer outside the safe range held as a number; use a bigint").

Fix: write an integer-valued float outside the safe range as a float. Number::from_f64(1e20) writes 1e20, and the engine's parser reads it back as the same float. Or narrow the refusal to the range where an integer was plausibly meant (for example, up to 2^64). Then add a test that decrypts a document and encrypts it again.


/// The value of an opened document's text, as a frame, by the rules in the
/// module docs.
pub(crate) fn opened(frame: &ValueFrame) -> Result<ValueFrame, Refusal> {

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: JSON keys constructor, prototype and __proto__.

vitaminc refuses these three property names in both directions. For a record that is a fine rule. In a JSON document they are ordinary keys (JSON.parse('{"constructor":1}') gives an own property). What happens now:

  • keyset.encrypt(json(JSON.parse('{"constructor":1}'))) gives { kind: 'value', code: 'InvalidArg', message: 'the value could not be read for encryption' }. The code is a napi status, not a stable one, and the message does not say why.
  • A document another SDK wrote with such a key gives { kind: 'internal', code: 'recipher::build_value' } on decrypt. internal means "not the caller's to fix", but the data is authentic and simply cannot be built in JS.

I reproduced both. For the decrypt case I sealed the text as a string and opened it with the JSON encoding, which is the same leaf the engine seals.

Fix: decide with vitaminc how a JSON document carries these keys. Until then, report kind open on decrypt and value on encrypt, with a code that names the key rule, and list the three keys in the README.

value instanceof VcDate ||
value instanceof VcTimestamp ||
value instanceof VcDecimal ||
value instanceof VcUuid

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: the UUID refusal does not say "UUID".

A VcUuid passes this check and is refused later, by the engine's value model. The result is:

{ kind: 'value', code: 'recipher::value',
  message: 'the value cannot be encrypted: expected a null, bool, integer, float, string, bytes, date, timestamp or decimal in range' }

A caller who reads the README will look for a UUID message and not find one. Since the SDK exports the class and knows it cannot be sealed, refuse it here with its own code, for example recipher::uuid and "a UUID cannot be encrypted yet: the engine's value model does not hold one". Assert that code in the values.test.ts UUID test, which checks only the kind today.

expect(result.err()?.kind).toBe('value')
})

it("an integer vitaminc cannot hold, with vitaminc's code", async () => {

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.

The test name promises vitaminc's code, but the test asserts only kind and the message. Today the code is ERR_INTEGER_RANGE (I checked), so add expect(result.err()?.code).toBe('ERR_INTEGER_RANGE'). Without it, a regression to a generic code would still pass.

const message = binding.error.message
const Missing = class {
constructor(_text: string) {
throw new TypeError(`${name} needs the native build: ${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.

Question / design: a missing addon throws here.

The plan says nothing escapes as an exception, and that a build that does not load is an Err. With this stand-in, new VcDate('2026-11-23') throws a TypeError when the addon is missing. It is the only SDK call that does. An alternative: a frozen stand-in that keeps its text and constructs normally. Then the failure arrives at keyset.encrypt(..), which already returns recipher::load without a build. Is the throw deliberate?

Related: wrapperClass calls native() at module load (line 78), so the addon is now loaded when the package is imported. native.ts still says it is "loaded once, on first use". Either make it lazy, or update that comment.

fn entry(&mut self, key: &str) -> Result<ToJson<Member<'_>>, NotJson> {
Ok(ToJson(Member {
object: &mut self.members,
key: key.to_owned(),

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: hygiene. This key copy is wiped only when it reaches the map. If the member's value is refused (bytes, a date, an unsafe float), ToJson<Member> is dropped with the key in it, and the key is freed without being wiped. The same happens when the member holds an array or object that is dropped unfinished: the Member sits in out and is dropped without a wipe. Holding the key in Zeroizing<String> until put would fix both.

/**
* A JSON value. An integer outside the safe range of a `number` is a
* `bigint`; on encrypt, a `number` that is an integer outside it is
* refused, and a `bigint` is written as its digits.

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 is written as its digits" does not mention the limit. A bigint outside the 64-bit range (below i64::MIN or above u64::MAX) is refused, because the engine's parser reads no wider. Please say so here and in the README.

keyset.encrypt takes every value in vitaminc's JavaScript mapping, an
array of them in one key request, and a JSON document made with json(..),
a native class that reads the document when it is made. Ciphertext
carries the kind it opens as, and Ciphertext.fromBytes(bytes, kind) reads
stored bytes as a kind, kinds.json among them. vitaminc's refusals each
get a code of their own. The binding interface is 2.
@coderdan
coderdan force-pushed the feat/recipher-js-values branch from 44064c7 to a94a1a7 Compare November 24, 2026 01:52
@coderdan
coderdan added this pull request to stack #1789 November 24, 2026 05:17

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