Skip to content

feat(recipher-js): walking skeleton of the TypeScript SDK - #1774

Draft
coderdan wants to merge 1 commit into
docs/typescript-sdk-planfrom
feat/recipher-js-skeleton
Draft

coderdan wants to merge 1 commit into
docs/typescript-sdk-planfrom
feat/recipher-js-skeleton

Conversation

@coderdan

@coderdan coderdan commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Step 1 of phase 1 of the TypeScript SDK plan (docs/plans/2026-11-22-recipher-typescript-sdk.md, PR #1747): a walking skeleton of @cipherstash/recipher. A TypeScript program can build a cipher, encrypt one string and decrypt it again on Node, through the Stack Encrypt engine (the Rust crate packages/stack-encrypt). No call throws and no promise rejects: every call resolves to a Result.

The SDK's classes (Cipher, Keyset, Ciphertext) are written in Rust, in one napi-rs 3 crate, and napi-rs generates their TypeScript declarations. The TypeScript adds only what Rust cannot express.

The package is private and is not published. It takes no changeset.

Changes

Rust: one crate, recipher-js, at languages/typescript/packages/recipher-js/crate, in a detached Cargo workspace with its own Cargo.lock (the root Cargo.toml excludes it).

  • Cipher (Cipher.create(), defaultKeyset(), decrypt), Keyset (encrypt, decrypt) and Ciphertext (Ciphertext.fromBytes, toBytes) are #[napi] classes. Each method takes its arguments as untyped JavaScript values and checks them itself, and returns an outcome object ({ ok, value } or { ok, error }) instead of throwing. An asynchronous call resolves to one and never rejects.
  • The crate uses the engine's types directly: the engine's ValueFrame for a value, stack_encrypt::Ciphertext inside the Ciphertext class, the engine's errors mapped once into the JS error object. Types that hold a secret or a ciphertext derive vitaminc's OpaqueDebug. One small wrapper remains, OneValue, and its doc says why: it is the check that a frame holds one scalar, which is what lets the engine seal it through its opaque scalar path (the path Rust's keyset.encrypt(value) takes).
  • Values are read and built only through vitaminc's vitaminc-aead-napi (JsRef::to_frame, JsBuilder::build). When vitaminc refuses a value, the crate turns that into an Err of kind value with a code of its own (recipher::unpaired_surrogate, recipher::not_plain, …), keeps vitaminc's own ERR_* code where it threw one, and never copies a thrown error's message.
  • createTesting(seed): a cipher over the engine's deterministic test keys. Only the debug build (--features testing) has one; any other build resolves it to Err(recipher::no_testing). The function exists in both builds, so the generated declarations do not depend on the feature.

napi-rs CLI v3. @napi-rs/cli 3.10.12 builds the addon (build:debug, build:native) and writes native.d.ts, which is committed. 3.10.12 is the newest v3 release the repo's seven-day install cooldown (minimumReleaseAge) allows: 3.11.0 is one day old and pnpm refuses it. It needs no post-install script and no onlyBuiltDependencies entry (the install reports only the existing esbuild scripts as ignored). It adds 97 package versions to pnpm-lock.yaml, 46 of them per-platform binaries of @napi-rs/lzma, @napi-rs/tar and @napi-rs/wasm-tools, of which a machine installs one each.

TypeScript: @cipherstash/recipher. No hand-written description of the native interface and no TypeScript class wraps a native one. src/ holds:

  • Result, with Rust's methods in camelCase (unchanged).
  • RecipherError, a small class over the generated RecipherErrorFields. It is in TypeScript because an error has to exist when the native build did not load.
  • src/binding.ts: the loader, and adapt, which replaces each method on the native classes with a getter that returns the method bound to its instance and its outcome turned into a Result. That is the TypeScript's one job over the native calls, and the comment says so. It runs once per class, however many copies of the module load it.
  • src/cipher.ts: the typed signatures over the native methods (one value in, one ciphertext out; the type a ciphertext opens as), and stand-in classes that resolve every call to the load error when the native build is missing.
  • @cipherstash/recipher/testing: testCipher().

Tests and CI.

  • test (root pnpm test): the Result, error and loader/adapter suites, the script-wiring suite, and tsc over the type tests. It runs no cargo.
  • test:addon: builds the TypeScript (tsup), then the suites that load the addon, including one that runs the ESM and the CommonJS build in one Node process.
  • test:cargo: cargo test --locked --all-features, cargo fmt --check and clippy.
  • .github/workflows/tests-recipher-js.yml: one Linux job, test:cargo, build:debug, a drift guard that fails when the build changes native.d.ts or Cargo.lock, and test:addon. Every action is pinned by SHA.
  • AGENTS.md (repository layout, Cargo workspaces), SECURITY.md (package list), biome.json (the generated native.d.ts is not formatted by Biome).

What the tests prove

  • The bytes are the engine's. In Rust, the crate's seal opens through the engine's typed keyset.decrypt::<String>, and the crate opens what the engine's keyset.encrypt(String) sealed.
  • The engine's futures are Send and 'static. napi's spawn_future_with_callback, which requires it, compiles over them.
  • What the crate must not reach (crate/tests/boundaries.rs): it names no Label or IntoLabel; cargo tree --locked shows no eql-bindings; and with its default features (the release build) cargo tree -e features shows neither the crate's testing feature nor the engine's test-support. I checked that the last test fails when testing is added to default.
  • No call throws. A method passed on its own (['a','b'].map(...), sealed.map(cipher.decrypt), const { fromBytes } = Ciphertext) keeps its instance. Arguments of every wrong type, a method called on the wrong object, testCipher(null), a getter that throws while a value is read, and a missing native build each resolve to an Err.
  • The loader's Err paths, against fake builds: a build that does not load, one missing each export, one reporting another binding interface number, one whose bindingInterface throws.
  • ESM and CommonJS in one process share the one addon and its classes: instanceof holds across the two, and each opens what the other sealed.

Verification

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

  • cargo fmt --all --check: passed.
  • cargo clippy --locked --all-targets --all-features -- -D warnings: passed. Also with default features: passed.
  • cargo test --locked --all-features: 11 passed (7 unit, 4 boundary).
  • pnpm run build:debug, then git status: the build left the tree clean.
  • pnpm run build:native (release, default features), loaded in Node: createTesting resolves to Err(recipher::no_testing), and native.d.ts is unchanged. (Run on the records branch, which has the same createTesting.)
  • pnpm run test:addon: 21 passed.
  • pnpm run test: 27 passed, tsc clean.
  • pnpm run code:check: no errors (the 197 warnings are the repository's existing ones; none is in this package).
  • pnpm run test:scripts: 96 files passed. pnpm run lint:typecheck-scope: passed.

Not run: anything against a live ZeroKMS. CI results are in the checks.

Deviations from the plan

  • A fifth error field and a ninth kind, as before: message, and internal for a build that did not load or a fault in driving the engine.
  • Calls return a Promise, not yet a builder. The builder carries .audit, .withCredential and .signal, which are step 5.
  • The test cipher is in the debug build only. How a published package offers @cipherstash/recipher/testing is left to step 5 or step 10.
  • The addon loads when the package is imported, not on first use. The package exports the native classes themselves, so it needs them at import. A missing build is still an Err from every call, never an exception at import.
  • new Cipher(), new Keyset() and new Ciphertext() throw (napi's "no constructor"). The TypeScript types give them no constructor, so such a line does not compile.

Needs from the engine

Nothing for this step.

Changed since the first review

Dan's decisions.

  1. One Rust crate. crates/core and crates/node are now one napi-rs 3 crate, recipher-js, at crate/. The detached workspace and its Cargo.lock stay.
  2. Use the engine's and vitaminc's types. Plaintext (around ValueFrame), the private Ciphertext, Refusal/Kind and the core crate's Cipher are gone; the crate holds ValueFrame, stack_encrypt::Ciphertext and the engine cipher directly. Hand-written impl Debug blocks are replaced by #[derive(OpaqueDebug)].
  3. Rust defines the API. Cipher, Keyset and Ciphertext are #[napi] classes; native.d.ts is generated by @napi-rs/cli v3 and checked for drift in CI. src/native.ts and the TypeScript classes are deleted. The Err conversion lives in two places, and both are needed: Rust turns everything it can see (wrong argument types, vitaminc's refusals, engine errors) into an outcome; the TypeScript adapter turns an outcome into a Result and catches what napi itself throws (a method on the wrong object).

Line counts for this step (old branch head 2232e0421, new 845303dec): Rust source 722 lines in two crates (651 without test modules) became 1,052 in one (942 without test modules); the TypeScript src/ went from 786 lines to 778. The Rust grew because what TypeScript used to do (check each argument, dispatch, classify vitaminc's refusals, turn a missing seed into an Err) now happens in the Rust methods; the TypeScript lost its classes and its interface description but gained the adapter and the stand-ins for a missing build.

Review findings.

  • (a) fromThrown keeping Node's ERR_* messages: fixed, and moved into Rust. Only vitaminc-aead-napi's six codes are kept, each with the SDK's own message; vitaminc's message text is never passed on, and anything else that was thrown is recipher::threw with no text of its own. An unpaired surrogate is recipher::unpaired_surrogate, not napi's InvalidArg.
  • (b) Detached calls throw; testCipher(null) rejects: fixed (methods are bound by adapt; options?.seed). Tested.
  • (c) No tests for the loader's Err paths or the no-testing refusal: fixed for the loader (__tests__/unit/binding.test.ts, fake builds) and the stand-ins for a missing build. The no-testing refusal is now produced in Rust; its message is unit-tested, and I checked it by hand against a release build (above). CI builds only the debug addon, so no CI test loads a release build.
  • (d) Nothing in CI proves a release build has no test cipher: fixed, a_default_build_has_no_test_cipher in crate/tests/boundaries.rs.
  • (e) instanceof Ciphertext across ESM and CJS: fixed by construction: the classes are the addon's, which Node loads once per process. Tested in a real two-format process. instanceof RecipherError and instanceof Ok still differ across the two builds (they are TypeScript classes); isOk() and kind work across both.
  • (f) Internal cases mapped to user-facing kinds: fixed: NotOpened, UnsupportedShape and KeysetMismatch are internal.
  • (g) Actions pinned by tag: fixed, both pinned by the SHAs the repo already uses.
  • Dan's inline note on value.rs ("use vitamin C opaque debug"): done throughout.

Related

Refs #1747 (the plan). #1775 and #1776 are based on this branch.

@changeset-bot

changeset-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 845303d

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

This PR includes no changesets

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

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

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

@coderabbitai

coderabbitai Bot commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true

@github-actions

Copy link
Copy Markdown
Contributor

Mutation testing (cargo-mutants, --in-diff, stack-auth + stack-encrypt + stack-encrypt-jsonpath)

No mutants were generated for the changed lines.

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

  1. fromThrown keeps the message of any TypeError with an ERR_ 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)
  2. A detached method throws synchronously (cts.map(cipher.decrypt)), and a detached keyset.encrypt reports the wrong error kind. (src/cipher.ts:135)
  3. The loader's Err paths (addon missing, wrong binding interface, missing function) and recipher::no_testing have no test. (src/native.ts:76)
  4. Nothing in CI checks that a default-feature addon has no test cipher. Every CI build turns testing on. (crates/node/Cargo.toml:20)

Question / design

  1. instanceof Ciphertext refuses a ciphertext from the other module format (ESM vs CJS) in the same process. (src/cipher.ts:207)

Nit

  1. NotOpened, UnsupportedShape and KeysetMismatch map to kinds that point the caller at the ciphertext. (crates/core/src/error.rs:140)
  2. 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 warnings without testing: clean.
  • build:debug, then test:addon (13 passed) and test (passed).
  • cargo build --release -p recipher-js-node, loaded in Node: no createTesting export, hasTesting() is false. cargo tree -e features with and without --features testing: stack-encrypt/test-support arrives only through testing.
  • A throwaway vitest probe against the debug addon (detached methods, unpaired surrogate, null options), and a script loading tsup'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.

export function fromThrown(thrown: unknown): RecipherError {
if (thrown instanceof TypeError) {
const code = codeOf(thrown)
if (code?.startsWith('ERR_')) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Should fix. This keeps thrown.message for any TypeError whose code starts with ERR_. vitaminc is not the only source of that prefix. Node's own errors use it, and they quote their argument:

Buffer.alloc("4111 1111 1111 1111")
// TypeError, code ERR_INVALID_ARG_TYPE:
// The "size" argument must be of type number. Received type string ('4111 1111 1111 1111')

Step 1 cannot reach this, because encrypt checks for a string first. Once #1775 walks objects, a getter that calls a Node API puts its argument into RecipherError.message, which the doc comment above says never happens.

Related: a string with an unpaired surrogate (keyset.encrypt('\uD800')) comes back with code: 'InvalidArg'. That is napi's status name, not one of the code families the RecipherError doc lists. An application's own code property is kept the same way.

Fix: keep the message and code only for vitaminc-aead-napi's own codes (in 0.10.0: ERR_INTEGER_RANGE, ERR_INVALID_DATE, ERR_INVALID_TIMESTAMP, ERR_INVALID_DECIMAL, ERR_NON_FINITE_DECIMAL, ERR_INVALID_UUID). Give everything else recipher::value and the SDK's own message. Add the Buffer.alloc case to error.test.ts.

decrypt<T extends Value>(
ciphertext: Ciphertext<T>,
): Promise<Result<T, RecipherError>> {
return open(this.#native, ciphertext, false)

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. decrypt is not async, so this.#native is read synchronously. A detached call throws:

await Promise.all(stored.map(cipher.decrypt))
// TypeError: Cannot read properties of undefined (reading '#native')

The same happens for keyset.decrypt (line 193). That breaks "no call throws" for a common JavaScript pattern. A detached keyset.encrypt does not throw, but the try at line 175 catches the same TypeError and returns kind: 'value', "the value could not be read for encryption". That sends the caller looking at their value. Separately, testCipher(null) rejects, because the default parameter covers only undefined. I checked all three with a probe test against the debug addon.

Fix: bind the public methods in the constructors before Object.freeze (or declare them as arrow-function fields). Then the try in encrypt only ever sees what the addon throws. Use options ?? {} in testCipher. A small version of the plan's "every call with a wrong argument" test (detached methods, null and undefined arguments) would hold this.

),
)
}
const version = binding.bindingInterface()

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. None of the loader's Err paths has a test: the addon does not load, it lacks a function, or it reports another binding interface. testCipher's recipher::no_testing path has no test either. The PR body states this behaviour, and the plan lists it as a test ("A build with another binding interface number is refused by Cipher.create"). It is also the path a user hits first when a platform package is missing.

Fix: export load with the require function (or the module path) as a parameter, so a unit test can hand it fakes: a binding whose bindingInterface() returns 2, one with no createDetected, one with hasTesting: () => false, and a require that throws. Assert each is an Err of kind internal, and that Cipher.create() and testCipher() resolve rather than reject. The cached loaded needs a reset hook for this.

# `createTesting`: a cipher over the engine's deterministic test keys, for
# `@cipherstash/recipher/testing`. The debug build (`build:debug`) has it;
# the release build (`build:native`) does not.
testing = ["recipher-js/testing"]

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 only thing that keeps the deterministic test keys out of a release addon is that build:native does not pass --features testing. Today that holds. I ran cargo build --release -p recipher-js-node and loaded it in Node: it exports no createTesting, and hasTesting() is false. cargo tree -e features shows stack-encrypt/test-support arrives only through this feature.

But nothing in CI checks it. Every CI build turns the feature on: test:cargo uses --all-features, and the workflow builds with build:debug. Both builds also write the same recipher.node. So a later change that brings test-support into the default build would ship a test cipher with no failure, for example testing added to default, or a normal dependency on stack-encrypt with test-support.

Fix: add a test next to no_build_of_the_core_links_eql_bindings that runs cargo tree --locked -p recipher-js-node -e features --prefix none with default features. It fails if the output lists stack-encrypt feature "test-support" or recipher-js feature "testing". It needs no build.

ciphertext: Ciphertext<T>,
defaultKeyset: boolean,
): Promise<Result<T, RecipherError>> {
if (!(ciphertext instanceof Ciphertext)) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Question. instanceof Ciphertext ties a ciphertext to one copy of the class. The ESM and CJS builds are separate copies. So in a process that loads both (an ESM app with a CJS dependency that also imports the SDK), one refuses the other's ciphertext. I checked against the tsup output: a Ciphertext.fromBytes from dist/index.cjs, decrypted with a cipher from dist/testing.js, gives Err(recipher::not_a_ciphertext). It is an Err, not a throw. But the message says the argument is not a Ciphertext when it is.

Is that acceptable for the pre-release? If not, two options: a brand check, such as a Symbol.for('@cipherstash/recipher/Ciphertext') property, in place of instanceof; or a CJS entry that re-exports the ESM build, since Node 22.12+ has require(esm). The same applies to the Cipher a ./testing caller gets from the other format.

},
Error::Config(_) => Kind::Credential,
Error::KeysetLoad { .. } | Error::NoKeyset => Kind::Zerokms,
Error::Aead | Error::OpenedType { .. } | Error::NotOpened | Error::UnsupportedShape => {

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. NotOpened means a field declared decryptable was not opened by its DecryptField implementation. UnsupportedShape means a destination does not accept the encrypted output shape. Both are bugs in an implementation, not a ciphertext that failed to open, so internal fits better than open. Likewise, KeysetMismatch (line 143) means two merged pendings were confined to different keysets. That is a caller-side mistake, not a ciphertext from another keyset, so foreign_keyset misleads. None is reachable in step 1. It is worth fixing before records (#1776) can reach them.

Comment thread .github/workflows/tests-recipher-js.yml Outdated
with:
workspaces: languages/typescript/packages/recipher-js -> target

- uses: pnpm/action-setup@v6.1.0

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. pnpm/action-setup (here) and actions/setup-node (line 97) are pinned by tag. The other actions in this file are pinned by SHA. The repository already uses SHA pins for both: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 and actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0.

/// `Debug` names the type and hides the value.
pub struct Plaintext(pub(crate) ValueFrame);

impl std::fmt::Debug for Plaintext {

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.

Just use vitamin C opaque debug, please.

coderdan added a commit that referenced this pull request Nov 24, 2026
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.
One napi-rs 3 crate, recipher-js, defines the Cipher, Keyset and
Ciphertext classes and runs encrypt and decrypt of one string through the
engine. @napi-rs/cli v3 builds it 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, so no call throws.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant