@kumiai/rpc 0.12.3 → 0.13.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.
@@ -1,3 +1,7 @@
1
+ export type AppCursorStoreSaveParams = {
2
+ topicID: string;
3
+ position: string;
4
+ };
1
5
  /**
2
6
  * The host's durable read position on ONE app-lane topic: the last frame the drain is DONE with.
3
7
  *
@@ -29,7 +33,7 @@
29
33
  */
30
34
  export type AppCursorStore = {
31
35
  load(topicID: string): Promise<string | null>;
32
- save(topicID: string, position: string): Promise<void>;
36
+ save(params: AppCursorStoreSaveParams): Promise<void>;
33
37
  };
34
38
  /**
35
39
  * A gap below retention: the hub confirms that a frame after this peer's read position aged out.
package/lib/app-cursor.js CHANGED
@@ -1,32 +1,4 @@
1
1
  /**
2
- * The host's durable read position on ONE app-lane topic: the last frame the drain is DONE with.
3
- *
4
- * It exists because the drain is the only thing that delivers a retained app frame to a peer that
5
- * was away, and without a position it re-reads the topic from the hub's oldest retained frame on
6
- * every restart. That re-read is not free: it re-delivers whatever the handle can still open, and
7
- * it hides the one thing a reader must be told — that the hub's retention floor has passed the
8
- * place this peer had got to, so frames between the two are gone. A position is what makes a
9
- * re-read unnecessary and a gap knowable, and both only if it survives the process.
10
- *
11
- * THE ADVANCE RULE, which the store's whole value rests on: a cursor may only pass a frame that is
12
- * DELIVERED or DEAD. A frame sealed at an epoch the walk has not reached yet is neither — it is
13
- * openable later, and only later — and a cursor that passed it would drop it on the next restart,
14
- * which is the exact loss this store exists to stop. See the drain in `app-lane.ts`, which is where
15
- * the rule is enforced.
16
- *
17
- * Keyed by TOPIC ID, and not folded into {@link "anchor".AnchorStore}: a topic ID already encodes
18
- * both the segment (it is anchor-bound) and the protocol, which is exactly the granularity a read
19
- * position has — the drain is per-protocol, and the position is written per drain rather than per
20
- * rotation. A rotation onto a new segment is a new topic and therefore a fresh position, with no
21
- * clearing to forget.
22
- *
23
- * `load` returning `null` means this peer has never processed a frame on that topic: read from the
24
- * hub's oldest retained frame, and report no gap — nothing is known to be missing from a place the
25
- * peer has never been.
26
- *
27
- * Positions are log positions (see `cursor.ts`), opaque to the host: store the string, compare
28
- * nothing.
29
- */ /**
30
2
  * A gap below retention: the hub confirms that a frame after this peer's read position aged out.
31
3
  *
32
4
  * Reported rather than silent, which is the whole point — a peer back from a long absence is
package/lib/app-lane.js CHANGED
@@ -203,7 +203,11 @@ function frameID(topicID, bytes) {
203
203
  let cursor = cursors.get(name);
204
204
  if (cursor == null) {
205
205
  const at = anchor();
206
- const topicID = protocolTopic(at.secret, at.epoch, name);
206
+ const topicID = protocolTopic({
207
+ secret: at.secret,
208
+ epoch: at.epoch,
209
+ protocol: name
210
+ });
207
211
  const stored = await appCursorStore?.load(topicID) ?? null;
208
212
  cursor = {
209
213
  topicID,
@@ -321,7 +325,10 @@ function frameID(topicID, bytes) {
321
325
  if (passed > 0) frames.splice(0, passed);
322
326
  if (position == null || position === cursor.position) return;
323
327
  cursor.position = position;
324
- await appCursorStore?.save(cursor.topicID, position);
328
+ await appCursorStore?.save({
329
+ topicID: cursor.topicID,
330
+ position
331
+ });
325
332
  };
326
333
  const orderedRecords = (name)=>pendingRecords.filter((record)=>record.frame.protocol === name).sort((a, b)=>a.frame.segment - b.frame.segment || a.frame.position.localeCompare(b.frame.position));
327
334
  const blockedByEarlierSealed = (record)=>{
@@ -363,7 +370,10 @@ function frameID(topicID, bytes) {
363
370
  const prc = message?.payload?.prc;
364
371
  const protocol = protocols[record.frame.protocol];
365
372
  const events = appEventHandlers.get(record.frame.protocol);
366
- if (normalizeDID(record.senderDID) !== localDID && message?.payload?.typ === 'event' && typeof prc === 'string' && protocol != null && retentionOf(protocol, prc) === 'log' && events != null) {
373
+ if (normalizeDID(record.senderDID) !== localDID && message?.payload?.typ === 'event' && typeof prc === 'string' && protocol != null && retentionOf({
374
+ protocol,
375
+ procedureName: prc
376
+ }) === 'log' && events != null) {
367
377
  const event = {
368
378
  data: message.payload.data ?? {},
369
379
  senderDID: normalizeDID(record.senderDID),
@@ -558,7 +568,8 @@ function frameID(topicID, bytes) {
558
568
  // `crypto.unwrap` always returns the full result — `senderDID` is REQUIRED — so there is
559
569
  // no bare-`Uint8Array` shortcut left to normalize away here. `expectedAAD` is bound to
560
570
  // the cursor's own topic, the authoritative answer to "what lane is this drain reading".
561
- opened = await crypto.unwrap(sealed, {
571
+ opened = await crypto.unwrap({
572
+ bytes: sealed,
562
573
  expectedAAD: encodeAppAAD({
563
574
  topicID: cursor.topicID,
564
575
  intent: 'log'
@@ -627,7 +638,10 @@ function frameID(topicID, bytes) {
627
638
  // whose dispatch would never do that. Retention is the protocol's word, not the frame's.
628
639
  const protocol = protocols[name];
629
640
  if (protocol === undefined) continue;
630
- if (retentionOf(protocol, prc) !== 'log') continue;
641
+ if (retentionOf({
642
+ protocol,
643
+ procedureName: prc
644
+ }) !== 'log') continue;
631
645
  try {
632
646
  // Same door as the live push: emit the retained frame's plaintext into the
633
647
  // per-protocol emitter the live bus is also built from. No listener → no-op.
@@ -40,8 +40,12 @@ export type CommitFrame = {
40
40
  /** The sealed ledger-entry bodies this Commit enacts. Opaque until opened. */
41
41
  sealedEntries: Uint8Array;
42
42
  };
43
+ export type EncodeCommitFrameParams = {
44
+ commit: Uint8Array;
45
+ sealedEntries: Uint8Array;
46
+ };
43
47
  /** Frame a Commit with the sealed blob of the entry bodies it enacts. */
44
- export declare function encodeCommitFrame(commit: Uint8Array, sealedEntries: Uint8Array): Uint8Array;
48
+ export declare function encodeCommitFrame({ commit, sealedEntries }: EncodeCommitFrameParams): Uint8Array;
45
49
  /**
46
50
  * Thrown by {@link decodeCommitFrame} for an unknown version byte, and ONLY for that: the lane
47
51
  * must treat it differently from "not a frame" (dropped) — a frame from the future goes to the
@@ -34,7 +34,7 @@
34
34
  const VERSION_BYTES = 1;
35
35
  const COMMIT_LENGTH_BYTES = 4;
36
36
  const HEADER_BYTES = VERSION_BYTES + COMMIT_LENGTH_BYTES;
37
- /** Frame a Commit with the sealed blob of the entry bodies it enacts. */ export function encodeCommitFrame(commit, sealedEntries) {
37
+ /** Frame a Commit with the sealed blob of the entry bodies it enacts. */ export function encodeCommitFrame({ commit, sealedEntries }) {
38
38
  const frame = new Uint8Array(HEADER_BYTES + commit.length + sealedEntries.length);
39
39
  frame[0] = COMMIT_FRAME_VERSION;
40
40
  new DataView(frame.buffer).setUint32(VERSION_BYTES, commit.length, true);
package/lib/commit.d.ts CHANGED
@@ -86,6 +86,10 @@ export type JournalEntry = {
86
86
  kind: CommitKind;
87
87
  journal: Uint8Array;
88
88
  };
89
+ export type CommitJournalMarkAcceptedParams = {
90
+ publishID: string;
91
+ sequenceID: string;
92
+ };
89
93
  /**
90
94
  * Durable single-slot journal, host-provided (the host already persists handle state; the peer
91
95
  * has no storage). Holds at most one pending commit — the peer's commit mutex written down: one
@@ -109,7 +113,7 @@ export type CommitJournal = {
109
113
  * Record that the hub accepted this commit as `sequenceID`. Must be durable before it
110
114
  * resolves, and must land before the host adopts.
111
115
  */
112
- markAccepted(publishID: string, sequenceID: string): Promise<void>;
116
+ markAccepted(params: CommitJournalMarkAcceptedParams): Promise<void>;
113
117
  get(): Promise<JournalEntry | null>;
114
118
  clear(publishID: string): Promise<void>;
115
119
  };
package/lib/crypto.d.ts CHANGED
@@ -1,3 +1,16 @@
1
+ export type GroupCryptoExportSecretParams = {
2
+ label: string;
3
+ length?: number;
4
+ };
5
+ export type GroupCryptoWrapParams = {
6
+ bytes: Uint8Array;
7
+ aad?: Uint8Array;
8
+ };
9
+ export type GroupCryptoUnwrapParams = {
10
+ bytes: Uint8Array;
11
+ expectedAAD?: Uint8Array;
12
+ frame?: AppFrameRef;
13
+ };
1
14
  /**
2
15
  * Consumer-supplied MLS crypto port: epoch number, epoch-bound domain-separated exported secrets
3
16
  * (`exportSecret`), byte-level encrypt/decrypt (`wrap`/`unwrap`), and the ledger-entry seal
@@ -12,8 +25,8 @@
12
25
  * `wrap`/`unwrap` close over the live group and always use current epoch state. `unwrap` returns
13
26
  * the authenticated sender (`senderDID`), REQUIRED — see {@link GroupUnwrapResult}.
14
27
  *
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`
28
+ * `wrap` takes an optional `aad`, so fixed-topic lanes adapt it to a `ByteTransform` closure, whilst
29
+ * directed lanes pass it directly. `unwrap`'s optional `expectedAAD`
17
30
  * is compared PRE-OPEN, so a wrong-topic frame costs no ratchet generation.
18
31
  *
19
32
  * `unwrap` MUST open bytes sealed at the handle's CURRENT epoch, and refuse a readable frame at any
@@ -59,10 +72,8 @@ export type GroupCrypto = {
59
72
  * the ledger-entry blobs of every commit enacted after its removal, with nothing throwing to
60
73
  * say so.
61
74
  */
62
- exportSecret(label: string, length?: number): ExportSecretResult | Promise<ExportSecretResult>;
63
- wrap(bytes: Uint8Array, opts?: {
64
- aad?: Uint8Array;
65
- }): Uint8Array | Promise<Uint8Array>;
75
+ exportSecret(params: GroupCryptoExportSecretParams): ExportSecretResult | Promise<ExportSecretResult>;
76
+ wrap(params: GroupCryptoWrapParams): Uint8Array | Promise<Uint8Array>;
66
77
  /**
67
78
  * Open a sealed app frame and recover who sent it. Returns {@link GroupUnwrapResult}, whose
68
79
  * `senderDID` is REQUIRED: an implementation that cannot name the sender must throw, not return
@@ -72,10 +83,7 @@ export type GroupCrypto = {
72
83
  * frames that would otherwise burn a ratchet generation (DoS).
73
84
  * A readable frame at another epoch throws {@link FrameEpochError} before decrypting.
74
85
  */
75
- unwrap(bytes: Uint8Array, opts?: {
76
- expectedAAD?: Uint8Array;
77
- frame?: AppFrameRef;
78
- }): GroupUnwrapResult | Promise<GroupUnwrapResult>;
86
+ unwrap(params: GroupCryptoUnwrapParams): GroupUnwrapResult | Promise<GroupUnwrapResult>;
79
87
  /** Cleartext app AAD for pre-open routing. Untrusted until unwrap authenticates it. Never throws. */
80
88
  frameAAD(bytes: Uint8Array): Uint8Array | null;
81
89
  /** Present iff opened app frames and their consumed handle state are saved atomically. */
@@ -175,10 +183,14 @@ export type ProcessCommitResult = {
175
183
  epochAfter: number;
176
184
  refusal?: RecoveryRefusalReason;
177
185
  };
186
+ export type FrameEpochErrorParams = {
187
+ frameEpoch: number;
188
+ handleEpoch: number;
189
+ };
178
190
  /** A frame refused against the locked handle epoch, before spending a decrypt key. */
179
191
  export declare class FrameEpochError extends Error {
180
192
  #private;
181
- constructor(frameEpoch: number, handleEpoch: number);
193
+ constructor({ frameEpoch, handleEpoch }: FrameEpochErrorParams);
182
194
  get frameEpoch(): number;
183
195
  get handleEpoch(): number;
184
196
  }
@@ -329,6 +341,10 @@ export type CommitContext = {
329
341
  */
330
342
  resolveLedgerEntries?: (ids: Array<string>) => Promise<Array<string>>;
331
343
  };
344
+ export type PendingRecoveryConfirmationKeyParams = {
345
+ position: string;
346
+ commitDigest: string;
347
+ };
332
348
  /**
333
349
  * A speculative external rejoin. Publication alone never authorises adoption.
334
350
  * The caller confirms the target epoch before accepting it.
@@ -338,9 +354,9 @@ export type PendingRecovery = {
338
354
  /** Mark an authoritative binding/lapse/floor refusal. Bounded memory survives ratchets, not restart. */
339
355
  markBindingUnusable(): void;
340
356
  /** Bind judgement to the published tuple and derive from the speculative epoch. */
341
- confirmationKey(position: string, commitDigest: string): Promise<Uint8Array>;
357
+ confirmationKey(params: PendingRecoveryConfirmationKeyParams): Promise<Uint8Array>;
342
358
  /** Call after confirmationKey resolves. Failed bindings or signer gates are advisory. */
343
- judgeVerdict(opened: OpenedRecoveryVerdict): 'authoritative' | 'advisory';
359
+ judgeVerdict(opened: OpenedRecoveryVerdict): Promise<'authoritative' | 'advisory'>;
344
360
  /** The external-commit bytes, framed at the epoch the sealed GroupInfo described. */
345
361
  commit: Uint8Array;
346
362
  /**
@@ -372,6 +388,34 @@ export type RecoveryConfirmationKey = {
372
388
  epoch: number;
373
389
  key: Uint8Array;
374
390
  };
391
+ export type GroupMLSConfirmationKeyParams = {
392
+ position: string;
393
+ commitDigest: string;
394
+ };
395
+ export type GroupMLSSealRecoveryVerdictParams = {
396
+ request: Uint8Array;
397
+ verdict: RecoveryVerdict;
398
+ };
399
+ export type GroupMLSOpenRecoveryVerdictParams = {
400
+ sealed: Uint8Array;
401
+ requestID: string;
402
+ };
403
+ export type GroupMLSProcessCommitParams = {
404
+ commit: Uint8Array;
405
+ context: CommitContext;
406
+ };
407
+ export type GroupMLSCreateRecoveryRequestParams = {
408
+ requestID: string;
409
+ deadlineMs?: number;
410
+ };
411
+ export type GroupMLSApplyRecoveryParams = {
412
+ sealed: Uint8Array;
413
+ requestID: string;
414
+ };
415
+ export type GroupMLSOpenSealedLedgerParams = {
416
+ sealed: Uint8Array;
417
+ requestID: string;
418
+ };
375
419
  /**
376
420
  * Consumer-supplied MLS lifecycle port. Sibling to {@link GroupCrypto}: this drives the
377
421
  * handshake lane — applying Commits to advance the epoch, re-syncing a stranded peer. group-rpc
@@ -386,9 +430,9 @@ export type RecoveryConfirmationKey = {
386
430
  export type GroupMLS = {
387
431
  /** Verify the signed ask without requiring its issuer to remain in the current tree. */
388
432
  verifyRecoveryRequest(request: Uint8Array): Promise<VerifiedRecoveryRequest | null>;
389
- confirmationKey(position: string, commitDigest: string): Promise<RecoveryConfirmationKey>;
390
- sealRecoveryVerdict(request: Uint8Array, verdict: RecoveryVerdict): Promise<Uint8Array>;
391
- openRecoveryVerdict(sealed: Uint8Array, requestID: string): Promise<OpenedRecoveryVerdict | null>;
433
+ confirmationKey(params: GroupMLSConfirmationKeyParams): Promise<RecoveryConfirmationKey>;
434
+ sealRecoveryVerdict(params: GroupMLSSealRecoveryVerdictParams): Promise<Uint8Array>;
435
+ openRecoveryVerdict(params: GroupMLSOpenRecoveryVerdictParams): Promise<OpenedRecoveryVerdict | null>;
392
436
  /** Published with the epoch, without taking the handle lock. */
393
437
  sendAdmission(): SendAdmission;
394
438
  /** Read the current handle epoch under the host's handle lock. */
@@ -466,7 +510,7 @@ export type GroupMLS = {
466
510
  * contract on a frame it should have applied, which the lane DOES re-read. See
467
511
  * {@link isMissingLedgerEntries}.
468
512
  */
469
- processCommit(commit: Uint8Array, context: CommitContext): Promise<ProcessCommitResult>;
513
+ processCommit(params: GroupMLSProcessCommitParams): Promise<ProcessCommitResult>;
470
514
  /** Check lifecycle binding availability once before a recovery attempt requests GroupInfo. */
471
515
  prepareRecovery(): Promise<'ready' | 'renewal-required'>;
472
516
  /**
@@ -483,7 +527,7 @@ export type GroupMLS = {
483
527
  * off the mint time is the natural bound; it lives here rather than as a new lane release
484
528
  * method that would obligate every {@link GroupMLS}.
485
529
  */
486
- createRecoveryRequest(requestID: string, deadlineMs?: number): Promise<Uint8Array>;
530
+ createRecoveryRequest(params: GroupMLSCreateRecoveryRequestParams): Promise<Uint8Array>;
487
531
  /**
488
532
  * Answer another member's request: verify the token, check the requester still holds a leaf in
489
533
  * THIS member's current ratchet tree, seal current GroupInfo to the ephemeral key inside the
@@ -510,7 +554,7 @@ export type GroupMLS = {
510
554
  * reply the AEAD refuses, or one that fails either check, is `null`; a throw is tolerated and
511
555
  * read the same way.
512
556
  */
513
- applyRecovery(sealed: Uint8Array, requestID: string): Promise<AppliedRecovery>;
557
+ applyRecovery(params: GroupMLSApplyRecoveryParams): Promise<AppliedRecovery>;
514
558
  /**
515
559
  * Whether the ledger this handle holds is the whole ledger its OWN GroupContext attests to: the
516
560
  * head folded from the entries it holds, against the authenticated head it carries. Purely
@@ -557,7 +601,7 @@ export type GroupMLS = {
557
601
  * a forged, lying, reordered or truncated one fails and is dropped — withhold, never rewrite. A
558
602
  * forged reply that merely decrypts costs one gather attempt: denial of service, not compromise.
559
603
  */
560
- openSealedLedger(sealed: Uint8Array, requestID: string): Promise<Array<string> | null>;
604
+ openSealedLedger(params: GroupMLSOpenSealedLedgerParams): Promise<Array<string> | null>;
561
605
  /**
562
606
  * Install a gathered ledger, verified against the authenticated head BEFORE a single entry is
563
607
  * folded. REPLACES the ledger this handle holds — sound because a list reproducing the head
package/lib/crypto.js CHANGED
@@ -1,36 +1,7 @@
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()` is a hint for display and logging; every decision uses the epoch a result reports.
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, and refuse a readable frame at any
20
- * other epoch with {@link FrameEpochError} before decrypting.
21
- *
22
- * `unwrap` throwing is ORDINARY CONTROL FLOW on the read paths, not an error — it means "not my
23
- * epoch". Readers walk logs full of frames from epochs they don't hold and drop them without
24
- * treating them as corrupt.
25
- *
26
- * IMPLEMENTING THIS PORT OBLIGES RUNNING `@kumiai/rpc-conformance` AGAINST THE IMPLEMENTATION.
27
- * Not a recommendation: the suite is where this port's contract actually lives, and the clauses
28
- * exist because implementations got them wrong. A host that writes its own `GroupCrypto` and does
29
- * not run the suite has an untested crypto boundary, whatever else it tests.
30
- */ /** A frame refused against the locked handle epoch, before spending a decrypt key. */ export class FrameEpochError extends Error {
1
+ /** A frame refused against the locked handle epoch, before spending a decrypt key. */ export class FrameEpochError extends Error {
31
2
  #frameEpoch;
32
3
  #handleEpoch;
33
- constructor(frameEpoch, handleEpoch){
4
+ constructor({ frameEpoch, handleEpoch }){
34
5
  super(`frame epoch ${frameEpoch} differs from handle epoch ${handleEpoch}`);
35
6
  this.name = 'FrameEpochError';
36
7
  this.#frameEpoch = frameEpoch;
package/lib/directed.d.ts CHANGED
@@ -32,6 +32,7 @@ export type InboxPathParams = {
32
32
  unwrap: (bytes: Uint8Array) => GroupUnwrapResult | Promise<GroupUnwrapResult>;
33
33
  /** Forwarded to {@link createOpenOncePath} — see there for what it decides. */
34
34
  retainOnFailure?: (message: StoredMessage, error: unknown) => boolean;
35
+ ingress?: (task: () => Promise<void>) => Promise<void>;
35
36
  };
36
37
  /**
37
38
  * The one path that opens an inbox topic's frames, for every consumer of it.
package/lib/directed.js CHANGED
@@ -19,6 +19,9 @@ import { createOpenOncePath } from './open-once.js';
19
19
  mux,
20
20
  topicID,
21
21
  unwrap,
22
+ ...params.ingress != null ? {
23
+ ingress: params.ingress
24
+ } : {},
22
25
  ...retainOnFailure != null ? {
23
26
  retainOnFailure
24
27
  } : {},
@@ -71,7 +74,8 @@ import { createOpenOncePath } from './open-once.js';
71
74
  return mux.mailbox.publish({
72
75
  senderDID: publishParams.senderDID,
73
76
  topicID: publishParams.topicID,
74
- payload: await wrap(tagged, {
77
+ payload: await wrap({
78
+ bytes: tagged,
75
79
  aad: encodeAppAAD({
76
80
  topicID: publishParams.topicID,
77
81
  intent: 'ephemeral'
@@ -233,7 +237,8 @@ import { createOpenOncePath } from './open-once.js';
233
237
  const sessionHub = {
234
238
  async publish (publishParams) {
235
239
  const tagged = encodeDirectedPayload(protocolName, publishParams.payload);
236
- const sealed = await wrap(tagged, {
240
+ const sealed = await wrap({
241
+ bytes: tagged,
237
242
  aad: encodeAppAAD({
238
243
  topicID: publishParams.topicID,
239
244
  intent: 'ephemeral'
package/lib/handlers.d.ts CHANGED
@@ -15,7 +15,7 @@ export type GroupProcedureHandlers<Protocol extends ProtocolDefinition> = {
15
15
  export type BusHandlerMaps = {
16
16
  /** Fire-and-forget event fan-out, keyed by procedure name. Host handlers are pre-registered. */
17
17
  events: EventEmitter<BusEvents>;
18
- /** Anycast request procedures: prc -> handler(param, { senderDID, signal }) -> result. */
18
+ /** Anycast request procedures: prc -> handler({ prm, context: { senderDID, signal } }) -> result. */
19
19
  requestHandlers: Record<string, BroadcastHandler>;
20
20
  };
21
21
  /**
package/lib/handlers.js CHANGED
@@ -51,7 +51,7 @@ import { createValidator } from '@sozai/schema';
51
51
  // async: a validation failure must reach the caller as a REJECTED promise (the shape
52
52
  // `createBroadcastResponder`'s handleRequest awaits), not a synchronous throw escaping the
53
53
  // call expression before any promise exists.
54
- const fn = async (param, context)=>{
54
+ const fn = async ({ prm: param, context })=>{
55
55
  if (validator != null) {
56
56
  const result = validator(param);
57
57
  if (result instanceof Error) throw result;
@@ -64,7 +64,10 @@ import { createValidator } from '@sozai/schema';
64
64
  message: busMessage(context?.senderDID)
65
65
  });
66
66
  };
67
- requestHandlers[prc] = Object.keys(suppress).length > 0 ? suppressible(fn, suppress) : fn;
67
+ requestHandlers[prc] = Object.keys(suppress).length > 0 ? suppressible({
68
+ handler: fn,
69
+ ...suppress
70
+ }) : fn;
68
71
  }
69
72
  }
70
73
  return {
@@ -59,8 +59,12 @@ export declare const HANDSHAKE_KIND: {
59
59
  readonly recoveryVerdict: 6;
60
60
  };
61
61
  export type HandshakeKind = (typeof HANDSHAKE_KIND)[keyof typeof HANDSHAKE_KIND];
62
+ export type EncodeHandshakeFrameParams = {
63
+ kind: HandshakeKind;
64
+ payload: Uint8Array;
65
+ };
62
66
  /** Wrap a payload with the magic + version + kind header. */
63
- export declare function encodeHandshakeFrame(kind: HandshakeKind, payload: Uint8Array): Uint8Array;
67
+ export declare function encodeHandshakeFrame({ kind, payload }: EncodeHandshakeFrameParams): Uint8Array;
64
68
  /**
65
69
  * Validate the header and split a frame into its version, kind and payload. Throws on a short
66
70
  * frame, a bad magic, or an unknown kind in the current version.
package/lib/handshake.js CHANGED
@@ -58,7 +58,7 @@ const KINDS = new Set(Object.values(HANDSHAKE_KIND));
58
58
  function isHandshakeKind(value) {
59
59
  return KINDS.has(value);
60
60
  }
61
- /** Wrap a payload with the magic + version + kind header. */ export function encodeHandshakeFrame(kind, payload) {
61
+ /** Wrap a payload with the magic + version + kind header. */ export function encodeHandshakeFrame({ kind, payload }) {
62
62
  const frame = new Uint8Array(HEADER_LENGTH + payload.length);
63
63
  frame.set(HANDSHAKE_MAGIC, 0);
64
64
  frame[HANDSHAKE_MAGIC.length] = HANDSHAKE_VERSION;
package/lib/hub-mux.js CHANGED
@@ -130,7 +130,11 @@ const warnReceiveEnded = (ended)=>{
130
130
  try {
131
131
  // Inside the try, and awaited: `subscribe` may reject OR throw synchronously (the type
132
132
  // allows `void`), and the old code's `Promise.resolve(...).catch()` caught only the first.
133
- await hub.subscribe(localDID, topicID, options);
133
+ await hub.subscribe({
134
+ subscriberDID: localDID,
135
+ topicID,
136
+ ...options
137
+ });
134
138
  if (disposed) return;
135
139
  subscriptions.set(topicID, {
136
140
  kind: 'held'
@@ -297,7 +301,9 @@ const warnReceiveEnded = (ended)=>{
297
301
  // still release a claim for a frame it already received.
298
302
  };
299
303
  };
300
- const subscription = hub.receive(localDID);
304
+ const subscription = hub.receive({
305
+ subscriberDID: localDID
306
+ });
301
307
  const iterator = subscription[Symbol.asyncIterator]();
302
308
  const pending = new Map();
303
309
  const ackUpstream = (position)=>{
@@ -438,7 +444,7 @@ const warnReceiveEnded = (ended)=>{
438
444
  }
439
445
  })();
440
446
  const bus = {
441
- publish: async (topicID, payload)=>{
447
+ publish: async ({ topicID, payload })=>{
442
448
  // A publish not yet reached: see `publishSuspended`'s note above for why this awaits
443
449
  // nothing and what it does NOT cover.
444
450
  if (publishSuspended) throw new PeerDisposedError('mux: publish after dispose');
@@ -450,7 +456,7 @@ const warnReceiveEnded = (ended)=>{
450
456
  payload
451
457
  });
452
458
  },
453
- subscribe: (topicID, onMessage)=>onInbound(topicID, (message, ack)=>onMessage(message.payload, ack))
459
+ subscribe: ({ topicID, onMessage })=>onInbound(topicID, (message, ack)=>onMessage(message.payload, ack))
454
460
  };
455
461
  const mailbox = {
456
462
  publish: async (publishParams)=>{
@@ -460,13 +466,13 @@ const warnReceiveEnded = (ended)=>{
460
466
  assertFrameFits(publishParams.payload);
461
467
  return await hub.publish(publishParams);
462
468
  },
463
- subscribe: (_subscriberDID, topicID)=>{
469
+ subscribe: ({ subscriberDID: _subscriberDID, topicID })=>{
464
470
  retain(topicID);
465
471
  },
466
- unsubscribe: (_subscriberDID, topicID)=>{
472
+ unsubscribe: ({ subscriberDID: _subscriberDID, topicID })=>{
467
473
  release(topicID);
468
474
  },
469
- receive: (_subscriberDID, options)=>{
475
+ receive: ({ subscriberDID: _subscriberDID, ...options })=>{
470
476
  const queue = [];
471
477
  let resolveNext;
472
478
  let closed = false;
package/lib/index.d.ts CHANGED
@@ -5,23 +5,33 @@
5
5
  */
6
6
  export type { Anchor, AnchorSlot, AnchorStore } from './anchor.js';
7
7
  export { type AppAAD, decodeAppAAD, encodeAppAAD } from './app-aad.js';
8
- export type { AppCursorStore, AppWindowPruned } from './app-cursor.js';
8
+ export type { AppCursorStore, AppCursorStoreSaveParams, AppWindowPruned } from './app-cursor.js';
9
9
  export type { AppDeliveryResumed, AppDeliveryStalled } from './app-lane.js';
10
10
  export { type AppOutbox, type AppOutboxEntry, type CommitCursor, MAX_APP_ENTRY_BYTES, } from './app-outbox.js';
11
11
  export { type AppliedCommit, type ClassifyCommitParams, type CommitClassifierState, type CommitDisposition, type CommitFrameEvidence, classifyCommit, digestAppliedCommit, UNKNOWN_FRAME_VERSION, } from './classify.js';
12
+ export type { CommitJournalMarkAcceptedParams } from './commit.js';
12
13
  export { CommitDeadlineError, type CommitJournal, type CommitKind, isHeadMismatch, type JournalEntry, JournalEpochError, type LaneResult, type LostCommit, type PendingCommit, RecoveryRequiredError, } from './commit.js';
14
+ export type { EncodeCommitFrameParams } from './commit-frame.js';
13
15
  export { COMMIT_FRAME_VERSION, type CommitFrame, decodeCommitFrame, encodeCommitFrame, isUnsupportedCommitFrameVersion, UnsupportedCommitFrameVersionError, } from './commit-frame.js';
16
+ export type { FrameEpochErrorParams, GroupCryptoExportSecretParams, GroupCryptoUnwrapParams, GroupCryptoWrapParams, GroupMLSApplyRecoveryParams, GroupMLSConfirmationKeyParams, GroupMLSCreateRecoveryRequestParams, GroupMLSOpenRecoveryVerdictParams, GroupMLSOpenSealedLedgerParams, GroupMLSProcessCommitParams, GroupMLSSealRecoveryVerdictParams, PendingRecoveryConfirmationKeyParams, } from './crypto.js';
14
17
  export { type AppFrameRef, AppFrameStorageError, type AppliedRecovery, type CommitContext, type CommitHeader, type ExportSecretResult, FrameEpochError, type GroupCrypto, type GroupMLS, type GroupUnwrapResult, isAppFrameStorageError, isMissingLedgerEntries, type OpenedRecoveryVerdict, type PendingAppFrame, type PendingAppFrames, type PendingRecovery, type ProcessCommitResult, type RecoveryConfirmationKey, type RecoveryRefusalReason, type RecoveryVerdict, type RosterEntry, type SealEntriesResult, type SendAdmission, sortPendingAppFrames, type VerifiedRecoveryRequest, } from './crypto.js';
15
18
  export { asDeliveryPosition, asLogPosition, type DeliveryPosition, type LogPosition, } from './cursor.js';
16
19
  export { AppEntryTooLargeError, AppOutboxFullError, CommitBuildHooksError, PeerDisposedError, PeerRemovedError, SendNotAdmissibleError, } from './errors.js';
17
20
  export { assertFrameFits, FrameTooLargeError } from './frame-size.js';
18
21
  export type { GroupProcedureHandlers } from './handlers.js';
22
+ export type { EncodeHandshakeFrameParams } from './handshake.js';
19
23
  export { decodeHandshakeFrame, encodeHandshakeFrame, HANDSHAKE_KIND, HANDSHAKE_MAGIC, HANDSHAKE_VERSION, type HandshakeKind, } from './handshake.js';
20
24
  export type { ReceiveLaneEnded, SubscribeFailure } from './hub-mux.js';
25
+ export type { CreateLedgerEntryResolverParams } from './ledger-entries.js';
21
26
  export { createLedgerEntryResolver, decodeLedgerEntries, encodeLedgerEntries, LEDGER_ENTRIES_VERSION, } from './ledger-entries.js';
22
27
  export type { AppOutboxCleared, EpochFloor } from './log-delivery.js';
23
28
  export { createGroupPeer, type GroupPeer, type GroupPeerMLSParams, type GroupPeerParams, type ProtocolSurface, type RecoveryEvent, type RecoveryFailureDetails, type RecoveryFailureReason, type RecoveryTrigger, type StrandConfidence, type StrandKind, type StrandObservation, } from './peer.js';
29
+ export type { GroupPeerCommitParams, GroupPeerDropAppFrameParams } from './peer-types.js';
30
+ export type { RetentionOfParams } from './protocol.js';
24
31
  export { defineGroupProtocol, type GroupProcedureDefinition, type GroupProtocolDefinition, type RetainableEventProcedureDefinition, type Retention, retentionOf, } from './protocol.js';
32
+ export type { EncodeLedgerReplyParams, EncodeLedgerRequestParams, EncodeRecoveryReplyParams, EncodeRecoveryRequestParams, EncodeRecoveryVerdictParams, } from './recovery.js';
25
33
  export { decodeLedgerReply, decodeLedgerRequest, decodeRecoveryConfirmRequest, decodeRecoveryReply, decodeRecoveryRequest, decodeRecoveryVerdict, encodeLedgerReply, encodeLedgerRequest, encodeRecoveryConfirmRequest, encodeRecoveryReply, encodeRecoveryRequest, encodeRecoveryVerdict, type RecoveryConfirmRequest, type RecoveryVerdictFrame, } from './recovery.js';
34
+ export type { DetectLeafAdmissionParams, DetectRosterChangeParams } from './roster.js';
26
35
  export { detectLeafAdmission, detectRosterChange } from './roster.js';
36
+ export type { InboxTopicParams, ProtocolTopicParams } from './topic.js';
27
37
  export { APP_TOPIC_LABEL, COMMIT_LABEL, commitTopic, discoveryTopic, INBOX_LABEL, inboxTopic, protocolTopic, RENDEZVOUS_LABEL, rendezvousTopic, } from './topic.js';
@@ -29,6 +29,10 @@ export declare function encodeLedgerEntries(tokens: Array<string>): Uint8Array;
29
29
  * on a version this build does not know.
30
30
  */
31
31
  export declare function decodeLedgerEntries(bytes: Uint8Array): Array<string>;
32
+ export type CreateLedgerEntryResolverParams = {
33
+ sealedEntries: Uint8Array;
34
+ openEntries: GroupCrypto['openEntries'];
35
+ };
32
36
  /**
33
37
  * A ledger-entry resolver over the blob of the commit frame being applied. The MLS port calls
34
38
  * it with the ids the Commit's control envelope names; it answers with the bodies sealed into
@@ -63,4 +67,4 @@ export declare function decodeLedgerEntries(bytes: Uint8Array): Array<string>;
63
67
  * order it is scheduled in. `openEntries` derives its key from the epoch's exporter secret, so it
64
68
  * is pure and re-entrant and this resolver may be called from anywhere the epoch is right.
65
69
  */
66
- export declare function createLedgerEntryResolver(sealedEntries: Uint8Array, openEntries: GroupCrypto['openEntries']): (ids: Array<string>) => Promise<Array<string>>;
70
+ export declare function createLedgerEntryResolver({ sealedEntries, openEntries, }: CreateLedgerEntryResolverParams): (ids: Array<string>) => Promise<Array<string>>;
@@ -101,7 +101,7 @@ const LENGTH_BYTES = 4;
101
101
  * mutates the handle; an open that does either is unsound while the handle is mid-apply, whatever
102
102
  * order it is scheduled in. `openEntries` derives its key from the epoch's exporter secret, so it
103
103
  * is pure and re-entrant and this resolver may be called from anywhere the epoch is right.
104
- */ export function createLedgerEntryResolver(sealedEntries, openEntries) {
104
+ */ export function createLedgerEntryResolver({ sealedEntries, openEntries }) {
105
105
  return async (_ids)=>{
106
106
  try {
107
107
  // Body trust comes from the token's own signature + content-address, which the caller
@@ -14,8 +14,10 @@ export type OpenOncePathParams<Opened> = {
14
14
  /** Called with the raw message once its open settles: `undefined` when it opened, else the
15
15
  * throw. The throw carries the handle's locked answer ({@link "crypto".FrameEpochError}). */
16
16
  note?: (message: StoredMessage, failure: unknown) => void;
17
- /** A live push that only asks its owner to read the retained log. */
18
- wakeup?: (message: StoredMessage) => boolean;
17
+ /** A live push whose retained open must settle before the next ingress task. */
18
+ wakeup?: (message: StoredMessage) => boolean | Promise<boolean>;
19
+ /** Shared across a group's topics. Called synchronously in mux delivery order. */
20
+ ingress?: (task: () => Promise<void>) => Promise<void>;
19
21
  /**
20
22
  * Consulted when the open fails (any throw in the chain — `unwrap`, `project`, or a listener).
21
23
  * Answering `true` withholds the ack: the frame is sealed at an epoch this handle has not reached
package/lib/open-once.js CHANGED
@@ -17,17 +17,19 @@
17
17
  const listeners = new Set();
18
18
  let unsubscribe;
19
19
  let opening = Promise.resolve();
20
+ const ingress = params.ingress ?? ((task)=>{
21
+ const op = opening.then(task);
22
+ opening = op.catch(()=>{});
23
+ return op;
24
+ });
20
25
  return (onOpened)=>{
21
26
  listeners.add(onOpened);
22
27
  unsubscribe ??= mux.onInbound(topicID, (message, ack)=>{
23
- if (wakeup?.(message) === true) {
24
- ack();
25
- return;
26
- }
27
28
  // Every outcome is HANDLED — opened, or permanently unopenable — except a failure
28
29
  // `retainOnFailure` says is not yet reachable, which flips this false to withhold the ack.
29
30
  let handled = true;
30
- opening = opening.then(async ()=>{
31
+ void ingress(async ()=>{
32
+ if (await wakeup?.(message)) return;
31
33
  let opened;
32
34
  try {
33
35
  opened = await unwrap(message.payload);
@@ -30,7 +30,7 @@ export type EpochRuntimeParams<Protocols extends Record<string, ProtocolDefiniti
30
30
  sealError: () => Error | undefined;
31
31
  isDisposed: () => boolean;
32
32
  note: AppLane['note'];
33
- requestAppPull: () => void;
33
+ requestAppPull: () => Promise<void>;
34
34
  };
35
35
  export type EpochRuntime = {
36
36
  buildEpoch: () => Promise<void>;