@kumiai/rpc 0.3.1 → 0.4.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
@@ -1,30 +1,173 @@
1
- import type { ByteTransform, Unwrap } from '@kumiai/broadcast';
1
+ import type { ByteTransform } from '@kumiai/broadcast';
2
2
  /**
3
- * Consumer-supplied MLS crypto port: epoch number, an epoch-bound topic-derivation secret,
4
- * byte-level encrypt (`wrap`) and decrypt-plus-recover-sender (`unwrap`). group-rpc never
5
- * imports MLS.
3
+ * Consumer-supplied MLS crypto port: epoch number, epoch-bound domain-separated exported secrets
4
+ * (`exportSecret`), byte-level encrypt/decrypt (`wrap`/`unwrap`), and the ledger-entry seal
5
+ * (`sealEntries`/`openEntries`). group-rpc never imports MLS.
6
6
  *
7
- * `epoch()` and `exportSecret()` are read on init and every {@link "peer".GroupPeer.resync}.
8
- * `wrap`/`unwrap` close over the live group, so they always use current epoch state. `unwrap`
9
- * returns the authenticated sender (`senderDID`) recovered from the ciphertext.
7
+ * TWO SEALS, not interchangeable. `wrap`/`unwrap` are ratchet-backed: each open consumes a
8
+ * message key and mutates the handle. `sealEntries`/`openEntries` use a key DERIVED from the
9
+ * epoch, so opening is pure and may run from inside a commit's own apply — the one place it does
10
+ * run, and which the ratchet-backed pair cannot serve.
11
+ *
12
+ * `epoch()` and `exportSecret(label)` are read on init and every {@link "peer".GroupPeer.resync}.
13
+ * `wrap`/`unwrap` close over the live group and always use current epoch state. `unwrap` returns
14
+ * the authenticated sender (`senderDID`), REQUIRED — see {@link GroupUnwrapResult}.
15
+ *
16
+ * `unwrap` MUST open bytes sealed at the handle's CURRENT epoch — that is the whole requirement.
17
+ * A real MLS handle also opens a few epochs behind (ts-mls keeps four; evicting the fifth zeroes
18
+ * their keys), but group-rpc must NOT depend on that window: it is spent by epoch TRANSITIONS
19
+ * rather than time, so a peer catching up destroys the very keys a past-epoch read would need.
20
+ * Implementations that open strictly at the current epoch are correct.
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.
10
25
  */
11
26
  export type GroupCrypto = {
12
27
  epoch(): number;
13
- exportSecret(): Uint8Array | Promise<Uint8Array>;
28
+ /**
29
+ * An MLS exporter secret for THIS epoch, domain-separated by `label`: different labels at the
30
+ * same epoch MUST derive different bytes (a conformance clause, not a suggestion).
31
+ *
32
+ * `label` IS REQUIRED, deliberately: an optional/ignored label type-checks against an
33
+ * implementation that returns identical bytes for every purpose — silent cross-domain key
34
+ * reuse, since nothing throws or type-errors. Required fails loudly instead. Do not make this
35
+ * optional or give it a default.
36
+ *
37
+ * `length` defaults to the implementation's natural export length (32 bytes for every real
38
+ * implementation here, matching XChaCha20-Poly1305's key size) and MAY be overridden. RFC 9420
39
+ * binds `length` into the exporter's `KDFLabel` struct (§8.5), so a same-label export at a
40
+ * different length is an INDEPENDENT key, not a truncation or extension of the default-length
41
+ * one.
42
+ */
43
+ exportSecret(label: string, length?: number): Uint8Array | Promise<Uint8Array>;
14
44
  wrap: ByteTransform;
15
- unwrap: Unwrap;
45
+ /**
46
+ * Open a sealed app frame and recover who sent it. Returns {@link GroupUnwrapResult}, whose
47
+ * `senderDID` is REQUIRED: an implementation that cannot name the sender must throw, not return
48
+ * the field missing. See {@link GroupUnwrapResult} for why.
49
+ */
50
+ unwrap(bytes: Uint8Array): GroupUnwrapResult | Promise<GroupUnwrapResult>;
51
+ /**
52
+ * The epoch a sealed frame was sealed at, read from its own CLEARTEXT without opening it —
53
+ * structural and pre-open, like {@link GroupMLS.readCommitHeader} is pre-apply. `null` for
54
+ * bytes that are not a readable sealed frame. Must NOT throw: it is asked about every frame a
55
+ * log holds, most of which are not this handle's to open.
56
+ *
57
+ * WHAT IT IS FOR: `unwrap` throwing says "not my epoch" but can't say which direction. A frame
58
+ * sealed AHEAD will open once the reader catches up; one sealed BELOW can never open again,
59
+ * because MLS ratchets forward. A reader that can't tell these apart can't hold a durable read
60
+ * position — passing an ahead frame loses it on restart, refusing everything pins the position
61
+ * forever. This is what makes the app lane's cursor (see {@link "app-cursor".AppCursorStore})
62
+ * safe.
63
+ *
64
+ * UNTRUSTED: it's the publisher's word, relayed by an untrusted hub. Use it only to decide what
65
+ * to try, never to decide bytes are authentic — only `unwrap` is authoritative about opening.
66
+ *
67
+ * Real host: MLS carries the epoch in a PrivateMessage's cleartext; `@kumiai/mls` exports
68
+ * `readMessageEpoch`.
69
+ */
70
+ frameEpoch(bytes: Uint8Array): number | null;
71
+ /**
72
+ * Seal the ledger-entry blob a Commit carries, under a key derived from THIS epoch's exporter
73
+ * secret. Its twin is {@link openEntries}.
74
+ *
75
+ * SEPARATE FROM `wrap`/`unwrap`: those consume a ratchet generation and mutate the handle on
76
+ * open, so they can't serve an open that must run from inside the apply of the commit carrying
77
+ * the blob. Derived-key sealing makes opening PURE — idempotent, re-entrant, no ratchet cost.
78
+ *
79
+ * PER-EPOCH: a different epoch derives a different key, so a removed member can't open entries
80
+ * from a commit enacted after its removal.
81
+ *
82
+ * AGREED WITHOUT EXCHANGE: every member at an epoch derives the same key from state it already
83
+ * holds — nothing transported, nothing to distribute or lose.
84
+ *
85
+ * The applying peer always holds the right key: a Commit is applied at the epoch it's framed
86
+ * at, and its author sealed the blob at that same epoch (a host that has already advanced
87
+ * cannot frame a commit) — so any peer in a position to apply it is, by construction, at the
88
+ * sealing epoch, including a returning member replaying the log in order.
89
+ *
90
+ * Confidentiality from the hub is all this buys. The bodies are signed, content-addressed
91
+ * tokens whose trust comes from their own signatures, which the MLS port re-verifies; the seal
92
+ * authenticates nobody.
93
+ */
94
+ sealEntries(bytes: Uint8Array): Uint8Array | Promise<Uint8Array>;
95
+ /**
96
+ * Open a blob {@link sealEntries} produced at THIS epoch. Throws for bytes sealed at any other
97
+ * epoch, for a group this member is not in, or for bytes that aren't a sealed blob — the same
98
+ * "not mine" `unwrap` throwing means, read the same way.
99
+ *
100
+ * PURE: opening the same bytes twice gives the same answer and changes no handle state.
101
+ * Callers open from inside an apply.
102
+ */
103
+ openEntries(sealed: Uint8Array): Uint8Array | Promise<Uint8Array>;
104
+ };
105
+ /**
106
+ * `GroupCrypto.unwrap`'s result: an opened app frame's plaintext and the AUTHENTICATED sender
107
+ * recovered from it. rpc's OWN type, not `@kumiai/broadcast`'s `UnwrapResult` — deliberately,
108
+ * though otherwise identical in shape.
109
+ *
110
+ * `senderDID` IS REQUIRED. Broadcast's `UnwrapResult` carries `senderDID?: string` because
111
+ * broadcast also serves transports with no identity to recover; reusing it here would let an
112
+ * implementation return a frame with no sender, and callers would silently treat
113
+ * "unauthenticated" the same as "authenticated as nobody in particular". group-rpc's app lane is
114
+ * always MLS-sealed, so there's no identity-less case to accommodate: a sender is either PRESENT
115
+ * and CORRECT, or the open throws. Optional would type-check against an implementation that has
116
+ * no sender to give and quietly returns one anyway. Do not widen this back to optional.
117
+ */
118
+ export type GroupUnwrapResult = {
119
+ payload: Uint8Array;
120
+ senderDID: string;
16
121
  };
17
122
  /**
18
123
  * What a Commit says about itself, readable WITHOUT applying it and without decrypting: the
19
- * epoch it is framed at, and its author. Both classify a frame before the peer touches it, and
20
- * both come from the commit's own bytes (authenticated by its signature), never from the
21
- * frame's transport sender — that is the hub's word, and the hub is not trusted.
124
+ * epoch it's framed at, its author, and whether it's an external commit. All come from the
125
+ * commit's own bytes, never from the frame's transport sender — that's the hub's word, and the
126
+ * hub is not trusted.
127
+ *
128
+ * The two facts have different trust and availability — conflating them is a defect. The epoch
129
+ * is CLEARTEXT: keyless, readable at any epoch, only the publisher's word. The committer is
130
+ * AUTHENTICATED: recovering it needs the epoch's sender-data secret, so it's available only for
131
+ * a commit framed at the reader's own current epoch. A header demanding both would be unreadable
132
+ * for every commit but the reader's own — precisely the frame a peer that fell behind must read.
22
133
  */
23
134
  export type CommitHeader = {
24
- /** The epoch the Commit is framed at — the epoch every member that can apply it is at. */
135
+ /**
136
+ * The epoch the Commit is framed at — the epoch every member that can apply it is at. Always
137
+ * present: rides the message's cleartext, needs no key.
138
+ *
139
+ * UNAUTHENTICATED: use only to decide what to TRY, never to decide bytes are authentic.
140
+ * Anything that can publish to the commit topic can claim any epoch here.
141
+ */
25
142
  epoch: number;
26
- /** The MLS-authenticated author of the Commit. Not the publisher of the frame. */
27
- committerDID: string;
143
+ /**
144
+ * The MLS-authenticated author of the Commit. Not the publisher of the frame.
145
+ *
146
+ * ABSENT when it cannot be authenticated — for a member commit, every epoch but the reader's
147
+ * own, since resolving it means decrypting sender-data with the epoch secret the reader holds
148
+ * right now. Absent means "cannot vouch for who wrote this", NEVER "no one wrote it": never
149
+ * substitute an unauthenticated committer for a missing one.
150
+ */
151
+ committerDID?: string;
152
+ /**
153
+ * Whether this Commit is an EXTERNAL commit: its committer joined the group with the commit
154
+ * itself rather than from a leaf it already held — a rejoin.
155
+ *
156
+ * The app-lane anchor rotates on it and CANNOT be told any other way: a rejoin by a member the
157
+ * roster still holds changes no DID ({@link rosterDIDs} reads the same set before and after)
158
+ * and no occupied leaf index (the resync blanks the member's old leaf and the new one lands on
159
+ * that same blank). Nothing a before/after diff can see moves, yet the rejoiner's fresh handle
160
+ * would anchor where it booted while the group stayed put — so the commit has to say so itself.
161
+ *
162
+ * Structural and pre-apply, like its neighbours: an external commit is a public message from a
163
+ * non-member, readable from the frame without advancing state, carrying its committer's DID in
164
+ * its own UpdatePath leaf (it has no pre-commit leaf to resolve one from). Absent — like
165
+ * `false` — for an ordinary member commit.
166
+ *
167
+ * Structural means UNAUTHENTICATED: it says what shape the frame is, never that the rejoin is
168
+ * genuine, so it must not be read as permission for anything the committer guards.
169
+ */
170
+ external?: boolean;
28
171
  };
29
172
  /** Context delivered alongside a received Commit on the raw handshake lane. */
30
173
  export type CommitContext = {
@@ -34,39 +177,37 @@ export type CommitContext = {
34
177
  */
35
178
  senderDID?: string;
36
179
  /**
37
- * The bodies riding this Commit's own frame: the signed control-ledger tokens it enacts,
38
- * sealed under the epoch the Commit is framed at. The port wires this into the MLS handle's
39
- * entry resolver for this commit's duration, so the named entries resolve from the frame that
40
- * carries them — no prior delivery, no store.
180
+ * The bodies riding this Commit's own frame: signed control-ledger tokens, sealed under the
181
+ * epoch the Commit is framed at. Wired into the MLS handle's entry resolver for this commit's
182
+ * duration, so named entries resolve from the frame that carries them — no prior delivery, no
183
+ * store.
41
184
  *
42
- * A resolver, not a value, and load-bearing: it opens the blob only when the port asks, and
43
- * the port asks only for a Commit it is applying — framed at this peer's epoch, which is the
44
- * epoch the blob is sealed under. A frame this peer cannot apply never has its blob touched.
45
- * The port binds each token to the id it asked for by digesting it (a responder can fail to
46
- * answer, never inject), and gets nothing for a blob it cannot open.
185
+ * A resolver, not a value: it opens the blob only when the port asks, for a Commit it's
186
+ * applying — at this peer's epoch, the epoch the blob is sealed under. A frame this peer can't
187
+ * apply never has its blob touched. Each token is bound to the id it was asked for by digest (a
188
+ * responder can fail to answer, never inject), and yields nothing for a blob it can't open.
47
189
  */
48
190
  resolveLedgerEntries?: (ids: Array<string>) => Promise<Array<string>>;
49
191
  };
50
192
  /**
51
- * The external commit that rejoins a stranded peer, BUILT and not adopted — the recovery twin
52
- * of {@link "commit".PendingCommit}, non-mutating for the same reason: the derived handle is
53
- * adopted only if the hub accepts the commit, or a peer that adopted first sits on a branch of
54
- * its own the moment it loses the compare-and-set.
193
+ * The external commit that rejoins a stranded peer, BUILT and not adopted — the recovery twin of
194
+ * {@link "commit".PendingCommit}: the derived handle is adopted only if the hub accepts the
195
+ * commit, since a peer that adopted first sits on its own branch the moment it loses the
196
+ * compare-and-set.
55
197
  *
56
- * Carries no entries — a GroupInfo has nowhere to put an entry envelope — which is why a heal
57
- * is TWO commits: this one rejoins, and the entries the peer still owes ride an ordinary
58
- * `commit()` behind it.
198
+ * Carries no entries — a GroupInfo has nowhere to put an entry envelope — so a heal is TWO
199
+ * commits: this one rejoins, and the entries the peer still owes ride an ordinary `commit()`
200
+ * behind it.
59
201
  */
60
202
  export type PendingRecovery = {
61
203
  /** The external-commit bytes, framed at the epoch the sealed GroupInfo described. */
62
204
  commit: Uint8Array;
63
205
  /**
64
- * Adopt the rejoined handle. Runs only if the hub accepts the external commit; the ONLY place
206
+ * Adopt the rejoined handle. Runs only if the hub accepts the external commit — the ONLY place
65
207
  * it may be adopted.
66
208
  *
67
209
  * The rejoined handle's ledger is EMPTY — a GroupInfo carries a head and no entries — so until
68
- * the ledger is bootstrapped the handle is internally inconsistent: a roster reset, not a
69
- * neutral one.
210
+ * bootstrapped the handle is internally inconsistent: a roster reset, not a neutral one.
70
211
  */
71
212
  onAccepted: () => Promise<void>;
72
213
  };
@@ -78,95 +219,118 @@ export type PendingRecovery = {
78
219
  */
79
220
  export type GroupMLS = {
80
221
  /**
81
- * Read what a Commit says about itself — epoch and committer — WITHOUT advancing state.
82
- * `null` for bytes that are not a Commit. Lets the lane classify a frame (epoch = this
83
- * peer's to apply? committer = this peer's own?) before touching it; neither question may
84
- * be answered by trying and failing.
222
+ * The DIDs this handle's ratchet tree currently holds a leaf for — one entry per leaf. Purely
223
+ * local: reads no secret, advances nothing.
224
+ *
225
+ * Read around {@link processCommit} to tell a Commit that dropped a leaf from one that didn't:
226
+ * a DID present before and absent after means a Remove was enacted (robust to a Commit
227
+ * carrying both an Add and a Remove, where the count is unchanged), and dropping a leaf
228
+ * rotates the app-lane anchor. Order doesn't matter — compared as a set.
85
229
  *
86
- * Async and handle-bound: a real host recovers a member commit's committer by decrypting
87
- * its sender-data with the epoch secret (an open, not an apply) and mapping the sender leaf
88
- * to a DID against the ratchet tree — both reachable only on the handle the host already
89
- * holds. The port reaches its own handle internally; the lane awaits.
230
+ * Membership only: a rejoin by a member the roster still holds changes no DID and is invisible
231
+ * here — {@link CommitHeader.external} is what the lane rotates on for that. The two together
232
+ * are the whole rotation rule.
233
+ */
234
+ rosterDIDs(): Promise<Array<string>>;
235
+ /**
236
+ * Read what a Commit says about itself — epoch, committer, and whether it's external — WITHOUT
237
+ * advancing state. Lets the lane classify a frame (epoch = this peer's to apply? committer =
238
+ * this peer's own? a rejoin?) before touching it; none of those may be answered by trying and
239
+ * failing.
240
+ *
241
+ * `null` means ONE thing: these bytes are not a Commit at all — undecodable, truncated, or some
242
+ * other message kind. It does NOT mean "a Commit I could not read": the lane files `null` as
243
+ * poison and steps over it, so a port that returned `null` for every commit framed away from
244
+ * its own epoch would make a peer that fell behind read the group's entire future as garbage
245
+ * and report itself fully reconciled at a dead epoch.
246
+ *
247
+ * If the bytes are a Commit, always return its `epoch`. Return `committerDID` only when the
248
+ * Commit itself authenticates one — leave it ABSENT rather than guessing, never fill it from
249
+ * the frame's transport sender.
250
+ *
251
+ * Async and handle-bound: a real host recovers a member commit's committer by decrypting its
252
+ * sender-data with the epoch secret and mapping the sender leaf to a DID against the ratchet
253
+ * tree — both reachable only on the handle the host already holds, and only for a Commit
254
+ * framed at the epoch that handle is at. That's why the committer is optional and the epoch is
255
+ * not. An external commit needs neither: its committer's DID rides its own UpdatePath leaf
256
+ * (which is also what makes it recognizable as external) — but the port must still check the
257
+ * commit's own signature before reporting a committer; it must not report one it hasn't
258
+ * authenticated. The port reaches its own handle internally; the lane awaits.
90
259
  */
91
260
  readCommitHeader(commit: Uint8Array): Promise<CommitHeader | null>;
92
261
  /**
93
- * Apply a received Commit and durably persist the result, returning whether the epoch
94
- * advanced (the signal to resync the app lane). Must be durable before it resolves.
262
+ * Apply a received Commit and durably persist the result, returning whether the epoch advanced
263
+ * (the signal to resync the app lane). Must be durable before it resolves.
95
264
  *
96
- * A frame it cannot apply is `{ advanced: false }`, NEVER a throw: a throw leaves the cursor
97
- * put and re-reads the frame, so a port that throws on a Commit it was never in a position to
98
- * apply wedges the lane on that frame forever (a late joiner would wedge on its own add-commit,
99
- * the first frame it reads). A Commit at another epoch, or one policy refuses, is both
100
- * `{ advanced: false }`.
265
+ * A frame it cannot apply is `{ advanced: false }`, NEVER a throw: a throw leaves the cursor put
266
+ * and re-reads the frame, wedging the lane on it forever (a late joiner would wedge on its own
267
+ * add-commit, the first frame it reads). A Commit at another epoch, or one policy refuses, is
268
+ * also `{ advanced: false }`.
101
269
  *
102
- * Throws for exactly ONE outcome: a Commit it SHOULD apply but cannot because the ledger
103
- * entries it names will not resolve from the Commit's own frame — the only place they ride.
104
- * The lane does NOT retry; the bodies never arrive later (sealed under the Commit's framed
105
- * epoch, so a peer that cannot open them is one no member at that epoch can), and the lane
106
- * steps over the frame as POISON — cursor advances, never re-read. The throw distinguishes
107
- * that poison case from a port that broke its contract on a frame it should have applied, which
108
- * the lane DOES re-read. See {@link isMissingLedgerEntries}.
270
+ * Throws for exactly ONE outcome: a Commit it SHOULD apply but can't, because the ledger
271
+ * entries it names won't resolve from the Commit's own frame — the only place they ride. The
272
+ * lane does NOT retry (no member at that epoch could resolve them either) and treats it as
273
+ * POISON: cursor advances, never re-read. This distinguishes that case from a port that broke
274
+ * contract on a frame it should have applied, which the lane DOES re-read. See
275
+ * {@link isMissingLedgerEntries}.
109
276
  */
110
277
  processCommit(commit: Uint8Array, context: CommitContext): Promise<{
111
278
  advanced: boolean;
112
279
  }>;
113
280
  /**
114
281
  * Mint the rendezvous request this peer publishes to ask the group for its state: an HPKE
115
- * keypair for this one request, its public half in a token signed by this member's identity
116
- * key. The private half is retained by the port keyed by `requestID`, and is what makes the
117
- * reply openable by this peer alone. Minted per request, not from the leaf, because the peers
118
- * that most need a heal (commit accepted and lost, on a discarded branch) no longer hold the
119
- * leaf key the group can see — their own commit rotated it and the new key died unpersisted.
120
- *
121
- * The port MUST bound retention of that private half itself — the lane has no release hook. A
122
- * gather/rejoin that times out and a `recover()` that fails before opening a reply both drop
123
- * their `requestID` on the rpc side (the waiter maps clear on finish/timeout/dispose) but tell
124
- * the port nothing, so a port that only evicts on reply-open accumulates one key per timed-out
125
- * round. A TTL off the request's mint time is the natural bound: a request older than one
126
- * requester deadline can no longer be answered. The bound lives here rather than as a lane
127
- * release call that would obligate every {@link GroupMLS} to a new method.
282
+ * keypair for this one request, public half in a token signed by this member's identity key.
283
+ * The private half is retained by the port keyed by `requestID`, making the reply openable by
284
+ * this peer alone. Minted per request, not from the leaf, because the peers that most need a
285
+ * heal (commit accepted and lost, on a discarded branch) no longer hold a leaf key the group
286
+ * can see.
287
+ *
288
+ * The port MUST bound retention of the private half itself — the lane has no release hook. A
289
+ * timed-out gather/rejoin or a failed `recover()` drops its `requestID` on the rpc side without
290
+ * telling the port, so a port that only evicts on reply-open leaks one key per timeout. A TTL
291
+ * off the mint time is the natural bound; it lives here rather than as a new lane release
292
+ * method that would obligate every {@link GroupMLS}.
128
293
  */
129
294
  createRecoveryRequest(requestID: string): Promise<Uint8Array>;
130
295
  /**
131
296
  * Answer another member's request: verify the token, check the requester still holds a leaf in
132
297
  * THIS member's current ratchet tree, seal current GroupInfo to the ephemeral key inside the
133
- * signed request, AND vouch for it — the reply carries a membership attestation this member
134
- * signs with its DID key, binding the group, the request and the exact GroupInfo bytes. The
135
- * seal is HPKE base mode and authenticates no one, so the attestation is what lets the
136
- * requester tell this member's reply from an observer's forgery.
298
+ * signed request, AND vouch for it with a membership attestation signed by this member's DID
299
+ * key, binding the group, the request, and the exact GroupInfo bytes. The seal itself is HPKE
300
+ * base mode and authenticates no one; the attestation is what lets the requester tell this
301
+ * member's reply from an observer's forgery.
137
302
  *
138
- * Authorization is roster-intrinsic, not a check the caller can forget: a removed member gets
139
- * nothing from any responder that has applied its removal. Throws for a request it refuses, and
140
- * the peer stays silent.
303
+ * Authorization is roster-intrinsic: a removed member gets nothing from any responder that has
304
+ * applied its removal. Throws for a request it refuses; the peer stays silent.
141
305
  */
142
306
  sealGroupInfo(request: Uint8Array): Promise<Uint8Array>;
143
307
  /**
144
308
  * Open a sealed reply with the key minted for `requestID` and BUILD the external commit that
145
- * rejoins this peer. Non-mutating: the rejoined handle is adopted in
146
- * {@link PendingRecovery.onAccepted} and nowhere else, because the commit still has to win a
147
- * compare-and-set at the head.
309
+ * rejoins this peer. Non-mutating: the rejoined handle is adopted only in
310
+ * {@link PendingRecovery.onAccepted}, because the commit still has to win a compare-and-set at
311
+ * the head.
148
312
  *
149
313
  * `null` for bytes this peer cannot open OR cannot trust. HPKE base mode needs only the
150
- * requester's public ephemeral key — all of which rides the public request in the clear — so a
151
- * hub-injected or observer-forged reply may DECRYPT. What refuses it: the responder must prove
152
- * membership by signing the reply with its DID key (open side requires the signer to hold a
153
- * leaf in this peer's last-known tree), and the offered GroupInfo's group id and genesis anchor
154
- * must match the group being healed. A reply the AEAD refuses, or one that fails either check,
155
- * is `null`. A throw is tolerated and read the same way.
314
+ * requester's public ephemeral key, which rides the public request in the clear — so a
315
+ * hub-injected or observer-forged reply may DECRYPT. What refuses it: the responder must sign
316
+ * the reply with its DID key (the signer must hold a leaf in this peer's last-known tree), and
317
+ * the offered GroupInfo's group id and genesis anchor must match the group being healed. A
318
+ * reply the AEAD refuses, or one that fails either check, is `null`; a throw is tolerated and
319
+ * read the same way.
156
320
  */
157
321
  applyRecovery(sealed: Uint8Array, requestID: string): Promise<PendingRecovery | null>;
158
322
  /**
159
- * Whether the ledger this handle holds is the whole ledger its OWN GroupContext attests to:
160
- * the head folded from the entries it holds, in their order, against the authenticated head it
161
- * carries. Purely local. False means incomplete — {@link bootstrapLedger} must run before this
162
- * handle can be trusted to fold a roster or judge an incoming commit. A handle that rejoined by
163
- * external commit reads false: empty ledger against a live, non-genesis head.
323
+ * Whether the ledger this handle holds is the whole ledger its OWN GroupContext attests to: the
324
+ * head folded from the entries it holds, against the authenticated head it carries. Purely
325
+ * local. False means incomplete — {@link bootstrapLedger} must run before this handle can be
326
+ * trusted to fold a roster or judge an incoming commit. A handle that rejoined by external
327
+ * commit reads false: empty ledger against a live, non-genesis head.
164
328
  */
165
329
  isLedgerComplete(): Promise<boolean>;
166
330
  /**
167
331
  * The WHOLE ordered ledger this handle holds, as signed tokens — what a peer about to rejoin
168
- * snapshots as the entries it may still owe, and filters its re-enactment against once the
169
- * group's ledger is back. Purely local, never on the wire (a responder uses {@link sealLedger}).
332
+ * snapshots as entries it may still owe, and filters its re-enactment against once the group's
333
+ * ledger is back. Purely local, never on the wire (a responder uses {@link sealLedger}).
170
334
  *
171
335
  * Order is load-bearing: the head is a chain digest, so a permuted list of the same tokens
172
336
  * folds to a different head and the requester rejects it.
@@ -177,38 +341,35 @@ export type GroupMLS = {
177
341
  * leaf in THIS member's current ratchet tree, and seal this handle's whole ordered ledger to
178
342
  * the ephemeral key inside the signed request.
179
343
  *
180
- * Same roster-intrinsic authorization {@link sealGroupInfo} makes, and not a nicety: the ledger
181
- * is the group's whole authority state on a public secretless topic, and a responder that
182
- * sealed without checking would hand every role and promotion to any stranger who minted a
183
- * request, encrypted to the stranger's key. Throws for a request it refuses; the peer stays silent.
344
+ * Same roster-intrinsic authorization as {@link sealGroupInfo}, not a nicety: the ledger is the
345
+ * group's whole authority state on a public secretless topic, and a responder that sealed
346
+ * without checking would hand every role and promotion to any stranger who minted a request.
347
+ * Throws for a request it refuses; the peer stays silent.
184
348
  *
185
- * The seal is EPOCH-INDEPENDENT and must remain so: the requester crashed between rejoin and
186
- * bootstrap and the lane gathers before it pulls, so it can be at an older epoch than every
187
- * responder, and a reply sealed under the responder's current epoch would be unopenable by it.
349
+ * The seal is EPOCH-INDEPENDENT and must remain so: the requester can be at an older epoch than
350
+ * every responder (it crashed between rejoin and bootstrap, and the lane gathers before it
351
+ * pulls), and a reply sealed under the responder's current epoch would be unopenable by it.
188
352
  */
189
353
  sealLedger(request: Uint8Array): Promise<Uint8Array>;
190
354
  /**
191
355
  * Open a sealed gather reply with the key minted for `requestID`, returning the responder's
192
356
  * whole ordered ledger as signed tokens.
193
357
  *
194
- * `null` when the AEAD refuses the bytes — sealed to another ephemeral key, or bound to another
195
- * member, request, or reply kind. It does NOT prove the sealer was a member: unlike the
196
- * GroupInfo reply the ledger reply carries no attestation, and HPKE base mode authenticates no
358
+ * `null` when the AEAD refuses the bytes. It does NOT prove the sealer was a member: unlike the
359
+ * GroupInfo reply, the ledger reply carries no attestation, and HPKE base mode authenticates no
197
360
  * one, so an observer of the request can forge a reply that decrypts. The key is NOT consumed:
198
361
  * every responder answers, and the requester must open the next reply after dropping one.
199
362
  *
200
363
  * Opening proves NOTHING about who sealed the tokens. The bound is {@link bootstrapLedger}'s
201
- * head check: a reply reproducing this group's authenticated head is its whole ledger in order,
202
- * and a forged, lying, reordered or truncated one fails and is dropped — withhold, never
203
- * rewrite. A forged reply that merely decrypts costs one gather attempt: denial of service, not
204
- * compromise.
364
+ * head check: a reply reproducing this group's authenticated head is its whole ledger in order;
365
+ * a forged, lying, reordered or truncated one fails and is dropped — withhold, never rewrite. A
366
+ * forged reply that merely decrypts costs one gather attempt: denial of service, not compromise.
205
367
  */
206
368
  openSealedLedger(sealed: Uint8Array, requestID: string): Promise<Array<string> | null>;
207
369
  /**
208
370
  * Install a gathered ledger, verified against the authenticated head BEFORE a single entry is
209
- * folded. REPLACES the ledger this handle holds, sound because the check is a fold from
210
- * genesis: a list reproducing the head this handle's own GroupContext carries IS the group's
211
- * entire ledger, in order.
371
+ * folded. REPLACES the ledger this handle holds — sound because a list reproducing the head
372
+ * this handle's own GroupContext carries IS the group's entire ledger, in order.
212
373
  *
213
374
  * Throws for a list whose recomputed head does not match — a lying responder can withhold,
214
375
  * never rewrite — and the peer drops that responder and folds the next reply instead.
@@ -226,13 +387,12 @@ export type GroupMLS = {
226
387
  *
227
388
  * The lane treats it as POISON: step over the frame, advance the cursor, never re-read. The
228
389
  * bodies are sealed under the Commit's framed epoch, so a peer that cannot resolve them is one no
229
- * member at that epoch can — nobody applies the commit, the group never moves past that epoch,
230
- * and the next honest commit is framed at the same epoch and compare-and-sets behind it.
231
- * Everything else the port says about a frame it will not apply is `{ advanced: false }`, poison
232
- * on the same terms: advances, never retried, does not heal.
390
+ * member at that epoch can — nobody applies the commit, and the next honest commit is framed at
391
+ * the same epoch and compare-and-sets behind it. Everything else the port says about a frame it
392
+ * will not apply is `{ advanced: false }`, poison on the same terms.
233
393
  *
234
394
  * Matched by NAME, not class: the port is consumer-supplied and its error type is not this
235
- * package's to import. A missing-entries error named anything else is treated as an unknown
236
- * failure — so the name is contract.
395
+ * package's to import. An error named anything else is treated as an unknown failure — so the
396
+ * name is contract.
237
397
  */
238
398
  export declare function isMissingLedgerEntries(error: unknown): boolean;
package/lib/crypto.js CHANGED
@@ -4,14 +4,13 @@
4
4
  *
5
5
  * The lane treats it as POISON: step over the frame, advance the cursor, never re-read. The
6
6
  * bodies are sealed under the Commit's framed epoch, so a peer that cannot resolve them is one no
7
- * member at that epoch can — nobody applies the commit, the group never moves past that epoch,
8
- * and the next honest commit is framed at the same epoch and compare-and-sets behind it.
9
- * Everything else the port says about a frame it will not apply is `{ advanced: false }`, poison
10
- * on the same terms: advances, never retried, does not heal.
7
+ * member at that epoch can — nobody applies the commit, and the next honest commit is framed at
8
+ * the same epoch and compare-and-sets behind it. Everything else the port says about a frame it
9
+ * will not apply is `{ advanced: false }`, poison on the same terms.
11
10
  *
12
11
  * Matched by NAME, not class: the port is consumer-supplied and its error type is not this
13
- * package's to import. A missing-entries error named anything else is treated as an unknown
14
- * failure — so the name is contract.
12
+ * package's to import. An error named anything else is treated as an unknown failure — so the
13
+ * name is contract.
15
14
  */ export function isMissingLedgerEntries(error) {
16
15
  return error instanceof Error && error.name === 'MissingLedgerEntriesError';
17
16
  }
package/lib/cursor.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * - A **log position** is a place in a *topic's log*: `fetchTopic`'s `after`, `head`,
5
5
  * `oldest`. Every reader of the topic sees the same log in the same order.
6
6
  * - A **delivery position** is a place in *this recipient's delivery queue*:
7
- * `hub/receive`'s `after` and `ack`. It runs across every subscribed topic, skips the
7
+ * `hub/v1/receive`'s `after` and `ack`. It runs across every subscribed topic, skips the
8
8
  * recipient's own frames, and is emptied by acking.
9
9
  *
10
10
  * Different sequences, different frames, different orders. Crossing them silently mis-pages
package/lib/cursor.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * - A **log position** is a place in a *topic's log*: `fetchTopic`'s `after`, `head`,
5
5
  * `oldest`. Every reader of the topic sees the same log in the same order.
6
6
  * - A **delivery position** is a place in *this recipient's delivery queue*:
7
- * `hub/receive`'s `after` and `ack`. It runs across every subscribed topic, skips the
7
+ * `hub/v1/receive`'s `after` and `ack`. It runs across every subscribed topic, skips the
8
8
  * recipient's own frames, and is emptied by acking.
9
9
  *
10
10
  * Different sequences, different frames, different orders. Crossing them silently mis-pages
package/lib/directed.d.ts CHANGED
@@ -2,20 +2,58 @@ import { Client } from '@enkaku/client';
2
2
  import type { ProtocolDefinition } from '@enkaku/protocol';
3
3
  import { type ProcedureHandlers } from '@enkaku/server';
4
4
  import type { ByteTransform, Unwrap } from '@kumiai/broadcast';
5
+ import { type Runtime } from '@sozai/runtime';
5
6
  import type { HubMux } from './hub-mux.js';
7
+ /**
8
+ * An inbound frame that has ALREADY been opened, with the sender the open authenticated.
9
+ *
10
+ * Every consumer of a topic is handed this rather than an `unwrap` of its own, because opening is
11
+ * a consuming operation: real MLS spends the frame's per-message key on the first open, so two
12
+ * consumers each calling `unwrap` race for one key and the loser sees a frame it cannot open. The
13
+ * inbox topic has several consumers at once — the acceptor, and one directed client per member —
14
+ * so this is the only shape that works there.
15
+ */
16
+ export type OpenedInbound = {
17
+ sequenceID: string;
18
+ /** Recovered from the ciphertext by the open, never the hub-asserted one. */
19
+ senderDID: string;
20
+ topicID: string;
21
+ payload: Uint8Array;
22
+ };
23
+ /** Subscribe to a topic's already-opened frames; returns the unsubscribe. */
24
+ export type InboundPath = (onOpened: (message: OpenedInbound) => void) => () => void;
25
+ export type InboxPathParams = {
26
+ mux: HubMux;
27
+ topicID: string;
28
+ unwrap: Unwrap;
29
+ };
30
+ /**
31
+ * The one path that opens an inbox topic's frames, for every consumer of it.
32
+ *
33
+ * A frame that opens without an authenticated sender is dropped HERE. The hub-asserted sender is
34
+ * never a fallback — directed RPC binds every session to the sender the open recovered, which is
35
+ * what stops a lying hub forging or splicing one.
36
+ */
37
+ export declare function createInboxPath(params: InboxPathParams): InboundPath;
6
38
  export type DirectedClientParams = {
7
39
  mux: HubMux;
8
40
  localDID: string;
9
41
  memberDID: string;
10
- secret: Uint8Array;
11
- epoch: number;
42
+ sendTopicID: string;
43
+ receiveTopicID: string;
44
+ /** The self-inbox topic's one open-once path, shared with the acceptor. */
45
+ inbound: InboundPath;
12
46
  wrap: ByteTransform;
13
- unwrap: Unwrap;
14
- getRandomID?: () => string;
47
+ /** Runtime providing platform primitives. Defaults to `createRuntime()`. */
48
+ runtime?: Runtime;
15
49
  };
16
50
  /**
17
51
  * Directed 1:1 RPC client to a single member, over a hub-tunnel transport whose
18
52
  * send/receive topics are the two members' inbox topics for the current epoch.
53
+ *
54
+ * Replies are authored by `memberDID`, so anything the shared path opens under a different
55
+ * MLS-authenticated sender belongs to another conversation on the same inbox and is left for
56
+ * the consumer it does belong to.
19
57
  */
20
58
  export declare function createDirectedClient<Protocol extends ProtocolDefinition>(params: DirectedClientParams): {
21
59
  client: Client<Protocol>;
@@ -25,12 +63,13 @@ export type InboxAcceptorParams<Protocol extends ProtocolDefinition> = {
25
63
  mux: HubMux;
26
64
  localDID: string;
27
65
  selfInboxTopic: string;
66
+ /** The self-inbox topic's one open-once path, shared with every directed client. */
67
+ inbound: InboundPath;
28
68
  /** Map an authenticated senderDID to the topic we send replies on (their inbox). */
29
69
  resolveSendTopic: (senderDID: string) => string;
30
70
  protocol: Protocol;
31
71
  handlers: ProcedureHandlers<Protocol>;
32
72
  wrap: ByteTransform;
33
- unwrap: Unwrap;
34
73
  };
35
74
  /**
36
75
  * Accept directed RPC. A single sealed drain of `selfInboxTopic` opens each inbound frame with