@nice-code/commander 0.77.0 → 0.78.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/cli.cjs CHANGED
@@ -4076,6 +4076,7 @@ var StorageAdapter = class StorageAdapter {
4076
4076
  * `true` on localStorage / Durable Object / KV, `undefined` (unknown) on custom methods.
4077
4077
  */
4078
4078
  durable;
4079
+ trackKeysForClearing;
4079
4080
  adapterStorage;
4080
4081
  /**
4081
4082
  * Serializes mutations of the `__usedKeys__` index so its read-modify-write cycles can't
@@ -4091,6 +4092,7 @@ var StorageAdapter = class StorageAdapter {
4091
4092
  this.durable = methods.durable;
4092
4093
  this.keyPrefix = keyPrefix ?? "";
4093
4094
  const _trackKeys = trackKeys ?? true;
4095
+ this.trackKeysForClearing = _trackKeys;
4094
4096
  this.adapterStorage = _trackKeys ? createTypedStorage({ storageAdapter: new StorageAdapter({
4095
4097
  methods,
4096
4098
  keyPrefix,
@@ -4113,12 +4115,14 @@ var StorageAdapter = class StorageAdapter {
4113
4115
  /**
4114
4116
  * Derive a new adapter over the *same* backing store with an extra key-prefix segment appended.
4115
4117
  * Lets an independent namespace (e.g. a second crypto identity) share one underlying storage without
4116
- * key collisions; the derived adapter tracks its own keys for `clearAll`, scoped to the new prefix.
4118
+ * key collisions. Key-tracking policy is inherited: deriving from an intentionally untracked
4119
+ * adapter must not silently create a `__usedKeys__` index.
4117
4120
  */
4118
4121
  withKeyPrefix(extraPrefix) {
4119
4122
  return new StorageAdapter({
4120
4123
  methods: this.implementation,
4121
- keyPrefix: `${this.keyPrefix}${extraPrefix}`
4124
+ keyPrefix: `${this.keyPrefix}${extraPrefix}`,
4125
+ trackKeysForClearing: this.trackKeysForClearing
4122
4126
  });
4123
4127
  }
4124
4128
  async trackUsedKey(rawKey) {
@@ -4543,6 +4547,14 @@ function createInMemoryTofuVerifyKeyResolver() {
4543
4547
  };
4544
4548
  } };
4545
4549
  }
4550
+ const tofuPinStorageKey = async (identity) => {
4551
+ return `pin:${[...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`nice-wire-tofu-v1:${identity}`)))].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
4552
+ };
4553
+ const pinMismatch = () => ({
4554
+ trusted: false,
4555
+ reason: "verify key changed for client identity (pin mismatch)",
4556
+ rejectId: HANDSHAKE_REJECT_ID_PIN_MISMATCH
4557
+ });
4546
4558
  /**
4547
4559
  * Storage-backed trust-on-first-use resolver: pins survive process restarts / Durable Object eviction
4548
4560
  * (e.g. back it with `createDurableObjectStorageAdapter`). Same policy as the in-memory variant — trust
@@ -4557,8 +4569,46 @@ function createInMemoryTofuVerifyKeyResolver() {
4557
4569
  * On an *eventually-consistent* store a stale "absent" read re-pins the **same** verify key the client
4558
4570
  * just presented (it is signature-verified before this runs), so the worst case is a harmless re-write,
4559
4571
  * never a weakened trust decision. Cross-isolate-strong pinning still wants a strongly-consistent store.
4572
+ *
4573
+ * Switching an existing host from `document` to `per_identity` is safe: on each identity's next
4574
+ * contact the legacy pin is honored and migrated to its per-identity record. The reverse switch is
4575
+ * NOT migrated — pins recorded per-identity are invisible to the `document` layout.
4560
4576
  */
4561
- function createStorageTofuVerifyKeyResolver(storageAdapter) {
4577
+ function createStorageTofuVerifyKeyResolver(storageAdapter, options = {}) {
4578
+ if (options.layout === "per_identity") {
4579
+ const identityLocks = /* @__PURE__ */ new Map();
4580
+ return { async resolve({ client, verifyPublicKey }) {
4581
+ const identity = tofuPinKey(client);
4582
+ const storageKey = await tofuPinStorageKey(identity);
4583
+ const operation = (identityLocks.get(storageKey) ?? Promise.resolve()).catch(() => void 0).then(async () => {
4584
+ const existing = await storageAdapter.getJson(storageKey);
4585
+ if (existing == null) {
4586
+ const legacy = (await storageAdapter.getJson("pins"))?.[identity];
4587
+ if (legacy != null) {
4588
+ await storageAdapter.setJson(storageKey, {
4589
+ identity,
4590
+ verifyPublicKey: legacy
4591
+ });
4592
+ return legacy === verifyPublicKey ? { trusted: true } : pinMismatch();
4593
+ }
4594
+ await storageAdapter.setJson(storageKey, {
4595
+ identity,
4596
+ verifyPublicKey
4597
+ });
4598
+ return { trusted: true };
4599
+ }
4600
+ if (existing.identity === identity && existing.verifyPublicKey === verifyPublicKey) return { trusted: true };
4601
+ return pinMismatch();
4602
+ });
4603
+ const tail = operation.then(() => void 0, () => void 0);
4604
+ identityLocks.set(storageKey, tail);
4605
+ try {
4606
+ return await operation;
4607
+ } finally {
4608
+ if (identityLocks.get(storageKey) === tail) identityLocks.delete(storageKey);
4609
+ }
4610
+ } };
4611
+ }
4562
4612
  const storage = createTypedStorage({ storageAdapter });
4563
4613
  return { async resolve({ client, verifyPublicKey }) {
4564
4614
  const key = tofuPinKey(client);
@@ -4571,11 +4621,7 @@ function createStorageTofuVerifyKeyResolver(storageAdapter) {
4571
4621
  return { trusted: true };
4572
4622
  }
4573
4623
  if (existing === verifyPublicKey) return { trusted: true };
4574
- return {
4575
- trusted: false,
4576
- reason: "verify key changed for client identity (pin mismatch)",
4577
- rejectId: HANDSHAKE_REJECT_ID_PIN_MISMATCH
4578
- };
4624
+ return pinMismatch();
4579
4625
  } };
4580
4626
  }
4581
4627
  function createClientHandshake(config) {
@@ -8621,6 +8667,7 @@ var WireAcceptor = class {
8621
8667
  _noneAllowed;
8622
8668
  _handshakeMode;
8623
8669
  _onConnectionBound;
8670
+ _disposed = false;
8624
8671
  _connByClient = /* @__PURE__ */ new Map();
8625
8672
  _clientByConn = /* @__PURE__ */ new Map();
8626
8673
  _levelByConn = /* @__PURE__ */ new Map();
@@ -8647,6 +8694,7 @@ var WireAcceptor = class {
8647
8694
  }
8648
8695
  /** Feed one inbound frame from a connection: keepalive, then handshake/session, then dispatch. */
8649
8696
  receive(connection, frame) {
8697
+ if (this._disposed) return;
8650
8698
  const wireBytes = this._tap != null ? wireFrameByteSize(frame) : 0;
8651
8699
  if (frame === KEEPALIVE_PING) {
8652
8700
  this._tapIn(connection, wireBytes, "keepalive");
@@ -8661,12 +8709,14 @@ var WireAcceptor = class {
8661
8709
  this._sessionFor(connection, security).receive(frame, wireBytes);
8662
8710
  }
8663
8711
  _receivePlain(connection, frame, wireBytes = 0) {
8712
+ if (this._disposed) return;
8664
8713
  this._tapIn(connection, wireBytes, this._laneFor(frame));
8665
8714
  if (this._dispatchProtocolFrame(connection, frame)) return;
8666
8715
  this._lane.onFrame(connection, frame, "none");
8667
8716
  }
8668
8717
  /** Route a decrypted frame from an authenticated connection: protocols first, then the lane. */
8669
8718
  _routeAuthed(connection, bytes, wireBytes = 0) {
8719
+ if (this._disposed) return;
8670
8720
  this._tapIn(connection, wireBytes, this._laneFor(bytes));
8671
8721
  if (this._dispatchProtocolFrame(connection, bytes)) return;
8672
8722
  this._lane.onFrame(connection, bytes, this._levelByConn.get(connection) ?? "authenticated");
@@ -8797,6 +8847,7 @@ var WireAcceptor = class {
8797
8847
  }
8798
8848
  /** Bind + persist a connection's authenticated identity once its handshake completes. */
8799
8849
  _onAuthenticated(connection, auth) {
8850
+ if (this._disposed) return;
8800
8851
  this._bind(connection, auth.client);
8801
8852
  this._levelByConn.set(connection, auth.securityLevel);
8802
8853
  this._lane.onAuthenticated?.(connection, auth);
@@ -8824,6 +8875,7 @@ var WireAcceptor = class {
8824
8875
  * Secure mode never calls this — the handshake binds the authenticated coordinate instead.
8825
8876
  */
8826
8877
  bindPlainConnection(connection, client) {
8878
+ if (this._disposed) return;
8827
8879
  const isNewBinding = this._clientByConn.get(connection)?.stringId !== client.stringId;
8828
8880
  this._bind(connection, client);
8829
8881
  if (isNewBinding) this._persist(connection, {
@@ -8840,6 +8892,7 @@ var WireAcceptor = class {
8840
8892
  * is ignored with a warning — the socket is simply treated as fresh (its client re-handshakes).
8841
8893
  */
8842
8894
  rehydrate(connection, binding) {
8895
+ if (this._disposed) return;
8843
8896
  if (binding.v !== 1) {
8844
8897
  console.warn(`[wire-acceptor] ignored a persisted connection binding of unknown schema version ${JSON.stringify(binding.v)} (expected 1) — treating the connection as fresh (err_nice_wire_connect.binding_version_mismatch).`);
8845
8898
  return;
@@ -8856,6 +8909,7 @@ var WireAcceptor = class {
8856
8909
  this._attachProtocols(connection, new Set(binding.protocols ?? []));
8857
8910
  }
8858
8911
  _persist(connection, binding) {
8912
+ if (this._disposed) return;
8859
8913
  this._bindingByConn.set(connection, binding);
8860
8914
  this._onConnectionBound?.(connection, binding);
8861
8915
  }
@@ -8865,6 +8919,11 @@ var WireAcceptor = class {
8865
8919
  }
8866
8920
  /** Forget a connection (call on socket close) so stale entries don't misroute later traffic. */
8867
8921
  drop(connection) {
8922
+ if (this._disposed) return;
8923
+ this._drop(connection);
8924
+ }
8925
+ /** Internal detach path used once during terminal disposal after public entry points are closed. */
8926
+ _drop(connection) {
8868
8927
  const client = this._clientByConn.get(connection);
8869
8928
  if (client != null && this._connByClient.get(client.stringId) === connection) this._connByClient.delete(client.stringId);
8870
8929
  this._lane.onDrop?.(connection, client);
@@ -8877,6 +8936,7 @@ var WireAcceptor = class {
8877
8936
  }
8878
8937
  /** Send a raw (already lane/protocol-encoded) frame — through the secure session when present. */
8879
8938
  sendTo(connection, frame) {
8939
+ if (this._disposed) return;
8880
8940
  const lane = this._laneFor(frame);
8881
8941
  const session = this._sessionByConn.get(connection);
8882
8942
  if (session == null) {
@@ -8917,6 +8977,20 @@ var WireAcceptor = class {
8917
8977
  bindingFor(connection) {
8918
8978
  return this._bindingByConn.get(connection);
8919
8979
  }
8980
+ /** Quiesce permanently: detach every known connection and ignore late/in-flight traffic. */
8981
+ dispose() {
8982
+ if (this._disposed) return;
8983
+ this._disposed = true;
8984
+ const connections = new Set([
8985
+ ...this._clientByConn.keys(),
8986
+ ...this._sessionByConn.keys(),
8987
+ ...this._bindingByConn.keys()
8988
+ ]);
8989
+ for (const connection of connections) this._drop(connection);
8990
+ }
8991
+ get disposed() {
8992
+ return this._disposed;
8993
+ }
8920
8994
  };
8921
8995
  //#endregion
8922
8996
  //#region ../nice-wire/src/SecureSession/exchangeTicketSeal.ts
@@ -11567,6 +11641,11 @@ var ActionSchema = class {
11567
11641
  * Declare the input schema (JSON-native or with explicit SERDE type param).
11568
11642
  * For non-JSON-native inputs, prefer the 3-argument form below to avoid
11569
11643
  * needing explicit type parameters.
11644
+ *
11645
+ * The schema runs at `request()` AND again on the receiving runtime before the handler executes,
11646
+ * so it must accept its own validated output. Plain validators always do; a `transform` whose
11647
+ * output fails its own input schema will reject valid requests on arrival — type conversion
11648
+ * belongs in the SERDE pack/unpack arguments, not in schema transforms.
11570
11649
  */
11571
11650
  input(options) {
11572
11651
  this.inputOptions = options;
@@ -12940,7 +13019,21 @@ var ActionRuntime = class {
12940
13019
  runningAction._completeWithResult(action.errorResult(castNiceError(err)));
12941
13020
  return runningAction;
12942
13021
  }
12943
- const runningAction = await handlerForAction.handleActionRequest(action, {
13022
+ let validatedAction;
13023
+ try {
13024
+ validatedAction = new ActionPayload_Request({ context: action.context }, action.context.validateInput(action.input), { time: action.time });
13025
+ validatedAction._callSite = action._callSite;
13026
+ } catch (err) {
13027
+ const runningAction = new RunningAction({
13028
+ context: action.context,
13029
+ request: action
13030
+ });
13031
+ runningAction.addUpdateListeners(observers);
13032
+ runningAction._completeWithResult(action.errorResult(castNiceError(err)));
13033
+ this._trySetupReturnDispatch(runningAction);
13034
+ return runningAction;
13035
+ }
13036
+ const runningAction = await handlerForAction.handleActionRequest(validatedAction, {
12944
13037
  ...options,
12945
13038
  targetLocalRuntime: this
12946
13039
  });
@@ -14153,6 +14246,10 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
14153
14246
  drop(connection) {
14154
14247
  this.wireAcceptor.drop(connection);
14155
14248
  }
14249
+ /** Permanently quiesce this acceptor and detach every live/rehydrated connection. */
14250
+ dispose() {
14251
+ this.wireAcceptor.dispose();
14252
+ }
14156
14253
  /** Lane cleanup when the wire acceptor drops a connection (fired with the bound client, if any). */
14157
14254
  _onConnectionDropped(connection, client) {
14158
14255
  if (client != null) {
@@ -15631,18 +15728,55 @@ function createHibernatableWsServerAdapter(options) {
15631
15728
  * carrier factory (`wsAcceptorCarrier`, a WebRTC carrier, the Cloudflare DO helper, …) so the
15632
15729
  * stateful-handle wiring lives in exactly one place.
15633
15730
  */
15634
- function createDuplexCarrierLifecycle() {
15731
+ function createDuplexCarrierLifecycle(limits) {
15635
15732
  let router;
15733
+ let disposed = false;
15734
+ const windows = /* @__PURE__ */ new Map();
15735
+ const maxFrameBytes = limits?.maxFrameBytes;
15736
+ const rate = limits?.rate;
15737
+ if (maxFrameBytes != null && (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes <= 0)) throw new Error("maxFrameBytes must be a positive safe integer");
15738
+ if (rate != null && (!Number.isSafeInteger(rate.maxMessages) || rate.maxMessages <= 0 || !Number.isSafeInteger(rate.windowMs) || rate.windowMs <= 0)) throw new Error("inbound rate limits must be positive safe integers");
15739
+ const frameBytes = (frame) => typeof frame === "string" ? new TextEncoder().encode(frame).byteLength : frame instanceof ArrayBuffer ? frame.byteLength : frame.byteLength;
15636
15740
  return {
15637
15741
  receive(connection, frame) {
15742
+ if (disposed) return;
15638
15743
  if (router == null) throw new Error("acceptor carrier not served yet — pass it to serveChannel() before feeding frames");
15744
+ if (maxFrameBytes != null && frameBytes(frame) > maxFrameBytes) {
15745
+ limits?.onExceeded(connection, "frame_bytes");
15746
+ return;
15747
+ }
15748
+ if (rate != null) {
15749
+ const now = Date.now();
15750
+ let window = windows.get(connection);
15751
+ if (window == null || now - window.startedAt >= rate.windowMs) {
15752
+ window = {
15753
+ count: 0,
15754
+ startedAt: now
15755
+ };
15756
+ windows.set(connection, window);
15757
+ }
15758
+ window.count++;
15759
+ if (window.count > rate.maxMessages) {
15760
+ limits?.onExceeded(connection, "message_rate");
15761
+ return;
15762
+ }
15763
+ }
15639
15764
  router.receive(connection, frame);
15640
15765
  },
15641
15766
  drop(connection) {
15767
+ if (disposed) return;
15768
+ windows.delete(connection);
15642
15769
  router?.drop(connection);
15643
15770
  },
15644
15771
  _activate(liveRouter) {
15772
+ if (disposed) throw new Error("acceptor carrier already disposed");
15645
15773
  router = liveRouter;
15774
+ },
15775
+ _dispose() {
15776
+ if (disposed) return;
15777
+ disposed = true;
15778
+ router = void 0;
15779
+ windows.clear();
15646
15780
  }
15647
15781
  };
15648
15782
  }
@@ -15757,19 +15891,24 @@ function serveChannel(runtime, channel, options) {
15757
15891
  }
15758
15892
  runtime.addHandlers([...options.handlers ?? [], ...acceptors]);
15759
15893
  const soleDuplex = singleDuplex ? duplexCarriers[0] : void 0;
15894
+ let disposed = false;
15760
15895
  const receive = (connection, frame) => {
15896
+ if (disposed) return;
15761
15897
  if (soleDuplex == null) throw new Error(duplexCarriers.length === 0 ? "serveChannel: no duplex carrier to receive on (this server has no socket transport)" : "serveChannel: several duplex carriers — feed each carrier handle's receive() directly");
15762
15898
  soleDuplex.receive(connection, frame);
15763
15899
  };
15764
15900
  const drop = (connection) => {
15901
+ if (disposed) return;
15765
15902
  soleDuplex?.drop(connection);
15766
15903
  };
15767
15904
  const pushToClient = (target, request, pushOptions) => {
15905
+ if (disposed) throw new Error("serveChannel: server disposed");
15768
15906
  const owner = target instanceof RuntimeCoordinate ? acceptors.find((acceptor) => acceptor.ownsLiveConnectionFor(target)) : acceptors.find((acceptor) => acceptor.hasConnection(target));
15769
15907
  if (owner == null) throw new Error("serveChannel: no duplex carrier holds a connection for the push target");
15770
15908
  return owner.pushToClient(runtime, target, request, pushOptions);
15771
15909
  };
15772
15910
  const broadcast = (makeRequest, broadcastOptions) => {
15911
+ if (disposed) throw new Error("serveChannel: server disposed");
15773
15912
  if (!singleDuplex) throw new Error("serveChannel: broadcast requires exactly one duplex carrier — broadcast over a specific acceptors[i] instead");
15774
15913
  acceptors[0].broadcast(makeRequest, {
15775
15914
  runtime,
@@ -15819,20 +15958,32 @@ function serveChannel(runtime, channel, options) {
15819
15958
  upgrade: carrier.upgrade
15820
15959
  });
15821
15960
  }
15961
+ const activeFetch = createActionFetchHandler(runtime, {
15962
+ cors: exchangeCarrier?.cors,
15963
+ onWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => (upgraders.find((u) => u.isUpgrade(request, url)) ?? upgraders[0]).upgrade(request, url),
15964
+ isWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => upgraders.some((u) => u.isUpgrade(request, url)),
15965
+ isActionPath: exchangeCarrier != null ? exchangeCarrier.isActionPath ?? (() => true) : () => false,
15966
+ security: exchangeSecurity,
15967
+ useErrorStatus: exchangeCarrier?.useErrorStatus,
15968
+ logger: options.logger,
15969
+ transportLabel: exchangeCarrier?.carrierLabel
15970
+ });
15971
+ const fetch = (request) => disposed ? Promise.resolve(new Response("serveChannel: server disposed", {
15972
+ status: 503,
15973
+ headers: { "cache-control": "no-store" }
15974
+ })) : activeFetch(request);
15975
+ const dispose = () => {
15976
+ if (disposed) return;
15977
+ disposed = true;
15978
+ for (const carrier of duplexCarriers) carrier._dispose?.();
15979
+ for (const acceptor of acceptors) acceptor.dispose();
15980
+ };
15822
15981
  return {
15823
15982
  acceptors,
15824
- fetch: createActionFetchHandler(runtime, {
15825
- cors: exchangeCarrier?.cors,
15826
- onWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => (upgraders.find((u) => u.isUpgrade(request, url)) ?? upgraders[0]).upgrade(request, url),
15827
- isWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => upgraders.some((u) => u.isUpgrade(request, url)),
15828
- isActionPath: exchangeCarrier != null ? exchangeCarrier.isActionPath ?? (() => true) : () => false,
15829
- security: exchangeSecurity,
15830
- useErrorStatus: exchangeCarrier?.useErrorStatus,
15831
- logger: options.logger,
15832
- transportLabel: exchangeCarrier?.carrierLabel
15833
- }),
15983
+ fetch,
15834
15984
  receive,
15835
15985
  drop,
15986
+ dispose,
15836
15987
  pushToClient,
15837
15988
  broadcast,
15838
15989
  connections
@@ -15882,7 +16033,7 @@ err_nice_transport.createChildDomain({
15882
16033
  */
15883
16034
  function wsAcceptorCarrier(options) {
15884
16035
  return {
15885
- ...createDuplexCarrierLifecycle(),
16036
+ ...createDuplexCarrierLifecycle(options.inboundLimits),
15886
16037
  shape: "duplex",
15887
16038
  carrierLabel: options.carrierLabel ?? "ws",
15888
16039
  secure: options.secure,