Skip to content

feat: unforgeable #[napi] class identity via Node object type tags - #3405

Merged
Brooooooklyn merged 24 commits into
mainfrom
feat/unforgeable-class-type-tag
Jul 20, 2026
Merged

Brooooooklyn merged 24 commits into
mainfrom
feat/unforgeable-class-type-tag

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Jul 18, 2026 •

Copy link
Copy Markdown
Member

🔧 Update — review fixes applied (supersedes the design details below where they differ)

Follow-up commits address the review findings. Where this section differs from the original description below, this section is current.

  • Tag is now content-derived, not address-derived. type_tag() derives the 128-bit tag from FNV-1a-128(crate@version::module_path::ClassName) instead of the address of a per-class static. This makes a class's tag stable across process reload and across two loaded copies of the same addon (matching Node's documented "type tags survive unload/reload" contract) — the address-based tag broke this (two loaded copies rejected each other's valid instances). Per-class uniqueness holds because Rust forbids two items at the same module_path::ident; CARGO_PKG_VERSION is included so different crate versions stay distinct.
  • MaybeTypeTag bound stays vacuous on wasm. It's gated napi8-native (all(napi8, not(wasm))), so wasm addons — where no tag is ever stamped or checked — don't narrow ClassInstance<T> / Reference<T> / new_instance<T> for zero benefit. The default (napi4) build is byte-identical in public API.
  • Method-receiver tag check kept as the portable guard. napi_define_class installs a V8 FunctionTemplate signature that rejects a wrong receiver with Illegal invocation before the native callback — but only on runtimes that honor it. Bun does not: TypeTagA.prototype.getValue.call(new TypeTagB(2)) runs the callback with the foreign receiver, so without a check napi_unwrap hands back the other class's pointer and the blind cast is type-confused (it returned 2 instead of throwing). So unwrap_raw keeps its own validate_type_tag receiver check (napi8 native) — the tag, not V8's signature, is the portable guard. Verified after the fix: wrong receiver throws on both Node (Illegal invocation, V8) and Bun (Value is not an instance of class `TypeTagA`, tag check). (Corrects an earlier revision of this PR that removed this check as "redundant".)
  • wrap_and_tag helper for manual napi_wrap wrappers. Instances created by hand-rolled napi_wrap (bypassing the generated constructor) were never stamped, so their own methods/accessors rejected them. napi::bindgen_prelude::wrap_and_tag::<T>(env, obj, native) wraps + stamps in one atomic step (rolls the wrap back if tagging fails, so a caller's error-path free can't leave a dangling wrap).
  • Finalizer hardening. raw_finalize_unchecked removes its REFERENCE_MAP entry before running user finalize() and unconditionally (even on Err), so an errored finalize can't leave a stale entry keyed on just-freed memory.
  • Optional #[napi(type_tag = "…")] salt override. The content tag keys on crate@version::module_path::ClassName, so two unrelated addons sharing an identical crate name+version+module+class would derive the same tag. A class can opt into a crate-unique salt (e.g. a UUID) that replaces the crate@version component — module_path + class name still apply, so the salt only needs crate-level uniqueness and can never cause an intra-crate self-collision. Compile-time constant (dual-load stays stable), runtime-only (never emitted to TypeScript), default output byte-identical.

⚠️ Semver (minor source break under napi8): code generic over an unbounded T using ClassInstance<T> / Reference<T> now needs T: MaybeTypeTag under napi8 (the tag check lives in their FromNapiValue, and JsValue: FromNapiValue propagates it). Inherent; rustc suggests the fix directly. Default napi4 is unaffected. Release napi + napi-derive-backend + macro in lockstep.

Out of scope (tracked follow-up, not a gap): all-version coverage (napi4–7 + wasm) is a separate semver-major change — the Node-API type tag is inherently napi8+, so below it (and on wasm) the type-confusion UB is unchanged from before this PR. The only sound all-version defense is a generational-handle validator (hand JS an (slot, generation) instead of a raw pointer, validated in Rust with no FFI); it changes what napi_unwrap returns and depends on the #3357 cross-thread finalize fix landing first. A raw pointer-value registry (stale-entry false-accept under current finalizer ordering) and an instanceof fallback (setPrototypeOf-spoofable) were both evaluated and rejected.


feat: unforgeable #[napi] class identity via Node object type tags

Problem

A #[napi] struct becomes a JS class. Instances are napi_wrap-ed with a raw Box<T> pointer carrying
no type identity. When JS passes such an object back to a #[napi] method as a &T / &mut T parameter,
the derive napi_unwraps it and blind-casts *mut c_void → *mut T with no check that the object is
actually a T:

// generated FromNapiRef, before this PR
napi_unwrap(env, napi_val, &mut wrapped_val)?;
Ok(&*(wrapped_val as *const T))   // wrong class => type-confused cast => UB

So passing a wrapped instance of the wrong class, or a real wrapped instance whose prototype has
been swapped
(Object.setPrototypeOf), reinterprets one Rust type's memory as another — undefined
behavior. #[napi(strict)] inserts an napi_instanceof check, but instanceof is prototype-based and
forgeable: a setPrototypeOf swap passes instanceof while the underlying wrapped pointer is still
the wrong type.

Fix

Stamp every class instance's JS object with a stable, per-class 128-bit Node-API object type tag
(napi_type_tag_object, node-api v8) right after napi_wrap, and verify the tag
(napi_check_object_type_tag) before every blind cast. The tag lives in a V8-side slot — unreachable and
unforgeable from JS, unaffected by prototype manipulation.

What changed

  • napi-sys: add the napi_type_tag struct (unconditional) and the napi_type_tag_object /
    napi_check_object_type_tag externs (under the existing napi8 module).
  • napi runtime: a TypeTag { fn type_tag() -> napi_type_tag } trait (unconditional, so generic
    bounds always type-check) plus tag_object / validate_type_tag helpers.
    • STAMP at the three (and only three) class-instance wrap sites: CallbackInfo::_construct (new X()),
      CallbackInfo::_factory (#[napi(factory)]), and new_instance (by-value return). The generated
      constructor early-returns under ___CALL_FROM_FACTORY, so each instance is wrapped — and therefore
      tagged — exactly once. Stamping happens after the instance is registered, so a tag failure cannot
      leak the reference bookkeeping.
    • CHECK before every class-pointer cast: the derive-generated from_napi_ref / from_napi_mut_ref
      (params — the decisive path, since no V8 signature guards a parameter), the method receiver
      unwrap_raw, ClassInstance<T>, Reference<T>, and the field accessor.
  • napi-derive-backend: emit impl TypeTag for #name whose type_tag() derives the 128-bit tag from
    the address of a per-class static anchor (a writable, non-mergeable AtomicU8). A static's
    address is unique to that class within the process and distinct across separately-loaded addons (each
    maps its statics at distinct addresses), so the encoding is injective — two distinct Rust classes get
    distinct tags by construction, with no possibility of collision (no nominal identity, no hashing, no
    birthday bound). The tag only needs per-process uniqueness, since the stamp and the check read the same
    anchor address in the same process. Inject the tag check into the generated from_napi_ref /
    from_napi_mut_ref.

Feature gating (and default-build compatibility)

Only active under napi8 (node-api v8+) on native targets. The TypeTag trait and the generated
impl TypeTag are unconditional; the tag_object / validate_type_tag helper bodies are gated
all(feature="napi8", not(target_family="wasm")) (a no-op returning Ok(()) otherwise; see Native-only
below). They are deliberately defined and called unconditionally: a
#[cfg(feature="napi8")] placed inside derive output would resolve against the consumer crate's
features (which do not include a napi8 feature), silently compiling the check out. Keeping the gate
inside the napi crate is what makes the generated param check actually take effect.

To avoid narrowing the default (napi4) public API, the T: TypeTag bounds on the runtime generics
(ClassInstance<T>, Reference<T>, CallbackInfo helpers, …) go through a cfg-split marker trait
MaybeTypeTag: under napi8 it is a supertrait alias for TypeTag (so the bodies can name
T::type_tag()); under napi4 it is blanket-implemented for every T, making the bounds vacuous and the
public signatures byte-identical to before this PR. #[napi(strict)] / the existing napi_instanceof
validate are left untouched; the tag check is the new always-on (within napi8) enforcement layer.

Tests

examples/napi/__tests__/type-tag.spec.ts (+ examples/napi/src/type_tag.rs):

  1. Normal usage still works across all three construction paths (new, factory, by-value return),
    including &T and &mut T params.
  2. Wrong-class argument throws a catchable error instead of a type-confused cast.
  3. Receiver spoof (ClassA.prototype.method.call(classBInstance)) throws a catchable error.
    (napi-rs registers classes with napi_define_class, whose V8 method signatures already reject a spoofed
    receiver before the native callback runs; the receiver tag check is defense-in-depth behind that.)
  4. Prototype-spoofed argument — a real wrapped ClassA re-parented onto ClassB.prototype (so
    instanceof ClassB passes) is still rejected as a &ClassB argument. This is exactly the hole
    instanceof / #[napi(strict)] cannot close.
  5. Subclassing still works — class Sub extends ClassA {} instances pass the ClassA tag check.
  6. Cross-namespace non-collision — two classes sharing a js_name in different namespaces get
    distinct tags; a wrong-namespace instance is rejected by a non-strict method (i.e. by the tag
    alone).

Plus backend/runtime unit tests proving two distinct Rust classes get distinct tags — including two
classes with the same js_name in the same namespace (different Rust types → distinct per-class anchor
statics → distinct tags) — and that type_tag() is deterministic.

yarn workspace @examples/napi test: 236 passed. cargo test -p napi-derive-backend, cargo build -p napi --features napi8, the default (napi4) build, and --workspace all compile clean; cargo fmt --check, cargo clippy, and yarn lint are clean.

Compatibility / notes

  • Default (napi4) builds are byte-for-byte unchanged in behavior and public API surface (via the
    MaybeTypeTag marker). The feature is only active on napi8+ native targets.
  • Native-only. Tagging is gated to not(target_family = "wasm"). A static's address is a
    process-global identity on native, but only an instance-local linear-memory offset on wasm (two
    instances of the same wasm addon would share offsets), and Node-API type-tag support on wasm/emnapi is
    host-dependent. So on wasm the stamp/check are a no-op and the binding keeps its pre-tag behavior
    (no worse than before this PR, no unresolved-symbol risk). A wasm story that mixes in a host-assigned
    module-instance identity is a follow-up.
  • napi_type_tag_object errors on an already-tagged object; the verified single-wrap-per-instance
    invariant guarantees each object is tagged exactly once.
  • Known pre-existing issues, not addressed here (candidate follow-ups):
    • AbortSignal::from_napi_value (and onabort) call napi_remove_wrap and cast the payload to
      AbortSignalStack with no discriminator — a different wrap domain than the #[napi] class Box<T>
      this PR tags, so a class instance passed there is still blind-cast. Pre-existing; a follow-up could tag
      that wrap domain too.
    • ___CALL_FROM_FACTORY is a single non-reentrant thread-local bool: new_instance restores it only
      after a fallible call (an error leaves it stuck), and a nested factory clears an outer factory's flag.
      Pre-existing; a scoped, target-aware RAII guard would fix it. This PR's tagging runs only after the
      flag is restored, so it neither causes nor worsens the issue.
    • Relatedly, gen_default_ctor (struct-level #[napi(constructor)]) does not honor
      ___CALL_FROM_FACTORY, so a class combining a struct-level constructor with a #[napi(factory)]
      double-wraps and throws at the second napi_wrap. Fixing it correctly depends on the reentrant-flag
      rework above, so it is left as a follow-up rather than bundled here.

🤖 Generated with Claude Code

https://claude.ai/code/session_019xA5HenM3skp8FwqRvjNXo


Note

High Risk
Touches every class unwrap/wrap path and changes generic bounds (T: MaybeTypeTag under napi8); mistakes could break addons or leave type-confusion holes, though default napi4/wasm behavior is unchanged.

Overview
Adds Node-API object type tags so #[napi] class instances are stamped after wrap and checked before every blind napi_unwrap cast, turning wrong-class / prototype-spoofed / method.call(wrongThis) inputs into catchable errors instead of UB.

Tags are content-derived at compile time (FNV-1a-128 over crate@version::module_path::ClassName, stable across reload and dual-load). Optional #[napi(type_tag = "…")] replaces the crate@version component with a crate-unique salt. The derive emits impl TypeTag plus checks in from_napi_ref / from_napi_mut_ref; runtime stamps in construct/factory/new_instance paths and validates in accessors, ClassInstance, Reference, and method unwrap_raw. Gating lives inside napi (napi8 + native only; no-op on wasm/default napi4) via MaybeTypeTag so public APIs stay unchanged unless napi8 is enabled.

Also adds wrap_and_tag for manual wraps, reorders raw_finalize_unchecked to always clear REFERENCE_MAP before surfacing finalize errors, wires napi-sys type-tag FFI, and adds example/AVA tests (TypeTagA/TypeTagB).

Reviewed by Cursor Bugbot for commit 2505312. Bugbot is set up for automated code reviews on this repo. Configure here.

Summary by CodeRabbit

  • New Features

    • Added native runtime type-tag stamping for #[napi] class instances to preserve correct type identity across construction, wrapping, and by-value returns.
    • Expanded the example surface with new TypeTagA, TypeTagB, and a makeTypeTagA helper to exercise type-tag behavior.
  • Bug Fixes

    • Improved safety by validating type tags during unwrapping and receiver handling, rejecting wrong-class and prototype-spoofed inputs (in supported Node-API native environments).
  • Tests

    • Added/expanded coverage for cross-type misuse, receiver/prototype spoofing, mutable references, subclasses, and by-value factory paths.

Brooooooklyn and others added 11 commits July 18, 2026 12:39
Add a `TypeTag` trait (defined unconditionally) carrying a per-class
128-bit `napi_type_tag`. Stamp every `#[napi]` class instance right after
`napi_wrap` at all three wrap sites (`_construct`, `_factory`,
`new_instance`) and verify the tag before every blind pointer cast:
method receiver (`unwrap_raw`), `ClassInstance<T>`, field accessor, and
`Reference<T>`. This rejects wrong-class / prototype-spoofed objects with
a catchable `InvalidArg` error instead of a type-confused cast (UB).

The `tag_object` / `validate_type_tag` helpers are defined unconditionally
with `napi8`-gated bodies (a no-op on builds without `napi8`), because
they are also invoked from derive-generated code that expands in the
consumer crate where a `#[cfg(feature = "napi8")]` would resolve against
the consumer's features rather than napi's. Default (napi4) builds are
unchanged.
Emit an unconditional `impl TypeTag` for every `#[napi]` class, with the
tag computed at macro-expansion time as an FNV-1a-128 hash of the class
`js_name` (the globally-unique registry key) split into two `u64`
literals. Inject a `validate_type_tag` check into the generated
`from_napi_ref` / `from_napi_mut_ref` so `&T` / `&mut T` params reject a
wrong-class / prototype-spoofed argument before the blind cast.

The check is emitted unconditionally (not `#[cfg(feature = "napi8")]`)
because it expands in the consumer crate; gating lives inside napi's
`validate_type_tag` (a no-op without `napi8`). The existing `strict` /
`instanceof` validation is left unchanged.
Add two `#[napi]` classes (constructed via `new`, `#[napi(factory)]` and
by-value return) and a spec covering: normal usage round-trips; a
wrong-class `&T` argument throws; a receiver spoof throws a catchable
error; a prototype-spoofed argument that would pass `instanceof` is still
rejected by the tag; and subclass instances still pass. Regenerates the
example addon bindings and the type-def snapshot for the new surface.
…le across addons)

The per-class type tag was FNV-1a-128 of the bare `js_name`, so two classes
sharing a js_name (same name in different namespaces, or in two separately
compiled addons loaded in one process) got IDENTICAL tags. A wrapped instance
of one then passed the other's tag check and was blind-cast to the wrong Rust
type -- type confusion / UB that deterministically defeats the feature.

Build the hash input from a stable identity that includes the crate identity
and module: `{CARGO_PKG_NAME}@{CARGO_PKG_VERSION}::{js_mod}::{js_name}`. The
package name/version are read with `std::env::var` (NOT `env!`) so that, at
proc-macro expansion time, they resolve to the *consumer* crate's values rather
than this backend crate's. The tag only needs per-process uniqueness (stamp and
check share the same generated const in the same binary), so this identity is
fully sufficient and closes both the cross-namespace and cross-addon collisions.

Test: two `#[napi]` classes with the same js_name ("CollisionClient") in
different namespaces now get distinct tags; passing one where the other's
`&`-ref is expected throws `not an instance of class`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019xA5HenM3skp8FwqRvjNXo
The `T: TypeTag` bounds added to the runtime generics (`ClassInstance<T>`
JsValue/JsObjectValue/FromNapiValue impls + assign_to_this_with_attributes;
`Reference<T>: FromNapiValue`; `new_instance`; the `CallbackInfo` construct/
factory/unwrap helpers; `ClassAccessorCallbackInfo::unwrap_raw` +
class_accessor_unwrap_this) were unconditional, so they narrowed the public API
even under the default napi4 build (where tagging is a no-op) -- a breaking
change for generic-over-class-`T` downstream code.

Introduce a marker bound `MaybeTypeTag` whose meaning is cfg-split once: under
napi8 it is a supertrait alias for `TypeTag` (so the napi8-only tag calls in the
generic bodies can still name `T::TYPE_TAG`); without napi8 it is a vacuous
blanket impl for every `T`, so the bounds disappear and the public signatures
are byte-identical to pre-change. Every runtime `T: TypeTag` bound becomes
`T: MaybeTypeTag`, and each in-body `tag_object`/`validate_type_tag` call is
gated `#[cfg(feature = "napi8")]` (the private `_construct`/`_factory` helpers
switch too, so a napi4 `MaybeTypeTag`-bound caller can reach them). The
derive-generated `from_napi_ref`/`from_napi_mut_ref` are untouched: they name
`<#name as TypeTag>::TYPE_TAG` on a concrete class (always satisfied) and must
stay unconditional. The `TypeTag` trait + generated impl remain unconditional.

Proof: a generic `fn f<T: 'static>(..) -> Reference<T>` (and the ClassInstance
equivalent) compiles under default napi4 with no TypeTag/MaybeTypeTag bound --
impossible under the old bound.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019xA5HenM3skp8FwqRvjNXo
…ailure

In `_construct`/`_factory` (callback_info.rs) and `new_instance`
(js_values/class.rs) the `tag_object(..)?` call ran BEFORE
`Reference::add_ref(..)` transferred the finalize-`Arc` and the `napi_ref` into
`REFERENCE_MAP`. A tag failure early-returned before `add_ref`, leaking both the
`Arc` (an `Arc::into_raw` never adopted) and the `napi_ref` (never stored, never
deleted).

Move each `tag_object(..)?` to AFTER its `Reference::add_ref(..)` (add_ref does
not depend on the tag). On a tag failure the object is now fully registered, so
GC reclaims value_ref + object_ref + Arc -- no leak.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019xA5HenM3skp8FwqRvjNXo
The per-class type tag was derived from
`format!("{pkg}@{ver}::{module}::{js_name}")` hashed with a plain FNV-1a-128
over the joined bytes. That serialization was non-injective: `(module="a::b",
js_name="c")` and `(module="a", js_name="b::c")` produce identical bytes, and
`None` vs `Some("")` for the module both collapse to `""`. Two distinct classes
could therefore share a tag — exactly the blind cast the tag exists to prevent.
It also could not distinguish two addons built from forks with identical
name+version manifest metadata.

Fixes:
- Replace `fnv1a_128(&str)` with `fnv1a_128_fields(&[&str])`, which hashes each
  component as a little-endian u64 length prefix followed by its bytes, so
  component boundaries are unambiguous and `["a::b","c"] != ["a","b::c"]`.
- Add `CARGO_MANIFEST_DIR` (read via `std::env::var`, like the other vars) as
  the leading identity component so different source trees / forks get distinct
  tags; the same source built twice resolves to the same dir.
- Encode `js_mod` via `encode_js_mod` (`None` -> "n", `Some(m)` -> "s{m}") so
  the no-module case never collides with an empty-string module.
- Do NOT fail closed on empty env: the injective encoding + manifest_dir already
  keep distinct within-process types distinct; an empty pkg only reduces
  cross-addon entropy. Rationale documented inline.

Add a `#[cfg(test)]` unit test proving injectivity of component boundaries,
None-vs-Some("") (and None-vs-Some("n")) module distinctness, and determinism.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019xA5HenM3skp8FwqRvjNXo
…er-type uniqueness

The per-class type tag was derived from string fields (manifest_dir/pkg/
version/js_mod/js_name), which omit the actual Rust type identity: two
distinct Rust classes sharing all five strings (duplicate js_name+namespace
in one addon, or same-path forks) received the same tag -> blind cast -> UB.

Derive the tag from std::any::TypeId instead -- rustc's canonical,
guaranteed-unique-per-type identity (unique across modules, addons, forks,
and feature variants via the crate SVH). napi already bounds every class
type to 'static, so TypeId::of::<T>() is always valid.

- TypeTag: const TYPE_TAG -> fn type_tag() -> napi_type_tag.
- Add unconditional type_tag_from_type_id(TypeId) helper: two fixed-seed
  DefaultHasher passes with distinct salt bytes -> deterministic 128-bit tag.
- Derive emits impl TypeTag { fn type_tag() { OnceLock cache ->
  type_tag_from_type_id(TypeId::of::<Name[<'static>]>()) } }; delete the
  fnv1a_128 / encode_js_mod string machinery and its unit tests.
- Replace every T::TYPE_TAG / <Name as TypeTag>::TYPE_TAG with the method
  call at the runtime stamp/check sites and in the generated ref accessors.
- Tests: two #[napi] classes sharing the SAME js_name AND namespace now get
  distinct tags; plus TypeId distinctness + determinism.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019xA5HenM3skp8FwqRvjNXo
The TypeId-based tag had two real defects: `impl Hash for TypeId` hashes
only the lower 64 bits, capping entropy at 64 bits and letting distinct
classes with a colliding TypeId-half share a tag deterministically; and
TypeId is nominal, so two separately-compiled same-metadata addon builds
can share a TypeId, colliding across addons.

Derive the tag instead from the address of a per-class `AtomicU8` static.
The address is process-unique by construction (distinct classes have
distinct anchor statics; separately-loaded addons map statics at distinct
addresses) and is fed in injectively as the tag's lower half, so distinct
classes can never collide (no hashing, no birthday bound). AtomicU8 gives
the static interior mutability so it lands in writable data and the linker
never merges two classes' anchors. The body no longer names the class type,
so lifetime classes need no `'static` form for the tag.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019xA5HenM3skp8FwqRvjNXo
The per-class tag is derived from a static's address. That is a
process-global identity only on native targets; on wasm it is an
instance-local linear-memory offset, so two instances of the same wasm
addon map their anchor statics at identical offsets and receive identical
tags, defeating cross-instance uniqueness. Node-API type-tag support on
wasm/emnapi is also host-dependent (the extern may be unresolved).

Gate the real bodies of `tag_object` / `validate_type_tag` to
`all(feature = "napi8", not(target_family = "wasm"))` and widen the no-op
fallbacks to `not(all(feature = "napi8", not(target_family = "wasm")))`.
On wasm the binding reverts to its pre-tag behavior (blind cast, or
`instanceof` under `strict`) — no worse than before, and no
unresolved-symbol risk. Native tagging is unchanged and still active.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019xA5HenM3skp8FwqRvjNXo
@cursor

cursor Bot commented Jul 18, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_8b8acee7-e1a1-4eb5-b930-22ee24fe53fe)

@coderabbitai

coderabbitai Bot commented Jul 18, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds content-derived per-class N-API type tags, stamps created objects, validates tags before native casts, updates wrapping and cleanup paths, and adds runtime coverage for wrong-class, spoofed-prototype, namespace-collision, manual-wrap, and subclass scenarios.

Changes

Type-tag validation

Layer / File(s) Summary
Type-tag contract and N-API bindings
crates/napi/src/bindgen_runtime/type_tag.rs, crates/sys/src/*, crates/napi/src/bindgen_runtime/mod.rs
Defines content-derived tags, N-API stamping/checking helpers, cfg-specific fallbacks, native bindings, rollback wrapping, and cleanup ordering.
Generated bindings and runtime validation
crates/backend/src/codegen/struct.rs, crates/napi/src/bindgen_runtime/*
Generated classes implement TypeTag; construction stamps objects and reference, receiver, accessor, and class conversions validate tags before casting.
Example classes and binding surface
examples/napi/src/*, examples/napi/index.*, examples/napi/example.wasi.*, examples/napi/__tests__/__snapshots__/*, examples/napi-cargo-test/src/lib.rs
Adds tag-aware classes, collision fixtures, declarations, forwarded exports, module wiring, and atomic manual wrapping.
Type-tag regression coverage
examples/napi/__tests__/type-tag.spec.ts
Tests deterministic and distinct tags, valid conversions, spoofing rejection, manual wrapping, and subclass behavior.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant JavaScript
  participant GeneratedBinding
  participant BindgenRuntime
  participant NAPI
  JavaScript->>GeneratedBinding: construct or pass class value
  GeneratedBinding->>BindgenRuntime: create or convert class instance
  BindgenRuntime->>NAPI: stamp or check napi_type_tag
  NAPI-->>BindgenRuntime: success or invalid argument
  BindgenRuntime-->>GeneratedBinding: native reference or error
Loading

Possibly related PRs

  • napi-rs/napi-rs#3364: Shares the class accessor runtime layer updated here for type-tag validation.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: adding unforgeable #[napi] class identity via Node object type tags.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/unforgeable-class-type-tag

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cf176747a5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Brooooooklyn and others added 2 commits July 18, 2026 23:20
… targets (Codex P2)

The `MaybeTypeTag` marker and the seven generic `T::type_tag()` stamp/check
call sites were gated on bare `feature = "napi8"`, so on wasm+napi8 the
marker forced `T: TypeTag` and the call sites compiled `T::type_tag()` while
invoking the (already no-op-on-wasm) helpers. That gratuitously narrowed the
public generic API (`Reference<T>`, `ClassInstance<T>`, `new_instance<T>`, the
`CallbackInfo`/class-accessor helpers) for wasm manual-class-wrapper users,
even though tagging does nothing on wasm.

Move the marker AND all seven call sites to the same native-only predicate
that already gates the real helper bodies:
`all(feature = "napi8", not(target_family = "wasm"))` (and the negation for
the vacuous marker variant). The marker and the six/seventh call sites must
move together: a vacuous marker with call sites still under bare `napi8`
would leave `T::type_tag()` unresolved on wasm+napi8. Net effect: on
wasm+napi8 the stamp/check sites compile out (helpers were no-ops there
anyway) and `MaybeTypeTag` is vacuous, so the generic public API is
byte-identical to the pre-tag / napi4 surface. Native napi8 is unchanged.

The derive-injected `<#name as TypeTag>::type_tag()` check in
crates/napi-derive-backend stays unconditional: it names the concrete type
(whose `impl TypeTag` is unconditional) and calls the no-op helper on wasm.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019xA5HenM3skp8FwqRvjNXo
Object type tags are a native-only guarantee: on wasm `tag_object` /
`validate_type_tag` are no-ops (the per-class anchor address is an
instance-local linear-memory offset, not a process-global identity, and
Node-API type-tag support on wasm/emnapi is host-dependent). So wrong-class,
receiver-spoof, prototype-spoof and same-js_name-collision arguments are not
rejected on wasm, and the four rejection assertions fail there.

Gate only those four negative tests to native via the repo's
`process.env.WASI_TEST` idiom (`const napi8NativeOnlyTest = process.env
.WASI_TEST ? test.skip : test`); the two positive round-trip tests keep
running everywhere. Native assertions are unchanged, and no wasm branch
asserts a blind-cast return value.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019xA5HenM3skp8FwqRvjNXo
@cursor

cursor Bot commented Jul 18, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_e86f95e5-a4aa-41a5-b38f-05130fe0d92e)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a0d9777bb9

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread examples/napi/index.d.cts Resolved
… by same-namespace assert_ne)

The two cross-namespace fixtures `AlphaCollision` / `BetaCollision` (both
`js_name = "CollisionClient"`, in namespaces `tag_collision_alpha` /
`tag_collision_beta`) exposed a PRE-EXISTING napi typegen bug: constructor
metadata is keyed by the bare `js_name` rather than `js_mod` + `js_name`, so the
generated `index.d.cts` was wrong (alpha non-constructible, beta with a
duplicated constructor). That typegen bug is unrelated to this type-tag PR and
is tracked separately.

The cross-namespace runtime check they backed is redundant: napi-cargo-test's
`SameNameOne` / `SameNameTwo` share the SAME `js_name` AND the SAME namespace
(`dup_tag`) and already `assert_ne!` on their `type_tag()`s -- strictly stronger,
since the address-based tag design makes js_name / namespace irrelevant by
construction. No real coverage is lost.

Removes the fixtures, the F1 spec test, and regenerates the example addon
bindings and the type-def snapshot for the trimmed surface.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019xA5HenM3skp8FwqRvjNXo
@cursor

cursor Bot commented Jul 18, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_b764d1d1-d440-465f-a05b-ce512618addc)

Brooooooklyn and others added 6 commits July 20, 2026 19:06
Replace the per-class-static-address anchor with a content-derived
128-bit FNV-1a of `crate@version::module_path::ClassName`. This keeps
the tag stable across process reload and dual-load (Node's documented
type-tag contract) while staying per-class unique because Rust forbids
duplicate `module_path::ident`.

`type_tag_from_ident` is a `const fn` so the derive-generated
`type_tag()` folds at compile time in every build, including default
napi4. Adds a golden known-vector unit test locking the wire value.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01XGgSCpV5sXobAnTALyZUaz
…(B2)

Change the `MaybeTypeTag` marker cfg from
`all(feature="napi8", not(target_family="wasm"))` to `feature="napi8"`,
so napi8 native and napi8 wasm present the identical `: TypeTag` bound.
The tag *bodies* (`tag_object`/`validate_type_tag`) stay
napi8-native-only and remain no-ops on wasm, so naming `T::type_tag()`
on wasm is harmless. Under napi4/no-napi8 the marker stays vacuous, so
the default public API is byte-identical to the pre-tag baseline.

Deviation from plan Task 2b: the three `MaybeTypeTag` bounds on
`ClassInstance` (JsValue/JsObjectValue impls and
`assign_to_this_with_attributes`) are NOT collateral — they are
transitively required under napi8 because `JsValue: FromNapiValue` and
`FromNapiValue for ClassInstance<T>` (the load-bearing site the plan
keeps) needs `T: MaybeTypeTag`. Removing any of them breaks the napi8
build, so they are retained with clarifying comments. Under napi4 they
are vacuous, so no un-narrowing was lost.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01XGgSCpV5sXobAnTALyZUaz
napi-rs registers class methods via `napi_define_class`, whose instance
methods carry a V8 FunctionTemplate signature bound to the constructing
template. A spoofed receiver (`ClassA.prototype.method.call(new ClassB())`)
is therefore rejected by V8 with "Illegal invocation" before the native
callback runs, making the `validate_type_tag` check on `self.this`
redundant on the hottest per-method path — net one fewer FFI per method
call. The V8-unguarded surfaces (field accessors, `&T`/`&mut T` params,
`ClassInstance`/`Reference` conversions) keep their own tag checks.

The `T: TypeName + MaybeTypeTag` bound on `unwrap_raw` is left intact so
signatures stay byte-stable across builds. Updates type-tag.spec test #3
comment: V8's signature is now the sole receiver guard; the test asserts
only that a catchable Error is thrown (not its message).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01XGgSCpV5sXobAnTALyZUaz
…tch (#4)

Add a documented, cfg-uniform public `wrap_and_tag<T: TypeTag>` helper:
it does `napi_wrap` + `tag_object` in one step so hand-rolled wrappers'
own V8-unguarded field accessors and `&T` params pass the tag check
instead of throwing "Value is not an instance of class". The tag stamp
is the same no-op as `tag_object` on non-napi8 builds and on all wasm
targets, so the helper is a bare `napi_wrap` there; its `T: TypeTag`
bound compiles on every target (the derive's impl is unconditional).

Route the `create_reentrant_borrow_order_test_target` fixture through
the helper (preserving its None-finalizer + drop-on-failure contract),
and add a native-only regression test asserting a manually-wrapped
instance round-trips its own `values` accessor. Verified TDD: the test
fails pre-stamp ("Value is not an instance of class
`ReentrantBorrowOrderTest`") and passes post-stamp.

Also refresh the now-stale wasm rationale in the `tag_object` /
`validate_type_tag` docs (they referenced the removed anchor-address
mechanism) to the content-derivation + host-dependent-extern reasoning,
and point manual wrappers at `wrap_and_tag`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01XGgSCpV5sXobAnTALyZUaz
#1)

Reorder `raw_finalize_unchecked`: take the payload box, remove the
`REFERENCE_MAP` entry, run the user `finalize()`, run the reference
bookkeeping (Arc release + `napi_delete_reference`), then throw the
finalize error LAST. Previously an errored `finalize()` early-returned
before removing the map entry, which could leave a stale entry keyed on
the just-freed pointer. The success path behaviour is unchanged; only
the `Err` path now also releases the map entry + napi_ref instead of
early-returning. Pure hardening (path is unreachable via the normal
public API today).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01XGgSCpV5sXobAnTALyZUaz
The manual-wrap helper wrapped `native` into `js_obj` and then stamped the
type tag as two independent steps. If `napi_wrap` succeeded but
`napi_type_tag_object` failed (napi8-native, e.g. an already-tagged object),
`wrap_and_tag` returned `Err` with `js_obj` still wrapping `native`. Callers
free `native` on that error (the `None` finalizer means the JS engine never
owns it), so `js_obj` was left holding dangling memory and the next
`napi_unwrap` would be a use-after-free.

Roll back the wrap with `napi_remove_wrap` when tagging fails, so the wrap+tag
is atomic and the caller's error-path free is always sound. On non-napi8 / wasm
`tag_object` is an infallible no-op, so the rollback branch is dead there and
the call remains a bare `napi_wrap`.

Found by the adversarial review of the type-tag fix delta.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01XGgSCpV5sXobAnTALyZUaz
@cursor

cursor Bot commented Jul 20, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_622ce406-200b-4ced-bde0-c69278c1b5d3)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4bc45f54d3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/backend/src/codegen/struct.rs Resolved
Addresses the Codex P2 review comment. Commit e6aadc1 originally gated the
MaybeTypeTag marker to napi8-native (`all(feature="napi8", not(wasm))`) so wasm
addons — where no tag is ever stamped or checked (the tag_object /
validate_type_tag bodies are no-ops on wasm) — do not narrow ClassInstance<T> /
Reference<T> / new_instance<T> for zero benefit. A later refactor unified the
gate to `feature="napi8"` alone, which re-introduced that gratuitous wasm
narrowing. Restore the native-only gate.

Verified: on wasm+napi8 a generic `fn f<T>(&ClassInstance<T>)` compiles with no
`T: MaybeTypeTag` bound; on napi8-native it still (correctly) requires the bound
because the tag check names `T::type_tag()`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01XGgSCpV5sXobAnTALyZUaz
@cursor

cursor Bot commented Jul 20, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_cca04a3c-6bba-4687-8a65-3e8500dd525b)

…rride

Let a `#[napi]` class opt into a crate-unique salt for its content-derived
type tag via `#[napi(type_tag = "SALT")]`. The salt REPLACES the default
`crate@version` identity component (module_path + ClassName still apply), so a
class's tag cannot collide with an unrelated addon that happens to share the
same crate name@version + module path + class name. Absent → unchanged default
`crate@version::module_path::ClassName`. Both forms are compile-time constants,
so the tag stays stable across process reload / dual-load, and module_path +
ClassName still prevent any intra-crate self-collision. Runtime-only; never
emitted into TypeScript.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01XGgSCpV5sXobAnTALyZUaz
@cursor

cursor Bot commented Jul 20, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_e0cec2a8-a100-426f-a2cc-5c43966cf713)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 98b151b08d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

…x P1)

The V8 FunctionTemplate signature that `napi_define_class` installs on
instance methods rejects a wrong receiver with "Illegal invocation" only
on runtimes that honor it. Bun does not: on Bun 1.3.14
`TypeTagA.prototype.getValue.call(new TypeTagB(2))` runs the native
callback with a foreign receiver, so `napi_unwrap` hands back TypeTagB's
pointer and the blind `*mut c_void -> *mut T` cast is type-confused (UB) —
it returned `2` instead of throwing.

Restore the `validate_type_tag` check in `unwrap_raw` (napi8 native only)
so the receiver tag is the portable guard, not V8's signature. Verified:
wrong-receiver now throws on Node ("Illegal invocation", V8) AND Bun
("Value is not an instance of class `TypeTagA`", tag check). The
type-tag spec's receiver-spoof case asserts only that a catchable Error
is thrown, since the message differs by runtime.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01XGgSCpV5sXobAnTALyZUaz
@cursor

cursor Bot commented Jul 20, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_5d12a7ca-31f6-4ae6-ab7e-d4072fa4624d)

@Brooooooklyn
Brooooooklyn merged commit 729ebed into main Jul 20, 2026
78 checks passed
@Brooooooklyn
Brooooooklyn deleted the feat/unforgeable-class-type-tag branch July 20, 2026 13:48
@github-actions github-actions Bot mentioned this pull request Jul 17, 2026
Brooooooklyn added a commit that referenced this pull request Jul 21, 2026
…rebase onto main

Main added the type-tag surface (#3405); the rebase text-merged its
export lines into the threaded WASI loaders but could not update the
embedded artifact-metadata export lists, the wasip1 flavor loaders, or
the binary AVA snapshot. Regenerated via yarn regenerate and a native
values.spec.ts snapshot update so every flavor exports TypeTagA,
TypeTagB and makeTypeTagA consistently.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
Brooooooklyn added a commit that referenced this pull request Jul 21, 2026
…rebase onto main

Main added the type-tag surface (#3405); the rebase text-merged its
export lines into the threaded WASI loaders but could not update the
embedded artifact-metadata export lists, the wasip1 flavor loaders, or
the binary AVA snapshot. Regenerated via yarn regenerate and a native
values.spec.ts snapshot update so every flavor exports TypeTagA,
TypeTagB and makeTypeTagA consistently.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
Brooooooklyn added a commit that referenced this pull request Jul 21, 2026
…rebase onto main

Main added the type-tag surface (#3405); the rebase text-merged its
export lines into the threaded WASI loaders but could not update the
embedded artifact-metadata export lists, the wasip1 flavor loaders, or
the binary AVA snapshot. Regenerated via yarn regenerate and a native
values.spec.ts snapshot update so every flavor exports TypeTagA,
TypeTagB and makeTypeTagA consistently.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda
Brooooooklyn added a commit that referenced this pull request Jul 21, 2026
* test(examples): carry the custom-async-runtime example (moved from the SPI PR during its minimal rewrite)

The example previously lived on the full custom-async-runtime SPI branch.
Its threadless-WASI build and test lanes are this PR's feature proof, so
the example moves here, adapted to the minimal async-runtime SPI:

- the removed napi helpers (spawn_on_custom_runtime,
  spawn_blocking_on_custom_runtime, try_block_on_custom_runtime,
  try_start/try_shutdown_async_runtime, JoinError) are replaced by
  example-local equivalents driven through the backend's own scheduler
- probes of the old lifecycle-hardening machinery (transition barriers,
  reentrancy gates, sticky shutdown, Tokio retirement, terminal
  finalizers, cancellation-order fixtures) are dropped together with
  pure-runtime-lifecycle.mjs, runtime-lifecycle-helper.mjs and
  src/cancellation_order.rs
- assertions now track the minimal SPI semantics: deferred registration
  errors surface on the first runtime-backed operation, a failed start
  rolls back through shutdown without failing the module load, every
  environment registration restarts the backend, and
  within_runtime_if_available stays Tokio-backed in combined builds

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* feat(cli): support non-threaded WASI targets

* feat(cli): migrate WASI loaders to emnapi v2

* fix(cli): always spawn cargo metadata with the host cargo binary

`createCargoMetadataInvocation` honored $CARGO, but $CARGO only overrides
the cargo/cross binary spawned for the actual build. The android-build
tests from main poison $CARGO with a nonexistent path to prove no real
build is spawned, so `cargo metadata` at the start of `buildProject`
failed with 'cargo metadata failed to run' on every native CI lane.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* fix(build): export emnapi v2 env management functions for WASI targets

@emnapi/core v2 acquires `exports.emnapi_create_env` /
`exports.emnapi_delete_env` during `napiModule.init()` and calls the
former to allocate the native environment. Without the explicit
`--export` link args the archive-defined functions are GC'd by wasm-ld
and every WASI addon fails to load with
'TypeError: _emnapi_create_env is not a function' (the 'Test node wasi
target' job failure).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* build: work around [email protected] packaging gaps (TEMPORARY)

The published [email protected] cannot support this PR yet, see
vendor/emnapi/README.md for the exact upstream requirements:

- `lib/wasm32-wasip1/libemnapi.a` is missing entirely, so every
  non-threaded WASI build aborts in `setWasiEnv`.
- `lib/wasm32-wasip1-threads/libemnapi-napi-rs-mt.a` references the env
  cleanup hooks through the `env` import module instead of `napi`,
  producing duplicate imports rejected by
  examples/napi/wasi-cleanup-hook-link/check-imports.mjs.
- The @emnapi/core TSFN plugin and
  napi_get_{typedarray,dataview,arraybuffer}_info capture heap views
  across operations that can grow (and thereby detach) a non-shared wasm
  memory.

Vendor archives rebuilt from the C sources shipped inside the npm
package (vendor/emnapi/build.mjs documents the flags), install them via
postinstall + explicit CI steps (CI installs with --mode=skip-build),
and carry the JS fixes as a yarn patch. Everything is version-pinned and
hard-fails on an emnapi upgrade so the workarounds cannot outlive the
alpha.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* fix(cli,wasm-runtime): restore threadless WASI runtime behavior on emnapi v2

Two behaviors were lost in the emnapi v2 loader migration:

- Single-threaded builds link an emnapi archive whose C async-work and
  threadsafe-function implementations are unconditional
  napi_generic_failure stubs, so module registration died creating the
  Custom GC TSFN. Re-export @emnapi/core's asyncWork/tsfn plugins from
  @napi-rs/wasm-runtime and wire them into every non-threaded loader
  (node cjs, browser, workerd-deferred) and the custom-async-runtime
  fixture loader.
- emnapi v2's Context constructor unconditionally registers a
  process.once('beforeExit') listener on Node that suppressDestroy()
  does not remove. Restore the capture-and-remove machinery in the
  eager node loader and the deferred loader's managed context so
  createInstance never leaves process-level listeners (workerd loader
  contract, checked by the create-npm-dirs workerd test and
  published-emnapi-v2-lifecycle spec).

Regenerate the committed examples/napi loader artifacts and update the
cli test mocks of @napi-rs/wasm-runtime to export the plugin symbols.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* test(examples): align WASI tests and snapshots with the emnapi v2 loaders

- Rewrite the threaded-browser-artifact rollback test against the
  consolidated emnapiContextLifecycle mechanism (the old
  __wasiInitializationWorkers machinery is gone; the new loader keeps
  the same guarantees: workers tracked and terminated on rollback and
  disposal, context destroyed and awaited before worker termination).
- Regenerate the stale values.spec.ts.snap: the emnapi v2 migration
  removed the @emnapi/*-stock devDependencies and updated the .md
  mirror but not the binary snapshot ava actually compares against.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* build: verify vendored emnapi archives against a committed manifest

build.mjs now records manifest.json (pinned emnapi version, wasi-sdk
version, sha512 of every npm-shipped file the archives are built from,
sha512 + ar member list of each archive). install.mjs re-verifies all of
it before copying, on every machine and every CI lane that consumes the
archives, and hard-fails on drift or tampering.

CI does not rebuild the archives byte-for-byte (wasi-sdk is not
provisioned on the consuming lanes, and clang output is only stable
against the exact recorded SDK; a local rebuild with wasi-sdk 32.0
reproduces the committed blobs bit-for-bit). The semantic import-module
property is functionally verified in CI by the cleanup-hook import check
and the native-lane wasip1 build test. Residual risk (a commit that
regenerates blobs and manifest together) is documented in the README.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* test(examples): assert disposal chains context destruction before worker termination

The rollback path already required the generated
Promise.resolve(destroyResult).catch(...).then(finish) chain; the
disposal path only asserted index ordering inside __startWasiDisposal,
which a started-but-not-awaited destroy would satisfy. Require the
thenable chain there too, and document why a destroy rejection
intentionally skips worker termination (disposal retry keeps the
binding alive; executable counterpart in wasi-deferred-dispose-failure).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* docs(wasm-runtime): document the plugin requirement for raw instantiate callers

Raw instantiateNapiModule(Sync) callers instantiating a single-threaded
napi-rs wasm must pass the re-exported emnapi plugins; without them
instantiation fails with a LinkError naming the missing import. Threaded
builds link the C implementations and are unaffected. This mirrors the
upstream @emnapi/core v2 plugin split (v1 bundled the implementations).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* ci: record the vendor/emnapi postinstall in the script-jail lock

The root postinstall now runs `node vendor/emnapi/install.mjs` (vendored
emnapi WASI archive verification + copy), so the committed script-jail
lock drifted and the audit job failed. Regenerate it with the same
pinned tooling and configuration the workflow uses (script-jail v0.2.10,
docker backend, spoof linux/x64).

The new entries are exactly the install script's observed behavior and
nothing broader:
- external_reads: the five vendor/emnapi files plus the two directory
  lookups ($REPO/vendor, $REPO/vendor/emnapi)
- escaped_writes: the two <CROSS_PACKAGE> archive copies into
  $NODE_MODULES/emnapi/lib/wasm32-wasip1{,-threads}/
- spawn_attempts: `node vendor/emnapi/install.mjs`

Verified locally: `check` mode re-runs the sandboxed audit and exits 0
against this lock, and the regenerated content matches the drift diff
from CI run 29182709223 byte-for-byte (modulo the canonicalized
generated_at timestamp).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* fix(build): keep thread-safe functions as JS plugin imports on threaded WASI

The vendored `libemnapi-napi-rs-mt.a` was built from the full `emnapi` gyp
source list, so it contained the C implementations of `threadsafe_function.c`
and `async_work.c`. The linker extracts them (the Rust side references
`napi_create_threadsafe_function` etc.), making TSFN/async-work wasm-local
and silently shadowing the `@emnapi/core` v2 JavaScript plugin protocol that
napi-rs is written against (upstream main links emnapi v1's *basic* flavor,
`emnapi-basic-mt`, for exactly this reason). This broke the browser TSFN
abort tests deterministically on any clean CI build: the test fixture
instruments `importObject.napi.napi_call_threadsafe_function` and the plugin
struct offsets (`wasi-worker-browser.mjs`), but the wasm never imported
those functions, so `releaseBoundedTsfnNativeWait` timed out waiting for
`NATIVE_QUEUE_CONFIRMED` (deferred-abort scenario) and the post-native
scenario drained the bounded queue through the uninstrumented C path.

- vendor/emnapi/build.mjs: build BOTH archives from the `emnapi_basic` gyp
  source list (no `async_work.c` / `threadsafe_function.c` in either
  threading mode) and add the `emnapi_basic` thread sources
  (`src/thread/async_worker_create.c`, `src/thread/async_worker_init.S`) to
  the threaded archive — the async-worker bootstrap the JS `asyncWork`
  plugin needs, matching v1's published `libemnapi-basic-napi-rs-mt.a`
  member list. `crates/build/src/wasi.rs` already exports
  `emnapi_async_worker_create` / `emnapi_async_worker_init` via
  `--export-if-defined` for these.
- cli templates: wire `plugins: [asyncWork, tsfn]` unconditionally — the
  threaded node/browser loaders and both WASI worker templates now provide
  the JavaScript implementations too (previously threadless-only), since
  every thread that instantiates the module must resolve the TSFN imports.
- examples/napi/build.mjs: teach the browser TSFN instrumentation markers
  about the new `plugins:` line and regenerate the committed loaders.

Verified locally: threaded browser suite 26/26 full-suite runs green
(8 tests each, including the two owner-agent TSFN abort tests that failed
twice in CI run 29184777431), node WASI example suite green (296 passed),
custom-async-runtime wasi + wasi-threads + browser fixtures green after a
forced relink, and the napi3/napi4 cleanup-hook import checks pass against
the rebuilt archive. The non-threaded archive rebuilds bit-identically.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* chore(examples,cli): adapt carried surfaces to the minimal SPI base and regenerate artifacts

The minimal async-runtime SPI base (PR #3352 rewrite) removed the fallible
lifecycle helpers, the lifecycle state machine, the TSFN exception-identity
hardening, and the napi_prepare_wasm_env_cleanup wasm hook. Adapt the carried
surfaces accordingly without touching crates/napi:

- examples/custom-async-runtime: spawn/block/blocking wrappers now drive the
  example's own executor directly; lifecycle wrappers call the infallible
  start/shutdown SPI; drop probes that asserted removed crates/napi behavior
  (admission gates, TSFN thrown-value identity, wrap-slot preservation,
  dispose-time settlement of pending promises).
- examples/napi: reduce build.mjs and the WASI specs to the surface that
  exists on the minimal base; regenerate loaders, typings and snapshots.
- cli + crates/backend typegen: adopt the PR #3353 typegen surface coherently
  (Buffer type imports, centralized JSON escaping, iterator typings); the
  wasm env-cleanup call in loaders stays behind a typeof guard so it is a
  no-op until the hook exists.
- examples/napi/src/class.rs: use 'declare class' in ts_return_type so the
  generated d.ts compiles under strict top-level declaration rules.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* test(examples): align explicit-shutdown assertions with the self-healing SPI base

The rebased base restarts an idle backend on the next napi dispatch
(ensure_started) and drains the lazily-created Tokio runtime at shutdown, so
the stopped-runtime rejection and Tokio-backed context-entry assertions no
longer describe the contract. Assert the restart (start metric + resolved
promise) instead, and drop the now-dead stopped-iterator helper.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* test(examples): drop the unused readFileEventually helper

Its callers were removed by the minimal-SPI adaptation commit; oxlint
(--deny-warnings) fails the Lint job on the dead declaration.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* test(examples): re-stop the backend before each restart scenario

The dispatch-driven self-heal grows startCalls before the worker-restart
and explicit-start scenarios run, so comparing them against the older
afterShutdown snapshot could pass even if the scenario started nothing.
Shut the backend down again before each scenario and compare against a
snapshot taken immediately before the action.

Also assert runtimeContextAdd right after the self-heal: since the SPI
base restores the drained Tokio peer on dispatch-driven self-heal, a
successful start leaves both halves live. Calling it after shutdown but
before any dispatch would still abort (inherited semantics).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* test(examples): assert the flavor-specific root artifacts per CI lane

The minimal SPI base no longer merges natively-gated exports (like
fetch) into WASI outputs, so the root index.d.cts only contains
'export declare function fetch(' when the native pass produced it. The
checked-in roots are the native ones (regenerateArtifacts restores
them), but the 'Test node wasi target' job regenerates the roots with
the wasm32-wasip1-threads build right before running this spec, which
drops the export and points browser.js at the threaded flavor. Assert
the state each lane actually produces, keyed off WASI_TEST like the
rest of the suite.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* test(examples): align the workerd dispose scenario with best-effort disposal

The minimal SPI base dropped the env-cleanup preparation hook that
settled pending napi promises before context destroy, so disposal no
longer cancels in-flight promises; awaiting one across dispose() hung
the workerd request until the runtime cancelled it (500), with the wasm
side panicking at deferred.rs 'Call threadsafe function in JsDeferred
failed'. Restoring that hook is a recorded napi-side follow-up.

Reshape /dispose-reload to the contract this base documents: settle
in-flight work before disposing and assert it completed, and keep
pending-across-dispose coverage best-effort by firing a never-settling
call that is recorded but never awaited in the response path. The
scenario still asserts dispose + reload yields fresh exports and that
new calls work. The stranded call may be cancelled or stay pending
forever, but must never resolve with a value and must not prevent
dispose or reload.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* docs(cli): scope the WASI disposal promise-settling to the preparation hook

On the minimal SPI base the generated binaries do not export
napi_prepare_wasm_env_cleanup (crates/build links it with
--export-if-defined), so disposal cannot settle still-pending napi-rs
promises. State the real contract: disposal releases the instance;
pending promises are settled only when the binary exports the
preparation hook (planned napi-side follow-up), otherwise they may
remain pending and callers should settle work before disposing.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* ci: run the native custom-async-runtime lane in the wasi job

The dedicated job only exercised the WASI modes and the example
workspace is excluded from the root yarn test, so the native
duplicate-registration, start-error, worker-reload and termination-loop
scenarios ran nowhere in CI. Build and run the native lane in the same
job before the WASI builds overwrite the shared root artifacts.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* fix(cli): use bigint/string file identity in the filesystem transaction journal

The filesystem-transaction journal captured file and parent dev/ino from a
non-bigint stat() and stored them as JSON numbers, then re-validated them on
recovery with Number.isSafeInteger. On Windows a 64-bit NTFS file reference
(ino) or volume serial (dev) frequently exceeds Number.MAX_SAFE_INTEGER, so the
non-bigint read is imprecise, Number.isSafeInteger returns false, and recovery
throws "Invalid file state in filesystem transaction journal" (flaky under the
400-file crash-recovery test on x86_64-pc-windows-msvc).

Capture dev/ino from stat(..., { bigint: true }) at every journal identity
source (openFileSystemTransactionIdentity, snapshotFileSystemTransactionInput
source/destination, captureTransactionParentIdentity) and persist them as exact
decimal strings, and compare the parent identity with a bigint stat at both the
in-process (assertTransactionParentUnchanged) and recovery
(assertFileSystemTransactionJournalParentUnchanged) checks so capture and
compare share one representation. normalize now accepts either a decimal string
or an exact (safe, non-negative) number and canonicalises both to a string, so
existing numeric journals still recover while imprecise values are still
rejected rather than allowed to false-match a different inode. The mode field
and the reconciliation-lock identity subsystem are unchanged.

No journal version bump: the reader stays backward compatible (numeric journals
canonicalise to the same string form), which the v1/v2/v3 recovery fixtures
require, so nothing is mis-parsed.

Adds deterministic tests that force a >2^53 identity through the
journal+recover path (accept/round-trip and no-false-match), which fail against
the previous Number.isSafeInteger code and pass now.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* fix(cli): use string identity in the transaction cleanup unlink guard

The failed-snapshot cleanup guard in snapshotFileSystemTransactionInput
compared the destination's dev/ino with the lossy Number fields of
lstat(). On Windows two distinct NTFS inodes past 2**53 (e.g. 2**53 and
2**53+1) collapse onto a single JS double, so a successor file that
replaced the transaction-owned pathname could be wrongly unlinked -
destroying a file the transaction never owned. This is the same
"successor replaced our artifact" threat already handled correctly with
string identity in the preparing-artifact cleanup path.

Capture the destination's exact 64-bit identity once from the open
handle (decimal strings) and gate the unlink on that string identity via
the new snapshotLeftoverIsTransactionOwned predicate, re-reading the
current file with a bigint stat. Also convert the source preflight's
expectedStats comparison to exact 64-bit identity (affectedStats now
holds bigint stats) so a Number-colliding external replacement of the
source is detected as a conflict instead of being silently adopted.

The fail-closed change-detection checks that only throw and the
reconciliation-lock subsystem are deliberately left on Number equality.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* fix(cli): re-bind transaction source identity to the opened descriptor

`snapshotFileSystemTransactionInput` validated the source's exact bigint
identity only in the pre-open preflight; the single post-open gate compared
the opened handle's Number `dev`/`ino` against the pre-window Number stat,
not the caller's `expectedStats`. A successor whose 64-bit `dev`/`ino`
collapse onto the same JS double (two distinct inodes past 2 ** 53) swapped
into the pre-open window would be opened, pass the lossy Number check, and be
snapshotted and recorded as the original.

Re-bind the exact identity to the pinned descriptor: after `open`, when
`expectedStats` is provided, `stat({ bigint: true })` the handle and raise a
`fileSystemTransactionConflictError` unless its exact bigint `dev`/`ino`
match. This completes the exact-identity binding 2496eb9 started and cannot
newly accept anything (it only rejects), so callers without `expectedStats`
are unaffected.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* fix(cli): gate transaction retire and recursive removal on exact bigint identity

`fileSystemTransactionStateMatches` authorized `retireFileSystemTransactionState`
(rename to a unique retired path + post-rename revalidation) and, through it,
the recursive `rm(..., { recursive: true })` of the retired tree. It compared
the Number `dev`/`ino` of live `Stats`, so a successor directory whose distinct
64-bit `dev`/`ino` collapse onto the same JS double (past 2 ** 53) passed both
the pre- and post-rename checks and had its entire tree deleted.

The structural mitigation (unique retire path + post-rename revalidation) was
already present; only the comparison precision was lossy. Take `BigIntStats`
and compare exact decimal strings (the pattern 2496eb9 already used for
`pathsReferToSameDirectoryEntry`), and thread `{ bigint: true }` through every
feeder: the candidate, sibling, journal and published captures plus the two
re-reads inside the retire helper. No feeder reads `mode`/`size`/numeric
`dev`, so no coercion is needed.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* fix(cli): preserve failed-snapshot leftovers whose identity fstat failed

2496eb9 hoisted the second (bigint identity) fstat on the exclusively created
('wx') snapshot handle out of the record block so it ran unconditionally, and
folded "no first fstat" and "identity fstat failed" into one condition that
unconditionally unlinked the leftover. When the first fstat succeeded but the
bigint fstat failed (`destinationStats` defined, `destinationIdentity`
undefined), the cleanup deleted a leftover whose ownership it could not prove.

Extract the cleanup decision into a pure `failedSnapshotLeftoverCleanupAction`
predicate and fail closed: only unconditionally unlink when no identity was
ever captured; when the identity fstat failed, PRESERVE the leftover for the
sibling scavenger; otherwise verify exact string identity before unlinking
(owned-branch behavior unchanged).

Also document the inherent two-syscall lstat-then-unlink pathname race in the
owned branch: exact string identity narrows precision false-matches but cannot
close the between-syscall window; a structural retire-by-rename fix is left as
a follow-up rather than attempted in this PR.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* chore: regenerate lockfile and example artifacts after rebase onto main

Reconcile the stacked non-threaded-WASI work with the squash-merged
AsyncRuntime SPI base (#3352) and per-registration cleanup-hook fix (#3400):

- yarn.lock: regenerated so it reconciles main's dependency bumps
  (notably oxc-parser 0.139.0 -> 0.140.0) with the example deps;
  `yarn install --immutable` is now clean.
- examples/napi WASI binding surfaces and the type-def snapshot:
  regenerated so every flavor carries main's createErroringReadableStream
  export (the carried #3353 surfaces predated it).

Produced via `yarn workspace @examples/napi regenerate` and
`ava --update-snapshots`; not hand-edited.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* test: trim internal-tooling test suites to main's baseline

The branch grew ~24k lines of tests for internal tooling: the pre-publish
pipeline, packed-tarball CLI internals, build.mjs orchestration, patched-emnapi
lifecycle guards, and hostile-lifecycle failure injection for the wasi
loaders. Internal tools do not need exhaustive suites; the package manager
already enforces patch application, and the loaders keep one eager and one
deferred before-exit smoke plus the public Buffer API coverage.

Ballooned pre-existing cli specs are restored to main's versions verbatim;
create-npm-dirs/new/artifacts keep only the minimal delta the non-threaded
wasi CLI behavior requires (engine floor, scaffold gitattributes, artifact
source completeness). The test-cli-node-baselines workflow job existed only
to run the deleted raw-cli harness and is removed with its needs entry;
typescript-legacy was only used by deleted typegen additions.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* feat(wasi): consume released emnapi 2.0.0-alpha.3 wasip1 archives

- bump emnapi/@emnapi/core/@emnapi/runtime to 2.0.0-alpha.3 and
  @emnapi/wasi-threads to 2.0.1 (deps + root resolutions); the release
  ships the complete wasip1 archive sets, so the vendored overlay,
  postinstall hook, CI install steps, and the @emnapi/core memory-view
  yarn patch are all removed
- link libemnapi-basic-napi-rs.a for non-threaded wasi (basic
  composition: async work + TSFN stay JS plugin imports) and keep
  libemnapi-napi-rs-mt.a for threads (now the full C composition with
  in-archive async_work/threadsafe_function; only the two env-cleanup
  hooks are imported from the `napi` wasm module)
- CLI preflight checks libemnapi-basic-napi-rs.a for wasm32-wasip1
- .script-jail.lock.yml postinstall profile hand-updated (vendored
  archive reads/writes/spawn removed); the docker-backend audit in CI
  validates it in check mode

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(napi): route remove_env_cleanup_hook through the wasm napi import module

add_env_cleanup_hook resolves through #[link(wasm_import_module =
"napi")] on wasm, but remove_env_cleanup_hook still went through sys,
emitting an env-module import for the same symbol. The emnapi wasip1
archives bind their own cleanup-hook references to the napi module, so
a wasm addon calling remove ended up importing
napi.napi_add_env_cleanup_hook next to env.napi_remove_env_cleanup_hook:
registration and removal targeted different implementations and a
"removed" hook still fired at env teardown.

Mirror the add side: declare the import in the wasm napi extern block
and split Env::remove_env_cleanup_hook into the same native / wasm /
wasm-noop arms.

Verified by extending the wasi cleanup-hook link probe to call remove:
both wasm32-wasip1 and wasm32-wasip1-threads now import exactly
napi.napi_{add,remove}_env_cleanup_hook, with zero env-module hook
imports and no cross-module duplicate imports.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(examples): restore fetch in the committed native binding surfaces

The emnapi alpha.3 commit (a75bfa2) validated the released archives
with a direct `build --target wasm32-wasip1 --profile wasi` run, which
always rewrites index.cjs/index.d.cts (build.mjs passes --js/--dts
unconditionally and only restores the native root outputs under
--regenerate-all). The wasm-flavored metadata lacks the
cfg(not(target_family = "wasm")) items, so `fetch` and `RequestInit`
vanished from the committed files.

The Linux docker test lanes consume these files as committed (they
download only the prebuilt *.node artifacts), so async-exit.js failed at
ESM instantiate ("Named export 'fetch' not found") and index.d.cts no
longer matched the type-def snapshot. Lanes that run a full build
regenerate the files and were unaffected.

Restore the native-build blobs from 41600e7, whose regenerate run
produced them with the rebased CLI; the restored index.d.cts is
byte-identical to the committed ava snapshot content.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(cli): drop the stray brace that disabled the node_modules export guard

resolveLegacyPackageTarget filters require.resolve results so a legacy
main/module/types/browser entry that realpaths into node_modules (for
example a symlinked entry file) is not emitted as a generated root export
target: npm pack never ships node_modules, so such a target is broken for
consumers. The guard's prefix string contained a literal 'node_modules}'
(template typo), making the prefix '<root>/node_modules}/' unmatchable,
so ./node_modules/... targets leaked into the generated exports map.
Remove the stray brace so the guard matches real <root>/node_modules/
resolutions and the original legacy value is preserved instead.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* fix(cli): write the threadless WASI facade exports back to their source map only

planThreadlessWasiRootFacade builds the facade export map from
publishConfig.exports when the package defines one, but
applyThreadlessWasiRootFacade then wrote that map to both the top-level
exports field and publishConfig.exports. Since the applied manifest is
synced back into the real package.json (stageRootReleasePlan ->
syncThreadlessWasiRootFacadeManifest ->
commitPrePublishFileSystemTransaction), the publish-only map clobbered
the package's local/dev exports. Write the facade result back to
whichever map it was built from - publishConfig.exports when that was
the source, top-level exports otherwise - mirroring
reconcileThreadlessWasiRootFacade, which already reconciles the two maps
separately on removal. Packlist validation is unaffected:
collectRootPackagePathReferences walks publishConfig.exports as well.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* fix(cli): compare filesystem identity as bigint across reconciliation and transaction guards

The reconciliation lock/reclaim/candidate subsystem captured and compared
ownership identity on numeric Stats.dev/ino, and the transaction snapshot /
file-identity flows still used numeric stats for their path-vs-handle
continuity checks. Past Number.MAX_SAFE_INTEGER (Windows NTFS file IDs and
volume serials) two distinct filesystem objects collapse onto one JS double,
so a replaced anchor, lock root, lock/reclaim/candidate metadata file, or
snapshot source/destination could pass an ownership or continuity gate it
should fail.

Factor a single statIdentitiesMatch helper over bigint stats and route every
dev/ino comparison in both subsystems through it (or through the decimal
strings already derived from bigint stats). The reconciliation lock key now
interpolates a bigint inode, so it stays exact past 2 ** 53; for inodes at or
below Number.MAX_SAFE_INTEGER the rendered key is unchanged. Non-identity
continuity fields move to their bigint forms (mtimeNs/ctimeNs are strictly
more precise than the float mtimeMs/ctimeMs they replace).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* fix(cli): retire failed-snapshot leftovers by rename before deleting them

The failed-snapshot cleanup guard verified ownership with an lstat of the
destination pathname and then unlinked the same pathname — a TOCTOU window
the code itself documented as a known limitation: a successor swapped onto
the pathname between the two syscalls was deleted even though the
transaction never owned it.

Close the window with the subsystem's existing retire idiom
(retireExactFileSystemTransactionPath /
restoreUnexpectedFileSystemTransactionRetirement): atomically rename the
leftover to a unique process-private sibling, revalidate the retired entry
against the recorded 64-bit decimal-string identity, and unlink only a
revalidated match — the retired name is unreachable to other writers, so
the unlink deletes exactly the revalidated inode. A mismatched entry is
hard-linked back to the destination, or preserved at the retired name when
an even newer successor already reoccupied the pathname.

The race window is covered deterministically in tests through the
onBeforeRetire seam, which swaps a distinct inode onto the pathname between
the ownership pre-check and the retirement rename.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* fix(cli): fall back to the module version export for emnapi v1 packages

emnapi v1 @emnapi/core and @emnapi/runtime do not list ./package.json in
their export maps, so the package.json subpath require threw a bare
ERR_PACKAGE_PATH_NOT_EXPORTED before the descriptive version-mismatch
error could fire for stale installs. Try the package.json subpath first
(works on the pinned 2.0.0-alpha.3) and fall back to the module's own
version export (works on v1).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* ci: do not persist checkout credentials in the custom async runtime wasi job

The job only builds and tests; it never pushes, so the checkout token
does not need to persist in the local git config (zizmor artipacked).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* chore(examples): regenerate WASI artifacts and values snapshot after rebase onto main

Main added the type-tag surface (#3405); the rebase text-merged its
export lines into the threaded WASI loaders but could not update the
embedded artifact-metadata export lists, the wasip1 flavor loaders, or
the binary AVA snapshot. Regenerated via yarn regenerate and a native
values.spec.ts snapshot update so every flavor exports TypeTagA,
TypeTagB and makeTypeTagA consistently.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* fix(cli): reject engines.node ranges disjoint from the WASI Node.js floor

restrictWasiNodeEngine fell back to the entire WASI-supported range when
the declared engines.node was valid but disjoint from it (e.g. ">=21 <22"
or "<20"), so create-npm-dirs and pre-publish published metadata claiming
support for Node.js versions the package explicitly excluded. Fail with an
error naming both ranges instead. Malformed ranges still fall back to the
WASI floor.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

* fix(cli): match generated .d.cts WASI loader typings in GENERATED_WASI_BINDING

The d\.[ct]s branch only matched literal d.ts/d.cs, so the generated
binary.wasi.d.cts / binary.wasip1.d.cts loader typings (already listed in
WASI_CI_ARTIFACT_PATTERNS and written to .gitattributes by this file) were
neither skipped by copyDirectory nor stripped by
updateGeneratedWasiAttributes. Use the d\.[cm]?ts idiom shared with
TYPE_DEF_FILE.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01T34fMrYCf2V13Mg8BKmnda

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Brooooooklyn added a commit to napi-rs/wasm-tools that referenced this pull request Jul 21, 2026
…gs) on native

The derive now stamps and checks Node-API object type tags on native, closing the
prototype-spoof type-confusion (1-C) that strict-`instanceof` alone could not: a real
wrapped instance of the wrong class re-parented via `Object.setPrototypeOf` passes the
prototype-based `instanceof` check but is rejected by the unforgeable, JS-invisible tag
before the `&T` cast. WASI keeps the strict-`instanceof` mitigation (the tag is a
native-only no-op there — a static's address is not a process-global identity on wasm),
so 1-C stays open on wasm until an upstream wasm-safe identity exists.

- Cargo.toml: napi 3.0.0 -> 3.11.0, feature napi6 -> napi8; napi-derive 3.0.0 -> 3.6.0
  (pulls napi-derive-backend 6.0.0, napi-sys 3.3.0 via the lock).
- package.json: engines.node ">= 10.17.0" -> ">= 12.22.0" (napi8 = Node-API v8 floor).
- src/handle.rs: reword the 1-B/1-C doc — 1-C now closed on native, WASI stays strict
  (upstream fix napi-rs/napi-rs#3405, now merged).
- __test__/elements.spec.ts: add one native-only test proving a setPrototypeOf-spoofed
  wrong-class handle (passing `instanceof`) is still rejected by the type tag on native.

Generated index.d.ts / index.js are byte-identical (the tag machinery is internal).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019xA5HenM3skp8FwqRvjNXo
@github-actions github-actions Bot mentioned this pull request Sep 20, 2026
@github-actions github-actions Bot mentioned this pull request Sep 22, 2026
This was referenced Oct 1, 2026
@github-actions github-actions Bot mentioned this pull request Oct 22, 2026
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