@kumiai/rpc 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/crypto.d.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  * epoch, so opening is pure and may run from inside a commit's own apply — the one place it does
9
9
  * run, and which the ratchet-backed pair cannot serve.
10
10
  *
11
- * `epoch()` and `exportSecret(label)` are read on init and every {@link "peer".GroupPeer.resync}.
11
+ * `epoch()` is a hint for display and logging; every decision uses the epoch a result reports.
12
12
  * `wrap`/`unwrap` close over the live group and always use current epoch state. `unwrap` returns
13
13
  * the authenticated sender (`senderDID`), REQUIRED — see {@link GroupUnwrapResult}.
14
14
  *
@@ -16,11 +16,8 @@
16
16
  * closure, whilst directed lanes call the two-arg form directly. `unwrap`'s optional `expectedAAD`
17
17
  * is compared PRE-OPEN, so a wrong-topic frame costs no ratchet generation.
18
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.
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.
24
21
  *
25
22
  * `unwrap` throwing is ORDINARY CONTROL FLOW on the read paths, not an error — it means "not my
26
23
  * epoch". Readers walk logs full of frames from epochs they don't hold and drop them without
@@ -32,6 +29,7 @@
32
29
  * not run the suite has an untested crypto boundary, whatever else it tests.
33
30
  */
34
31
  export type GroupCrypto = {
32
+ /** Published hint; decisions must use an epoch returned by the operation they await. */
35
33
  epoch(): number;
36
34
  /**
37
35
  * An MLS exporter secret for THIS epoch, domain-separated by `label`: different labels at the
@@ -61,7 +59,7 @@ export type GroupCrypto = {
61
59
  * the ledger-entry blobs of every commit enacted after its removal, with nothing throwing to
62
60
  * say so.
63
61
  */
64
- exportSecret(label: string, length?: number): Uint8Array | Promise<Uint8Array>;
62
+ exportSecret(label: string, length?: number): ExportSecretResult | Promise<ExportSecretResult>;
65
63
  wrap(bytes: Uint8Array, opts?: {
66
64
  aad?: Uint8Array;
67
65
  }): Uint8Array | Promise<Uint8Array>;
@@ -72,22 +70,25 @@ export type GroupCrypto = {
72
70
  *
73
71
  * `expectedAAD` is compared PRE-OPEN: authenticating without opening defends against wrong-topic
74
72
  * frames that would otherwise burn a ratchet generation (DoS).
73
+ * A readable frame at another epoch throws {@link FrameEpochError} before decrypting.
75
74
  */
76
75
  unwrap(bytes: Uint8Array, opts?: {
77
76
  expectedAAD?: Uint8Array;
77
+ frame?: AppFrameRef;
78
78
  }): GroupUnwrapResult | Promise<GroupUnwrapResult>;
79
+ /** Cleartext app AAD for pre-open routing. Untrusted until unwrap authenticates it. Never throws. */
80
+ frameAAD(bytes: Uint8Array): Uint8Array | null;
81
+ /** Present iff opened app frames and their consumed handle state are saved atomically. */
82
+ pending?: PendingAppFrames;
79
83
  /**
80
84
  * The epoch a sealed frame was sealed at, read from its own CLEARTEXT without opening it —
81
85
  * structural and pre-open, like {@link GroupMLS.readCommitHeader} is pre-apply. `null` for
82
86
  * bytes that are not a readable sealed frame. Must NOT throw: it is asked about every frame a
83
87
  * log holds, most of which are not this handle's to open.
84
88
  *
85
- * WHAT IT IS FOR: `unwrap` throwing says "not my epoch" but can't say which direction. A frame
86
- * sealed AHEAD will open once the reader catches up; one sealed BELOW can never open again,
87
- * because MLS ratchets forward. A reader that can't tell these apart can't hold a durable read
88
- * position — passing an ahead frame loses it on restart, refusing everything pins the position
89
- * forever. This is what makes the app lane's cursor (see {@link "app-cursor".AppCursorStore})
90
- * safe.
89
+ * A frame sealed AHEAD can open once the reader catches up; one sealed BELOW cannot. This
90
+ * cleartext hint helps route frames before opening. A mismatched open reports the authoritative
91
+ * direction in {@link FrameEpochError}.
91
92
  *
92
93
  * UNTRUSTED: it's the publisher's word, relayed by an untrusted hub. Use it only to decide what
93
94
  * to try, never to decide bytes are authentic — only `unwrap` is authoritative about opening.
@@ -119,7 +120,7 @@ export type GroupCrypto = {
119
120
  * tokens whose trust comes from their own signatures, which the MLS port re-verifies; the seal
120
121
  * authenticates nobody.
121
122
  */
122
- sealEntries(bytes: Uint8Array): Uint8Array | Promise<Uint8Array>;
123
+ sealEntries(bytes: Uint8Array): SealEntriesResult | Promise<SealEntriesResult>;
123
124
  /**
124
125
  * Open a blob {@link sealEntries} produced at THIS epoch. Throws for bytes sealed at any other
125
126
  * epoch, for a group this member is not in, or for bytes that aren't a sealed blob — the same
@@ -130,6 +131,56 @@ export type GroupCrypto = {
130
131
  */
131
132
  openEntries(sealed: Uint8Array): Uint8Array | Promise<Uint8Array>;
132
133
  };
134
+ export type AppFrameRef = {
135
+ /** Stable identity derived from topic and ciphertext. */
136
+ id: string;
137
+ topicID: string;
138
+ protocol: string;
139
+ /** App-lane anchor epoch of the frame's segment. */
140
+ segment: number;
141
+ /** Position in this topic's log. */
142
+ position: string;
143
+ };
144
+ export type ExportSecretResult = {
145
+ secret: Uint8Array;
146
+ epoch: number;
147
+ };
148
+ export type SealEntriesResult = {
149
+ sealed: Uint8Array;
150
+ epoch: number;
151
+ };
152
+ export type ProcessCommitResult = {
153
+ advanced: boolean;
154
+ epochBefore: number;
155
+ epochAfter: number;
156
+ };
157
+ /** A frame refused against the locked handle epoch, before spending a decrypt key. */
158
+ export declare class FrameEpochError extends Error {
159
+ #private;
160
+ constructor(frameEpoch: number, handleEpoch: number);
161
+ get frameEpoch(): number;
162
+ get handleEpoch(): number;
163
+ }
164
+ export type PendingAppFrame = {
165
+ frame: AppFrameRef;
166
+ payload: Uint8Array;
167
+ senderDID: string;
168
+ };
169
+ export type PendingAppFrames = {
170
+ /** Every saved, uncompleted record in (segment, position) order. */
171
+ list(): Promise<Array<PendingAppFrame>>;
172
+ /** Unknown IDs resolve successfully. */
173
+ complete(id: string): Promise<void>;
174
+ };
175
+ /** A failed atomic handle-state and pending-record write; callers may retry the same frame. */
176
+ export declare class AppFrameStorageError extends Error {
177
+ constructor(message: string, options?: ErrorOptions);
178
+ }
179
+ /** Whether an open refused a frame sealed at an epoch the handle has not reached. */
180
+ export declare function isFrameAhead(error: unknown): error is FrameEpochError;
181
+ export declare function isAppFrameStorageError(error: unknown): error is AppFrameStorageError;
182
+ /** Hub positions are numeric strings; retain a stable lexical fallback for opaque hosts. */
183
+ export declare function sortPendingAppFrames(records: Array<PendingAppFrame>): Array<PendingAppFrame>;
133
184
  /**
134
185
  * `GroupCrypto.unwrap`'s result: an opened app frame's plaintext and the AUTHENTICATED sender
135
186
  * recovered from it. rpc's OWN type, not `@kumiai/broadcast`'s `UnwrapResult` — deliberately,
@@ -142,10 +193,33 @@ export type GroupCrypto = {
142
193
  * always MLS-sealed, so there's no identity-less case to accommodate: a sender is either PRESENT
143
194
  * and CORRECT, or the open throws. Optional would type-check against an implementation that has
144
195
  * no sender to give and quietly returns one anyway. Do not widen this back to optional.
196
+ * `epoch` is the locked handle epoch that opened the frame.
145
197
  */
146
198
  export type GroupUnwrapResult = {
147
199
  payload: Uint8Array;
148
200
  senderDID: string;
201
+ epoch: number;
202
+ };
203
+ /**
204
+ * One occupied leaf of a group's ratchet tree. `rosterEntries()` yields these in ascending
205
+ * `leafIndex` order.
206
+ */
207
+ export type RosterEntry = {
208
+ /** Normalized short DID of the member holding this leaf. */
209
+ did: string;
210
+ /**
211
+ * MLS ratchet-tree leaf index. Stable WHILE this leaf remains present — a commit that does not
212
+ * remove this member does not move it. A remove-then-rejoin (external commit) MAY reassign it:
213
+ * the rejoin takes the leftmost blank, which need not be the slot just vacated. Not a stable
214
+ * per-member identity across a membership gap.
215
+ */
216
+ leafIndex: number;
217
+ /**
218
+ * The leaf credential's long form when it carries one, else `id` (real impl:
219
+ * `parsed.longForm ?? parsed.id`). Never absent — but NOT a dereferenceable/resolvable DID
220
+ * guarantee: it is whatever the credential holds, and for an id with no long form it is the id.
221
+ */
222
+ longForm: string;
149
223
  };
150
224
  /**
151
225
  * What a Commit says about itself, readable WITHOUT applying it and without decrypting: the
@@ -182,10 +256,11 @@ export type CommitHeader = {
182
256
  * itself rather than from a leaf it already held — a rejoin.
183
257
  *
184
258
  * The app-lane anchor rotates on it and CANNOT be told any other way: a rejoin by a member the
185
- * roster still holds changes no DID ({@link rosterDIDs} reads the same set before and after)
186
- * and no occupied leaf index (the resync blanks the member's old leaf and the new one lands on
187
- * that same blank). Nothing a before/after diff can see moves, yet the rejoiner's fresh handle
188
- * would anchor where it booted while the group stayed put — so the commit has to say so itself.
259
+ * roster still holds changes no DID ({@link rosterEntries} reads the same `did` set before and
260
+ * after) but MAY move that member's `leafIndex` (leftmost-blank, not necessarily the just-
261
+ * vacated slot — RFC 9420 §12.4.3.2). A `did`-set diff can't see the rejoin either way, yet the
262
+ * rejoiner's fresh handle would anchor where it booted while the group stayed put — so the
263
+ * commit has to say so itself.
189
264
  *
190
265
  * Structural and pre-apply, like its neighbours: an external commit is a public message from a
191
266
  * non-member, readable from the frame without advancing state, carrying its committer's DID in
@@ -251,20 +326,21 @@ export type PendingRecovery = {
251
326
  * until the suite was made to cover the shape rather than a sample of it.
252
327
  */
253
328
  export type GroupMLS = {
329
+ /** Read the current handle epoch under the host's handle lock. */
330
+ readEpoch(): Promise<number>;
254
331
  /**
255
- * The DIDs this handle's ratchet tree currently holds a leaf for — one entry per leaf. Purely
256
- * local: reads no secret, advances nothing.
332
+ * The leaves this handle's ratchet tree currently holds, one {@link RosterEntry} per leaf, in
333
+ * ascending `leafIndex` order. Purely local: reads no secret, advances nothing.
257
334
  *
258
335
  * Read around {@link processCommit} to tell a Commit that dropped a leaf from one that didn't:
259
- * a DID present before and absent after means a Remove was enacted (robust to a Commit
260
- * carrying both an Add and a Remove, where the count is unchanged), and dropping a leaf
261
- * rotates the app-lane anchor. Order doesn't matter — compared as a set.
336
+ * a `did` present before and absent after means a Remove was enacted (robust to a Commit
337
+ * carrying both an Add and a Remove). Compared as a set of `did` — order and `leafIndex` do not
338
+ * matter to that diff (see {@link "roster".detectRosterChange}).
262
339
  *
263
- * Membership only: a rejoin by a member the roster still holds changes no DID and is invisible
264
- * here — {@link CommitHeader.external} is what the lane rotates on for that. The two together
265
- * are the whole rotation rule.
340
+ * Membership only: a rejoin by a member the roster still holds changes no `did` and is invisible
341
+ * to a `did` diff — {@link CommitHeader.external} is what the lane rotates on for that.
266
342
  */
267
- rosterDIDs(): Promise<Array<string>>;
343
+ rosterEntries(): Promise<Array<RosterEntry>>;
268
344
  /**
269
345
  * Read what a Commit says about itself — epoch, committer, and whether it's external — WITHOUT
270
346
  * advancing state. Lets the lane classify a frame (epoch = this peer's to apply? committer =
@@ -295,7 +371,8 @@ export type GroupMLS = {
295
371
  * Apply a received Commit and durably persist the result, returning whether the epoch advanced
296
372
  * (the signal to resync the app lane). Must be durable before it resolves.
297
373
  *
298
- * A frame it cannot apply is `{ advanced: false }`, NEVER a throw: a throw leaves the cursor put
374
+ * A frame it cannot apply has `advanced: false` and equal before/after epochs, NEVER a throw:
375
+ * a throw leaves the cursor put
299
376
  * and re-reads the frame, wedging the lane on it forever (a late joiner would wedge on its own
300
377
  * add-commit, the first frame it reads). A Commit at another epoch, or one policy refuses, is
301
378
  * also `{ advanced: false }`.
@@ -307,9 +384,7 @@ export type GroupMLS = {
307
384
  * contract on a frame it should have applied, which the lane DOES re-read. See
308
385
  * {@link isMissingLedgerEntries}.
309
386
  */
310
- processCommit(commit: Uint8Array, context: CommitContext): Promise<{
311
- advanced: boolean;
312
- }>;
387
+ processCommit(commit: Uint8Array, context: CommitContext): Promise<ProcessCommitResult>;
313
388
  /**
314
389
  * Mint the rendezvous request this peer publishes to ask the group for its state: an HPKE
315
390
  * keypair for this one request, public half in a token signed by this member's identity key.
package/lib/crypto.js CHANGED
@@ -8,7 +8,7 @@
8
8
  * epoch, so opening is pure and may run from inside a commit's own apply — the one place it does
9
9
  * run, and which the ratchet-backed pair cannot serve.
10
10
  *
11
- * `epoch()` and `exportSecret(label)` are read on init and every {@link "peer".GroupPeer.resync}.
11
+ * `epoch()` is a hint for display and logging; every decision uses the epoch a result reports.
12
12
  * `wrap`/`unwrap` close over the live group and always use current epoch state. `unwrap` returns
13
13
  * the authenticated sender (`senderDID`), REQUIRED — see {@link GroupUnwrapResult}.
14
14
  *
@@ -16,11 +16,8 @@
16
16
  * closure, whilst directed lanes call the two-arg form directly. `unwrap`'s optional `expectedAAD`
17
17
  * is compared PRE-OPEN, so a wrong-topic frame costs no ratchet generation.
18
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.
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.
24
21
  *
25
22
  * `unwrap` throwing is ORDINARY CONTROL FLOW on the read paths, not an error — it means "not my
26
23
  * epoch". Readers walk logs full of frames from epochs they don't hold and drop them without
@@ -30,7 +27,52 @@
30
27
  * Not a recommendation: the suite is where this port's contract actually lives, and the clauses
31
28
  * exist because implementations got them wrong. A host that writes its own `GroupCrypto` and does
32
29
  * not run the suite has an untested crypto boundary, whatever else it tests.
33
- */ /**
30
+ */ /** A frame refused against the locked handle epoch, before spending a decrypt key. */ export class FrameEpochError extends Error {
31
+ #frameEpoch;
32
+ #handleEpoch;
33
+ constructor(frameEpoch, handleEpoch){
34
+ super(`frame epoch ${frameEpoch} differs from handle epoch ${handleEpoch}`);
35
+ this.name = 'FrameEpochError';
36
+ this.#frameEpoch = frameEpoch;
37
+ this.#handleEpoch = handleEpoch;
38
+ }
39
+ get frameEpoch() {
40
+ return this.#frameEpoch;
41
+ }
42
+ get handleEpoch() {
43
+ return this.#handleEpoch;
44
+ }
45
+ }
46
+ /** A failed atomic handle-state and pending-record write; callers may retry the same frame. */ export class AppFrameStorageError extends Error {
47
+ constructor(message, options){
48
+ super(message, options);
49
+ this.name = 'AppFrameStorageError';
50
+ }
51
+ }
52
+ /** Whether an open refused a frame sealed at an epoch the handle has not reached. */ // Both checks go by name: a host with two copies of this package still classifies correctly.
53
+ export function isFrameAhead(error) {
54
+ if (!(error instanceof Error) || error.name !== 'FrameEpochError') return false;
55
+ const { frameEpoch, handleEpoch } = error;
56
+ return typeof frameEpoch === 'number' && typeof handleEpoch === 'number' && frameEpoch > handleEpoch;
57
+ }
58
+ export function isAppFrameStorageError(error) {
59
+ return error instanceof Error && error.name === 'AppFrameStorageError';
60
+ }
61
+ /** Hub positions are numeric strings; retain a stable lexical fallback for opaque hosts. */ export function sortPendingAppFrames(records) {
62
+ return [
63
+ ...records
64
+ ].sort((a, b)=>{
65
+ if (a.frame.segment !== b.frame.segment) return a.frame.segment - b.frame.segment;
66
+ const aPos = a.frame.position;
67
+ const bPos = b.frame.position;
68
+ if (/^\d+$/.test(aPos) && /^\d+$/.test(bPos)) {
69
+ const difference = BigInt(aPos) - BigInt(bPos);
70
+ return difference < 0n ? -1 : difference > 0n ? 1 : 0;
71
+ }
72
+ return aPos < bPos ? -1 : aPos > bPos ? 1 : 0;
73
+ });
74
+ }
75
+ /**
34
76
  * The one throw {@link GroupMLS.processCommit} is allowed: the Commit named ledger entries whose
35
77
  * bodies would not resolve from the frame the Commit rides in.
36
78
  *
package/lib/cursor.d.ts CHANGED
@@ -28,6 +28,10 @@ export type DeliveryPosition = string & {
28
28
  * publish returns. A sequenceID from a *pushed* message is NOT one of them.
29
29
  */
30
30
  export declare function asLogPosition(sequenceID: string): LogPosition;
31
+ /** Reject a hub page that cannot move a log cursor forward. */
32
+ export declare function assertForwardPage(after: LogPosition | null, messages: ReadonlyArray<{
33
+ sequenceID: string;
34
+ }>): void;
31
35
  /** Name a sequenceID as a position in this recipient's delivery queue (i.e. an ack). */
32
36
  export declare function asDeliveryPosition(sequenceID: string): DeliveryPosition;
33
37
  export {};
package/lib/cursor.js CHANGED
@@ -21,6 +21,16 @@
21
21
  */ export function asLogPosition(sequenceID) {
22
22
  return sequenceID;
23
23
  }
24
+ /** Reject a hub page that cannot move a log cursor forward. */ export function assertForwardPage(after, messages) {
25
+ let previous = after;
26
+ for (const message of messages){
27
+ const position = asLogPosition(message.sequenceID);
28
+ if (previous != null && position <= previous) {
29
+ throw new Error('hub returned non-increasing log positions');
30
+ }
31
+ previous = position;
32
+ }
33
+ }
24
34
  /** Name a sequenceID as a position in this recipient's delivery queue (i.e. an ack). */ export function asDeliveryPosition(sequenceID) {
25
35
  return sequenceID;
26
36
  }
package/lib/directed.d.ts CHANGED
@@ -1,10 +1,9 @@
1
1
  import { Client } from '@enkaku/client';
2
2
  import { type ProtocolDefinition } from '@enkaku/protocol';
3
3
  import { type ProcedureHandlers } from '@enkaku/server';
4
- import type { Unwrap } from '@kumiai/broadcast';
5
4
  import type { StoredMessage } from '@kumiai/hub-protocol';
6
5
  import { type Runtime } from '@sozai/runtime';
7
- import type { GroupCrypto } from './crypto.js';
6
+ import type { GroupCrypto, GroupUnwrapResult } from './crypto.js';
8
7
  import type { HubMux } from './hub-mux.js';
9
8
  /**
10
9
  * An inbound frame that has ALREADY been opened, with the sender the open authenticated.
@@ -30,9 +29,9 @@ export type InboundPath = (onOpened: (message: OpenedInbound) => void) => () =>
30
29
  export type InboxPathParams = {
31
30
  mux: HubMux;
32
31
  topicID: string;
33
- unwrap: Unwrap;
32
+ unwrap: (bytes: Uint8Array) => GroupUnwrapResult | Promise<GroupUnwrapResult>;
34
33
  /** Forwarded to {@link createOpenOncePath} — see there for what it decides. */
35
- retainOnFailure?: (message: StoredMessage) => boolean;
34
+ retainOnFailure?: (message: StoredMessage, error: unknown) => boolean;
36
35
  };
37
36
  /**
38
37
  * The one path that opens an inbox topic's frames, for every consumer of it.
package/lib/directed.js CHANGED
@@ -3,8 +3,8 @@ import { ErrorCodes } from '@enkaku/protocol';
3
3
  import { HandlerError, Server } from '@enkaku/server';
4
4
  import { normalizeDID } from '@kokuin/token';
5
5
  import { createHubTunnelTransport, decodeFrame, encodeFrame } from '@kumiai/hub-tunnel';
6
- import { fromUTF } from '@sozai/codec';
7
6
  import { createRuntime } from '@sozai/runtime';
7
+ import { encodeAppAAD } from './app-aad.js';
8
8
  import { decodeDirectedPayload, encodeDirectedPayload, isLegacyDirectedPayload } from './directed-tag.js';
9
9
  import { createOpenOncePath } from './open-once.js';
10
10
  /**
@@ -72,7 +72,10 @@ import { createOpenOncePath } from './open-once.js';
72
72
  senderDID: publishParams.senderDID,
73
73
  topicID: publishParams.topicID,
74
74
  payload: await wrap(tagged, {
75
- aad: fromUTF(publishParams.topicID)
75
+ aad: encodeAppAAD({
76
+ topicID: publishParams.topicID,
77
+ intent: 'ephemeral'
78
+ })
76
79
  })
77
80
  });
78
81
  },
@@ -231,7 +234,10 @@ import { createOpenOncePath } from './open-once.js';
231
234
  async publish (publishParams) {
232
235
  const tagged = encodeDirectedPayload(protocolName, publishParams.payload);
233
236
  const sealed = await wrap(tagged, {
234
- aad: fromUTF(publishParams.topicID)
237
+ aad: encodeAppAAD({
238
+ topicID: publishParams.topicID,
239
+ intent: 'ephemeral'
240
+ })
235
241
  });
236
242
  return mux.mailbox.publish({
237
243
  senderDID: publishParams.senderDID,
package/lib/handlers.d.ts CHANGED
@@ -1,6 +1,17 @@
1
- import type { ProtocolDefinition } from '@enkaku/protocol';
1
+ import type { EventProcedureDefinition, ProtocolDefinition } from '@enkaku/protocol';
2
+ import type { EventHandlerContext, ProcedureHandlers } from '@enkaku/server';
2
3
  import { type BroadcastHandler, type BusEvents, type SuppressConfig } from '@kumiai/broadcast';
3
4
  import { EventEmitter } from '@sozai/event';
5
+ import type { AppFrameRef } from './crypto.js';
6
+ /** Log deliveries carry a stable frame ref; live ephemeral events have no frame.
7
+ * A handler that never settles blocks later log events in its protocol. Disposal does not cancel
8
+ * it; the host must settle its work or restart the peer to retry the pending record.
9
+ */
10
+ export type GroupProcedureHandlers<Protocol extends ProtocolDefinition> = {
11
+ [Procedure in keyof Protocol & string]: Protocol[Procedure] extends EventProcedureDefinition ? (context: EventHandlerContext<Protocol, Procedure> & {
12
+ frame?: AppFrameRef;
13
+ }) => void | Promise<void> : ProcedureHandlers<Protocol>[Procedure];
14
+ };
4
15
  export type BusHandlerMaps = {
5
16
  /** Fire-and-forget event fan-out, keyed by procedure name. Host handlers are pre-registered. */
6
17
  events: EventEmitter<BusEvents>;
package/lib/handlers.js CHANGED
@@ -29,7 +29,8 @@ import { createValidator } from '@sozai/schema';
29
29
  if (handler == null) continue;
30
30
  if (definition.type === 'event') {
31
31
  const validator = definition.data != null ? createValidator(definition.data) : undefined;
32
- events.on(prc, ({ data, senderDID })=>{
32
+ events.on(prc, (event)=>{
33
+ const { data, senderDID, frame } = event;
33
34
  if (validator != null) {
34
35
  const result = validator(data);
35
36
  if (result instanceof Error) {
@@ -39,7 +40,10 @@ import { createValidator } from '@sozai/schema';
39
40
  }
40
41
  return handler({
41
42
  data,
42
- message: busMessage(senderDID)
43
+ message: busMessage(senderDID),
44
+ ...frame == null ? {} : {
45
+ frame
46
+ }
43
47
  });
44
48
  });
45
49
  } else if (definition.type === 'request') {
@@ -37,11 +37,8 @@ export declare const HANDSHAKE_MAGIC: Uint8Array<ArrayBuffer>;
37
37
  */
38
38
  export declare const HANDSHAKE_VERSION = 1;
39
39
  /**
40
- * The message kinds carried on the handshake lane. {@link decodeHandshakeFrame} THROWS on a kind
41
- * byte not listed here, before the caller learns the frame's version — and on the commit topic a
42
- * throw is poison, not the heal. So no future version may publish a kind this enum lacks:
43
- * `commit` stays `0` forever, and a new commit-topic message needs its kind added HERE, not just
44
- * allowed by a version bump. Deliberate — kind is validated before version.
40
+ * The message kinds carried on the current handshake version. An unsupported version is returned
41
+ * before its kind is validated, so the commit lane can classify it as ahead.
45
42
  */
46
43
  export declare const HANDSHAKE_KIND: {
47
44
  /** An MLS Commit fanned out to advance every member's epoch. */
@@ -64,7 +61,7 @@ export type HandshakeKind = (typeof HANDSHAKE_KIND)[keyof typeof HANDSHAKE_KIND]
64
61
  export declare function encodeHandshakeFrame(kind: HandshakeKind, payload: Uint8Array): Uint8Array;
65
62
  /**
66
63
  * Validate the header and split a frame into its version, kind and payload. Throws on a short
67
- * frame, a bad magic, or an unknown kind — bytes that are not this protocol at all.
64
+ * frame, a bad magic, or an unknown kind in the current version.
68
65
  *
69
66
  * DOES NOT throw on an unsupported VERSION; it returns it, since the right answer differs by
70
67
  * lane and only the caller knows which lane it's on. Every caller MUST compare `version` against
package/lib/handshake.js CHANGED
@@ -38,11 +38,8 @@
38
38
  */ export const HANDSHAKE_VERSION = 1;
39
39
  const HEADER_LENGTH = HANDSHAKE_MAGIC.length + 2;
40
40
  /**
41
- * The message kinds carried on the handshake lane. {@link decodeHandshakeFrame} THROWS on a kind
42
- * byte not listed here, before the caller learns the frame's version — and on the commit topic a
43
- * throw is poison, not the heal. So no future version may publish a kind this enum lacks:
44
- * `commit` stays `0` forever, and a new commit-topic message needs its kind added HERE, not just
45
- * allowed by a version bump. Deliberate — kind is validated before version.
41
+ * The message kinds carried on the current handshake version. An unsupported version is returned
42
+ * before its kind is validated, so the commit lane can classify it as ahead.
46
43
  */ export const HANDSHAKE_KIND = {
47
44
  /** An MLS Commit fanned out to advance every member's epoch. */ commit: 0,
48
45
  /** A stranded peer asking the group for current state. */ recoveryRequest: 1,
@@ -68,7 +65,7 @@ function isHandshakeKind(value) {
68
65
  }
69
66
  /**
70
67
  * Validate the header and split a frame into its version, kind and payload. Throws on a short
71
- * frame, a bad magic, or an unknown kind — bytes that are not this protocol at all.
68
+ * frame, a bad magic, or an unknown kind in the current version.
72
69
  *
73
70
  * DOES NOT throw on an unsupported VERSION; it returns it, since the right answer differs by
74
71
  * lane and only the caller knows which lane it's on. Every caller MUST compare `version` against
@@ -83,6 +80,16 @@ function isHandshakeKind(value) {
83
80
  }
84
81
  const version = frame[HANDSHAKE_MAGIC.length];
85
82
  const kind = frame[HANDSHAKE_MAGIC.length + 1];
83
+ if (version === undefined || kind === undefined) {
84
+ throw new Error('handshake frame is too short');
85
+ }
86
+ if (version !== HANDSHAKE_VERSION) {
87
+ return {
88
+ version,
89
+ kind: kind,
90
+ payload: frame.subarray(HEADER_LENGTH)
91
+ };
92
+ }
86
93
  if (!isHandshakeKind(kind)) {
87
94
  throw new Error(`unknown handshake kind: ${kind}`);
88
95
  }
@@ -0,0 +1 @@
1
+ export declare function notifyHost<T>(callback: ((value: T) => void | Promise<void>) | undefined, value: T): void;
@@ -0,0 +1,12 @@
1
+ export function notifyHost(callback, value) {
2
+ if (callback == null) return;
3
+ try {
4
+ const result = callback(value);
5
+ if (result != null && typeof result.then === 'function') {
6
+ ;
7
+ result.then(undefined, ()=>{});
8
+ }
9
+ } catch {
10
+ // An observer cannot change a lane outcome.
11
+ }
12
+ }
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/index.d.ts CHANGED
@@ -4,17 +4,20 @@
4
4
  * @module rpc
5
5
  */
6
6
  export type { Anchor, AnchorStore } from './anchor.js';
7
+ export { type AppAAD, decodeAppAAD, encodeAppAAD } from './app-aad.js';
7
8
  export type { AppCursorStore, AppWindowPruned } from './app-cursor.js';
9
+ export type { AppDeliveryStalled } from './app-lane.js';
8
10
  export { type AppliedCommit, type ClassifyCommitParams, type CommitClassifierState, type CommitDisposition, type CommitFrameEvidence, classifyCommit, digestAppliedCommit, UNKNOWN_FRAME_VERSION, } from './classify.js';
9
11
  export { CommitDeadlineError, type CommitJournal, type CommitKind, isHeadMismatch, type JournalEntry, JournalEpochError, type LaneResult, type LostCommit, type PendingCommit, RecoveryRequiredError, } from './commit.js';
10
12
  export { COMMIT_FRAME_VERSION, type CommitFrame, decodeCommitFrame, encodeCommitFrame, isUnsupportedCommitFrameVersion, UnsupportedCommitFrameVersionError, } from './commit-frame.js';
11
- export { type CommitContext, type CommitHeader, type GroupCrypto, type GroupMLS, type GroupUnwrapResult, isMissingLedgerEntries, type PendingRecovery, } from './crypto.js';
13
+ export { type AppFrameRef, AppFrameStorageError, type CommitContext, type CommitHeader, type ExportSecretResult, FrameEpochError, type GroupCrypto, type GroupMLS, type GroupUnwrapResult, isAppFrameStorageError, isMissingLedgerEntries, type PendingAppFrame, type PendingAppFrames, type PendingRecovery, type ProcessCommitResult, type RosterEntry, type SealEntriesResult, sortPendingAppFrames, } from './crypto.js';
12
14
  export { asDeliveryPosition, asLogPosition, type DeliveryPosition, type LogPosition, } from './cursor.js';
13
15
  export { PeerDisposedError } from './errors.js';
16
+ export type { GroupProcedureHandlers } from './handlers.js';
14
17
  export { decodeHandshakeFrame, encodeHandshakeFrame, HANDSHAKE_KIND, HANDSHAKE_MAGIC, HANDSHAKE_VERSION, type HandshakeKind, } from './handshake.js';
15
18
  export type { ReceiveLaneEnded, SubscribeFailure } from './hub-mux.js';
16
19
  export { createLedgerEntryResolver, decodeLedgerEntries, encodeLedgerEntries, LEDGER_ENTRIES_VERSION, } from './ledger-entries.js';
17
- export { createGroupPeer, type GroupPeer, type GroupPeerMLSParams, type GroupPeerParams, type ProtocolSurface, } from './peer.js';
20
+ export { createGroupPeer, type GroupPeer, type GroupPeerMLSParams, type GroupPeerParams, type ProtocolSurface, type RecoveryEvent, type RecoveryFailureReason, type RecoveryTrigger, type StrandConfidence, type StrandKind, type StrandObservation, } from './peer.js';
18
21
  export { defineGroupProtocol, type GroupProcedureDefinition, type GroupProtocolDefinition, type RetainableEventProcedureDefinition, type Retention, retentionOf, } from './protocol.js';
19
22
  export { decodeLedgerReply, decodeLedgerRequest, decodeRecoveryReply, decodeRecoveryRequest, encodeLedgerReply, encodeLedgerRequest, encodeRecoveryReply, encodeRecoveryRequest, } from './recovery.js';
20
23
  export { detectRosterChange } from './roster.js';