Skip to content

chore(auth): build the node bindings with napi-rs 3 - #1778

Draft
coderdan wants to merge 1 commit into
nextfrom
chore/napi-rs-3
Draft

coderdan wants to merge 1 commit into
nextfrom
chore/napi-rs-3

Conversation

@coderdan

Copy link
Copy Markdown
Contributor

Summary

@cipherstash/auth and @cipherstash/profile are Node.js packages whose core is Rust, compiled into a native .node file with napi-rs (a Rust library plus a build CLI). This moves both from napi-rs 2 to napi-rs 3, so the repository uses one napi-rs version once the recipher binding (draft #1774) lands, which needs napi-rs 3.

Nothing a user calls changes. The JavaScript API, the hand-written index.d.ts, the loader, the exports map, the six platform packages and the .node file names are the same. The native binary that @cipherstash/auth ships is rebuilt, so this carries an @cipherstash/auth patch changeset.

Changes

Rust

  • napi 2.16.17 to 3.16.2 and napi-derive 2.16.13 to 3.7.1, in both crates.
  • napi-build stays at 2 (2.6.0). There is no stable napi-build 3: the only 3.x release is a yanked beta, and napi-rs 3's own crates build with napi-build 2. The napi-rs migration guide says napi-build = "3", which does not resolve.
  • stack-auth-node: the ThreadsafeFunction API was rewritten in v3. ThreadsafeFunction<T, ErrorStrategy::Fatal> becomes ThreadsafeFunction<T, Promise<R>, T, Status, false>. The false is v2's "Fatal" mode (no error-first argument). The return type is now part of the type, so each call_with_return_value callback receives a Result and passes it on with ?, as the v2 closure did. stack-profile-node needed no source change.
  • New crates in Cargo.lock: ctor 1.0.14 (was 0.2.9), link-section, nohash-hasher, napi-sys 3.4.1, napi-derive-backend 7.0.1, plus convert_case and libloading bumps. All of them are at least 7 days old (the repository's Dependabot cooldown). napi 3.16.3 and napi-derive 3.7.2 were published yesterday and are deliberately not used.

CLI and config

  • @napi-rs/cli ^2 (2.18.4) to ^3 (3.10.12) in both packages. 3.11.0 is the latest, but it was published yesterday, and the 7-day minimumReleaseAge in pnpm-workspace.yaml refuses it; pnpm picked 3.10.12.
  • package.json napi config: name becomes binaryName, and triples: { defaults: false, additional: [...] } becomes a flat targets list with the same six triples. v3 still reads the old keys but prints a deprecation warning on every build. The six triples map to the same platform names and .node file names as before (checked with v3's own parseTriple).
  • The build:debug and build:native scripts are unchanged: napi build [--release] --dts native.d.ts means the same thing in v3.

Release build (_build-auth-artifacts.yml) and its guard

  • --js false becomes --no-js, in the host build and in the Alpine (musl) build. This is the important one. With --platform, napi writes its own generated loader over the committed index.js. In v2, --js false turned that off. In v3, --js false is read as a file path: the build writes a 36 KB loader to a file named false (I ran it). index.js is left alone, so the existing git diff --exit-code check passes, but the new file is untracked and nothing catches it. v3's flag is --no-js. Without either flag, v3 overwrites index.js exactly as v2 did (also checked).
  • The "Verify the build changed no tracked file" step now also fails when the build adds an untracked file (git status --porcelain). The .node output is gitignored, so it does not trip this.
  • scripts/__tests__/auth-build-artifacts.test.mjs now requires --no-js, refuses any --js <path>, requires the added-file check, and reads napi.targets. I checked that it fails against each regression: putting --js false back, having --no-js and --js false together, and removing the added-file check.
  • Other flags: --platform, --release, --target, --strip and --dts keep the same names and meaning in v3. The output is still stack-auth-node.<platform>.node in the package directory, and native.d.ts is still rewritten in place.

Docs

  • AGENTS.md: "napi-rs v2" becomes "napi-rs v3".
  • .changeset/auth-napi-rs-3.md: @cipherstash/auth patch. The six platform packages are in its fixed version group, so they move with it.

native.d.ts, line by line

native.d.ts is the generated typings of the raw binding. The published types entry is the hand-written index.d.ts, which re-exports only TokenResult, AuthResult and AutoStrategyOptions from it and declares everything else itself. native.d.ts is in the tarball but is not in the exports map.

@cipherstash/auth/native.d.ts:

  • Header (cosmetic): /* tslint:disable */ /* eslint-disable */ /* auto-generated by NAPI-RS */ becomes /* auto-generated by NAPI-RS */ /* eslint-disable */.

  • Order and spacing (cosmetic): v3 sorts the declarations (classes, then interfaces and functions, alphabetically) and puts a blank line between them. Every declaration's text, doc comment included, is unchanged except for the three below.

  • TokenResult, AuthResult, AutoStrategyOptions (the three index.d.ts re-exports): unchanged.

  • Real type change, not visible to consumers: the three OidcFederationStrategy callbacks are now typed precisely instead of as any:

    • getJwt: () => any becomes getJwt: (() => Promise<string>) (in create and createWithStore)
    • loadToken: () => any becomes loadToken: (() => Promise<string | undefined | null>)
    • saveToken: (arg: string) => any becomes saveToken: ((arg: string) => Promise<undefined>)

    This comes from the v3 ThreadsafeFunction type carrying its return type. Consumers do not see it: index.d.ts declares OidcFederationStrategy itself, with the wider () => Promise<string> | string signatures, and index.js always passes the native side a Promise-returning wrapper.

@cipherstash/profile/native.d.ts (private package): the header change only.

What behaves differently at runtime

I built a v2 binary from next and a v3 binary from this branch and compared them through the real loader. The class and function names, every static and prototype member with its property descriptor and arity, and the CJS and ESM export names are byte-for-byte identical (a JSON dump of both, diffed). The release binary matches too. Three small differences exist, all in napi itself, all reachable only through the raw native getToken(). index.js's getToken() calls getJwt in JavaScript and does not take this path:

  1. The raw binding calls getJwt with no arguments. v2 passed one undefined. index.js wraps getJwt in () => Promise.resolve(getJwt()), so a user's callback gets no arguments either way.
  2. When getJwt rejects, the failure message reads getJwt rejected: GenericFailure, no session. v2 read ... GenericFailure, Error: no session. v3 reads the error's message instead of converting the error to a string.
  3. A callback that throws synchronously, or returns something that is not a Promise, is still fatal. v2 called napi_fatal_error, which aborts the process. v3 raises it with napi_fatal_exception, an uncaught exception, so an uncaughtException handler can see it. index.js always passes a Promise-returning wrapper, but Promise.resolve(getJwt()) still runs getJwt() synchronously, so a throwing getJwt reaches this path from the raw getToken() only.

Unchanged, and worth knowing: in both v2 and v3, a process that has created an OidcFederationStrategy does not exit on its own while the strategy is alive. The threadsafe functions hold the event loop open. I checked v2 and v3 side by side.

Supply chain

pnpm install (pnpm 10.33.2, minimumReleaseAge honoured) changed pnpm-lock.yaml from 738 to 834 packages: 97 added, 1 removed (@napi-rs/cli@2.18.4).

  • What came in: @napi-rs/cli@3.10.12 and its dependency tree. That is @inquirer/* (16 packages, interactive prompts for napi new), @octokit/* (14, for napi pre-publish), @napi-rs/cross-toolchain, @napi-rs/lzma + 17 platform packages, @napi-rs/tar + 16, @napi-rs/wasm-tools + 13, @emnapi/core / @emnapi/runtime 2.0.0-beta.3 (the CLI's optional peers, a beta), @emnapi/wasi-threads, @napi-rs/wasm-runtime, @tybys/wasm-util, typescript@6.0.3 (a direct dependency of the CLI, separate from the repository's TypeScript 5), js-yaml@5.5.0, es-toolkit, obug and 8 small utilities. The platform packages are prebuilt native binaries selected by os/cpu, so only the host's is installed.
  • No added package has a preinstall, install or postinstall script. I checked every one of the 97 against the registry. Two declare prepare (@tybys/wasm-util, content-type), which npm and pnpm do not run for a registry install. pnpm install reported no new ignored build scripts (the existing esbuild notice is unchanged). Nothing was added to onlyBuiltDependencies.
  • The CLI needs Node ^20.17 || ^22.13 || >=23.5. CI uses Node 22 and the musl image is node:22-alpine.
  • e2e/tests/supply-chain.e2e.test.ts passes.

Verification

Run locally on macOS arm64, Rust 1.94.1, pnpm 10.33.2. mise is not trusted in this worktree, so cargo ran as MISE_DISABLE=1 RUSTUP_TOOLCHAIN=1.94.1 ~/.cargo/bin/cargo.

  • cargo fmt --all --check: clean.
  • cargo clippy --locked --no-deps --workspace --all-targets --all-features -- -D warnings (the CI command): clean.
  • cargo nextest run --locked -p stack-auth-node -p stack-profile-node --all-features: 25 passed.
  • The package test:cargo (cargo test --locked) fails 5 to 6 of the start_paused device-code tests in stack-auth-node. It fails the same way on next with napi-rs 2 (checked, 3 runs each). That is the race AGENTS.md describes for plain cargo test; CI uses nextest.
  • napi build --dts native.d.ts (debug) for both packages, then the drift guard's sequence (pnpm --filter @cipherstash/auth --filter @cipherstash/profile run build:debug) three more times, including once after cargo clean -p of both crates, with v3's target/napi-rs typings cache deleted and both native.d.ts removed first. Both files came out byte-identical every time.
  • The release command, as _build-auth-artifacts.yml runs it for darwin-arm64: pnpm exec napi build --platform --release --target aarch64-apple-darwin --strip --dts native.d.ts --no-js. The output was stack-auth-node.darwin-arm64.node (Mach-O arm64) in the package directory, index.js was unchanged (same SHA), and native.d.ts was identical to the debug build's. I then ran the workflow's next steps: the tree check passed, the binary was moved into platforms/darwin-arm64/, npm pack ran, and the tarball check passed.
  • The release binary, loaded through the real loader's platform-package fallback (require('@cipherstash/auth-darwin-arm64')), in CJS and ESM. A smoke script ran AccessKeyStrategy.create (both arms), beginDeviceCodeFlow (INVALID_REGION), OidcFederationStrategy.create (INVALID_URL) and createWithStore, and the raw getToken() through the threadsafe function, against an unroutable host with both a resolving and a rejecting getJwt. All offline.
  • pnpm --filter @cipherstash/auth --filter @cipherstash/profile test: profile 14 passed, auth 120 passed and 3 skipped (the wasm-inline-result file skips itself without a wasm build), Biome clean. The auth suite also passes against the release binary.
  • pnpm run test:scripts: 96 files, 1597 passed, 29 skipped.
  • pnpm run code:check: no errors (the existing warnings only).

Not run: no test here needs credentials, so none were skipped for that reason. mise run test:integration:* was not run through mise (untrusted). Its steps (a plain cargo build, a copy, vitest) were covered by the runs above.

Before the next auth release

I cannot run release.yml or _build-auth-artifacts.yml. Only the darwin-arm64 leg was reproduced, locally. Before merging a Version Packages PR that releases @cipherstash/auth, dispatch auth-preflight.yml against it. Not verified:

  • The five other targets: darwin-x64 (built on an arm64 macOS runner with an explicit --target), linux-x64-gnu, linux-arm64-gnu, win32-x64-msvc, and above all linux-x64-musl. That one builds inside the Alpine container with pnpm install --frozen-lockfile --ignore-scripts --filter "@cipherstash/auth...", which now installs the larger v3 CLI tree on musl. The CLI's own platform helpers (@napi-rs/lzma, tar, wasm-tools) have linux-x64-musl builds and are not loaded by napi build, but that has not been run.
  • That the Windows build adds no untracked file (for example a .pdb) to the package directory. The new added-file check would fail the leg if it did.
  • The C library check and the musl load test (node -e "require(...)" in Alpine) on a v3-built binary.
  • The macOS -no_fixup_chains linker flag in languages/typescript/packages/auth/.cargo/config.toml. napi 3 still registers exports through ctor (now 1.0), and the locally built v3 binary exports every class, so the flag still applies. Its comment is unchanged.

Review notes

  • Look first at the --no-js change and its comment in _build-auth-artifacts.yml. The v3 failure is quiet: a stray untracked file instead of an overwritten index.js.
  • languages/typescript/packages/auth/src/lib.rs: the ThreadsafeFunction port. The #[napi] factories write the full types instead of the aliases, because napi builds native.d.ts from the type as written and would print the alias name.
  • The recipher packages and branches (feat(recipher-js): walking skeleton of the TypeScript SDK #1774 to feat(recipher-js): records through the engine's Planned #1776) are untouched. That binding has no @napi-rs/cli dependency, and it also pins napi-build = "2".

The repository is moving to one napi-rs version, and the recipher binding
needs napi-rs 3. This moves @cipherstash/auth and @cipherstash/profile from
napi-rs 2 to napi-rs 3: napi 3.16.2 and napi-derive 3.7.1, @napi-rs/cli
3.10.12. napi-build stays on 2 (2.6.0): napi-rs 3 has no stable napi-build 3,
and its own crates build with napi-build 2.

The one Rust change is the ThreadsafeFunction API, which napi-rs 3 rewrote.
`ThreadsafeFunction<T, ErrorStrategy::Fatal>` becomes
`ThreadsafeFunction<T, Promise<R>, T, Status, false>`: `false` is the old
Fatal (no error-first argument, a throwing callback is fatal), and the return
type moves from the closure into the type, so the callback now receives a
`Result` and propagates it with `?` as the v2 closure did.

The CLI changed under the release build. napi v2 turned off its generated
loader with `--js false`; napi v3 reads `--js false` as a path and writes the
loader to a file named `false`, which `git diff --exit-code` does not see
because the file is untracked. The release build now passes `--no-js`, its
tree check also fails on an added file, and auth-build-artifacts.test.mjs
holds both. The package.json napi config moves to v3's `binaryName` and
`targets`, which v3 reads without a deprecation warning; the six target
triples and the binary names are unchanged.

native.d.ts is regenerated: v3 sorts the declarations, changes the header,
and types the three OidcFederationStrategy callbacks precisely instead of as
`() => any`. index.d.ts, the published types entry, re-exports only the three
unchanged interfaces from it, so consumers see no type change.
@changeset-bot

changeset-bot Bot commented Nov 24, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 628a69f

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 19 packages
Name Type
@cipherstash/auth Patch
stash Patch
@cipherstash/stack Patch
@cipherstash/wizard Patch
@cipherstash/ffi-integration-tests Patch
@cipherstash/basic-example Patch
@cipherstash/e2e Patch
@cipherstash/bench Patch
@cipherstash/stack-drizzle Patch
@cipherstash/stack-prisma Patch
@cipherstash/stack-supabase Patch
@cipherstash/test-kit Patch
@cipherstash/prisma-example Patch
@cipherstash/auth-darwin-arm64 Patch
@cipherstash/auth-darwin-x64 Patch
@cipherstash/auth-linux-arm64-gnu Patch
@cipherstash/auth-linux-x64-gnu Patch
@cipherstash/auth-linux-x64-musl Patch
@cipherstash/auth-win32-x64-msvc Patch

Not sure what this means? Click here to learn what changesets are.

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

@coderabbitai

coderabbitai Bot commented Nov 24, 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.

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