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