Repository navigation
Conversation
|
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: true |
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.
| export function fromThrown(thrown: unknown): RecipherError { | ||
| if (thrown instanceof TypeError) { | ||
| const code = codeOf(thrown) | ||
| if (code?.startsWith('ERR_')) { |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
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"] |
There was a problem hiding this comment.
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)) { |
There was a problem hiding this comment.
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 => { |
There was a problem hiding this comment.
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.
| with: | ||
| workspaces: languages/typescript/packages/recipher-js -> target | ||
|
|
||
| - uses: pnpm/action-setup@v6.1.0 |
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
Just use vitamin C opaque debug, please.
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.
2232e04 to
845303d
Compare
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 onestringand decrypt it again on Node, through the Stack Encrypt engine (the Rust cratepackages/stack-encrypt). No call throws and no promise rejects: every call resolves to aResult.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, atlanguages/typescript/packages/recipher-js/crate, in a detached Cargo workspace with its ownCargo.lock(the rootCargo.tomlexcludes it).Cipher(Cipher.create(),defaultKeyset(),decrypt),Keyset(encrypt,decrypt) andCiphertext(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.ValueFramefor a value,stack_encrypt::Ciphertextinside theCiphertextclass, the engine's errors mapped once into the JS error object. Types that hold a secret or a ciphertext derive vitaminc'sOpaqueDebug. 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'skeyset.encrypt(value)takes).vitaminc-aead-napi(JsRef::to_frame,JsBuilder::build). When vitaminc refuses a value, the crate turns that into anErrof kindvaluewith a code of its own (recipher::unpaired_surrogate,recipher::not_plain, …), keeps vitaminc's ownERR_*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 toErr(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/cli3.10.12 builds the addon (build:debug,build:native) and writesnative.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 noonlyBuiltDependenciesentry (the install reports only the existingesbuildscripts as ignored). It adds 97 package versions topnpm-lock.yaml, 46 of them per-platform binaries of@napi-rs/lzma,@napi-rs/tarand@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 generatedRecipherErrorFields. It is in TypeScript because an error has to exist when the native build did not load.src/binding.ts: the loader, andadapt, which replaces each method on the native classes with a getter that returns the method bound to its instance and its outcome turned into aResult. 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(rootpnpm test): theResult, error and loader/adapter suites, the script-wiring suite, andtscover 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 --checkand clippy..github/workflows/tests-recipher-js.yml: one Linux job,test:cargo,build:debug, a drift guard that fails when the build changesnative.d.tsorCargo.lock, andtest:addon. Every action is pinned by SHA.AGENTS.md(repository layout, Cargo workspaces),SECURITY.md(package list),biome.json(the generatednative.d.tsis not formatted by Biome).What the tests prove
keyset.decrypt::<String>, and the crate opens what the engine'skeyset.encrypt(String)sealed.Sendand'static. napi'sspawn_future_with_callback, which requires it, compiles over them.crate/tests/boundaries.rs): it names noLabelorIntoLabel;cargo tree --lockedshows noeql-bindings; and with its default features (the release build)cargo tree -e featuresshows neither the crate'stestingfeature nor the engine'stest-support. I checked that the last test fails whentestingis added todefault.['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 anErr.Errpaths, against fake builds: a build that does not load, one missing each export, one reporting another binding interface number, one whosebindingInterfacethrows.instanceofholds 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, thengit status: the build left the tree clean.pnpm run build:native(release, default features), loaded in Node:createTestingresolves toErr(recipher::no_testing), andnative.d.tsis unchanged. (Run on the records branch, which has the samecreateTesting.)pnpm run test:addon: 21 passed.pnpm run test: 27 passed,tscclean.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
message, andinternalfor a build that did not load or a fault in driving the engine.Promise, not yet a builder. The builder carries.audit,.withCredentialand.signal, which are step 5.@cipherstash/recipher/testingis left to step 5 or step 10.Errfrom every call, never an exception at import.new Cipher(),new Keyset()andnew 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.
crates/coreandcrates/nodeare now one napi-rs 3 crate,recipher-js, atcrate/. The detached workspace and itsCargo.lockstay.Plaintext(aroundValueFrame), the privateCiphertext,Refusal/Kindand the core crate'sCipherare gone; the crate holdsValueFrame,stack_encrypt::Ciphertextand the engine cipher directly. Hand-writtenimpl Debugblocks are replaced by#[derive(OpaqueDebug)].Cipher,KeysetandCiphertextare#[napi]classes;native.d.tsis generated by@napi-rs/cliv3 and checked for drift in CI.src/native.tsand the TypeScript classes are deleted. TheErrconversion 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 aResultand catches what napi itself throws (a method on the wrong object).Line counts for this step (old branch head
2232e0421, new845303dec): Rust source 722 lines in two crates (651 without test modules) became 1,052 in one (942 without test modules); the TypeScriptsrc/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 anErr) 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.
fromThrownkeeping Node'sERR_*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 isrecipher::threwwith no text of its own. An unpaired surrogate isrecipher::unpaired_surrogate, not napi'sInvalidArg.testCipher(null)rejects: fixed (methods are bound byadapt;options?.seed). Tested.Errpaths 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.a_default_build_has_no_test_cipherincrate/tests/boundaries.rs.instanceof Ciphertextacross 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 RecipherErrorandinstanceof Okstill differ across the two builds (they are TypeScript classes);isOk()andkindwork across both.NotOpened,UnsupportedShapeandKeysetMismatchareinternal.value.rs("use vitamin C opaque debug"): done throughout.Related
Refs #1747 (the plan). #1775 and #1776 are based on this branch.