Repository navigation
feat(recipher-js): walking skeleton of the TypeScript SDK - #1774
Conversation
|
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the
|
Mutation testing (cargo-mutants,
|
coderdan
left a comment
There was a problem hiding this comment.
This is an automated code review, run at the PR author's request.
Summary. The binding looks sound. A string goes from JavaScript into vitaminc's wiped Buffer, then a ValueFrame, then the engine; an opened value comes back in a Protected buffer straight into JsBuilder. I found no unwiped plaintext copy, no unwrap or panic reachable from JavaScript, no unsafe, and no JavaScript value touched off the JavaScript thread. The release addon really has no test cipher. Nothing is blocking. The findings are about the edges of the "no call throws" contract, one error path that would copy a Node error's text, and two guards the PR describes but does not test.
Should fix
fromThrownkeeps the message of anyTypeErrorwith anERR_code. Node's own errors use that prefix and quote their argument. Latent in step 1, reachable once objects are walked. (src/error.ts:129)- A detached method throws synchronously (
cts.map(cipher.decrypt)), and a detachedkeyset.encryptreports the wrong error kind. (src/cipher.ts:135) - The loader's
Errpaths (addon missing, wrong binding interface, missing function) andrecipher::no_testinghave no test. (src/native.ts:76) - Nothing in CI checks that a default-feature addon has no test cipher. Every CI build turns
testingon. (crates/node/Cargo.toml:20)
Question / design
instanceof Ciphertextrefuses a ciphertext from the other module format (ESM vs CJS) in the same process. (src/cipher.ts:207)
Nit
NotOpened,UnsupportedShapeandKeysetMismatchmap to kinds that point the caller at the ciphertext. (crates/core/src/error.rs:140)- Two actions are pinned by tag, not SHA. (
.github/workflows/tests-recipher-js.yml:93)
What I ran (macOS arm64, Rust 1.94.1, Node 24, pnpm 10.33.2):
cargo test --locked --all-features: 16 passed.cargo clippy --locked --workspace -- -D warningswithouttesting: clean.build:debug, thentest:addon(13 passed) andtest(passed).cargo build --release -p recipher-js-node, loaded in Node: nocreateTestingexport,hasTesting()isfalse.cargo tree -e featureswith and without--features testing:stack-encrypt/test-supportarrives only throughtesting.- A throwaway vitest probe against the debug addon (detached methods, unpaired surrogate,
nulloptions), and a script loadingtsup's ESM and CJS output in one process. Neither is committed. - The new workflow's first run: it did run the 16 cargo tests and the addon suite.
Checked and fine: the Rust error mapping never formats a napi error's message (only its status); Ciphertext.fromBytes and Debug hide the bytes; NativeCipher cannot be constructed from JavaScript; the core crate names no Label/IntoLabel; eql-bindings is not in this workspace's Cargo.lock at all; the package is private; build and test reach no cargo; the root Cargo.toml excludes the workspace; the workflow has contents: read, persist-credentials: false and --frozen-lockfile.
From review of #1774. The SDK has one Rust crate, the Node addon. The split into a core crate and a thin node crate had one consumer, and the core mostly re-wrapped engine types. A common crate is split off when the wasm build exists and what the two builds share can be seen. Cipher, Keyset and Ciphertext are napi classes written in Rust, and napi-rs generates their types. TypeScript keeps only what Rust cannot express: Result, the declaration types and the typed signatures. There is no hand-written description of the native interface. The crate uses the engine's and vitaminc's types directly, and derives OpaqueDebug for a type that holds a secret. The plan no longer takes the Python SDK as an example.
2232e04 to
845303d
Compare
845303d to
872ff2e
Compare
483e05d to
d4c9028
Compare
From review of #1774. The SDK has one Rust crate, the Node addon. The split into a core crate and a thin node crate had one consumer, and the core mostly re-wrapped engine types. A common crate is split off when the wasm build exists and what the two builds share can be seen. Cipher, Keyset and Ciphertext are napi classes written in Rust, and napi-rs generates their types. TypeScript keeps only what Rust cannot express: Result, the declaration types and the typed signatures. There is no hand-written description of the native interface. The crate uses the engine's and vitaminc's types directly, and derives OpaqueDebug for a type that holds a secret. The plan no longer takes the Python SDK as an example.
d4c9028 to
af22a61
Compare
@cipherstash/recipher is the TypeScript SDK on the Stack Encrypt engine. This first step encrypts and decrypts one string on Node, through the engine, and no call throws: every call resolves to a Result. One napi-rs 3 crate, recipher-js, defines the Cipher, Keyset and Ciphertext classes and runs each call through the engine. It reads and builds JavaScript values only through the value bridge beside it, recipher-value-napi, and reads a refused value's rule from the bridge's Refusal, never from a message's wording. @napi-rs/cli v3 builds the addon and writes its TypeScript declarations to the committed native.d.ts. The TypeScript holds Result, RecipherError, the typed signatures over the native methods, and the adapter that turns each native outcome into a Result. An error is the engine's diagnostic and nothing else: its code, message, help, url, severity, structured fields and causes, with field and record where the SDK names them. A caller switches on the code. The SDK's own errors are one Rust enum deriving miette's Diagnostic, and one function converts any diagnostic, the engine's, the bridge's or the SDK's, into the object JavaScript receives. A cause from another library is reported as one, and its message is never copied. createTesting gives a cipher over the engine's deterministic test keys, in the debug build only. tests-recipher-js.yml now also builds the addon, checks that the build leaves native.d.ts and Cargo.lock as committed, and runs the suites that load the addon. Closes #1811 Closes #1800
stack-kms on next depends on zerokms-keyset 0.3.4 in place of recipher, and this workspace builds it by path, so its lockfile follows.
872ff2e to
4046495
Compare
… its own workflow Three repo checks failed once the skeleton joined the value bridge: - The lock parity test compared every vitaminc crate the workspace lock names. The engine reaches an older vitaminc of its own, which the bridge never runs. It now follows each lock's graph from recipher-value-napi and compares what the bridge reaches. - The live-job gate excludes recipher-js, and the scan counted the package's own suites reading its own files as a hole. They run in tests-recipher-js.yml, which every change to the package starts. A read inside such a package is no longer counted, and a test holds the workflow to running the suites and to watching the package. - The workflow ran the package's `test` bare. It now goes through turbo, which builds the package's dependencies first.
…rom the engine's The engine's codes are named after its crate, stack_encrypt::, and it will take the name recipher. The SDK's own codes were recipher::, so the two would then share a namespace: the SDK's opened_type already matches the engine's, and the SDK passes the engine's codes through unchanged, so a caller could not tell which one fired. Naming the SDK's codes after its crate, recipher_js::, keeps every SDK code apart from every engine code, now and as either side adds more.
The package's TypeScript wrapped every native method (`adapt`) to turn an outcome object into a `Result`, and repeated each method's signature in hand-written interfaces so callers saw the typed API. Every method added to the addon meant three edits that nothing kept in step. Rust now builds each `Result`: the loader hands the addon `Ok`, `Err` and `RecipherError` once (`installResult`, kept in the environment's instance data, the first install wins when the ESM and CommonJS builds both load), and each method returns `new Ok(value)` or `new Err(new RecipherError(fields))`. Each signature is written in Rust with napi-rs's `ts_type`, `ts_args_type` and `ts_return_type`, and a header (`native-header.d.ts`) gives `Ciphertext` its type parameter, so the generated `native.d.ts` is the public type and its documentation comes from the Rust doc comments. The cost, decided in #1801: a method called without its object, as in `stored.map(cipher.decrypt)`, throws a `TypeError`. The JavaScript engine checks the object before any Rust runs. The tests that said such a call is an `Err` now say it throws; a wrong or missing argument is still an `Err`, and still tested. The binding interface goes to 3, because the addon now needs its `Result` classes installed. What stays in TypeScript is what Rust cannot do: `Result`, `RecipherError`, the loader, stand-in classes for a build that did not load, and class types without napi-rs's implied constructor, so `new Cipher()` still does not compile.
A method called without its object throws a TypeError; everything else is an Err. The plan described a TypeScript layer of typed signatures over the native classes, which is gone now that Rust returns each Result and writes each signature, so those passages say what the package does instead.
…r docs No build of the package has been released, so no addon and TypeScript of different versions can meet yet, and counting the interface up on each unmerged change only says how many drafts it went through. It starts at 1 and changes from the first release on, as the crate's docs now say. The module docs of the loader and the classes, and the header's comment, are rewritten to pass the plain-language checker: one idea per sentence and the serial comma.
cipherstash-bot
left a comment
There was a problem hiding this comment.
Recommendation: 🟡 merge after changes
One fix is needed before merging: testCipher must return an Err for a primitive options value. AGENTS.md must also stop describing the removed TypeScript adapter. The other findings are test gaps and small hardening items that can wait for a follow-up. The Rust review found no panic that JavaScript can reach.
Other findings not posted as comments
languages/typescript/packages/recipher-js/src/cipher.ts:62— Fix in a follow-up:typed<T>casts the stand-in classes to the full class types, so a new static method compiles without a stand-in.languages/typescript/packages/recipher-js/native-header.d.ts:17— Fix in a follow-up:interface Ciphertext<T = string>merges with a generatedclass Ciphertextthat has no type parameter.languages/typescript/packages/recipher-js/crate/src/js.rs:97— Optional: the secondunsafeblock intake_exceptionbuilds anUnknownthat both callers drop, and its SAFETY comment is not accurate.languages/typescript/packages/recipher-js/crate/src/outcome.rs:79— Optional:classes()returns&'static ResultClasses, but Node frees the instance data when the environment closes.languages/typescript/packages/recipher-js/native.d.ts:205— Optional:RecipherErrorFields.fieldsisRecord<string, any>in an exported type..github/workflows/tests-recipher-js.yml:22— Optional:turbo.jsonis not in the workflow path filters, but the last step runsturbo run test.
How this review was made
| Agent | Model | Review type | Result |
|---|---|---|---|
| claude | claude-opus-5-5 | test-gap | 3 found, 3 posted |
| claude | claude-opus-5-5 | rust | 3 found, 1 posted |
| claude | claude-opus-5-5 | infracode | 2 found, 1 posted |
| claude | claude-opus-5-5 | typescript | 4 found, 1 posted |
| codex | gpt-5.6-terra | test-gap | 1 found, 1 posted |
| codex | gpt-5.6-terra | rust | 0 found, 0 posted |
| codex | gpt-5.6-terra | infracode | 0 found, 0 posted |
| codex | gpt-5.6-terra | typescript | 1 found, 1 posted |
Synthesis: claude-sonnet-5-5 merged the findings, removed duplicates and dropped findings it could not confirm in the code. 1 posted finding(s) were raised by two or more models.
Plain language: claude-sonnet-5-5 read every comment as a new reader would. 2 comment(s) had a problem that stopped the reader acting; it rewrote 0.
Stack: 1 earlier and 3 later pull request(s) (#1229, *️⃣ #1774, #1775, #1776, #1791). *️⃣ marks this pull request.
Context loaded: the description, 3 linked issue(s) and 43 discussion entries.
Findings not posted:
- Fix in a follow-up: the 10-minute timeout and its "under three minutes" comment are from the old job, which built far fewer crates. Fixed in #1775 (refs/stack/1775 .github/workflows/tests-recipher-js.yml sets timeout-minutes: 45 (line 68).).
| ): Promise<Result<Cipher, RecipherError>> { | ||
| let seed: unknown | ||
| try { | ||
| seed = options?.seed ?? new Uint8Array(32).fill(DEFAULT_SEED_BYTE) |
There was a problem hiding this comment.
Change before merge: a primitive options value passed to testCipher creates a default test cipher instead of returning an Err.
Impact: A JavaScript caller can pass 42, true or a string, despite the declared TestCipherOptions | null type. options?.seed is then undefined, so the default seed is used and the call succeeds. The package promises that a wrong argument gives an Err.
Evidence: seed = options?.seed ?? new Uint8Array(32).fill(DEFAULT_SEED_BYTE) reads seed from any non-nullish value.
Fix: If options is not null, not undefined and not an object, set seed to undefined, so the addon returns recipher_js::testing_seed. Add test cases for primitive options.
Found by 1 model: codex
There was a problem hiding this comment.
Fixed in 597c138. A primitive options value now resolves to recipher_js::testing_seed; undefined and null still give the default seed. The test in __tests__/addon/value.test.ts covers a number, a boolean, a string, a bigint and a symbol, and failed before the fix.
| - `packages/stack-auth`, `packages/stack-profile`, `packages/stack-kms`, `packages/stack-encrypt`, `packages/stack-encrypt-derive`, `packages/stack-encrypt-jsonpath`, `packages/stack-guest-abi`: The Rust crates imported from `cipherstash/cipherstash-suite` with their history, and one added here — `stack-auth` and `stack-profile` (published to crates.io, one version group), `stack-kms` (published to crates.io from 0.1.0, its own version group, re-exported by `stack-encrypt` as `stack_encrypt::kms`), `stack-encrypt` and `stack-encrypt-derive` (published to crates.io from 0.1.0, one version group; `eql-bindings`' `stack-encrypt` feature depends on them from the registry), `stack-encrypt-jsonpath` (the JSONPath grammar of the JSON index and the SQL/JSON path predicate grammar its `match` operator reads, moved out of `stack-encrypt` so the derive can check a field's declared paths, and `predicate!` a predicate's text, at compile time; in the `stack-encrypt` version group, re-exported at `stack_encrypt::json`; its first version is published by hand, as the others' were, before Trusted Publishing can take it), and `stack-guest-abi` (`publish = false`). They are the members of the **root Cargo workspace**, with the three node binding crates below. See "Working on the Rust crates". | ||
| - `languages/typescript/packages/auth`, `languages/typescript/packages/profile`, `languages/typescript/packages/stack-auth-wasm`: The node bindings of those crates. `@cipherstash/auth` (napi-rs v2) and its six `platforms/*` packages are published to npm from this repository by `release.yml` (`auth-artifacts`, `publish-auth`); a change to what it ships, the `stack-auth` crate included, needs an `@cipherstash/auth` changeset (`require-auth-npm-changeset.yml`). `@cipherstash/profile` and its platforms are private and never published; `@cipherstash/stack-auth-wasm` is private and builds the wasm that `@cipherstash/auth` ships. Their `build` and `test` scripts never invoke cargo; `build:native`, `build:debug` and `test:cargo` do. `@cipherstash/auth` also ships two pure-JS framework adapters over the wasm `OidcFederationStrategy`: `./next` (Next.js App Router, hands the token to the render on a request header) and `./start` (TanStack Start: `csFederateCurrent` is called inside a function middleware the app declares itself, which hands the token to the server function through `next({ context })`; `@tanstack/react-start` is an optional peer loaded only by that entry). | ||
| - `languages/typescript/packages/recipher-js`: The Rust half of `@cipherstash/recipher`, the TypeScript SDK on the Stack Encrypt engine (design: `docs/plans/2026-11-22-recipher-typescript-sdk.md`). For now it holds the value bridge alone: `value-napi/` (crate `recipher-value-napi`, napi-rs 3), which reads JavaScript values into vitaminc's plaintext model and builds JavaScript values from it. It is a copy of vitaminc's `vitaminc-aead-napi` 0.10.0, unpublished (`publish = false`), the one member of a **detached Cargo workspace** with its own `Cargo.lock`. The root workspace names its members, so it needs no `exclude` entry there; leave the root `Cargo.toml` alone, because a change to it starts every stack-* crate workflow. It has a detached test addon workspace of its own at `value-napi/tests/addon`, which its `tests/node.rs` builds before it runs the Node suites against it, and vitaminc's value conformance corpus at `value-napi/tests/testdata`; Biome does not check that directory. `.github/workflows/tests-recipher-js.yml` is the only workflow a change under the directory runs, apart from `tests.yml`'s ungated lint and repo checks: it runs `cargo test --locked`, `cargo fmt --check` and clippy over the workspace, and fmt and clippy over the test addon by its manifest. One Dependabot cargo entry covers both lockfiles, and `scripts/__tests__/recipher-js-lock-parity.test.mjs` fails when they resolve different napi or vitaminc crates. | ||
| - `languages/typescript/packages/recipher-js`: `@cipherstash/recipher`, the TypeScript SDK on the Stack Encrypt engine (design: `docs/plans/2026-11-22-recipher-typescript-sdk.md`). **Private and unpublished**: it has no platform packages and no release job yet, so it must stay `"private": true` (a public manifest would be published by `changeset publish` on merge) and takes no changeset. Its Rust is **two crates** in a **detached Cargo workspace** with its own `Cargo.lock`. The root workspace names its members, so it needs no `exclude` entry there; leave the root `Cargo.toml` alone, because a change to it starts every stack-* crate workflow. The two crates: `crate/` (crate `recipher-js`, napi-rs 3), which defines the `Cipher`, `Keyset` and `Ciphertext` classes the package exports, runs every operation through the engine, and reads and builds JavaScript values only through the value bridge beside it, `value-napi/` (crate `recipher-value-napi`, a copy of vitaminc's `vitaminc-aead-napi` 0.10.0, unpublished, with a detached test addon workspace of its own at `value-napi/tests/addon` and vitaminc's value conformance corpus at `value-napi/tests/testdata`; Biome does not check that directory). A test fails if it links `eql-bindings` or reaches the engine's `test-support` with its default features. `@napi-rs/cli` v3 builds it (`build:debug`, `build:native`) and writes its generated TypeScript declarations to the committed `native.d.ts`; CI fails when the build changes that file. The TypeScript (`src/`) holds only `Result`, `RecipherError`, the typed signatures over the native methods and the adapter that turns each native outcome into a `Result`. Its `build` (tsup) and `test` (the suites in `__tests__/unit` and `tsc` over `src`, the tests and `type-tests`) never run cargo; `build:debug` (the addon with the deterministic test cipher behind `@cipherstash/recipher/testing`), `build:native`, `test:addon` (the suites that load `recipher.node`) and `test:cargo` do. `.github/workflows/tests-recipher-js.yml` runs all four, and fmt and clippy over the value bridge's test addon by its manifest: `tests.yml`'s live jobs skip a change that touches only this package, so apart from that file's ungated lint and repo checks it is the only workflow such a change runs. One Dependabot cargo entry covers both lockfiles, and `scripts/__tests__/recipher-js-lock-parity.test.mjs` fails when they resolve different napi or vitaminc crates. |
There was a problem hiding this comment.
Change before merge: the recipher-js entry describes a TypeScript adapter that this PR removes.
Impact: The entry says src/ holds the typed signatures over the native methods and the adapter that turns each native outcome into a Result. In this PR, Rust returns each Result itself, and napi-rs's generated native.d.ts is the public type. An agent that reads this entry looks for an adapter, or adds one back.
Evidence: src/ has no adapter. #1775 and #1776 keep the same sentence.
Fix: Replace the clause with what src/ holds now: Result, RecipherError, the loader src/binding.ts that installs them in the addon, and stand-in classes for a missing build. The class types come from the generated native.d.ts.
Found by 1 model: claude
There was a problem hiding this comment.
| ) | ||
| } | ||
| try { | ||
| binding.installResult({ Ok, Err, RecipherError }) |
There was a problem hiding this comment.
Fix in a follow-up: when the ESM and CommonJS builds both load, instanceof Ok, instanceof Err and instanceof RecipherError can be false for the results of the second build.
Impact: Each build bundles its own Ok, Err and RecipherError. The addon keeps the classes of the first build, and the return value of installResult is ignored here. A caller of the second build who writes result.error instanceof RecipherError gets false, while the types say it is true.
Evidence: __tests__/addon/builds.test.ts checks that Cipher and Ciphertext are shared. It does not check Ok, Err or RecipherError.
Fix: Give the three classes a Symbol.hasInstance that checks a Symbol.for(...) brand, so both copies agree. Add the case to builds.test.ts.
Found by 1 model: claude
There was a problem hiding this comment.
Fixed in 9c39d52. Ok, Err and RecipherError now have a Symbol.hasInstance that checks a Symbol.for brand, so both builds agree. builds.test.ts checks instanceof both ways for results from each build, and failed before the fix. A type test checks that instanceof Ok still narrows.
| break; | ||
| } | ||
| next = match cause { | ||
| Cause::Ours(diagnostic) => { |
There was a problem hiding this comment.
Fix in a follow-up: causes_of copies the message of every cause that implements miette::Diagnostic, not only the engine's own causes.
Impact: The module doc says a cause from another library gets a fixed message. The code decides by trait, not by origin. A dependency's miette error attached with #[diagnostic_source] would send its to_string() to JavaScript, and that text may quote a value. Today every such source in stack-encrypt and stack-kms is a CipherStash type, so nothing leaks now. No test stops a leak later.
Evidence: next_of maps every diagnostic_source() to Cause::Ours, and that arm pushes diagnostic.to_string().
Fix: Treat a diagnostic as the engine's own only when its code is in a namespace you own (checked with stack_encrypt::diagnostic::is_code_of). Report all others with UNDESCRIBED_CAUSE. Add a test with a foreign-code #[diagnostic_source].
Found by 1 model: claude
There was a problem hiding this comment.
Fixed in 9c39d52. A cause is copied only when its code is in a CipherStash namespace (stack_encrypt, stack_kms, stack_auth, stack_profile or recipher_js), checked with is_code_of. Any other diagnostic gets the fixed message, and the walk then follows plain sources only. The test with a foreign #[diagnostic_source] failed before the fix.
| } | ||
|
|
||
| /// Decrypts a ciphertext made under this keyset. A ciphertext of another | ||
| /// keyset fails with the code `stack_encrypt::foreign_keyset`, before |
There was a problem hiding this comment.
Fix in a follow-up: no test shows that keyset.decrypt refuses a ciphertext of another keyset while cipher.decrypt opens it.
Impact: The two calls differ only in the Confined argument. If a change ignores confined or swaps the arms, keyset.decrypt opens values of every keyset and no test fails. All current tests use the default keyset only.
Fix: Add a test in crate/src/engine_tests.rs. Encrypt under a second keyset of the deterministic cipher. Expect unseal on the default keyset to fail with stack_encrypt::foreign_keyset. Expect unseal on the cipher to return the value.
Found by 1 model: claude
There was a problem hiding this comment.
Fixed in c3ff8af. The Confined match moved into open_in, which both decrypt calls use. A test in engine_tests.rs encrypts under a second keyset, and expects Confined::ToDefault to give stack_encrypt::foreign_keyset and Confined::No to return the value.
| //! define those classes, because `isOk()` narrows a type only in TypeScript. | ||
| //! So the package's TypeScript gives the three classes to the addon once, | ||
| //! when it loads the addon ([`install_result`]). The addon keeps them in | ||
| //! the environment's instance data. A worker thread loads the addon in an |
There was a problem hiding this comment.
Fix in a follow-up: no test loads the package in a worker thread, though the docs say each worker has its own Result classes.
Impact: If the classes moved to a process-wide static, or binding.ts skipped installResult when the addon is already loaded, every call in a worker would throw or use the main thread's classes. No test would fail. builds.test.ts checks two builds in one environment, never two environments.
Fix: In __tests__/addon/builds.test.ts, load the addon in the main thread. Then start a Worker that requires the built CommonJS testing entry and does an encrypt and a decrypt. Expect the plaintext back with no exception.
Found by 1 model: claude
There was a problem hiding this comment.
Added in 9c39d52. builds.test.ts loads the package in the main thread, then starts a worker that requires the CommonJS build. The worker encrypts and decrypts, opens a ciphertext from the main thread, and checks instanceof Ok and instanceof RecipherError. It passed before the change, so it is a guard rather than a fix.
| let mut out = Vec::new(); | ||
| let mut next = next_of(error); | ||
| while let Some(cause) = next { | ||
| if out.len() == MAX_CAUSES { |
There was a problem hiding this comment.
Fix in a follow-up: no test reaches the MAX_CAUSES limit in causes_of.
Impact: The limit stops a looping or very long cause chain from making the walk run forever on the JavaScript thread. If a change moves or removes the out.len() == MAX_CAUSES check, no test fails. The existing tests use chains of two causes. The Cause::Foreign arm has its own loop that no test covers either.
Fix: Add two tests in the tests module of error.rs. One uses an error that is its own diagnostic_source. The other uses an error that is its own source. Expect causes.len() == MAX_CAUSES for both, and the fixed UNDESCRIBED_CAUSE message on foreign causes.
Found by 2 models: claude, codex
There was a problem hiding this comment.
Added in 9c39d52: one test with an error that is its own diagnostic_source, and one with an error that is its own source. Both expect MAX_CAUSES causes, and the second expects the fixed message on every cause.
`options?.seed` reads `undefined` from a number, a string or any other primitive, so `testCipher(42)` quietly made a cipher with the default seed. The package promises that a wrong argument is an Err, so a primitive is now refused with `recipher_js::testing_seed`, as a bad seed is. `undefined` and `null` still mean the default seed.
…nceof across builds A cause counted as the engine's own whenever it implemented miette's Diagnostic, so a dependency's diagnostic attached as a diagnostic source would have sent its message, which may quote a value, to JavaScript. A cause is now copied only when its code is in one of CipherStash's namespaces; any other gets the fixed message. Tests cover that case and the cause limit on looping chains of both kinds. When the ESM and CommonJS builds both load, the addon builds every Result from the classes of the build that loaded first, so `instanceof Ok`, `Err` or `RecipherError` was false from the other build. The three classes now check a Symbol.for brand. A worker thread test shows a worker gets Result classes of its own. `RecipherErrorFields.fields` is typed `Record<string, unknown>` rather than `any`.
keyset.decrypt and cipher.decrypt differ only in the Confined value, and no test showed that one refuses another keyset's ciphertext while the other opens it. The choice moves into open_in, which the engine tests drive with a second keyset. Also: a stand-in class must now have every static method of the class it stands in for, or it does not compile; the pending-exception helper no longer builds a value nobody reads; the workflow runs when turbo.json changes, since its last step runs turbo; and AGENTS.md describes the package as it is, with no TypeScript adapter.
|
Replies to the findings in the review of 7cff71a that have no thread:
|
Summary
Closes #1811
Closes #1800
Closes #1801
This PR adds
@cipherstash/recipher, the TypeScript SDK on the Stack Encrypt engine (the Rust cratepackages/stack-encrypt). A TypeScript program on Node can make a cipher, encrypt onestring, and decrypt it again. Every call returns, or resolves to, aResult, and no promise rejects. A wrong or missing argument is anErr, not an exception.One call throws, as decided in #1801: a method called without its object, such as
stored.map(cipher.decrypt). The JavaScript engine throws aTypeErrorbefore any of the addon's code runs. In exchange, Rust returns eachResultitself, and napi-rs's generatednative.d.tsis the package's public type. The TypeScript layer that wrapped each native method (adapt) and the hand-written interfaces that repeated each signature are gone.An error is the engine's diagnostic and nothing else. A diagnostic is the engine's error type: a stable code, a message, and often help, structured fields and causes. A caller switches on the code.
Folded in: #1791 (an error carries the whole diagnostic), the addon half of #1805 (refusals read through the bridge's
Refusal), #1807 (nokind; the SDK's own errors are one enum), and from #1808 the removal of theLabelcheck and the plain-language docs.The package is private and not published, so there is no changeset.
Changes
Rust: one crate,
recipher-js, atlanguages/typescript/packages/recipher-js/crate, the second member of therecipher-jsCargo workspace.Cipher(Cipher.create(),defaultKeyset(),decrypt),Keyset(encrypt,decrypt) andCiphertext(Ciphertext.fromBytes,toBytes) are napi-rs classes. Each method checks its own arguments and returns the package'sResult:new Ok(value)ornew Err(new RecipherError(fields)).Ok,ErrandRecipherErrorclasses once, when it loads it (installResult). The addon keeps them in the environment's instance data, so a worker thread has its own. When the ESM and the CommonJS builds both load, the first to install wins and the other shares it.ts_type(generic methods),ts_args_typeandts_return_typeattributes.native-header.d.tsis the header napi-rs puts at the top ofnative.d.ts: it importsResultandRecipherError, and declaresinterface Ciphertext<T = string>, which TypeScript merges into the generated class. The Rust doc comments are the declarations' documentation.ValueFramefor a value,stack_encrypt::CiphertextinsideCiphertext.OneValuechecks that a value is one string, so the engine encrypts it through the same path as Rust'skeyset.encrypt(value).recipher-value-napi, by path. A refused value's code comes from the bridge'sRefusal, never from a message's text.crate/src/error.rs): the SDK's own errors are one enum,Error, derivingthiserror::Errorandmiette::Diagnostic.RecipherErrorFields::diagnosticis the one function that turns any diagnostic into the fields of aRecipherError:code,message,help,url,severity,fields,causes,fieldandrecord. A cause from another library is reported with a fixed message, and its own message is never copied. A test builds every variant and checks each code with the engine'sdiagnostic::is_code_of.createTesting(seed): a cipher over the engine's deterministic test keys, in the debug build only (--features testing). Any other build resolves it torecipher_js::no_testing.crate/tests/boundaries.rs: the crate does not linkeql-bindings, and a build with default features cannot reach the engine's test keys.TypeScript:
@cipherstash/recipher.@napi-rs/cli3.10.12 builds the addon and writes the committednative.d.ts.src/holds only what Rust cannot do:Result, with Rust's method names in camelCase.RecipherError, a small class whose constructor the addon calls with the generatedRecipherErrorFields. It is in TypeScript because an error must exist when the addon did not load.src/binding.ts: the loader. It checks the build's exports and interface number, installs theResultclasses, and freezes the native classes.src/cipher.ts: stand-in classes that resolve every call to the load error when the addon is missing, and the class types without napi-rs's implied constructor, sonew Cipher()still does not compile. The exported instance types are the generated ones.@cipherstash/recipher/testing:testCipher().Repository files.
.github/workflows/tests-recipher-js.ymlnow installs the workspace, runstest:cargo, builds the debug addon, fails if the build changesnative.d.tsorCargo.lock, and runs the suites that load the addon.AGENTS.md,SECURITY.mdandbiome.jsonlist the package.pnpm-lock.yamlgains@napi-rs/cli3.10.12; it needs no post-install script.docs/plans/2026-11-22-recipher-typescript-sdk.mdrecords #1801 as decided.Verification
Run locally on macOS (arm64), Rust 1.94.1, Node 24, pnpm 10.33.2, at this PR's head:
cargo fmt --all --check: clean.cargo test --locked --all-features:recipher-js11 unit tests and 2 boundary tests passed;recipher-value-napi33 unit tests andtests/node.rspassed.cargo clippy --locked --all-targets --all-features -- -D warnings: clean.cargo fmt --checkandcargo clippy --locked --target-dir target/napi-test-addon -- -D warningsby its manifest: clean.build:debug:native.d.tsregenerated and committed; a second build leaves the tree clean.test:addon(tsup, then the suites that load the addon): 24 passed. These include:keyset.encrypt,keyset.decrypt,cipher.decrypt,cipher.defaultKeyset,ciphertext.toBytes,[x].map(cipher.decrypt)) throws aTypeErrorsynchronously, and so does one called on an object of another class;Ciphertext.fromBytes) works;Err, or work, without throwing;test(the suites that need no addon, thentscwith the type tests): 26 passed, typecheck clean.biome checkon the changed files: clean. The repository's script tests: no new failures against the branch before this change.Not run: the release build, and anything against a live ZeroKMS. CI results are in the checks.
Review notes
TypeError. This is the decision in@cipherstash/recipherwraps every native method by hand to return aResult— spike returningResultfrom Rust sonative.d.tsis the public type #1801, and__tests__/addon/value.test.tsasserts it so it stays documented. The README, the package's module docs and theCipherandKeysetdocs name the exception and the fix:stored.map((ciphertext) => cipher.decrypt(ciphertext)).tscreadsnative.d.ts, sotype-tests/native.tsnow checks the generated types directly: the exported types are the generated ones, aCiphertext<number>is not aCiphertext<string>, decrypting gives the ciphertext's type, and the classes have no constructor.Cipher$1,Ciphertext$1and so on, because tsup's bundle holds both the generated class and the exported type alias. A type error a user sees shows that name.recipher.nodewithout the package no longer works: with noResultclasses installed, a call throws. Nothing but the package loads it.kinddoes not exist. No single code stands for a group such as "a credential problem". A caller lists the codes it cares about.fieldandrecordare on the error from the start. Records arrive in feat(recipher-js): records through the engine's Planned #1776; until thenrecordis never set.recipher_js::outcomeis the addon's "the engine returned no result", a bug rather than something a caller acts on. The TypeScript no longer has an outcome to check.Errfrom every call, never an exception at import.Related