@kumiai/rpc 0.8.0 → 0.9.1

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/lib/app-lane.js CHANGED
@@ -1,4 +1,5 @@
1
- import { toUTF } from '@sozai/codec';
1
+ import { normalizeDID } from '@kokuin/token';
2
+ import { fromUTF, toUTF } from '@sozai/codec';
2
3
  import { asLogPosition } from './cursor.js';
3
4
  import { retentionOf } from './protocol.js';
4
5
  import { protocolTopic } from './topic.js';
@@ -301,7 +302,8 @@ const APP_FETCH_LIMIT = 100;
301
302
  };
302
303
  for (const [name, frames] of segment){
303
304
  const events = appEventHandlers.get(name);
304
- if (events == null || frames.length === 0) continue;
305
+ const cursor = cursors.get(name);
306
+ if (events == null || cursor == null || frames.length === 0) continue;
305
307
  for (const frame of frames){
306
308
  const sealed = frame.sealed;
307
309
  if (sealed == null) continue; // done on an earlier pass, and only holding its place
@@ -317,18 +319,28 @@ const APP_FETCH_LIMIT = 100;
317
319
  let opened;
318
320
  try {
319
321
  // `crypto.unwrap` always returns the full result — `senderDID` is REQUIRED — so there is
320
- // no bare-`Uint8Array` shortcut left to normalize away here.
321
- opened = await crypto.unwrap(sealed);
322
+ // no bare-`Uint8Array` shortcut left to normalize away here. `expectedAAD` is bound to
323
+ // the cursor's own topic, the authoritative answer to "what lane is this drain reading".
324
+ opened = await crypto.unwrap(sealed, {
325
+ expectedAAD: fromUTF(cursor.topicID)
326
+ });
322
327
  } catch {
323
- // It claimed this epoch and the handle refused it. Only `unwrap` is authoritative, and
324
- // the handle never comes back to this epoch, so nothing will ever open these bytes: dead.
328
+ // Claimed this epoch and the handle refused it — OR its AAD did not match this topic (a
329
+ // wrong-topic frame, or a pre-upgrade empty-AAD frame). Either way, dead: the handle
330
+ // never returns to this epoch and the topic binding never changes. Retained history from
331
+ // before this bind existed is DELIBERATELY invalidated, not silently re-offered.
325
332
  frame.sealed = null;
326
333
  continue;
327
334
  }
328
335
  // Opened, so it is done whatever the payload turns out to be — every path below either
329
336
  // delivers it or drops it exactly as the live transport would.
330
337
  frame.sealed = null;
331
- if (opened.senderDID === localDID) continue; // its own echo, as the live path would not
338
+ // This `unwrap` is its own ingress — not fed by `peer.ts`'s normalized inbound path — so
339
+ // the recovered sender is normalized HERE, once, before either use below: `localDID` (the
340
+ // param above) is already normalized at peer construction, and the two must compare on
341
+ // the same canonical form for the self-echo check to hold across DID forms.
342
+ const senderDID = normalizeDID(opened.senderDID);
343
+ if (senderDID === localDID) continue; // its own echo, as the live path would not
332
344
  let message;
333
345
  try {
334
346
  message = JSON.parse(toUTF(opened.payload));
@@ -337,13 +349,6 @@ const APP_FETCH_LIMIT = 100;
337
349
  }
338
350
  const prc = message.payload?.prc;
339
351
  if (message.payload?.typ !== 'event' || typeof prc !== 'string') continue;
340
- // Same door as the live push: a payload shaped like a control frame (kind 'req'/'res') is
341
- // not an app event — the responder drops it, so the drain must too, or a frame is dropped
342
- // live but delivered on replay.
343
- const drainData = message.payload?.data;
344
- if (drainData != null && typeof drainData === 'object' && (drainData.kind === 'req' || drainData.kind === 'res')) {
345
- continue;
346
- }
347
352
  // A retained frame naming an EPHEMERAL procedure was published `retain: 'log'` by a member
348
353
  // whose dispatch would never do that. Retention is the protocol's word, not the frame's.
349
354
  if (retentionOf(protocols[name], prc) !== 'log') continue;
@@ -352,7 +357,7 @@ const APP_FETCH_LIMIT = 100;
352
357
  // per-protocol emitter the live bus is also built from. No listener → no-op.
353
358
  await events.emit(prc, {
354
359
  data: message.payload.data ?? {},
355
- senderDID: opened.senderDID
360
+ senderDID
356
361
  });
357
362
  } catch {
358
363
  // A host listener that threw has been delivered to. Re-delivering on the next pull
package/lib/crypto.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- import type { ByteTransform } from '@kumiai/broadcast';
2
1
  /**
3
2
  * Consumer-supplied MLS crypto port: epoch number, epoch-bound domain-separated exported secrets
4
3
  * (`exportSecret`), byte-level encrypt/decrypt (`wrap`/`unwrap`), and the ledger-entry seal
@@ -13,6 +12,10 @@ import type { ByteTransform } from '@kumiai/broadcast';
13
12
  * `wrap`/`unwrap` close over the live group and always use current epoch state. `unwrap` returns
14
13
  * the authenticated sender (`senderDID`), REQUIRED — see {@link GroupUnwrapResult}.
15
14
  *
15
+ * `wrap` takes an optional second argument (AAD), so fixed-topic lanes adapt it to a `ByteTransform`
16
+ * closure, whilst directed lanes call the two-arg form directly. `unwrap`'s optional `expectedAAD`
17
+ * is compared PRE-OPEN, so a wrong-topic frame costs no ratchet generation.
18
+ *
16
19
  * `unwrap` MUST open bytes sealed at the handle's CURRENT epoch — that is the whole requirement.
17
20
  * A real MLS handle also opens a few epochs behind (ts-mls keeps four; evicting the fifth zeroes
18
21
  * their keys), but group-rpc must NOT depend on that window: it is spent by epoch TRANSITIONS
@@ -59,13 +62,20 @@ export type GroupCrypto = {
59
62
  * say so.
60
63
  */
61
64
  exportSecret(label: string, length?: number): Uint8Array | Promise<Uint8Array>;
62
- wrap: ByteTransform;
65
+ wrap(bytes: Uint8Array, opts?: {
66
+ aad?: Uint8Array;
67
+ }): Uint8Array | Promise<Uint8Array>;
63
68
  /**
64
69
  * Open a sealed app frame and recover who sent it. Returns {@link GroupUnwrapResult}, whose
65
70
  * `senderDID` is REQUIRED: an implementation that cannot name the sender must throw, not return
66
71
  * the field missing. See {@link GroupUnwrapResult} for why.
72
+ *
73
+ * `expectedAAD` is compared PRE-OPEN: authenticating without opening defends against wrong-topic
74
+ * frames that would otherwise burn a ratchet generation (DoS).
67
75
  */
68
- unwrap(bytes: Uint8Array): GroupUnwrapResult | Promise<GroupUnwrapResult>;
76
+ unwrap(bytes: Uint8Array, opts?: {
77
+ expectedAAD?: Uint8Array;
78
+ }): GroupUnwrapResult | Promise<GroupUnwrapResult>;
69
79
  /**
70
80
  * The epoch a sealed frame was sealed at, read from its own CLEARTEXT without opening it —
71
81
  * structural and pre-open, like {@link GroupMLS.readCommitHeader} is pre-apply. `null` for
package/lib/crypto.js CHANGED
@@ -1,4 +1,36 @@
1
1
  /**
2
+ * Consumer-supplied MLS crypto port: epoch number, epoch-bound domain-separated exported secrets
3
+ * (`exportSecret`), byte-level encrypt/decrypt (`wrap`/`unwrap`), and the ledger-entry seal
4
+ * (`sealEntries`/`openEntries`). group-rpc never imports MLS.
5
+ *
6
+ * TWO SEALS, not interchangeable. `wrap`/`unwrap` are ratchet-backed: each open consumes a
7
+ * message key and mutates the handle. `sealEntries`/`openEntries` use a key DERIVED from the
8
+ * epoch, so opening is pure and may run from inside a commit's own apply — the one place it does
9
+ * run, and which the ratchet-backed pair cannot serve.
10
+ *
11
+ * `epoch()` and `exportSecret(label)` are read on init and every {@link "peer".GroupPeer.resync}.
12
+ * `wrap`/`unwrap` close over the live group and always use current epoch state. `unwrap` returns
13
+ * the authenticated sender (`senderDID`), REQUIRED — see {@link GroupUnwrapResult}.
14
+ *
15
+ * `wrap` takes an optional second argument (AAD), so fixed-topic lanes adapt it to a `ByteTransform`
16
+ * closure, whilst directed lanes call the two-arg form directly. `unwrap`'s optional `expectedAAD`
17
+ * is compared PRE-OPEN, so a wrong-topic frame costs no ratchet generation.
18
+ *
19
+ * `unwrap` MUST open bytes sealed at the handle's CURRENT epoch — that is the whole requirement.
20
+ * A real MLS handle also opens a few epochs behind (ts-mls keeps four; evicting the fifth zeroes
21
+ * their keys), but group-rpc must NOT depend on that window: it is spent by epoch TRANSITIONS
22
+ * rather than time, so a peer catching up destroys the very keys a past-epoch read would need.
23
+ * Implementations that open strictly at the current epoch are correct.
24
+ *
25
+ * `unwrap` throwing is ORDINARY CONTROL FLOW on the read paths, not an error — it means "not my
26
+ * epoch". Readers walk logs full of frames from epochs they don't hold and drop them without
27
+ * treating them as corrupt.
28
+ *
29
+ * IMPLEMENTING THIS PORT OBLIGES RUNNING `@kumiai/rpc-conformance` AGAINST THE IMPLEMENTATION.
30
+ * Not a recommendation: the suite is where this port's contract actually lives, and the clauses
31
+ * exist because implementations got them wrong. A host that writes its own `GroupCrypto` and does
32
+ * not run the suite has an untested crypto boundary, whatever else it tests.
33
+ */ /**
2
34
  * The one throw {@link GroupMLS.processCommit} is allowed: the Commit named ledger entries whose
3
35
  * bodies would not resolve from the frame the Commit rides in.
4
36
  *
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Format version of the directed-payload tag, AND the byte that tells a tagged frame from a
3
+ * legacy one: legacy directed frames are `JSON.stringify` output (`hub-tunnel/frame.ts`), so they
4
+ * begin with `{` or JSON leading whitespace — never `0x00`. The first byte alone disambiguates.
5
+ */
6
+ export declare const DIRECTED_TAG_VERSION = 0;
7
+ /** Whether these bytes are NOT a tagged directed payload (empty, or a non-version leading byte). */
8
+ export declare function isLegacyDirectedPayload(bytes: Uint8Array): boolean;
9
+ /**
10
+ * Prepend the authenticated protocol tag to a directed frame, to be sealed by `crypto.wrap`. The
11
+ * fixed-width length makes the `protocol ‖ frame` split injective regardless of the name's bytes.
12
+ */
13
+ export declare function encodeDirectedPayload(protocol: string, frame: Uint8Array): Uint8Array;
14
+ /**
15
+ * Split a sealed directed payload into its protocol tag and inner frame. Throws on a legacy or
16
+ * malformed buffer (a caller that must drop rather than throw checks {@link isLegacyDirectedPayload}
17
+ * first). Never a partial read: an overrunning length or ill-formed UTF-8 name is rejected.
18
+ */
19
+ export declare function decodeDirectedPayload(bytes: Uint8Array): {
20
+ protocol: string;
21
+ frame: Uint8Array;
22
+ };
@@ -0,0 +1,53 @@
1
+ import { fromUTF, toUTF } from '@sozai/codec';
2
+ /**
3
+ * Format version of the directed-payload tag, AND the byte that tells a tagged frame from a
4
+ * legacy one: legacy directed frames are `JSON.stringify` output (`hub-tunnel/frame.ts`), so they
5
+ * begin with `{` or JSON leading whitespace — never `0x00`. The first byte alone disambiguates.
6
+ */ export const DIRECTED_TAG_VERSION = 0x00;
7
+ const VERSION_BYTES = 1;
8
+ const LENGTH_BYTES = 2;
9
+ const HEADER_BYTES = VERSION_BYTES + LENGTH_BYTES;
10
+ const MAX_PROTOCOL_BYTES = 0xffff;
11
+ /** Whether these bytes are NOT a tagged directed payload (empty, or a non-version leading byte). */ export function isLegacyDirectedPayload(bytes) {
12
+ return bytes.length === 0 || bytes[0] !== DIRECTED_TAG_VERSION;
13
+ }
14
+ /**
15
+ * Prepend the authenticated protocol tag to a directed frame, to be sealed by `crypto.wrap`. The
16
+ * fixed-width length makes the `protocol ‖ frame` split injective regardless of the name's bytes.
17
+ */ export function encodeDirectedPayload(protocol, frame) {
18
+ const name = fromUTF(protocol);
19
+ if (name.length > MAX_PROTOCOL_BYTES) {
20
+ throw new Error(`encodeDirectedPayload: protocol name is ${name.length} bytes, exceeds the ${MAX_PROTOCOL_BYTES}-byte tag limit`);
21
+ }
22
+ const out = new Uint8Array(HEADER_BYTES + name.length + frame.length);
23
+ out[0] = DIRECTED_TAG_VERSION;
24
+ new DataView(out.buffer).setUint16(VERSION_BYTES, name.length, false);
25
+ out.set(name, HEADER_BYTES);
26
+ out.set(frame, HEADER_BYTES + name.length);
27
+ return out;
28
+ }
29
+ /**
30
+ * Split a sealed directed payload into its protocol tag and inner frame. Throws on a legacy or
31
+ * malformed buffer (a caller that must drop rather than throw checks {@link isLegacyDirectedPayload}
32
+ * first). Never a partial read: an overrunning length or ill-formed UTF-8 name is rejected.
33
+ */ export function decodeDirectedPayload(bytes) {
34
+ if (bytes.length < HEADER_BYTES) {
35
+ throw new Error('decodeDirectedPayload: buffer shorter than the tag header');
36
+ }
37
+ if (bytes[0] !== DIRECTED_TAG_VERSION) {
38
+ throw new Error(`decodeDirectedPayload: unexpected version byte ${bytes[0]}`);
39
+ }
40
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
41
+ const nameLength = view.getUint16(VERSION_BYTES, false);
42
+ const frameStart = HEADER_BYTES + nameLength;
43
+ if (bytes.length < frameStart) {
44
+ throw new Error('decodeDirectedPayload: protocol length overruns the buffer');
45
+ }
46
+ // `toUTF` is a fatal TextDecoder in this repo (fromUTF/toUTF wrap WHATWG codecs); ill-formed
47
+ // UTF-8 throws here rather than yielding replacement chars.
48
+ const protocol = toUTF(bytes.subarray(HEADER_BYTES, frameStart));
49
+ return {
50
+ protocol,
51
+ frame: bytes.subarray(frameStart)
52
+ };
53
+ }
package/lib/directed.d.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import { Client } from '@enkaku/client';
2
- import type { ProtocolDefinition } from '@enkaku/protocol';
2
+ import { type ProtocolDefinition } from '@enkaku/protocol';
3
3
  import { type ProcedureHandlers } from '@enkaku/server';
4
- import type { ByteTransform, Unwrap } from '@kumiai/broadcast';
4
+ import type { Unwrap } from '@kumiai/broadcast';
5
5
  import type { StoredMessage } from '@kumiai/hub-protocol';
6
6
  import { type Runtime } from '@sozai/runtime';
7
+ import type { GroupCrypto } from './crypto.js';
7
8
  import type { HubMux } from './hub-mux.js';
8
9
  /**
9
10
  * An inbound frame that has ALREADY been opened, with the sender the open authenticated.
@@ -19,6 +20,9 @@ export type OpenedInbound = {
19
20
  /** Recovered from the ciphertext by the open, never the hub-asserted one. */
20
21
  senderDID: string;
21
22
  topicID: string;
23
+ /** The protocol this frame is tagged for, decoded from the sealed in-frame discriminator. */
24
+ protocol: string;
25
+ /** The inner hub-tunnel frame, with the protocol tag stripped. */
22
26
  payload: Uint8Array;
23
27
  };
24
28
  /** Subscribe to a topic's already-opened frames; returns the unsubscribe. */
@@ -38,6 +42,14 @@ export type InboxPathParams = {
38
42
  * what stops a lying hub forging or splicing one.
39
43
  */
40
44
  export declare function createInboxPath(params: InboxPathParams): InboundPath;
45
+ /**
46
+ * Default `requestTimeoutMs` a directed client aborts a unary request after. The unary-only
47
+ * backstop for a request the recipient never answers: enkaku applies it to `request`, not to
48
+ * stream/channel creation, so those lean on the unrouted-tag NACK ({@link createUnroutedTagResponder})
49
+ * instead. 30s is a deliberate ceiling — a call the peer means to answer answers well inside it,
50
+ * so its expiry is evidence the call was dropped.
51
+ */
52
+ export declare const DEFAULT_DIRECTED_REQUEST_TIMEOUT_MS = 30000;
41
53
  export type DirectedClientParams = {
42
54
  mux: HubMux;
43
55
  localDID: string;
@@ -46,9 +58,17 @@ export type DirectedClientParams = {
46
58
  receiveTopicID: string;
47
59
  /** The self-inbox topic's one open-once path, shared with the acceptor. */
48
60
  inbound: InboundPath;
49
- wrap: ByteTransform;
61
+ wrap: GroupCrypto['wrap'];
50
62
  /** Runtime providing platform primitives. Defaults to `createRuntime()`. */
51
63
  runtime?: Runtime;
64
+ /** The protocol name outbound frames are tagged with, and inbound frames filtered on. */
65
+ protocol: string;
66
+ /**
67
+ * How long a unary request waits before aborting. Defaults to
68
+ * {@link DEFAULT_DIRECTED_REQUEST_TIMEOUT_MS}. Unary only — enkaku does not apply it to
69
+ * stream/channel creation.
70
+ */
71
+ requestTimeoutMs?: number;
52
72
  };
53
73
  /**
54
74
  * Directed 1:1 RPC client to a single member, over a hub-tunnel transport whose
@@ -71,8 +91,10 @@ export type InboxAcceptorParams<Protocol extends ProtocolDefinition> = {
71
91
  /** Map an authenticated senderDID to the topic we send replies on (their inbox). */
72
92
  resolveSendTopic: (senderDID: string) => string;
73
93
  protocol: Protocol;
94
+ /** The tag's string NAME — distinct from `protocol` above, which is the definition object. */
95
+ protocolName: string;
74
96
  handlers: ProcedureHandlers<Protocol>;
75
- wrap: ByteTransform;
97
+ wrap: GroupCrypto['wrap'];
76
98
  };
77
99
  /**
78
100
  * Accept directed RPC. A single sealed drain of `selfInboxTopic` opens each inbound frame with
@@ -80,7 +102,47 @@ export type InboxAcceptorParams<Protocol extends ProtocolDefinition> = {
80
102
  * and feeds decrypted bytes into a per-session in-memory transport whose replies are sealed
81
103
  * with `wrap`. Frames whose recovered sender does not match the session binding are dropped, so
82
104
  * a malicious hub can neither read the lane nor forge/splice a sender.
105
+ *
106
+ * The recovered sender is stamped into each frame's header and threaded into the handler's
107
+ * `message.payload.iss` (see {@link withHeaderSenderIss}), so directed attribution is symmetric
108
+ * with the broadcast lane.
83
109
  */
84
110
  export declare function createInboxAcceptor<Protocol extends ProtocolDefinition>(params: InboxAcceptorParams<Protocol>): {
85
111
  dispose: () => Promise<void>;
86
112
  };
113
+ export type UnroutedTagResponderParams = {
114
+ mux: HubMux;
115
+ localDID: string;
116
+ /** The self-inbox topic's one open-once path, shared with every acceptor. */
117
+ inbound: InboundPath;
118
+ /** Whether this peer serves the tag's protocol; a tag outside it is unrouted. */
119
+ isRegistered: (protocol: string) => boolean;
120
+ /**
121
+ * Seal an already-tagged NACK for a recipient's inbox under ONE anchor snapshot, returning the
122
+ * topic that agrees with the seal. Topic and seal must come from the same anchor: reading the
123
+ * topic and sealing as two steps lets a mid-flight rotation address an old inbox with new-epoch
124
+ * ciphertext, lost onto a topic the recipient no longer reads.
125
+ */
126
+ sealReply: (recipientDID: string, taggedPayload: Uint8Array) => Promise<{
127
+ topicID: string;
128
+ payload: Uint8Array;
129
+ }>;
130
+ };
131
+ /**
132
+ * Restores failure legibility for a frame tagged for a protocol this peer does not serve. Every
133
+ * acceptor filters on its own protocol, so a frame tagged for none is fed to no acceptor and would
134
+ * be silently dropped; this single peer-level consumer of the shared inbound path NACKs it, so a
135
+ * caller's unary request rejects with `INVALID_MESSAGE` (and a stream/channel creation, which the
136
+ * client timeout cannot abort, rejects at all) instead of hanging.
137
+ *
138
+ * Three constraints, each of which if broken makes this worse than nothing:
139
+ * - The NACK is tagged with the OFFENDING protocol, not one of ours, or the caller's own protocol
140
+ * filter drops it.
141
+ * - Only REQUEST-like frames are answered: a `result`/`error`/`receive` reply carries an `rid` too,
142
+ * and NACKing one lets two peers that both lack the tag volley error frames forever.
143
+ * - The reply reuses the offending frame's `sessionID` (the caller's tunnel locks to it) and a
144
+ * fresh, monotonic `seq` (the tunnel drops `seq` below what it has already seen).
145
+ */
146
+ export declare function createUnroutedTagResponder(params: UnroutedTagResponderParams): {
147
+ dispose: () => void;
148
+ };
package/lib/directed.js CHANGED
@@ -1,7 +1,11 @@
1
1
  import { Client } from '@enkaku/client';
2
- import { Server } from '@enkaku/server';
3
- import { createHubTunnelTransport, decodeFrame } from '@kumiai/hub-tunnel';
2
+ import { ErrorCodes } from '@enkaku/protocol';
3
+ import { HandlerError, Server } from '@enkaku/server';
4
+ import { normalizeDID } from '@kokuin/token';
5
+ import { createHubTunnelTransport, decodeFrame, encodeFrame } from '@kumiai/hub-tunnel';
6
+ import { fromUTF } from '@sozai/codec';
4
7
  import { createRuntime } from '@sozai/runtime';
8
+ import { decodeDirectedPayload, encodeDirectedPayload, isLegacyDirectedPayload } from './directed-tag.js';
5
9
  import { createOpenOncePath } from './open-once.js';
6
10
  /**
7
11
  * The one path that opens an inbox topic's frames, for every consumer of it.
@@ -18,14 +22,37 @@ import { createOpenOncePath } from './open-once.js';
18
22
  ...retainOnFailure != null ? {
19
23
  retainOnFailure
20
24
  } : {},
21
- project: (message, opened)=>opened.senderDID == null ? undefined : {
25
+ project: (message, opened)=>{
26
+ if (opened.senderDID == null) return undefined;
27
+ // The tag is inside the seal, so it is authenticated to the recovered sender. A legacy or
28
+ // malformed payload is dropped HERE — the open already spent the ratchet key.
29
+ if (isLegacyDirectedPayload(opened.payload)) return undefined;
30
+ let decoded;
31
+ try {
32
+ decoded = decodeDirectedPayload(opened.payload);
33
+ } catch {
34
+ return undefined;
35
+ }
36
+ return {
22
37
  sequenceID: message.sequenceID,
23
- senderDID: opened.senderDID,
38
+ // Normalized at the open: every consumer keyed on this (the directed client's own
39
+ // `senderDID` filter, the acceptor's session binding) must see one canonical sender
40
+ // regardless of which DID form MLS recovered the frame under.
41
+ senderDID: normalizeDID(opened.senderDID),
24
42
  topicID: message.topicID,
25
- payload: opened.payload
26
- }
43
+ protocol: decoded.protocol,
44
+ payload: decoded.frame
45
+ };
46
+ }
27
47
  });
28
48
  }
49
+ /**
50
+ * Default `requestTimeoutMs` a directed client aborts a unary request after. The unary-only
51
+ * backstop for a request the recipient never answers: enkaku applies it to `request`, not to
52
+ * stream/channel creation, so those lean on the unrouted-tag NACK ({@link createUnroutedTagResponder})
53
+ * instead. 30s is a deliberate ceiling — a call the peer means to answer answers well inside it,
54
+ * so its expiry is evidence the call was dropped.
55
+ */ export const DEFAULT_DIRECTED_REQUEST_TIMEOUT_MS = 30_000;
29
56
  /**
30
57
  * Directed 1:1 RPC client to a single member, over a hub-tunnel transport whose
31
58
  * send/receive topics are the two members' inbox topics for the current epoch.
@@ -34,15 +61,19 @@ import { createOpenOncePath } from './open-once.js';
34
61
  * MLS-authenticated sender belongs to another conversation on the same inbox and is left for
35
62
  * the consumer it does belong to.
36
63
  */ export function createDirectedClient(params) {
37
- const { mux, localDID, memberDID, sendTopicID, receiveTopicID, inbound, wrap } = params;
64
+ const { mux, localDID, memberDID, sendTopicID, receiveTopicID, inbound, wrap, protocol } = params;
65
+ const requestTimeoutMs = params.requestTimeoutMs ?? DEFAULT_DIRECTED_REQUEST_TIMEOUT_MS;
38
66
  const { getRandomID } = params.runtime ?? createRuntime();
39
67
  let unsubscribe;
40
68
  const hub = {
41
69
  async publish (publishParams) {
70
+ const tagged = encodeDirectedPayload(protocol, publishParams.payload);
42
71
  return mux.mailbox.publish({
43
72
  senderDID: publishParams.senderDID,
44
73
  topicID: publishParams.topicID,
45
- payload: await wrap(publishParams.payload)
74
+ payload: await wrap(tagged, {
75
+ aad: fromUTF(publishParams.topicID)
76
+ })
46
77
  });
47
78
  },
48
79
  subscribe () {},
@@ -65,7 +96,7 @@ import { createOpenOncePath } from './open-once.js';
65
96
  }
66
97
  };
67
98
  unsubscribe = inbound((message)=>{
68
- if (closed || message.topicID !== receiveTopicID || message.senderDID !== memberDID) return;
99
+ if (closed || message.topicID !== receiveTopicID || message.protocol !== protocol || message.senderDID !== memberDID) return;
69
100
  if (resolveNext != null) {
70
101
  const resolve = resolveNext;
71
102
  resolveNext = undefined;
@@ -118,7 +149,8 @@ import { createOpenOncePath } from './open-once.js';
118
149
  });
119
150
  const client = new Client({
120
151
  transport,
121
- serverID: memberDID
152
+ serverID: memberDID,
153
+ requestTimeoutMs
122
154
  });
123
155
  return {
124
156
  client,
@@ -129,17 +161,65 @@ import { createOpenOncePath } from './open-once.js';
129
161
  }
130
162
  };
131
163
  }
164
+ /**
165
+ * Frame-HEADER field the acceptor stamps with the MLS-recovered sender, read back by
166
+ * {@link withHeaderSenderIss}. It rides the header, not the call payload: enkaku validates the
167
+ * payload against a closed schema (`additionalProperties: false`; `iss` is legal only on a signed
168
+ * message, and directed frames are unsigned), so a payload `iss` is rejected before any handler
169
+ * runs — whereas the unsigned header schema is open (`additionalProperties: true`), so a stamped
170
+ * header field survives validation and reaches the handler context.
171
+ *
172
+ * The `kumiai/` header namespace is RESERVED by the acceptor: every inbound directed frame has this
173
+ * key overwritten with the authenticated sender, so a host must not use it for its own metadata.
174
+ * The namespaced, unlikely-to-collide name keeps that reservation explicit.
175
+ */ const HEADER_SENDER_KEY = 'kumiai/senderDID';
176
+ /**
177
+ * Wrap every handler so it surfaces the frame's MLS-recovered sender at `message.payload.iss`,
178
+ * mirroring what `adaptBusHandlers` injects on the broadcast lane — so a handler reads the same
179
+ * authenticated `iss` regardless of which lane served it.
180
+ *
181
+ * The value is injected into the handler CONTEXT (never the wire payload), read from the header
182
+ * field the acceptor stamped ({@link HEADER_SENDER_KEY}). One wrapper serves the single shared
183
+ * Server: the sender is per-FRAME (from the header the acceptor overwrote with the recovered
184
+ * sender), so it does not need a Server per session to stay correct.
185
+ */ function withHeaderSenderIss(handlers) {
186
+ const wrapped = {};
187
+ for (const [procedure, handler] of Object.entries(handlers)){
188
+ const fn = handler;
189
+ wrapped[procedure] = (context)=>{
190
+ const message = context.message;
191
+ const senderDID = message?.header?.[HEADER_SENDER_KEY];
192
+ return fn({
193
+ ...context,
194
+ message: {
195
+ ...message,
196
+ payload: {
197
+ ...message?.payload,
198
+ iss: senderDID
199
+ }
200
+ }
201
+ });
202
+ };
203
+ }
204
+ return wrapped;
205
+ }
132
206
  /**
133
207
  * Accept directed RPC. A single sealed drain of `selfInboxTopic` opens each inbound frame with
134
208
  * `unwrap`, binds every session to the MLS-authenticated sender recovered from the ciphertext,
135
209
  * and feeds decrypted bytes into a per-session in-memory transport whose replies are sealed
136
210
  * with `wrap`. Frames whose recovered sender does not match the session binding are dropped, so
137
211
  * a malicious hub can neither read the lane nor forge/splice a sender.
212
+ *
213
+ * The recovered sender is stamped into each frame's header and threaded into the handler's
214
+ * `message.payload.iss` (see {@link withHeaderSenderIss}), so directed attribution is symmetric
215
+ * with the broadcast lane.
138
216
  */ export function createInboxAcceptor(params) {
139
- const { mux, localDID, selfInboxTopic, inbound, resolveSendTopic, protocol, handlers, wrap } = params;
217
+ const { mux, localDID, selfInboxTopic, inbound, resolveSendTopic, protocol, protocolName, handlers, wrap } = params;
218
+ // One shared Server across all sessions (its own resource limiter caps handlers/controllers
219
+ // collectively). Its handlers are wrapped once to surface each frame's stamped sender as `iss`.
140
220
  const server = new Server({
141
221
  protocol,
142
- handlers,
222
+ handlers: withHeaderSenderIss(handlers),
143
223
  requireAuth: false
144
224
  });
145
225
  const sessions = new Map();
@@ -149,7 +229,10 @@ import { createOpenOncePath } from './open-once.js';
149
229
  let closed = false;
150
230
  const sessionHub = {
151
231
  async publish (publishParams) {
152
- const sealed = await wrap(publishParams.payload);
232
+ const tagged = encodeDirectedPayload(protocolName, publishParams.payload);
233
+ const sealed = await wrap(tagged, {
234
+ aad: fromUTF(publishParams.topicID)
235
+ });
153
236
  return mux.mailbox.publish({
154
237
  senderDID: publishParams.senderDID,
155
238
  topicID: publishParams.topicID,
@@ -258,7 +341,7 @@ import { createOpenOncePath } from './open-once.js';
258
341
  // guarantee: it opens one frame at a time, so a session is never double-created and a tunnel is
259
342
  // never fed out of wire order (which drops as a stale seq).
260
343
  const unsubscribe = inbound((message)=>{
261
- if (message.topicID !== selfInboxTopic) return;
344
+ if (message.topicID !== selfInboxTopic || message.protocol !== protocolName) return;
262
345
  const senderDID = message.senderDID;
263
346
  let frame;
264
347
  try {
@@ -275,13 +358,25 @@ import { createOpenOncePath } from './open-once.js';
275
358
  return;
276
359
  }
277
360
  if (frame.kind !== 'message') return;
361
+ // Drop a sender mismatch on an established session (splice attempt) BEFORE re-encoding, so a
362
+ // hostile member cannot make us serialise a large frame per rejected splice.
363
+ if (existing != null && existing.senderDID !== senderDID) return;
364
+ // Stamp the MLS-recovered sender into the frame header, overwriting any caller-supplied value,
365
+ // so the shared Server's handler wrapper can surface it as `message.payload.iss`. The header
366
+ // schema is open (the payload schema is not); the acceptor is the authority on the sender, so
367
+ // the write is unconditional and a caller cannot assert its own.
368
+ frame.body.header = {
369
+ ...frame.body.header,
370
+ [HEADER_SENDER_KEY]: senderDID
371
+ };
372
+ const stamped = encodeFrame(frame);
278
373
  if (existing != null) {
279
- if (existing.senderDID === senderDID) existing.feed(message.payload);
280
- return; // sender mismatch on an established session — splice attempt, drop
374
+ existing.feed(stamped);
375
+ return;
281
376
  }
282
377
  const session = createSession(senderDID);
283
378
  sessions.set(frame.sessionID, session);
284
- session.feed(message.payload);
379
+ session.feed(stamped);
285
380
  });
286
381
  return {
287
382
  dispose: async ()=>{
@@ -291,7 +386,84 @@ import { createOpenOncePath } from './open-once.js';
291
386
  ].map((session)=>session.dispose());
292
387
  sessions.clear();
293
388
  await Promise.allSettled(pending);
389
+ // The shared Server drains its in-flight handlers here (bounded by enkaku's cleanup timeout),
390
+ // covering sessions torn down by a `session-end` frame whose own dispose is not awaited.
294
391
  await server.dispose();
295
392
  }
296
393
  };
297
394
  }
395
+ /** Frame payload types that carry a NEW request a peer must answer — the only ones worth NACKing. */ const REQUEST_LIKE = new Set([
396
+ 'request',
397
+ 'stream',
398
+ 'channel',
399
+ 'send'
400
+ ]);
401
+ /**
402
+ * Restores failure legibility for a frame tagged for a protocol this peer does not serve. Every
403
+ * acceptor filters on its own protocol, so a frame tagged for none is fed to no acceptor and would
404
+ * be silently dropped; this single peer-level consumer of the shared inbound path NACKs it, so a
405
+ * caller's unary request rejects with `INVALID_MESSAGE` (and a stream/channel creation, which the
406
+ * client timeout cannot abort, rejects at all) instead of hanging.
407
+ *
408
+ * Three constraints, each of which if broken makes this worse than nothing:
409
+ * - The NACK is tagged with the OFFENDING protocol, not one of ours, or the caller's own protocol
410
+ * filter drops it.
411
+ * - Only REQUEST-like frames are answered: a `result`/`error`/`receive` reply carries an `rid` too,
412
+ * and NACKing one lets two peers that both lack the tag volley error frames forever.
413
+ * - The reply reuses the offending frame's `sessionID` (the caller's tunnel locks to it) and a
414
+ * fresh, monotonic `seq` (the tunnel drops `seq` below what it has already seen).
415
+ */ export function createUnroutedTagResponder(params) {
416
+ const { mux, localDID, inbound, isRegistered, sealReply } = params;
417
+ // Monotonic across every session this responder answers: a caller's virgin tunnel expects seq 0,
418
+ // and any seq >= its expected value is accepted, so one NACK per caller session is always fresh.
419
+ // `seq` is assigned INSIDE the chained task below, immediately before the frame is built, so
420
+ // seq-assignment order always equals publish order (see the tail chain).
421
+ let seq = 0;
422
+ // Seal+publish is best-effort and async, but must run in enqueue order: two unrouted frames from
423
+ // one caller tunnel get consecutive seq, and if the later one published first the caller's tunnel
424
+ // would advance `expectedSeq` past the earlier NACK and drop it as stale. Chaining through a
425
+ // single tail promise serialises them (one seal in flight at a time) and pins publish order to
426
+ // enqueue order; a failed link is swallowed so it never stalls the chain.
427
+ let tail = Promise.resolve();
428
+ const unsubscribe = inbound((message)=>{
429
+ if (isRegistered(message.protocol)) return;
430
+ let frame;
431
+ try {
432
+ frame = decodeFrame(message.payload);
433
+ } catch {
434
+ return;
435
+ }
436
+ if (frame.kind !== 'message') return;
437
+ const payload = frame.body.payload;
438
+ const rid = payload.rid;
439
+ if (typeof rid !== 'string' || !REQUEST_LIKE.has(payload.typ)) return;
440
+ const errorPayload = new HandlerError({
441
+ code: ErrorCodes.INVALID_MESSAGE,
442
+ message: `No handler registered for protocol "${message.protocol}"`
443
+ }).toPayload(rid);
444
+ const protocol = message.protocol;
445
+ const senderDID = message.senderDID;
446
+ tail = tail.then(async ()=>{
447
+ const nack = encodeFrame({
448
+ v: 1,
449
+ sessionID: frame.sessionID,
450
+ seq: seq++,
451
+ kind: 'message',
452
+ body: {
453
+ header: {},
454
+ payload: errorPayload
455
+ }
456
+ });
457
+ const tagged = encodeDirectedPayload(protocol, nack);
458
+ const { topicID, payload: sealed } = await sealReply(senderDID, tagged);
459
+ await mux.mailbox.publish({
460
+ senderDID: localDID,
461
+ topicID,
462
+ payload: sealed
463
+ });
464
+ }).catch(()=>{});
465
+ });
466
+ return {
467
+ dispose: unsubscribe
468
+ };
469
+ }
package/lib/hub-mux.d.ts CHANGED
@@ -111,6 +111,19 @@ export type HubMux = {
111
111
  * is not held, so a later retain asks again, carrying its own `options`.
112
112
  */
113
113
  retainTopic: (topicID: string, options?: HubSubscribeOptions) => void;
114
+ /**
115
+ * Clear a latched subscribe refusal and ask once more, for a topic whose refusal may now be
116
+ * answered differently — an `AuthorizationDeniedError` cleared by the peer since becoming a group
117
+ * member, above all. Single-shot: it re-asks exactly once and re-latches if the hub still refuses,
118
+ * so the host calls it on each authorization change rather than to poll. A no-op unless the topic
119
+ * is currently refused and still retained; re-asks with the options the hub refused.
120
+ */
121
+ rearmTopic: (topicID: string) => void;
122
+ /**
123
+ * Rearm every currently-refused topic at once — the group-wide {@link rearmTopic}, for a caller
124
+ * that has become authorized and does not track which topics were individually refused.
125
+ */
126
+ rearmRefusedTopics: () => void;
114
127
  /** Pull a topic's log as the local DID. */
115
128
  fetchTopic: (params: MuxFetchTopicParams) => Promise<HubFetchTopicResult>;
116
129
  onInbound: (topicID: string, listener: InboundListener, options?: HubSubscribeOptions) => () => void;
package/lib/hub-mux.js CHANGED
@@ -151,7 +151,7 @@ const warnReceiveEnded = (ended)=>{
151
151
  kind: 'refused',
152
152
  error,
153
153
  permanent,
154
- retention: options?.retention
154
+ options
155
155
  });
156
156
  reportFailure({
157
157
  topicID,
@@ -183,12 +183,51 @@ const warnReceiveEnded = (ended)=>{
183
183
  // downgrade the hub refused to perform, which is worse than the refusal it replaces.
184
184
  //
185
185
  // A retry-exhausted failure carries no answer, so any retain re-asks.
186
- if (state.permanent && (options?.retention == null || options.retention === state.retention)) {
186
+ if (state.permanent && (options?.retention == null || options.retention === state.options?.retention)) {
187
187
  return;
188
188
  }
189
189
  void attemptSubscribe(topicID, options, 0);
190
190
  };
191
191
  /**
192
+ * Clear a latched refusal so the topic is asked for once more, on the caller's word that the
193
+ * answer may now be different. A permanent refusal — an `AuthorizationDeniedError` above all — is
194
+ * an answer to a request made under conditions that CAN change: a peer refused because it was not
195
+ * yet a group member is admitted moments later, and nothing about that transition re-shapes the
196
+ * request, so the retain gate (which only re-asks under a different retention) never re-drives it.
197
+ * This is the external-event clear the note on `createHubMux` describes, the same shape a freed
198
+ * quota would need: the host, which owns the membership/authorization change the hub cannot see,
199
+ * says "ask again."
200
+ *
201
+ * Single-shot by construction: it re-asks EXACTLY once (via `attemptSubscribe(..., 0)`), and if
202
+ * the hub still refuses, the topic re-latches. A rearm is one fresh chance to ask, never a retry
203
+ * loop — call it again on the next authorization change. A no-op unless the topic is currently
204
+ * `refused` (a held or in-flight subscription is left untouched) and still has holders (a topic
205
+ * nothing retains is not resurrected). Re-asks with the SAME `options` the hub refused.
206
+ */ const rearmTopic = (topicID)=>{
207
+ if (disposed) return;
208
+ const state = subscriptions.get(topicID);
209
+ if (state?.kind !== 'refused') return;
210
+ const { options } = state;
211
+ subscriptions.delete(topicID);
212
+ if ((refcount.get(topicID) ?? 0) > 0) {
213
+ void attemptSubscribe(topicID, options, 0);
214
+ }
215
+ };
216
+ /**
217
+ * Rearm EVERY currently-refused topic — the group-wide form of {@link rearmTopic}, for a caller
218
+ * that learns it has become authorized without tracking which individual topics were refused
219
+ * (a freshly-admitted group member, whose whole set of group topics was refused during the window
220
+ * before its membership landed). Snapshots the refused set first, so rearming one — which deletes
221
+ * its subscription entry — does not disturb the iteration.
222
+ */ const rearmRefusedTopics = ()=>{
223
+ if (disposed) return;
224
+ const refused = [];
225
+ for (const [topicID, state] of subscriptions){
226
+ if (state.kind === 'refused') refused.push(topicID);
227
+ }
228
+ for (const topicID of refused)rearmTopic(topicID);
229
+ };
230
+ /**
192
231
  * The enforcement half. A topic the hub refused is one this peer cannot read, so it does not go
193
232
  * on transmitting there as a full participant either: every publish and every fetch on it
194
233
  * rejects with the hub's own error.
@@ -518,6 +557,8 @@ const warnReceiveEnded = (ended)=>{
518
557
  retainTopic: (topicID, options)=>{
519
558
  retain(topicID, options);
520
559
  },
560
+ rearmTopic,
561
+ rearmRefusedTopics,
521
562
  fetchTopic,
522
563
  onInbound,
523
564
  suspendPublishing: ()=>{
package/lib/peer.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Client } from '@enkaku/client';
2
- import type { ProtocolDefinition } from '@enkaku/protocol';
2
+ import type { DataOf, EventProcedureDefinition, ProtocolDefinition, RequestProcedureDefinition, ReturnOf } from '@enkaku/protocol';
3
3
  import type { ProcedureHandlers } from '@enkaku/server';
4
4
  import { type GatheredReply, type GatherOptions, type RequestOptions, type SuppressConfig } from '@kumiai/broadcast';
5
5
  import type { LogHub } from '@kumiai/hub-tunnel';
@@ -9,6 +9,7 @@ import type { AppCursorStore, AppWindowPruned } from './app-cursor.js';
9
9
  import { type CommitJournal, type LaneResult, type PendingCommit } from './commit.js';
10
10
  import { type GroupCrypto, type GroupMLS } from './crypto.js';
11
11
  import { type ReceiveLaneEnded, type SubscribeFailure } from './hub-mux.js';
12
+ import { type GroupProtocolDefinition } from './protocol.js';
12
13
  /**
13
14
  * How long the hub is asked to keep the commit log: **28 days**. Bounds how long a member may be
14
15
  * offline and still converge by pulling alone, without another member awake to heal it.
@@ -63,7 +64,7 @@ export type GroupPeerMLSParams = {
63
64
  */
64
65
  adoptJournalled: (journal: Uint8Array) => Promise<void>;
65
66
  };
66
- export type GroupPeerParams<Protocols extends Record<string, ProtocolDefinition>> = {
67
+ export type GroupPeerParams<Protocols extends Record<string, GroupProtocolDefinition>> = {
67
68
  hub: LogHub;
68
69
  crypto: GroupCrypto;
69
70
  localDID: string;
@@ -140,13 +141,52 @@ export type GroupPeerParams<Protocols extends Record<string, ProtocolDefinition>
140
141
  anchorStore?: undefined;
141
142
  appCursorStore?: undefined;
142
143
  });
143
- export type ProtocolSurface<Protocol extends ProtocolDefinition> = {
144
- dispatch: (prc: string, data?: Record<string, unknown>) => Promise<void>;
145
- request: (prc: string, prm?: unknown, options?: RequestOptions) => Promise<unknown>;
146
- gather: (prc: string, prm?: unknown, options?: GatherOptions) => Promise<Array<GatheredReply>>;
144
+ type FilterNever<T> = {
145
+ [K in keyof T as T[K] extends never ? never : K]: T[K];
146
+ };
147
+ type GroupEventDefs<Protocol extends GroupProtocolDefinition> = FilterNever<{
148
+ [P in keyof Protocol & string]: Protocol[P] extends EventProcedureDefinition ? {
149
+ Data: DataOf<Protocol[P]['data']>;
150
+ } : never;
151
+ }>;
152
+ type GroupRequestDefs<Protocol extends GroupProtocolDefinition> = FilterNever<{
153
+ [P in keyof Protocol & string]: Protocol[P] extends RequestProcedureDefinition ? {
154
+ Param: DataOf<Protocol[P]['param']>;
155
+ Result: ReturnOf<Protocol[P]['result']>;
156
+ } : never;
157
+ }>;
158
+ export type ProtocolSurface<Protocol extends GroupProtocolDefinition> = ProtocolSurfaceOf<Protocol>;
159
+ type ProtocolSurfaceOf<Protocol extends GroupProtocolDefinition, Events extends GroupEventDefs<Protocol> = GroupEventDefs<Protocol>, Requests extends GroupRequestDefs<Protocol> = GroupRequestDefs<Protocol>> = {
160
+ dispatch: <P extends keyof Events & string, T extends Events[P] = Events[P]>(prc: P, ...args: T['Data'] extends never ? [config?: {
161
+ data?: never;
162
+ }] : [config: {
163
+ data: T['Data'];
164
+ }]) => Promise<void>;
165
+ request: <P extends keyof Requests & string, T extends Requests[P] = Requests[P]>(prc: P, ...args: T['Param'] extends never ? [config?: {
166
+ param?: never;
167
+ } & RequestOptions] : [config: {
168
+ param: T['Param'];
169
+ } & RequestOptions]) => Promise<T['Result']>;
170
+ gather: <P extends keyof Requests & string, T extends Requests[P] = Requests[P]>(prc: P, ...args: T['Param'] extends never ? [config?: {
171
+ param?: never;
172
+ } & GatherOptions] : [config: {
173
+ param: T['Param'];
174
+ } & GatherOptions]) => Promise<Array<GatheredReply<T['Result']>>>;
147
175
  to: (memberDID: string) => Promise<Client<Protocol>>;
148
176
  };
149
- export type GroupPeer<Protocols extends Record<string, ProtocolDefinition>> = {
177
+ export type InternalSurface = {
178
+ dispatch: (prc: string, config?: {
179
+ data?: Record<string, unknown>;
180
+ }) => Promise<void>;
181
+ request: (prc: string, config?: {
182
+ param?: unknown;
183
+ } & RequestOptions) => Promise<unknown>;
184
+ gather: (prc: string, config?: {
185
+ param?: unknown;
186
+ } & GatherOptions) => Promise<Array<GatheredReply>>;
187
+ to: (memberDID: string) => Promise<Client<ProtocolDefinition>>;
188
+ };
189
+ export type GroupPeer<Protocols extends Record<string, GroupProtocolDefinition>> = {
150
190
  protocol: <K extends keyof Protocols>(name: K) => ProtocolSurface<Protocols[K]>;
151
191
  /**
152
192
  * Commit to the group, rebasing until it lands.
@@ -204,6 +244,17 @@ export type GroupPeer<Protocols extends Record<string, ProtocolDefinition>> = {
204
244
  * caller can observe a roster change being detected without reaching into the port.
205
245
  */
206
246
  anchorEpoch: () => number;
247
+ /**
248
+ * Re-drive any hub subscription this peer latched as refused, on the host's word that the refusal
249
+ * may now be answered differently. The one case that needs it: a peer whose group topics were
250
+ * subscribed the instant it joined — before the app-level authorization that gates them had landed
251
+ * — is refused `AuthorizationDeniedError`, and that refusal is latched permanent (a busy retry
252
+ * against an answer would be worse). Once the host knows the peer is authorized (its membership
253
+ * row has replicated), it calls this to ask again. Single-shot per call: a topic the hub still
254
+ * refuses simply re-latches, so call it on each authorization change rather than to poll.
255
+ */
256
+ reauthorize: () => void;
207
257
  dispose: () => Promise<void>;
208
258
  };
209
259
  export declare function createGroupPeer<Protocols extends Record<string, ProtocolDefinition>>(params: GroupPeerParams<Protocols>): GroupPeer<Protocols>;
260
+ export {};
package/lib/peer.js CHANGED
@@ -1,4 +1,6 @@
1
+ import { normalizeDID } from '@kokuin/token';
1
2
  import { BroadcastClient, createBroadcastResponder, createBroadcastTransport, defaultJitter, encodeEventFrame } from '@kumiai/broadcast';
3
+ import { fromUTF } from '@sozai/codec';
2
4
  import { createRuntime } from '@sozai/runtime';
3
5
  import { createAppLane } from './app-lane.js';
4
6
  import { classifyCommit, digestAppliedCommit, UNKNOWN_FRAME_VERSION } from './classify.js';
@@ -6,7 +8,7 @@ import { CommitDeadlineError, isHeadMismatch, JournalEpochError, RecoveryRequire
6
8
  import { decodeCommitFrame, encodeCommitFrame, isUnsupportedCommitFrameVersion } from './commit-frame.js';
7
9
  import { isMissingLedgerEntries } from './crypto.js';
8
10
  import { asLogPosition } from './cursor.js';
9
- import { createDirectedClient, createInboxAcceptor, createInboxPath } from './directed.js';
11
+ import { createDirectedClient, createInboxAcceptor, createInboxPath, createUnroutedTagResponder } from './directed.js';
10
12
  import { PeerDisposedError } from './errors.js';
11
13
  import { adaptBusHandlers } from './handlers.js';
12
14
  import { decodeHandshakeFrame, encodeHandshakeFrame, HANDSHAKE_KIND, HANDSHAKE_VERSION } from './handshake.js';
@@ -57,7 +59,11 @@ const DEFAULT_RECOVERY_JITTER_MS = 250;
57
59
  * request count, so eviction only reaches ids whose deadline long passed.
58
60
  */ const SUPPRESSED_REQUESTS_MAX = 1024;
59
61
  export function createGroupPeer(params) {
60
- const { hub, crypto, mls, journal, adoptJournalled, anchorStore, appCursorStore, localDID, protocols, handlers, suppress } = params;
62
+ const { hub, crypto, mls, journal, adoptJournalled, anchorStore, appCursorStore, protocols, handlers, suppress } = params;
63
+ // Normalized ONCE, here, at the one ingress every downstream `localDID` use reads from —
64
+ // equivalent DID forms must compare and derive topics identically (`@kokuin/token`
65
+ // canonicalizes, it does not validate).
66
+ const localDID = normalizeDID(params.localDID);
61
67
  const onAppWindowPruned = params.onAppWindowPruned;
62
68
  // Destructured rather than held as `runtime`: that name is taken in this scope by
63
69
  // {@link ProtocolRuntime}, which is a different thing entirely.
@@ -86,6 +92,12 @@ export function createGroupPeer(params) {
86
92
  * topic is anchor-bound, so a roster change moves it.
87
93
  */ let inboxLane;
88
94
  /**
95
+ * The one peer-level consumer of the shared inbox path that NACKs a frame tagged for a protocol
96
+ * no acceptor here serves — every acceptor filters on its own tag, so such a frame would
97
+ * otherwise be dropped silently. Rebuilt with the epoch, since it replies on the anchor-bound
98
+ * inbox topics the rotation moves.
99
+ */ let unroutedTagResponder;
100
+ /**
89
101
  * The host's app event handlers, per protocol, as the drain calls them — the same adaptation
90
102
  * the live bus server is built from, so a drained frame and a pushed one reach the host by the
91
103
  * same door. Built once: the handlers a host passed at construction do not change, and the
@@ -198,7 +210,9 @@ export function createGroupPeer(params) {
198
210
  return createOpenOncePath({
199
211
  mux,
200
212
  topicID,
201
- unwrap: crypto.unwrap,
213
+ unwrap: (b)=>crypto.unwrap(b, {
214
+ expectedAAD: fromUTF(topicID)
215
+ }),
202
216
  retainOnFailure,
203
217
  project: (_message, opened)=>{
204
218
  const { payload, senderDID } = opened;
@@ -209,9 +223,12 @@ export function createGroupPeer(params) {
209
223
  // shared open-once signature's wider `UnwrapResult`.
210
224
  return undefined;
211
225
  }
226
+ // Normalized at the open, before it is keyed: every consumer of `openedFrames` (the
227
+ // acceptor, `gather`'s quorum) must see one canonical sender regardless of which DID form
228
+ // MLS recovered this frame under.
212
229
  openedFrames.set(payload, {
213
230
  payload,
214
- senderDID
231
+ senderDID: normalizeDID(senderDID)
215
232
  });
216
233
  return payload;
217
234
  },
@@ -265,10 +282,21 @@ export function createGroupPeer(params) {
265
282
  path: createInboxPath({
266
283
  mux,
267
284
  topicID: selfInbox,
268
- unwrap: crypto.unwrap,
285
+ unwrap: (b)=>crypto.unwrap(b, {
286
+ expectedAAD: fromUTF(selfInbox)
287
+ }),
269
288
  retainOnFailure
270
289
  })
271
290
  };
291
+ // ONE responder for the whole peer, on the shared path: it NACKs any frame whose tag names a
292
+ // protocol not in `protocols`, restoring the legible reply an acceptor's own filter drops.
293
+ unroutedTagResponder = createUnroutedTagResponder({
294
+ mux,
295
+ localDID,
296
+ inbound: inboxLane.path,
297
+ isRegistered: (name)=>Object.hasOwn(protocols, name),
298
+ sealReply: sealDirectedReply
299
+ });
272
300
  for (const [name, protocol] of Object.entries(protocols)){
273
301
  // The app topic is bound to the ANCHOR, not the live epoch — see {@link sealForSegment}.
274
302
  // Content stays sealed under the live epoch crypto below; only the topic ID is anchor-bound.
@@ -305,6 +333,7 @@ export function createGroupPeer(params) {
305
333
  inbound: inboxLane.path,
306
334
  resolveSendTopic: (senderDID)=>inboxTopic(anchor.secret, anchor.epoch, senderDID),
307
335
  protocol: protocol,
336
+ protocolName: name,
308
337
  handlers: handlers[name],
309
338
  wrap: crypto.wrap
310
339
  });
@@ -321,6 +350,10 @@ export function createGroupPeer(params) {
321
350
  // Disposal order is independent, so tear everything down concurrently and surface every
322
351
  // failure rather than dying on the first.
323
352
  const disposals = [];
353
+ // A bare unsubscribe of the shared path — synchronous, cannot reject — dropped alongside the
354
+ // acceptor consumers of that same path.
355
+ unroutedTagResponder?.dispose();
356
+ unroutedTagResponder = undefined;
324
357
  for (const runtime of runtimes.values()){
325
358
  for (const directed of runtime.directed.values())disposals.push(directed.dispose());
326
359
  runtime.directed.clear();
@@ -359,9 +392,32 @@ export function createGroupPeer(params) {
359
392
  */ const sealForSegment = async (name, bytes)=>{
360
393
  while(true){
361
394
  const at = anchor;
362
- const payload = await crypto.wrap(bytes);
395
+ const topicID = protocolTopic(at.secret, at.epoch, name);
396
+ const payload = await crypto.wrap(bytes, {
397
+ aad: fromUTF(topicID)
398
+ });
399
+ if (anchor === at) return {
400
+ topicID,
401
+ payload
402
+ };
403
+ }
404
+ };
405
+ /**
406
+ * Seal a directed reply (the unrouted-tag NACK) to a recipient's inbox under ONE anchor snapshot.
407
+ * The reply topic and the seal must agree on the epoch: were the topic read from the live anchor
408
+ * and the seal taken as a separate step, a rotation landing between them would address an
409
+ * old-epoch inbox with new-epoch ciphertext, published onto a topic the recipient no longer reads
410
+ * and silently lost. Re-read the anchor after the seal and re-seal if it moved — same identity
411
+ * (not epoch-equality) guard as {@link sealForSegment}.
412
+ */ const sealDirectedReply = async (recipientDID, tagged)=>{
413
+ while(true){
414
+ const at = anchor;
415
+ const topicID = inboxTopic(at.secret, at.epoch, recipientDID);
416
+ const payload = await crypto.wrap(tagged, {
417
+ aad: fromUTF(topicID)
418
+ });
363
419
  if (anchor === at) return {
364
- topicID: protocolTopic(at.secret, at.epoch, name),
420
+ topicID,
365
421
  payload
366
422
  };
367
423
  }
@@ -370,13 +426,14 @@ export function createGroupPeer(params) {
370
426
  const runtime = runtimes.get(name);
371
427
  if (runtime == null) throw new Error(`Unknown protocol: ${name}`);
372
428
  return {
373
- dispatch: async (prc, data)=>{
429
+ dispatch: async (prc, config)=>{
430
+ const data = config?.data ?? {};
374
431
  // Route by the procedure's declared retention. A `log` event goes to the app topic's log
375
432
  // lane (retained, pullable); ephemeral events and RPC stay on the live mailbox lane. The
376
433
  // log payload is byte-identical to what the broadcast transport would produce, so online
377
434
  // subscribers still receive it through the same drain.
378
435
  if (retentionOf(protocols[name], prc) === 'log') {
379
- const { topicID, payload } = await sealForSegment(name, encodeEventFrame(prc, data ?? {}));
436
+ const { topicID, payload } = await sealForSegment(name, encodeEventFrame(prc, data));
380
437
  await mux.publish({
381
438
  topicID,
382
439
  payload,
@@ -386,29 +443,41 @@ export function createGroupPeer(params) {
386
443
  }
387
444
  await runtime.client.dispatch(prc, data);
388
445
  },
389
- request: (prc, prm, options)=>runtime.client.request(prc, prm, options),
390
- gather: (prc, prm, options)=>runtime.client.gather(prc, prm, options),
446
+ request: (prc, config)=>runtime.client.request(prc, config?.param, {
447
+ errorThreshold: config?.errorThreshold,
448
+ timeoutMs: config?.timeoutMs
449
+ }),
450
+ gather: (prc, config)=>runtime.client.gather(prc, config?.param, {
451
+ quorum: config?.quorum,
452
+ timeoutMs: config?.timeoutMs
453
+ }),
391
454
  to: async (memberDID)=>{
392
- const cached = runtime.directed.get(memberDID);
455
+ // Normalized ONCE, at the ingress: the cache key, the topic derivation and the
456
+ // directed client's own filter (`senderDID !== memberDID`) must all see one canonical
457
+ // form, or a long-form caller never converges onto the short form MLS actually replies
458
+ // under.
459
+ const member = normalizeDID(memberDID);
460
+ const cached = runtime.directed.get(member);
393
461
  if (cached != null) return cached.client;
394
462
  const lane = inboxLane;
395
463
  if (lane == null) throw new Error('Peer is not started');
396
464
  const created = createDirectedClient({
397
465
  mux,
398
466
  localDID,
399
- memberDID,
400
- sendTopicID: inboxTopic(anchor.secret, anchor.epoch, memberDID),
467
+ memberDID: member,
468
+ sendTopicID: inboxTopic(anchor.secret, anchor.epoch, member),
401
469
  // The epoch's own inbox topic and its one open path: reading replies through a path
402
470
  // built for a topic this client does not receive on would spend keys opening frames for
403
471
  // a lane nobody listens to.
404
472
  receiveTopicID: lane.topicID,
405
473
  inbound: lane.path,
406
474
  wrap: crypto.wrap,
475
+ protocol: name,
407
476
  ...params.runtime != null ? {
408
477
  runtime: params.runtime
409
478
  } : {}
410
479
  });
411
- runtime.directed.set(memberDID, created);
480
+ runtime.directed.set(member, created);
412
481
  return created.client;
413
482
  }
414
483
  };
@@ -738,7 +807,9 @@ export function createGroupPeer(params) {
738
807
  // it. Per frame-epoch, not per rotation: a segment spanning five epochs is dispensed five
739
808
  // times off the one pull.
740
809
  await appLane.deliver();
741
- const rosterBefore = await port.rosterDIDs();
810
+ // Normalized at this ingress so an MLS-recovered form flip between the two reads (never a
811
+ // real membership change) does not read as one — see {@link detectRosterChange}.
812
+ const rosterBefore = (await port.rosterDIDs()).map(normalizeDID);
742
813
  const epochBefore = crypto.epoch();
743
814
  const advanced = await advance();
744
815
  // GATED ON THE HANDLE ACTUALLY RATCHETING: a roster diff alone is not evidence that it did. A
@@ -754,7 +825,7 @@ export function createGroupPeer(params) {
754
825
  // frames were sealed at, and a frame the live lane staged mid-walk would be thrown away
755
826
  // openable.
756
827
  const ratcheted = crypto.epoch() !== epochBefore;
757
- if (ratcheted && (detectRosterChange(rosterBefore, await port.rosterDIDs()) || rotatesAnyway(advanced))) {
828
+ if (ratcheted && (detectRosterChange(rosterBefore, (await port.rosterDIDs()).map(normalizeDID)) || rotatesAnyway(advanced))) {
758
829
  await captureAnchor();
759
830
  }
760
831
  return advanced;
@@ -883,7 +954,14 @@ export function createGroupPeer(params) {
883
954
  // `message.senderDID` — the hub's word about who handed it over, and the hub is not
884
955
  // trusted: it could stamp every recipient's own DID onto one poison frame and make the
885
956
  // whole group heal at once.
886
- const header = await port.readCommitHeader(commitFrame.commit);
957
+ const readHeader = await port.readCommitHeader(commitFrame.commit);
958
+ // Normalized before `classifyCommit` compares it against `state.localDID` (also
959
+ // normalized, at construction) — an own-unmerged commit authenticated under a different
960
+ // form of this member's own DID must still be recognized as its own.
961
+ const header = readHeader?.committerDID != null ? {
962
+ ...readHeader,
963
+ committerDID: normalizeDID(readHeader.committerDID)
964
+ } : readHeader;
887
965
  const disposition = classifyCommit({
888
966
  header,
889
967
  sequenceID: position,
@@ -1628,16 +1706,22 @@ export function createGroupPeer(params) {
1628
1706
  assertLive();
1629
1707
  return fn();
1630
1708
  };
1709
+ // Hoisted and explicitly typed (rather than inlined in the return object below) so the
1710
+ // checker can match its type against `GroupPeer<Protocols>['protocol']` by identity: inlined,
1711
+ // the whole return-object structural check against `GroupPeer<Protocols>` recurses through
1712
+ // `ProtocolSurface`'s definitions-map machinery for a still-abstract `Protocols` and blows
1713
+ // TypeScript's instantiation-depth limit (TS2589).
1714
+ const protocolMethod = (name)=>{
1715
+ const key = String(name);
1716
+ return {
1717
+ dispatch: (prc, config)=>withReady(()=>surfaceFor(key).dispatch(prc, config)),
1718
+ request: (prc, config)=>withReady(()=>surfaceFor(key).request(prc, config)),
1719
+ gather: (prc, config)=>withReady(()=>surfaceFor(key).gather(prc, config)),
1720
+ to: (memberDID)=>withReady(()=>surfaceFor(key).to(memberDID))
1721
+ };
1722
+ };
1631
1723
  return {
1632
- protocol: (name)=>{
1633
- const key = String(name);
1634
- return {
1635
- dispatch: (prc, data)=>withReady(()=>surfaceFor(key).dispatch(prc, data)),
1636
- request: (prc, prm, options)=>withReady(()=>surfaceFor(key).request(prc, prm, options)),
1637
- gather: (prc, prm, options)=>withReady(()=>surfaceFor(key).gather(prc, prm, options)),
1638
- to: (memberDID)=>withReady(()=>surfaceFor(key).to(memberDID))
1639
- };
1640
- },
1724
+ protocol: protocolMethod,
1641
1725
  commit,
1642
1726
  replay,
1643
1727
  recover,
@@ -1656,6 +1740,13 @@ export function createGroupPeer(params) {
1656
1740
  await runSerial(()=>rebuildEpoch());
1657
1741
  },
1658
1742
  anchorEpoch: ()=>anchor.epoch,
1743
+ reauthorize: ()=>{
1744
+ // No `assertLive`/`ready` wait: rearming a refused subscription is a synchronous, idempotent
1745
+ // hint the mux applies against its own state, safe on a peer that is still initializing and a
1746
+ // no-op on a disposed one (the mux guards `disposed`). It touches only topics the hub already
1747
+ // refused, so it cannot subscribe anything a normal retain would not have.
1748
+ mux.rearmRefusedTopics();
1749
+ },
1659
1750
  dispose: ()=>{
1660
1751
  if (disposePromise != null) return disposePromise;
1661
1752
  disposed = true;
package/lib/topic.d.ts CHANGED
@@ -29,8 +29,9 @@ export declare const RENDEZVOUS_LABEL = "kumiai/rendezvous/v1";
29
29
  export declare function protocolTopic(secret: Uint8Array, epoch: number, protocol: string, scope?: string): string;
30
30
  /**
31
31
  * Group-scoped personal inbox topic for unicast/directed RPC to `memberDID`.
32
- * Opaque; derivable only by fellow members. Uses the reserved {@link INBOX_LABEL}
33
- * so it never collides with an application protocol of the same name.
32
+ * Opaque; derivable only by fellow members. Uses the reserved {@link INBOX_LABEL};
33
+ * {@link protocolTopic} enforces the separation from application protocols by
34
+ * rejecting the `kumiai/` namespace.
34
35
  */
35
36
  export declare function inboxTopic(secret: Uint8Array, epoch: number, memberDID: string): string;
36
37
  /**
package/lib/topic.js CHANGED
@@ -22,17 +22,22 @@ import { fromUTF, toB64U } from '@sozai/codec';
22
22
  /** Reserved label for the non-rotating recovery-rendezvous topic. */ export const RENDEZVOUS_LABEL = 'kumiai/rendezvous/v1';
23
23
  const DISCOVERY_PREFIX = 'kumiai/discovery/v1';
24
24
  const SEP = '\0';
25
+ /** Framework label namespace. Host protocols may not derive topics under it — see {@link protocolTopic}. */ const RESERVED_LABEL_PREFIX = 'kumiai/';
25
26
  /**
26
27
  * Group-scoped broadcast/multicast topic for an application protocol. Opaque to
27
28
  * the hub; derivable only by members holding the epoch secret. `scope`
28
29
  * discriminates a subgroup (e.g. an ephemeral room) sharing the protocol.
29
30
  */ export function protocolTopic(secret, epoch, protocol, scope = '') {
31
+ if (protocol.startsWith(RESERVED_LABEL_PREFIX)) {
32
+ throw new Error(`protocolTopic: protocol must not use the reserved "${RESERVED_LABEL_PREFIX}" namespace`);
33
+ }
30
34
  return deriveTopicID(secret, epoch, protocol, scope);
31
35
  }
32
36
  /**
33
37
  * Group-scoped personal inbox topic for unicast/directed RPC to `memberDID`.
34
- * Opaque; derivable only by fellow members. Uses the reserved {@link INBOX_LABEL}
35
- * so it never collides with an application protocol of the same name.
38
+ * Opaque; derivable only by fellow members. Uses the reserved {@link INBOX_LABEL};
39
+ * {@link protocolTopic} enforces the separation from application protocols by
40
+ * rejecting the `kumiai/` namespace.
36
41
  */ export function inboxTopic(secret, epoch, memberDID) {
37
42
  return deriveTopicID(secret, epoch, INBOX_LABEL, memberDID);
38
43
  }
@@ -60,5 +65,8 @@ const SEP = '\0';
60
65
  * enumerable from the DID alone; the published domain-separation tag makes it
61
66
  * nothing-up-my-sleeve.
62
67
  */ export function discoveryTopic(memberDID) {
68
+ if (!memberDID.isWellFormed()) {
69
+ throw new Error('discoveryTopic: memberDID must be well-formed UTF-16 (no lone surrogates)');
70
+ }
63
71
  return toB64U(sha256(fromUTF(`${DISCOVERY_PREFIX}${SEP}${memberDID}`)));
64
72
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kumiai/rpc",
3
- "version": "0.8.0",
3
+ "version": "0.9.1",
4
4
  "description": "High-level MLS-aware group RPC for Enkaku: bus broadcast/anycast/gather plus directed RPC over the pub/sub hub",
5
5
  "keywords": [
6
6
  "rpc",
@@ -26,13 +26,14 @@
26
26
  "lib/*"
27
27
  ],
28
28
  "dependencies": {
29
- "@enkaku/client": "^0.21.1",
30
- "@enkaku/protocol": "^0.21.0",
29
+ "@enkaku/client": "^0.21.2",
30
+ "@enkaku/protocol": "^0.21.1",
31
31
  "@enkaku/server": "^0.21.2",
32
32
  "@enkaku/transport": "^0.21.0",
33
- "@kumiai/broadcast": "^0.8.0",
34
- "@kumiai/hub-protocol": "^0.8.0",
35
- "@kumiai/hub-tunnel": "^0.8.0",
33
+ "@kokuin/token": "^0.5.0",
34
+ "@kumiai/broadcast": "^0.9.0",
35
+ "@kumiai/hub-protocol": "^0.9.0",
36
+ "@kumiai/hub-tunnel": "^0.9.0",
36
37
  "@noble/hashes": "^2.4.0",
37
38
  "@sozai/codec": "^0.4.0",
38
39
  "@sozai/event": "^0.1.3",
@@ -41,8 +42,8 @@
41
42
  "@sozai/schema": "^0.1.2"
42
43
  },
43
44
  "devDependencies": {
44
- "@kumiai/hub-conformance": "^0.8.0",
45
- "@kumiai/rpc-conformance": "^0.8.0",
45
+ "@kumiai/hub-conformance": "^0.9.0",
46
+ "@kumiai/rpc-conformance": "^0.9.0",
46
47
  "@noble/curves": "^2.4.0",
47
48
  "vitest": "^4.1.11"
48
49
  },