Skip to content

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

Merged
coderdan merged 27 commits into
nextfrom
feat/recipher-js-values
Nov 29, 2026
Merged

coderdan merged 27 commits into
nextfrom
feat/recipher-js-values

Conversation

@coderdan

@coderdan coderdan commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #1812

This PR lets @cipherstash/recipher encrypt every value type in the value bridge's mapping, arrays of values, and JSON documents. A value's type decides how it is encrypted; no call names a type. A ciphertext read back from stored bytes can be given a kind (a value type, such as kinds.string), so a stored JSON document decrypts as the document and not as its text.

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

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

Changes

Values. keyset.encrypt(value) takes one of these, and resolves to a Result of a Ciphertext<T>, where T is the type it decrypts to:

  • a string, a boolean, or a number (a float);
  • a bigint, stored as an integer at the narrowest width that fits it;
  • a Uint8Array or a Buffer, or a Date;
  • an RcTimestamp, an RcDate, or an RcDecimal;
  • a Json.

A lone null is refused: see "Null is opt-in" below. The addon exports the bridge's wrapper classes, and the package re-exports them.

Wrapper classes are made with from(text).

  • RcDate.from('1815-12-10') returns a Result<RcDate, RecipherError>. So do RcTimestamp.from, RcDecimal.from, and RcUuid.from.
  • Each checks the text in Rust with the rule that encrypt uses, so an instance that exists is valid. Bad text, or a value that is not a string, is an Err with the value bridge's code, such as ERR_INVALID_DATE.
  • The addon installs the factory that from calls when the package loads it (Wrappers::install_from, Wrappers::from_text).
  • The classes have no constructor in their types. The constructor takes a token that only the classes' script contains. So new RcDate('x') throws a TypeError that names RcDate.from(text), as new Cipher() throws.
  • A decrypted value is still an instance of the same classes.

Arrays. An array in gives an array out, in the same order, through the engine's collection path: one key request each way. If one element is refused, the whole array is an Err, before any request.

JSON documents. json(document) is a native function that returns a native Json. It reads the document when it is called, and never throws. The conversion 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 is refused, because an integer was likely meant; any other finite number, such as 1e20, is a float;
  • a document nested deeper than 127 levels is refused as recipher_js::too_deep;
  • a map key is kept in Zeroizing until it is in the object, so a refused member leaves no unwiped copy.

Reading stored bytes as a kind.

  • Ciphertext.fromBytes(bytes, kinds.string) is typed Ciphertext<string>. Decrypting it refuses a value encrypted as another type (recipher_js::opened_type).
  • An integer kind takes an integer of any width that fits. kinds.json decrypts the text as a document.
  • Ciphertext.fromBytes(bytes) with no kind is a Ciphertext<OpenedScalar>: it can decrypt to any scalar, or null.

Null is opt-in, with nullable(kind), as Rust's Option<T>. A kind from kinds takes no null.

  • Ciphertext.fromBytes(bytes, kinds.int64) is a Ciphertext<bigint>. Decrypting a stored null with it is an Err with the code recipher_js::opened_null, as Rust's decrypt::<i64> refuses one.
  • nullable(kinds.int64) reads a stored null as null. It works with a kind of any width.
  • nullable(kind) is { name, nullable: true }, frozen like each of kinds. The addon refuses any other key, and any nullable that is not true, with recipher_js::not_a_kind.
  • When encrypting, null with nullable(..) of a fixed-width kind goes to the engine as a typed null of the kind. The engine refuses it until stack-encrypt: single-value encrypt refuses every null — seal a typed fixed-width null as records do #2023 lands, so it is an Err today.
  • null with no kind, with a plain kind, or with nullable(..) of a variable-width kind does not compile. When the code runs, it is recipher_js::null_value.
  • A value that is not null encrypts with nullable(kind) as it does with kind.
  • ReadAs<K> and Declared<K> follow nullable.

Signatures. The new overloads are ts_type strings on the Rust methods, one per line: encrypt and decrypt on an array (crate/src/cipher.rs), and fromBytes<K extends Kind>(bytes, kind) (crate/src/ciphertext.rs). json takes a JsonValue. native-header.d.ts imports the types they name, makes Ciphertext's default OpenedScalar, and marks Json so no other object type-checks as one.

Where the value types live. The types the signatures name (Value, Opened, OpenedScalar, JsonValue, the wrapper interfaces) are in src/value-types.ts, which imports nothing. native.d.ts imports them, and a module that loaded the addon would make the declarations import themselves, which the declaration bundler cannot build. src/values.ts keeps the runtime part: the wrapper classes and json, with stand-ins.

Errors. Each new refusal is a variant of the SDK's error enum, with its own code. The codes are recipher_js::undefined, uuid, not_a_scalar, plain_object, null_value, not_json, too_deep, not_sealed, not_a_kind, opened_type, opened_null, and not_a_document. The skeleton's recipher_js::not_a_string is gone. The bridge's refusals keep the bridge's codes. recipher_js::reserved_key reaches the caller on decrypt too, through the bridge's Refusal.

Decrypting through open_in. The array and kind decrypt path runs through #1774's open_in, so keyset confinement stays in one place.

AGENTS.md. The recipher-js entry now names the Json class, and says that src/kinds.ts and src/value-types.ts hold the types the generated signatures name and must never load the addon.

Missing build. Without the addon, the wrapper classes and json are stand-ins. A stand-in's from returns the load error, and its new throws as the class's does. Every other call resolves to the load error.

The binding interface number stays 1: nothing is released.

Verification

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

  • cargo fmt --all --check: clean.
  • cargo test --locked --all-features: recipher-js 38 unit tests and 2 boundary tests passed. recipher-value-napi 54 unit tests passed, and so did tests/node.rs, which runs the Node suites and the README example.
  • cargo clippy --locked --all-targets --all-features -- -D warnings: clean.
  • The value bridge's test addon: cargo fmt --check and cargo clippy --locked --target-dir target/napi-test-addon -- -D warnings by its manifest: clean.
  • build:debug: native.d.ts regenerated and committed; the build leaves no other change.
  • test:addon: 96 passed. The unit suites: 30 passed. tsc with the type tests: clean.
  • Biome over the package: clean.
  • The repository's script tests (pnpm run test:scripts): 1651 passed, 29 skipped.

Each behaviour change has a test that fails without it. For example, two Rust tests fail if a plain kind reads a stored null as null again. The Node suite fails if from skips its check, or if the constructor takes no token.

The Rust tests check that the engine and the SDK each decrypt what the other encrypted, for every type, and that an array is one key request each way. Not run: anything against a live ZeroKMS. CI results are in the checks.

Review notes

  • One type test changed: type-tests/native.ts checked that Ciphertext with no type named is Ciphertext<string>. It is now Ciphertext<OpenedScalar>, because a ciphertext read from stored bytes with no kind can decrypt to any scalar. The test also checks that Json and json are the generated ones.
  • The value profile and the fuzz target are not here. Step 2 of the plan lists both. The value profile covers the record kinds, so it needs records (feat(recipher-js): records through the engine's Planned #1776). The fuzz target compares the wasm build's frame with the napi bridge's, so it needs the wasm build. recipher-value-napi lost its mutation, CRAP and dependency checks in the move from vitaminc, and Biome skips it — restore them and add fuzzing #1797 tracks the bridge's fuzz targets.
  • opaque(..) is not here. The engine has no entry point from a frame to its storage-profile bytes.
  • An RcUuid is refused with recipher_js::uuid on this branch. feat(recipher-js): encrypt a VcUuid as the engine's UUID #1996 adds the UUID kind.
  • new on a wrapper class throws. The types have no constructor, so the call does not compile. From JavaScript or past a cast, it throws a TypeError that names from, as new Cipher() throws. The README lists this as the second kind of call that throws, after a method called without its object.
  • A kind in encrypt's options that is not a kind is now recipher_js::not_a_kind, not recipher_js::options. The options' shape is still recipher_js::options.
  • A JSON document read back with no kind decrypts as its JSON text. The bytes do not say a value is JSON. kinds.json reads it as a document.
  • The JSON number rule is narrower than the plan's. Only whole numbers between 2^53 and 2^64 are refused, so a document another SDK wrote with 1e20 encrypts again.
  • recipher_js::reserved_key has the same code on encrypt and decrypt. Only the call that failed says which.
  • OneValue in crate/src/value.rs is widened here to a scalar or a JSON document. The engine's own single-value frame will replace it later.

Related

@changeset-bot

changeset-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: b284a8e

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: 3da2ebe1-2c47-489a-ae20-52cc2e691e30

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.

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.

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 (fc5c851). The bridge checks the depth when json(..) reads the document, at most 127 levels (crate/src/json.rs:33-39). A deeper document is recipher_js::too_deep, not an engine Aead error. seal also maps an engine Aead error on encrypt to recipher_js::not_sealed (crate/src/cipher.rs:399-404), because no ciphertext exists yet.

Tests: 127 and 128 levels at __tests__/addon/values.test.ts:538-552, and the parser's limit at crate/src/json.rs:206-210. Errors no longer have a kind, so a caller switches on the code.

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

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 (fc5c851). Ciphertext.fromBytes(bytes, kinds.json) reads stored bytes as a JSON document (src/kinds.ts:52, crate/src/ciphertext.rs:80-86). The fromBytes doc (crate/src/ciphertext.rs:96-103) and README.md:150-155 say that with no kind a document decrypts as its text. Both also say that JSON.parse of that text loses digits.

Test: __tests__/addon/values.test.ts:388-404 reads stored bytes with kinds.json, and gets 18446744073709551615n back.

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

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. The row at README.md:67 now says a document decrypts as the document from the Ciphertext that encrypt returned, or from one read with kinds.json. README.md:150-155 covers bytes read back from storage.

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.

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.

Mostly fixed, with one gap. The refusal is narrowed to a whole number from 2^53 up to 2^64 (value-napi/src/scalar.rs:139-152). A larger whole number is stored as a float. So 1e20, Number.MAX_VALUE, and 6.02e23 encrypt, decrypt, and encrypt again (__tests__/addon/values.test.ts:555-569).

The gap is a float from 2^53 up to 2^64 that another SDK wrote, such as 1e18. The engine reads 1e18 as a float, so it decrypts as a number. Encrypting that number again is refused. This gap comes from reading the code, and has not been run. No test or doc covers it.

The choice is between documenting the gap with a test, and writing such a number as a float, as the review first suggested.


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

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.

Partly. Both directions now give recipher_js::reserved_key (value-napi/src/error.rs:25, crate/src/js.rs:149-156). The code names the rule.

README.md:88 and README.md:146-149 list the three names, and say a document from another SDK with one of them does not decrypt here. Test: __tests__/addon/values.test.ts:571-588, both ways. Errors no longer have a kind.

Still open: the SDK still cannot encrypt or decrypt a document that contains one of these keys. Nobody has decided how the SDK should handle such a document.

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.

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 (fc5c851). An RcUuid gets its own code, recipher_js::uuid, with help to encrypt it as a string (crate/src/js.rs:55-57, crate/src/error.rs:46). The test asserts the code, and that the message says UUID (__tests__/addon/values.test.ts:644-651). The pull request #1996 later removes the refusal, when the SDK can encrypt a UUID.

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.

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. The test now asserts the code, ERR_INTEGER_RANGE, and that the message does not contain the value (__tests__/addon/values.test.ts:653-659).

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.

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. A stand-in wrapper class now constructs from a string, as the real class does (src/values.ts:73-97, last changed in dab69c5). Both throw a TypeError only for an argument that is not a string, and README.md:199-202 says so. With no addon, the failure then comes from encrypt, as recipher_js::load. __tests__/addon/builds.test.ts:75-76 tests this case.

The addon now loads when the package is imported, and the docs say so: src/binding.ts:19 and :133, and README.md:288.

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.

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.

No longer applies. The addon's JSON walk is gone (e0cc1c6), and the key copy went with it. The bridge now writes the JSON text straight into a Buffer that wipes each allocation it outgrows (value-napi/src/json.rs:18-21). Each key the bridge reads is a Zeroizing<String> (value-napi/src/js.rs:66-69).

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

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. The docs give the range, from -(2n ** 63n) to 2n ** 64n - 1n, and say a bigint outside the range is refused. The range is in crate/src/json.rs:137-138, src/values.ts:165-168, README.md:125-126, and README.md:135. napi copies the Rust doc to native.d.ts:266-267. The test is at __tests__/addon/values.test.ts:424.

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.

Finished in 89a3b27. The earlier reply said src/values.ts gives the range, but that doc said only "within 64 bits". The doc now gives the range, from -(2n ** 63n) to 2n ** 64n - 1n, and says a bigint outside it is refused. The Rust doc and the README already said this.

@coderdan

Copy link
Copy Markdown
Contributor Author

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

The skeleton encrypts one string. An application needs every value
JavaScript has, arrays of them, and JSON documents.

keyset.encrypt now takes every value in the value bridge's mapping: a
string, a boolean, a number, a bigint at the narrowest width that holds
it, bytes, a Date, the wrapper classes for a date, a fine timestamp and a
decimal, and null. An array in gives an array out, in one key request each
way, and one refused element fails the whole array before any request.
json(..) is a native function that reads a document when it is called
and holds the engine's JsonPlaintext, so a document is encrypted as the
engine encrypts one.

A Ciphertext records the kind it decrypts as, and
Ciphertext.fromBytes(bytes, kind) reads stored bytes as a kind, so a JSON
document read back with kinds.json decrypts to the document, not to its
text. Each refusal is a variant of the SDK's error enum with a
recipher_js:: code of its own, and the bridge's refusals keep the
bridge's codes.

Every new signature is written on the Rust method, as the skeleton's are:
the array overloads of encrypt and decrypt, and the kind overload of
fromBytes, are ts_type strings, one overload per line, so the generated
native.d.ts stays the public type. The value types those signatures name
live in src/value-types.ts, which imports nothing: the declarations
import it, and a module that loaded the addon would make them import
themselves. A Json is the native class, marked in the header so no other
object type-checks as one. A ciphertext with no type named now allows any
scalar, since one read from stored bytes with no kind can decrypt to any.

Nothing is released, so the binding interface stays 1.

Closes #1812
@coderdan
coderdan force-pushed the feat/recipher-js-values branch from a5555b7 to fc5c851 Compare November 25, 2026 12:40
if value.get_type().ok() == Some(ValueType::Undefined) {
return Err(Error::Undefined.into());
}
let uuid = is_uuid(env, &value);

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.

Why is there a special case for UUID?

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.

Not removed in this PR yet. The check is at crate/src/js.rs:55-57, and the pull request #1996 deletes it.

The engine accepts a UUID now, but this PR does not. The uuid kind (#1929) reached this branch when next was merged in (85c1fc8). This PR has no kinds.uuid and no UUID round-trip test. The TypeScript types in this PR say an RcUuid is not a Scalar. Without the check, encrypt would store a value that those types refuse.

The pull request #1996 adds the kind, the types, and the tests. The same pull request removes the check.

Four places are out of date. Each says the engine has no UUID type: README.md:79-81, src/values.ts:134-140, src/value-types.ts:36-40, and the test name at __tests__/addon/values.test.ts:644. Each should say that this PR does not take a UUID yet.

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 out-of-date text is fixed in 78c2c78. The docs, the type comments and the error message now say that this version of the SDK does not encrypt a UUID yet, instead of saying the engine has no UUID type. The check itself stays until #1996, which removes it.

.map_err(|error| refused(env, &error))?;
ValueFrame::from_bytes(frame.as_protected_ref()).map_err(|_| Error::Value.into())
ValueFrame::from_bytes(frame.as_protected_ref())
.map_err(|_| RecipherErrorFields::from(if uuid { Error::Uuid } else { Error::Value }))

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.

That's a nasty hack.

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.

Partly fixed. The flag that chose the error code after a failed read is gone (merge 85c1fc8). An RcUuid is now refused by a direct check before the walk, at crate/src/js.rs:55-57.

The check is still a special case, and the pull request #1996 removes it. The reply to the question about the UUID special case says why the check is still here.

.to_frame()
.map_err(|error| refused(env, &error))?;
ValueFrame::from_bytes(frame.as_protected_ref()).map_err(|_| Error::Value.into())
ValueFrame::from_bytes(frame.as_protected_ref())

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 code in this method seems to be doing multiple conversions from a JS ref to a frame and then to a value frame. There are several layers of indirection here.

I would have thought that the napi crate did all of this already directly from the unknown type into our value types.

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.

Partly. The value is converted once. One extra layer is already gone. One more goes with #2011. Two more could go.

The path today, for keyset.encrypt(value) at 1cf2f55:

  1. napi passes the argument as Unknown (crate/src/cipher.rs:174-178). The argument has no fixed type because it can be one value, an array of values, or a Json.
  2. js::elements (crate/src/js.rs:99-135) checks for an array, and reads each element as an own property.
  3. one_value (crate/src/cipher.rs:379-384) sends a Json to the JSON path, and any other value to js::read.
  4. JsRef::to_frame (crate/src/js.rs:58-60) is the one conversion. The bridge walks the JavaScript value, and writes the frame's bytes into a buffer that is wiped when it drops.
  5. OwnedFrame::from_buffer (crate/src/js.rs:62) moves that buffer into the engine's type without a copy. The call parses the bytes once to check them.
  6. OneValue::scalar (crate/src/value.rs:53-59) refuses an array or an object, and wraps the frame. The engine's opaque encrypt takes only a Scalar type, and a frame is not one.
  7. seal (crate/src/cipher.rs:389-405) encrypts on napi's runtime, off the JavaScript thread.

On fc5c851, step 5 built a second type, ValueFrame, from the bridge's bytes. Merge 85c1fc8 replaced that type with OwnedFrame::from_buffer.

Why there is a frame at all: the addon runs the engine's future with napi's spawn_future_with_callback. spawn_future_with_callback needs a Send + 'static future (crate/src/cipher.rs:10-12). An Unknown belongs to the JavaScript thread. So the value is copied out of JavaScript before the key request. The frame is that copy.

The frame is also the engine's own type for a value whose type is known only at run time. So no second conversion is needed.

What napi does: napi gives the type checks and the scalar reads. The bridge uses them: get_type, is_array, is_date, is_typedarray, f64, bool, BigInt, and Uint8ArraySlice (value-napi/src/js_ref.rs:178-282). The napi version in Cargo.lock is 3.16.2.

What napi cannot do: napi has no conversion into the engine's value model. The one conversion of a whole value that napi has is to serde_json::Value (napi-3.16.2/src/bindgen_runtime/js_values/serde.rs:151). That conversion breaks the SDK's rules in five ways:

  • A whole number in the u32 or i32 range becomes an integer, and any other number a float (serde.rs:375-391). In the SDK, a number is always a 64-bit float.
  • A bigint that does not fit 64 bits becomes a string, with no error (serde.rs:202-217).
  • A Date, a Buffer, a Uint8Array, and the Rc* classes are read as plain objects (serde.rs:170-197).
  • An array element is read with napi_get_element (serde.rs:186). So a value on a polluted Array.prototype fills a hole.
  • To decrypt, napi sets each member with napi_set_property (serde.rs:110). That call runs a setter on a polluted Object.prototype. A member named __proto__ sets the prototype.

napi's typed reads are not safe either. napi reads an i64 with napi_get_value_int64 (number.rs:70), and that call drops a fraction. So the bridge reads every number as an f64.

What still looks unnecessary:

Decrypt converts once too. The engine decrypts into an OwnedFrame, and JsBuilder::build builds the JavaScript value (crate/src/js.rs:145-147).

Comment on lines +120 to +130
/// 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.

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.

Included an example here. I can't reason about how this would be used.

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.

Partly. json(..) has an example now, in the Rust doc (crate/src/json.rs:117-124) and in README.md:104-112. napi copies the Rust doc to native.d.ts:245-253.

That example shows a bigint round trip. The example does not show the case this comment was on. The case is a large whole number given as a number, and json(..) refuses that number.

Proposed text, for the README's JSON section, the Rust doc, and the TypeScript doc of json (src/values.ts:156-177):

A whole number from 2^53 up to 2^64 may not have the digits you wrote, so json(..) refuses it. Give the integer as a bigint:

// JSON.parse reads 9007199254740993 as 9007199254740992.
const parsed = JSON.parse('{"id": 9007199254740993}')
const refused = await keyset.encrypt(json(parsed))
refused.err()?.code // 'recipher_js::not_json'

const sealed = (await keyset.encrypt(json({ id: 9007199254740993n }))).unwrap()
const opened = (await cipher.decrypt(sealed)).unwrap()
// { id: 9007199254740993n }

Each line matches the code and the tests: value-napi/src/scalar.rs:139-152, and __tests__/addon/values.test.ts:363-386 and :406-414. The example itself has not been run.

Rewrite the comments, doc comments and Markdown that the values work
added, so that each passes the plain-language checker. No code changes.

- One idea in each sentence, and lists for parallel cases.
- Each term is defined where a doc first uses it: engine, value bridge,
  walk, frame, kind, wrapper class, safe range.
- Things have literal verbs: a document "contains" a value.
- The value bridge's README is rewritten in full, with headings for the
  safety rules.
- `native.d.ts` is regenerated, because the build copies the doc
  comments of the `#[napi]` items into it.
- The addon's crate docs no longer link to the private `js` module, so
  `cargo doc` with warnings denied passes.
A TypeScript developer reads these messages without knowing the engine.
The messages said "seal", "open", "hold", and "takes". The README says
"encrypt", "decrypt", "contain", and "accept", so the messages now use
those words. Each message says what was wrong with the value that was
passed, and the help says what to do.

No error code, error field, or refusal changes. Only the text changes,
with the tests and docs that quote it.

- The addon's errors say "encrypt" and "decrypt". `not_a_scalar` and
  `plain_object` say that the value cannot be encrypted as one value,
  and the help says what `json(..)` does.
- `not_a_kind` now states the fault in the message. The rule that was
  the message is now the help.
- `opened_type` names the kind that the caller gave, in backticks. No
  message names the kind that a value decrypted as.
- A refused JSON value reads "a JSON document cannot contain ...". The
  messages for a large `number` and for a typed value end with a
  sentence that says what to pass.
- A wrapper class's constructor throws "RcDate accepts only a string".
  The addon's class and the stand-in throw the same text.
@coderdan

Copy link
Copy Markdown
Contributor Author

This replies to review 6058012745.

Status of the review on too many layers, at 1cf2f55. Point 3 is done. Point 4 waits on #2011. Points 1 and 2 are not done, and the stand-ins need your decision.

  1. Wrapper classes in five places: not done. The bridge still defines the classes (value-napi/src/wrappers.js). The addon exports them (crate/src/lib.rs:90-106), and src/value-types.ts:12-46 declares them by hand. src/values.ts:103-110 still reads them with Reflect.get, and src/values.ts:73-97 makes the stand-ins. The aliases are now one line each (1e200d6).

    The draft spike(recipher-js): the value bridge declares its own TypeScript types #1829 prototypes your step 1. The draft is not merged here, and still uses the Vc* names.

  2. Kinds table: not done. src/kinds.ts:33-53 still copies the engine's names, and pairs each with its TypeScript type. This PR also added a Rust list of the kinds that fromBytes accepts (crate/src/ciphertext.rs:183-197, bb51af7). An addon test keeps that list the same as kinds. The list is still a third copy. The draft spike(recipher-js): the value bridge declares its own TypeScript types #1829 proposes the mapping from kind to type in the bridge.

  3. JSON conversion: done, in another shape. The number rules are in the bridge (value-napi/src/scalar.rs:139-176), with JsRef::to_json and JsBuilder::build_json (c001978). To encrypt, the addon gives the bridge's text to the engine's JsonPlaintext::parse (crate/src/json.rs:166-171). To decrypt, the addon calls the engine's dynamic::read_json (crate/src/json.rs:180-182).

    The file crate/src/json.rs is now 245 lines. Of those lines, 62 are tests (e0cc1c6).

  4. OneValue: waits on feat(stack-encrypt)!: encrypt and decrypt one value known only at run time, and bound the typed decrypt to a scalar #2011. OneValue is still at crate/src/value.rs:37. The pull request feat(stack-encrypt)!: encrypt and decrypt one value known only at run time, and bound the typed decrypt to a scalar #2011 deletes it, and seal calls the engine's dynamic::value::encrypt for each value. This branch gets that change when it merges next after feat(stack-encrypt)!: encrypt and decrypt one value known only at run time, and bound the typed decrypt to a scalar #2011. The pull request feat(stack-encrypt): add dynamic::ScalarFrame to seal one runtime-typed value with keyset.encrypt #1827 (ScalarFrame) is still open too.

Stand-ins: your decision. The stand-ins are all still here: src/values.ts:73-97 and :182-186, and src/cipher.ts:86-116. The wrapper stand-in now constructs as the real class does (dab69c5).

Scope: besides the array overloads, the kind on fromBytes, and the new errors, the PR still contains the JSON work and the class rename. Nothing has been split out.

@coderdan

Copy link
Copy Markdown
Contributor Author

This replies to review 6030302742.

Status of the automated review of 23 November, at 1cf2f55. Errors no longer have a kind, so the list below gives each refusal's code. The inline comments have the details.

These findings are fixed:

    1. A document that is too deep is recipher_js::too_deep.
    1. Stored bytes read back with kinds.json decrypt to the document.
    1. An RcUuid gets recipher_js::uuid.
    1. crate/src/engine_tests.rs:68-104 opens what the engine sealed for an i64, u64::MAX, bytes, a Timestamp, and a Decimal. crate/src/engine_tests.rs:107-120 does the same for a JsonPlaintext that contains u64::MAX. The test of the bridge's code now asserts the code.
    1. A stand-in wrapper class constructs from a string.
    1. The key copy is gone with the addon's JSON walk.
    1. The bigint range is documented.
    1. A Uint16Array is recipher_js::not_bytes, at the top and in an array (__tests__/addon/values.test.ts:677-685).

These findings are partly fixed:

    1. Large floats: the refusal is narrowed to a whole number from 2^53 up to 2^64. A float in that range from another SDK still decrypts, and then cannot be encrypted again.
    1. Reserved keys: one code, recipher_js::reserved_key, in both directions, and documented. Nobody has decided how the SDK should handle a document that contains these keys.
    1. Binding interface: the export check refuses a step-1 build. BINDING_INTERFACE is still 1.

…efused

The engine accepts a UUID now. This version of the SDK still refuses an
`RcUuid`, because it has no kind and no TypeScript type for a UUID yet.
The README, two doc comments, a test, and the error message said that the
engine has no UUID type. Those places now say that this version of the SDK does
not encrypt a UUID yet. The test now checks the new message.

`encrypt` and `decrypt` changed shape since the first addon build, but the
binding interface number was still 1. So the TypeScript would load an older
addon build and fail later, on a call. The number is now 2 in the crate and
in `src/binding.ts`. The comments on both say what the number is for, and
when to change it.
The TypeScript doc of `json` said a `bigint` is stored "within 64 bits".
The range is from -(2n ** 63n) to 2n ** 64n - 1n, which no single 64-bit
type holds, and the doc did not say a `bigint` outside it is refused.
The Rust doc and the README already give the range. This makes the
TypeScript doc match them.
@coderdan

Copy link
Copy Markdown
Contributor Author

This replies to the two findings in the body of review 6094305185. An earlier comment listed both as not done.

…gint

json() refused a whole number from 2^53 up to 2^64 with a message that
says to pass a bigint. Below -2^63 that advice is wrong. A bigint that
size is outside the 64-bit range, so json() refuses it too. The integer
has no exact form in a JSON document.

A whole number below -2^63 and above -2^64 now has its own refusal,
NoJsonForm::NoExactForm, under the same recipher_js::not_json code. The
refusal says the integer has no exact form. The message does not ask
for a bigint. From -2^53 down to -2^63 the message still asks for one,
since a bigint of that size is accepted. The json() docs, the README
files, and the type docs now state both rules.

The tests cover these values:

- the first number below -2^63, -1e19, and the last number above -2^64;
- -2^63, as a number and as a bigint;
- -2^64, as a float.
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.
@coderdan

Copy link
Copy Markdown
Contributor Author

I pushed 5c78ecf to this branch. json() now refuses a whole number below -2^63 and above -2^64 with its own message. The message says the integer has no exact form in a JSON document, and no longer asks for a bigint.

Why: before this commit, json([-1e19]) was refused with UnsafeInteger, whose message ends "Pass a bigint instead." The bigint -10000000000000000000n is also refused, with BigIntRange, because it is below -2^63. So the message sent the caller to a form that is refused too. The review of #2019 found this, and Dan decided the fix.

Changes:

  • value-napi/src/error.rs: a new NoJsonForm::NoExactForm, under the same recipher_js::not_json code as UnsafeInteger and BigIntRange. The message gives the range and no part of the value.
  • value-napi/src/scalar.rs: json_number returns NoExactForm for a whole number below -2^63 whose size is below 2^64. From -2^53 down to -2^63, the refusal is still UnsafeInteger, because a bigint of that size is accepted. A whole number of 2^64 or more is still a float, on either side of zero.
  • These now state both rules: the docs of json in crate/src/json.rs and native.d.ts, src/values.ts, src/value-types.ts, both README files, and the table in value-napi/src/js_ref.rs. native.d.ts is the same as the file that build:debug generates.

Tests:

  • Rust (scalar.rs): three numbers each return NoExactForm. They are -2^63 - 2048, -1e19, and the last number above -2^64. The first one is the first number below -2^63, because -2^63 - 1 rounds to -2^63. The tests also show that -2^63 as a number is still UnsafeInteger, -2^64 is a float, and -2^63 as a bigint is an integer. The new test fails with the fix removed.
  • Node (value-napi/tests/json.cjs) and the addon (__tests__/addon/values.test.ts): the same three numbers are refused with recipher_js::not_json. The message contains "no exact form" and not "Pass a bigint". The addon test also round-trips -(2n ** 63n), and -2^64 and -1e20 are stored as floats.

Checks run: cargo fmt --check, cargo clippy --all-targets --all-features -D warnings, and cargo test --all-features (both crates and the Node suites, under Node 24). Also build:debug, test:addon (75 tests), the unit vitest (31 tests), tsc, Biome on the package, and the three scripts/__tests__/recipher-js* tests (16 tests). Not run: the repo-wide pnpm test.

#1776 and #1996 are stacked on this branch, so they need this commit merged in.

coderdan added a commit that referenced this pull request Nov 29, 2026
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.
next removed the addon's OneValue and sent its string-only encrypt
through the engine's dynamic::value::encrypt. This branch encrypts every
value type, so its cipher.rs, engine_tests.rs, value.rs and Cargo.toml
keep this branch's side here, and OneValue stays for now. The next
commit removes OneValue and uses dynamic::value on this branch too.
…declared kind

next removed the addon's OneValue wrapper. The engine's
dynamic::value::encrypt now encrypts the one scalar in a frame. This
commit removes this branch's OneValue too, and sends every single-value
encrypt through dynamic::value::encrypt. A json(..) value goes in as its
JSON text, with the declared kind json. The engine parses the text into
the JsonPlaintext it encrypts, so the stored form does not change.

keyset.encrypt takes a second argument, { kind }, with a kind from
kinds. The addon passes the kind to the engine. The engine converts a
value to the kind when the conversion is exact, as a record write does.
The ciphertext then decrypts as that kind: 34 declared as uint64 decrypts
as 34n. For an array of values, the kind applies to each value.

The kind is an options object, not a positional argument, so that a
context can be added later under its own name. Neither can then be
passed in the other's place. The options refuse any key but kind, with
recipher_js::options, so an option that this version does not have is
never ignored.

What changes for a JavaScript caller:

- A lone null is now refused, with the new code recipher_js::null. The
  error's help says to store a database NULL, or to declare the kind of a
  fixed-width type. The engine refuses a null, because a ciphertext
  contains one value.
- A null declared as a fixed-width kind is refused today as well. Issue
  #2023 changes the engine to encrypt it as a padded typed null. A Rust
  test and a JavaScript test check today's refusal, and name #2023.
- The TypeScript types accept null only with a fixed-width kind. A null
  with no options still type-checks, and fails when the call runs.
- json(..) declared as another kind, or kinds.json declared for a value
  that is not a json(..), is refused with recipher_js::json_kind.
- A second argument that is not { kind } is refused. Before, a second
  argument was ignored.
- recipher_js::not_sealed is gone. The engine reports a JSON text it
  cannot parse with its own code. The bridge writes no such text.
- The codes for an array inside an array (recipher_js::not_a_scalar)
  and a plain object (recipher_js::plain_object) are the same. The
  addon now maps them from the engine's refusal.
…l_value

feat/recipher-js-records already uses recipher_js::null for a null mode
that the engine does not have. The two errors are about different things,
so a lone null now has its own code, recipher_js::null_value.

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

Review of commits 2dbc9fd and 6b52b68 (the single-value path through dynamic::value, and { kind }). Line numbers are at 6b52b68, under languages/typescript/packages/recipher-js/. There is no blocking correctness bug. One finding is important.

  1. Important. An integer kind accepts a number that has already lost digits. src/kinds.ts:63-69 lets any number through for an integer kind, and crate/src/cipher.rs:420 passes it to the engine. So encrypt(9007199254740993, { kind: kinds.int64 }) stores and decrypts as 9007199254740992n, and encrypt(12345678901234567890, { kind: kinds.uint64 }) as 12345678901234567168n. The result looks exact but is not. The json(..) path refuses the same case with recipher_js::not_json. Refuse a whole number outside ±(2^53 − 1) for an integer kind, before the engine, and add a test.
  2. Minor. null as the options is ignored. crate/src/ciphertext.rs:165,190: napi maps null to None, so keyset.encrypt(34, null) encrypts with no kind. The README (lines 119-120) says options other than { kind } are refused. The refusal test (__tests__/addon/values.test.ts:736) has no null case.
  3. Minor. The recipher_js::undefined help says to use null (crate/src/error.rs:40, pinned at :434 and :586). A lone null is now refused with recipher_js::null_value.
  4. Minor. The recipher_js::null_value help suggests a call that fails today (crate/src/error.rs:77-78). It says to "declare its kind, as in { kind: kinds.int64 }". That same call is refused until #2023, with this help. The help is also shown for null with kinds.string, where a kind never helps.
  5. Minor, types. Declared<K> does not distribute over a union of kinds (src/kinds.ts:63-69). With kinds.int64 | kinds.json, encrypt({ a: 1 }, { kind: k }) type-checks and fails at run time. With kinds.int64 | kinds.string, a valid 34 is rejected. Write it as K extends Kind ? … : never.
  6. Minor, types. encrypt(null) type-checks and always fails (src/value-types.ts:48-59,110). A lone untyped null stays refused after #2023 too, so the input type should leave null out. encrypt(null, { kind: kinds.int64 }) fails until #2023 by design, but the Declared and OpenedAs comments in src/kinds.ts do not say so.
  7. Minor, for #2023. A sealed typed null will not decrypt through the addon. crate/src/ciphertext.rs:256-258 (as_kind) reads frame.kind(). For a null that is None. So once #2023 seals encrypt(null, { kind: kinds.int64 }), decrypting it fails with recipher_js::opened_type. The test at crate/src/engine_tests.rs:359-365 will need as_kind and Ciphertext::opened to accept a null too.
  8. Minor, docs. src/values.ts:19 still lists | null | null | null |. The Scalar and Value comments in src/value-types.ts present null as an input. README line 66 says a null decrypts as "not applicable". A stored null still decrypts as null: one from an older ciphertext, or from Rust's encrypt_tree. The same line's "refused with no kind" suggests that a kind makes it work today.
  9. Minor, engine help. Every engine refusal other than an array, an object, or a null keeps stack_encrypt::dynamic_value. That error has one help text ("A scalar is text … encrypt each value separately …"). It does not fit a conversion refusal such as encrypt(34.5, { kind: kinds.uint64 }). The code and fields are right. The help may belong in the engine, but this PR makes it visible in JavaScript.
  10. Minor, tests. No Rust test decrypts a declared-kind ciphertext with the typed call (for example 34.0 declared uint64, decrypted as u64). __tests__/addon/values.test.ts:678 says "The stored bytes are those of a uint64", but fromBytes(…, kinds.uint64) accepts any integer width, so it shows "an integer", not "a uint64".

Nothing found in these areas:

  • Routing. No path is left to OneValue. A nested array, an object, a null, or a passthrough is refused before any key request.
  • The kind confused with another argument. Each of these is refused with recipher_js::options: a bare kind, a string, an array, an inherited kind, extra keys, and a throwing getter.
  • Error mapping, and plaintext in errors.

…x the null help

A whole number outside 2^53 - 1 either side of zero, declared as an
integer kind, was stored as the number it had become. For example,
12345678901234567890 declared as uint64 decrypted as
12345678901234567168n. Such a number is now refused before the engine
reads it, with the code recipher_js::unsafe_integer. The help asks for a
bigint. json(..) already refuses the same numbers.

The other changes:

- null as the options of encrypt is refused with recipher_js::options.
  Before, napi read it as no options.
- The help for undefined no longer says to use null. A lone null is
  refused too.
- The help for a refused null no longer suggests a declared kind that
  fails today. With no kind or a fixed-width kind, it says a declared
  kind will work once the engine encrypts typed nulls. With a
  variable-width kind, it says only to store a database NULL.
- A value that does not convert to its declared kind keeps the engine's
  code and fields, with a help about the conversion.
- A stored null decrypts as null when it is read with a fixed-width kind.
  So fromBytes with such a kind now has the type bigint | null, and so
  on for each fixed-width kind.
- Declared distributes over a union of kinds.
- encrypt with no kind no longer takes null in its type: Scalar has no
  null. OpenedScalar still has it, for a stored null.
- A crate test checks that 34 declared as uint64 is stored as a uint64.
@coderdan

Copy link
Copy Markdown
Contributor Author

Reply to review 6101801632. All ten findings are fixed in 988ae6a. Each behaviour change has a test that failed before the fix.

  1. A number that has lost digits, with an integer kind. Fixed. A finite number outside 2^53 - 1 either side of zero, declared as any int or uint kind, is now refused before the engine reads it. The code is recipher_js::unsafe_integer, and the help asks for a bigint. I did not reuse recipher_js::not_json. Its message says "a JSON document cannot contain", but this value is not in a document. TypeScript cannot check a number's range, so the type is unchanged. Declared says the refusal comes when encrypt runs. The addon test covers every width, both signs, 12345678901234567890, Number.MAX_VALUE, and an array. A second test checks that Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER still encrypt.

  2. null as the options. Fixed. keyset.encrypt now takes its second argument as Unknown, not Option<Unknown>. So null reaches declared_kind and is refused with recipher_js::options. A missing argument is still undefined. The options test has a null case.

  3. The recipher_js::undefined help. Fixed. It now reads: "Check that the value is set: a misspelt property name gives undefined. Store a value that is not there as a database NULL." The pins in crate/src/error.rs and an addon test check the new text.

  4. The recipher_js::null_value help. Fixed. The help now depends on the declared kind:

    • With no kind, or a fixed-width kind, it says to store a database NULL. It adds that a null declared as a fixed-width kind will encrypt once the engine encrypts typed nulls.
    • With a variable-width kind, it says only to store a database NULL.

    No issue number is in the error.

  5. Declared<K> and a union of kinds. Fixed. Declared is now K extends Kind ? … : never. type-tests/values.ts checks two unions:

    • int64 | json: a plain object is refused, and a json(..) and 34 compile.
    • int64 | string: 34 and 'Ada' compile, and true does not.
  6. encrypt(null) type-checks. Fixed. Scalar no longer has null, so encrypt(null) and encrypt(['x', null]) with no kind are compile errors. null is still allowed with a fixed-width kind. The comments on Declared, OpenedAs, and Scalar say that this null is refused at run time until the engine encrypts typed nulls. OpenedScalar keeps null, for a stored null.

  7. A sealed typed null through the addon. Fixed. When the kind is fixed-width, as_kind and Ciphertext::opened now return a plain null or a typed null. For any other kind, it refuses the null with recipher_js::opened_type. Tests: a unit test on as_kind, and an engine_tests.rs test that decrypts a null that encrypt_tree sealed, as int64 and as string. The addon cannot make a null ciphertext on this branch, so there is no JavaScript test.

    One type change follows from this. Ciphertext.fromBytes(bytes, kind) now has the type ReadAs<K>. That type adds | null for a fixed-width kind, so fromBytes(bytes, kinds.int64) is a Ciphertext<bigint | null>. Without it, the type would say bigint for a value that can decrypt as null.

    I can change it back to ValueOf<K> if you prefer.

  8. Docs. Fixed in three places: the null row in src/values.ts, the comments on Scalar and Value in src/value-types.ts, and README line 66. The README now says three things:

    The README's "Stored bytes" section also covers the | null type.

  9. The engine's help for a conversion refusal. Fixed in the addon. A refusal with the reason field_type keeps the engine's code, stack_encrypt::dynamic_value, and its fields. Only the help changes. It reads: "Pass a value of the declared kind, or one that converts to it exactly, such as a whole number for an integer kind." A crate test checks the code, the reason field, and the help. The addon test for 34.5 checks the help too. The engine's own help is unchanged.

  10. A typed decrypt of a declared kind. Fixed. A new test in engine_tests.rs declares 34.0 as uint64. The typed call decrypts it as the u64 34. With no kind, the stored frame equals the frame of 34u64. That shows the width as well as the value. The comment in values.test.ts now says only that an integer kind reads the bytes back, and points to that test.

The fix is merged up the stack: c6ad7ef on feat/recipher-js-records (#1776) and 55374eb on feat/recipher-js-uuid (#1996). On the UUID branch, a UUID counts as fixed-width. So fromBytes(bytes, kinds.uuid) is a Ciphertext<RcUuid | null>.

I ran these checks on each of the three branches:

  • cargo fmt --check, cargo clippy --all-targets --all-features -D warnings, and cargo test --all-features --locked over the whole recipher-js workspace;
  • build:debug, with native.d.ts regenerated and committed;
  • test:addon, the unit Vitest suite, and tsc --noEmit with the type tests;
  • Biome on the package.

…ption

A kind from `kinds` now takes no null, as a Rust type that is not an
`Option` takes no `None`. `Ciphertext.fromBytes(bytes, kinds.int64)` is a
`Ciphertext<bigint>`. Decrypting a stored null with it is an `Err` with the
new code `recipher_js::opened_null`, whose help says to read with
`nullable(..)`. Rust's `decrypt::<i64>` refuses a null the same way.

`nullable(kind)` is the kind that also takes `null`. The value is
`{ name, nullable: true }`, frozen like each of `kinds`. `nullable` never throws.

- Reading: a stored null opens as `null`, for a kind of any width. A
  stored null can exist for any type, such as one that Rust's
  `encrypt_tree(None::<String>)` wrote.
- Encrypting: a `null` declared as `nullable(..)` of a fixed-width kind
  goes to the engine as a typed null of the kind. The engine refuses it
  until #2023 lands, so it is an `Err` today. A test checks the refusal
  and names #2023.
- A `null` with no kind, with a plain kind, or with `nullable(..)` of a
  variable-width kind does not compile. When the code runs, it is a
  `recipher_js::null_value` error. The help depends on the kind, and
  points to `nullable(..)` where that will help.
- A value that is not `null` encrypts with `nullable(kind)` as it does
  with `kind`.

The addon reads a kind with any other key, or with a `nullable` that is not
`true`, as not a kind (`recipher_js::not_a_kind`). So a misspelt key is
never read as a plain kind. A kind in the options of `encrypt` that is not
a kind is now `recipher_js::not_a_kind` too, and no longer
`recipher_js::options`.

`ReadAs<K>` now follows `nullable`, and `Declared<K>` takes `null` only for
`nullable(..)` of a fixed-width kind. The type tests cover each case,
unions of kinds included.
`new RcDate(20261123)` threw a `TypeError`, and nothing else in the package
throws apart from `unwrap` and `expect`. A wrapper is now made with a
static factory that returns a `Result`:

    const born = RcDate.from('1815-12-10') // Result<RcDate, RecipherError>

`RcDate.from`, `RcTimestamp.from`, `RcDecimal.from`, and `RcUuid.from` check
the text in Rust, with the rule that `encrypt` uses. So an instance that
exists is always valid. Bad text, or a value that is not a string, is an
`Err` with the value bridge's code, such as `ERR_INVALID_DATE`. The `Err` contains no part of the text. `from` reads no
`this`, so `texts.map(RcDate.from)` works.

The addon installs the factory that `from` calls when the package loads it,
next to the `Result` classes. The value bridge provides
`Wrappers::from_text` for the check, and `Wrappers::install_from` to set
the factory once for each environment.

The classes have no constructor in their types, so `new RcDate('x')` does
not compile. The constructor takes a token that only the classes' script
contains. When `new` is called anyway, from JavaScript or past a cast, it
throws a `TypeError` that names `RcDate.from(text)`. `new Cipher()` throws
too, so `new` on a class whose type has no constructor is the second kind
of call that throws. The README says so.

A decrypted value is still built as an instance of the same classes, with
the token. `instanceof`, the freezing, and the plain-object checks are
unchanged. The text is still checked when the value is encrypted, because
`Object.create` makes an object that `instanceof` accepts.

The stand-in classes for an addon that did not load return the load error
from `from`, and throw the same `TypeError` for `new`.
@coderdan

Copy link
Copy Markdown
Contributor Author

Two design changes are on this branch now. They follow the package's rule that every call returns a Result, and that only unwrap and expect throw.

1. Null is opt-in, with nullable(kind), as Rust's Option<T> (0b88351)

A kind from kinds takes no null, as a Rust type that is not an Option takes no None. nullable(kind) is the kind that also takes null.

import { Ciphertext, kinds, nullable } from '@cipherstash/recipher'

// Reading: a plain kind refuses a stored null, as `decrypt::<i64>` does.
const age = Ciphertext.fromBytes(bytes, kinds.int64) // Ciphertext<bigint>
// Decrypting a stored null with it is an Err: recipher_js::opened_null.

const maybe = Ciphertext.fromBytes(bytes, nullable(kinds.int64)) // Ciphertext<bigint | null>

// Encrypting: a value that is not null encrypts as the plain kind would.
await keyset.encrypt(34, { kind: nullable(kinds.uint64) })
  • nullable(..) works with every kind when you read, variable-width kinds included. A stored null can exist for any type: Rust's encrypt_tree(None::<String>) writes one.
  • keyset.encrypt(null, { kind: nullable(kinds.int64) }) compiles. The SDK gives the engine a typed null of the kind. The engine refuses it until stack-encrypt: single-value encrypt refuses every null — seal a typed fixed-width null as records do #2023 lands, so the call is an Err today, and a test names stack-encrypt: single-value encrypt refuses every null — seal a typed fixed-width null as records do #2023.
  • null with no kind, with a plain kind, or with nullable(..) of a variable-width kind does not compile. When the code runs, the call is an Err with the code recipher_js::null_value. The help points to nullable(..) where that will help.
  • How nullable crosses napi: it is { name, nullable: true }, frozen like each of kinds. The addon refuses any other key, and any nullable that is not true, with recipher_js::not_a_kind. So a misspelt key is never read as a plain kind. nullable(x) never throws: for something that is not a kind, it returns a value that the addon refuses as not a kind.
  • ReadAs<K> now follows nullable. Declared<K> takes null only for nullable(..) of a fixed-width kind. The type tests cover each case, unions included.
  • One small change in behaviour: a kind inside the options of encrypt that is not a kind is now recipher_js::not_a_kind, not recipher_js::options.

2. Wrapper classes are made with from(text), which returns a Result (b284a8e)

import { RcDate } from '@cipherstash/recipher'

const born = RcDate.from('1815-12-10') // Result<RcDate, RecipherError>
if (born.isErr()) {
  return born // ERR_INVALID_DATE for text that is not a date
}
await keyset.encrypt(born.value)
  • RcDate.from, RcTimestamp.from, RcDecimal.from, and RcUuid.from check the text in Rust, with the rule that encrypt uses. So an instance that exists is always valid. Bad text, or a value that is not a string, is an Err with the value bridge's code, such as ERR_INVALID_DATE. The Err contains no part of the text.
  • The addon installs the factory that from calls when the package loads it, next to the Result classes. In the value bridge, Wrappers::from_text makes the check, and Wrappers::install_from sets the factory once for each environment.
  • What new RcDate('x') does now: it does not compile, because the classes have no constructor in their types. The constructor takes a token that only the classes' script contains. When new is called anyway, from JavaScript or past a cast, it throws a TypeError that names RcDate.from(text). new Cipher(), new Keyset(), and new Ciphertext() already throw the same way. The throw is acceptable under the rule, for two reasons. TypeScript stops the call before it runs, and the throw is loud at the line that made the mistake. An object that looked like a wrapper would fail later, far from the cause. The README now lists this as the second kind of call that throws, after a method called without its object.
  • A decrypted value is still an instance of the same classes, made with the token. instanceof, the freezing, and the plain-object checks are unchanged. encrypt still checks the text, because Object.create(RcDate.prototype) makes an object that instanceof accepts.

Up the stack

Checks at each head: cargo fmt, clippy with -D warnings, and cargo test --all-features --locked over the recipher-js workspace, with the node suites. Then build:debug, test:addon, the unit tests, tsc with the type tests, and Biome. All passed. The repository's script tests pass on this branch.

@coderdan

Copy link
Copy Markdown
Contributor Author

Two open points from the comment above are decided, with no change: new on a wrapper class keeps throwing a TypeError that names from(text) (its type has no constructor, so the call does not compile), and RcUuid.from stays on this branch.

@coderdan
coderdan merged commit 88316ce into next Nov 29, 2026
35 checks passed
@coderdan
coderdan deleted the feat/recipher-js-values branch November 29, 2026 08:29
coderdan added a commit that referenced this pull request Nov 29, 2026
#1775 has merged, so step 2 of the build order is built. Its last
changes made a null opt-in, as Rust's Option is: a plain kind reads no
null, and nullable(kind) reads and encrypts one. They also made each
wrapper class come from a from(text) factory that returns a Result. The
value table and the value rules now say so.
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.

@cipherstash/recipher encrypts a string only — add every value type, arrays and JSON documents

2 participants