@kumiai/rpc 0.2.0 → 0.3.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,14 +1,12 @@
1
1
  import type { ByteTransform, Unwrap } from '@kumiai/broadcast';
2
2
  /**
3
- * Consumer-supplied MLS crypto port. The consumer adapts its live MLS group into
4
- * this shape (epoch number, an epoch-bound topic-derivation secret, byte-level
5
- * encrypt via `wrap`, and decrypt-plus-recover-sender via `unwrap`). group-rpc
6
- * never imports MLS.
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.
7
6
  *
8
- * `epoch()` and `exportSecret()` are read on init and on every
9
- * {@link "peer".GroupPeer.resync}. `wrap`/`unwrap` close over the live group, so
10
- * they always use current epoch state. `unwrap` returns the authenticated
11
- * sender (`senderDID`) recovered from the ciphertext.
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.
12
10
  */
13
11
  export type GroupCrypto = {
14
12
  epoch(): number;
@@ -16,54 +14,220 @@ export type GroupCrypto = {
16
14
  wrap: ByteTransform;
17
15
  unwrap: Unwrap;
18
16
  };
17
+ /**
18
+ * 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.
22
+ */
23
+ export type CommitHeader = {
24
+ /** The epoch the Commit is framed at — the epoch every member that can apply it is at. */
25
+ epoch: number;
26
+ /** The MLS-authenticated author of the Commit. Not the publisher of the frame. */
27
+ committerDID: string;
28
+ };
19
29
  /** Context delivered alongside a received Commit on the raw handshake lane. */
20
30
  export type CommitContext = {
21
31
  /**
22
- * The hub-authenticated publisher of the frame. This is the transport sender,
23
- * NOT the MLS-cryptographic committer (the Commit authenticates its committer
24
- * internally) — auxiliary information (logging, rate-limiting), not an
25
- * authorization boundary.
32
+ * The hub-authenticated publisher of the frame — the transport sender, NOT the
33
+ * MLS committer. Auxiliary (logging, rate-limiting), not an authorization boundary.
26
34
  */
27
35
  senderDID?: string;
36
+ /**
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.
41
+ *
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.
47
+ */
48
+ resolveLedgerEntries?: (ids: Array<string>) => Promise<Array<string>>;
49
+ };
50
+ /**
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.
55
+ *
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.
59
+ */
60
+ export type PendingRecovery = {
61
+ /** The external-commit bytes, framed at the epoch the sealed GroupInfo described. */
62
+ commit: Uint8Array;
63
+ /**
64
+ * Adopt the rejoined handle. Runs only if the hub accepts the external commit; the ONLY place
65
+ * it may be adopted.
66
+ *
67
+ * 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.
70
+ */
71
+ onAccepted: () => Promise<void>;
28
72
  };
29
73
  /**
30
- * Consumer-supplied MLS lifecycle port. Sibling to {@link GroupCrypto}: where
31
- * `GroupCrypto` adapts application encrypt/decrypt, this drives the handshake
32
- * lane — applying Commits to advance the epoch and re-syncing a stranded peer.
33
- * group-rpc owns the transport + orchestration (subscribe the non-rotating
34
- * handshake topic, run these methods, resync when the epoch advances); the
35
- * consumer owns the MLS state and any storage/atomicity, entirely below this
36
- * interface.
74
+ * Consumer-supplied MLS lifecycle port. Sibling to {@link GroupCrypto}: this drives the
75
+ * handshake lane — applying Commits to advance the epoch, re-syncing a stranded peer. group-rpc
76
+ * owns transport + orchestration; the consumer owns MLS state and any storage/atomicity below
77
+ * this interface.
37
78
  */
38
79
  export type GroupMLS = {
39
80
  /**
40
- * Apply a received Commit to the MLS state and durably persist the result,
41
- * returning whether the epoch advanced (the signal to resync the app lane).
42
- * Implementations make this atomic; the orchestration only requires that the
43
- * write is durable before it resolves.
81
+ * Read what a Commit says about itself — epoch and committer — WITHOUT applying it or opening
82
+ * anything. `null` for bytes that are not a Commit. Lets the lane classify a frame (epoch =
83
+ * this peer's to apply? committer = this peer's own?) before touching it; neither question may
84
+ * be answered by trying and failing.
85
+ */
86
+ readCommitHeader(commit: Uint8Array): CommitHeader | null;
87
+ /**
88
+ * Apply a received Commit and durably persist the result, returning whether the epoch
89
+ * advanced (the signal to resync the app lane). Must be durable before it resolves.
90
+ *
91
+ * A frame it cannot apply is `{ advanced: false }`, NEVER a throw: a throw leaves the cursor
92
+ * put and re-reads the frame, so a port that throws on a Commit it was never in a position to
93
+ * apply wedges the lane on that frame forever (a late joiner would wedge on its own add-commit,
94
+ * the first frame it reads). A Commit at another epoch, or one policy refuses, is both
95
+ * `{ advanced: false }`.
96
+ *
97
+ * Throws for exactly ONE outcome: a Commit it SHOULD apply but cannot because the ledger
98
+ * entries it names will not resolve from the Commit's own frame — the only place they ride.
99
+ * The lane does NOT retry; the bodies never arrive later (sealed under the Commit's framed
100
+ * epoch, so a peer that cannot open them is one no member at that epoch can), and the lane
101
+ * steps over the frame as POISON — cursor advances, never re-read. The throw distinguishes
102
+ * that poison case from a port that broke its contract on a frame it should have applied, which
103
+ * the lane DOES re-read. See {@link isMissingLedgerEntries}.
44
104
  */
45
105
  processCommit(commit: Uint8Array, context: CommitContext): Promise<{
46
106
  advanced: boolean;
47
107
  }>;
48
108
  /**
49
- * Export current group state for a recovery responder, sealed to the
50
- * requesting member's MLS leaf so only that requester (not the hub, not other
51
- * members) can open it.
109
+ * Mint the rendezvous request this peer publishes to ask the group for its state: an HPKE
110
+ * keypair for this one request, its public half in a token signed by this member's identity
111
+ * key. The private half is retained by the port keyed by `requestID`, and is what makes the
112
+ * reply openable by this peer alone. Minted per request, not from the leaf, because the peers
113
+ * that most need a heal (commit accepted and lost, on a discarded branch) no longer hold the
114
+ * leaf key the group can see — their own commit rotated it and the new key died unpersisted.
115
+ *
116
+ * The port MUST bound retention of that private half itself — the lane has no release hook. A
117
+ * gather/rejoin that times out and a `recover()` that fails before opening a reply both drop
118
+ * their `requestID` on the rpc side (the waiter maps clear on finish/timeout/dispose) but tell
119
+ * the port nothing, so a port that only evicts on reply-open accumulates one key per timed-out
120
+ * round. A TTL off the request's mint time is the natural bound: a request older than one
121
+ * requester deadline can no longer be answered. The bound lives here rather than as a lane
122
+ * release call that would obligate every {@link GroupMLS} to a new method.
52
123
  */
53
- exportGroupInfo(requesterDID: string): Promise<Uint8Array>;
124
+ createRecoveryRequest(requestID: string): Promise<Uint8Array>;
54
125
  /**
55
- * Re-sync from a sealed recovery reply, returning whether the epoch advanced.
56
- * The bytes may be hub-injected or sealed to a different member; implementations
57
- * SHOULD return `{ advanced: false }` for input they cannot open. A throw is also
58
- * tolerated — the caller treats it as no advance — but returning is preferred.
126
+ * Answer another member's request: verify the token, check the requester still holds a leaf in
127
+ * THIS member's current ratchet tree, seal current GroupInfo to the ephemeral key inside the
128
+ * signed request, AND vouch for it — the reply carries a membership attestation this member
129
+ * signs with its DID key, binding the group, the request and the exact GroupInfo bytes. The
130
+ * seal is HPKE base mode and authenticates no one, so the attestation is what lets the
131
+ * requester tell this member's reply from an observer's forgery.
132
+ *
133
+ * Authorization is roster-intrinsic, not a check the caller can forget: a removed member gets
134
+ * nothing from any responder that has applied its removal. Throws for a request it refuses, and
135
+ * the peer stays silent.
59
136
  */
60
- applyRecovery(groupInfo: Uint8Array): Promise<{
61
- advanced: boolean;
62
- }>;
137
+ sealGroupInfo(request: Uint8Array): Promise<Uint8Array>;
63
138
  /**
64
- * The epoch-independent secret for the non-rotating handshake/recovery topic.
65
- * Stable for the group's whole life so a stranded peer on any epoch can always
66
- * derive the rendezvous.
139
+ * Open a sealed reply with the key minted for `requestID` and BUILD the external commit that
140
+ * rejoins this peer. Non-mutating: the rejoined handle is adopted in
141
+ * {@link PendingRecovery.onAccepted} and nowhere else, because the commit still has to win a
142
+ * compare-and-set at the head.
143
+ *
144
+ * `null` for bytes this peer cannot open OR cannot trust. HPKE base mode needs only the
145
+ * requester's public ephemeral key — all of which rides the public request in the clear — so a
146
+ * hub-injected or observer-forged reply may DECRYPT. What refuses it: the responder must prove
147
+ * membership by signing the reply with its DID key (open side requires the signer to hold a
148
+ * leaf in this peer's last-known tree), and the offered GroupInfo's group id and genesis anchor
149
+ * must match the group being healed. A reply the AEAD refuses, or one that fails either check,
150
+ * is `null`. A throw is tolerated and read the same way.
151
+ */
152
+ applyRecovery(sealed: Uint8Array, requestID: string): Promise<PendingRecovery | null>;
153
+ /**
154
+ * Whether the ledger this handle holds is the whole ledger its OWN GroupContext attests to:
155
+ * the head folded from the entries it holds, in their order, against the authenticated head it
156
+ * carries. Purely local. False means incomplete — {@link bootstrapLedger} must run before this
157
+ * handle can be trusted to fold a roster or judge an incoming commit. A handle that rejoined by
158
+ * external commit reads false: empty ledger against a live, non-genesis head.
159
+ */
160
+ isLedgerComplete(): Promise<boolean>;
161
+ /**
162
+ * The WHOLE ordered ledger this handle holds, as signed tokens — what a peer about to rejoin
163
+ * snapshots as the entries it may still owe, and filters its re-enactment against once the
164
+ * group's ledger is back. Purely local, never on the wire (a responder uses {@link sealLedger}).
165
+ *
166
+ * Order is load-bearing: the head is a chain digest, so a permuted list of the same tokens
167
+ * folds to a different head and the requester rejects it.
168
+ */
169
+ getLedger(): Promise<Array<string>>;
170
+ /**
171
+ * Answer another member's ledger gather: verify the token, check the requester still holds a
172
+ * leaf in THIS member's current ratchet tree, and seal this handle's whole ordered ledger to
173
+ * the ephemeral key inside the signed request.
174
+ *
175
+ * Same roster-intrinsic authorization {@link sealGroupInfo} makes, and not a nicety: the ledger
176
+ * is the group's whole authority state on a public secretless topic, and a responder that
177
+ * sealed without checking would hand every role and promotion to any stranger who minted a
178
+ * request, encrypted to the stranger's key. Throws for a request it refuses; the peer stays silent.
179
+ *
180
+ * The seal is EPOCH-INDEPENDENT and must remain so: the requester crashed between rejoin and
181
+ * bootstrap and the lane gathers before it pulls, so it can be at an older epoch than every
182
+ * responder, and a reply sealed under the responder's current epoch would be unopenable by it.
183
+ */
184
+ sealLedger(request: Uint8Array): Promise<Uint8Array>;
185
+ /**
186
+ * Open a sealed gather reply with the key minted for `requestID`, returning the responder's
187
+ * whole ordered ledger as signed tokens.
188
+ *
189
+ * `null` when the AEAD refuses the bytes — sealed to another ephemeral key, or bound to another
190
+ * member, request, or reply kind. It does NOT prove the sealer was a member: unlike the
191
+ * GroupInfo reply the ledger reply carries no attestation, and HPKE base mode authenticates no
192
+ * one, so an observer of the request can forge a reply that decrypts. The key is NOT consumed:
193
+ * every responder answers, and the requester must open the next reply after dropping one.
194
+ *
195
+ * Opening proves NOTHING about who sealed the tokens. The bound is {@link bootstrapLedger}'s
196
+ * head check: a reply reproducing this group's authenticated head is its whole ledger in order,
197
+ * and a forged, lying, reordered or truncated one fails and is dropped — withhold, never
198
+ * rewrite. A forged reply that merely decrypts costs one gather attempt: denial of service, not
199
+ * compromise.
200
+ */
201
+ openSealedLedger(sealed: Uint8Array, requestID: string): Promise<Array<string> | null>;
202
+ /**
203
+ * Install a gathered ledger, verified against the authenticated head BEFORE a single entry is
204
+ * folded. REPLACES the ledger this handle holds, sound because the check is a fold from
205
+ * genesis: a list reproducing the head this handle's own GroupContext carries IS the group's
206
+ * entire ledger, in order.
207
+ *
208
+ * Throws for a list whose recomputed head does not match — a lying responder can withhold,
209
+ * never rewrite — and the peer drops that responder and folds the next reply instead.
210
+ */
211
+ bootstrapLedger(tokens: Array<string>): Promise<void>;
212
+ /**
213
+ * The epoch-independent secret for the non-rotating handshake/recovery topic. Stable for the
214
+ * group's whole life so a stranded peer on any epoch can always derive the rendezvous.
67
215
  */
68
216
  exportRecoverySecret(): Uint8Array | Promise<Uint8Array>;
69
217
  };
218
+ /**
219
+ * The one throw {@link GroupMLS.processCommit} is allowed: the Commit named ledger entries whose
220
+ * bodies would not resolve from the frame the Commit rides in.
221
+ *
222
+ * The lane treats it as POISON: step over the frame, advance the cursor, never re-read. The
223
+ * bodies are sealed under the Commit's framed epoch, so a peer that cannot resolve them is one no
224
+ * member at that epoch can — nobody applies the commit, the group never moves past that epoch,
225
+ * and the next honest commit is framed at the same epoch and compare-and-sets behind it.
226
+ * Everything else the port says about a frame it will not apply is `{ advanced: false }`, poison
227
+ * on the same terms: advances, never retried, does not heal.
228
+ *
229
+ * Matched by NAME, not class: the port is consumer-supplied and its error type is not this
230
+ * package's to import. A missing-entries error named anything else is treated as an unknown
231
+ * failure — so the name is contract.
232
+ */
233
+ export declare function isMissingLedgerEntries(error: unknown): boolean;
package/lib/crypto.js CHANGED
@@ -1,9 +1,17 @@
1
1
  /**
2
- * Consumer-supplied MLS lifecycle port. Sibling to {@link GroupCrypto}: where
3
- * `GroupCrypto` adapts application encrypt/decrypt, this drives the handshake
4
- * lane — applying Commits to advance the epoch and re-syncing a stranded peer.
5
- * group-rpc owns the transport + orchestration (subscribe the non-rotating
6
- * handshake topic, run these methods, resync when the epoch advances); the
7
- * consumer owns the MLS state and any storage/atomicity, entirely below this
8
- * interface.
9
- */ export { };
2
+ * The one throw {@link GroupMLS.processCommit} is allowed: the Commit named ledger entries whose
3
+ * bodies would not resolve from the frame the Commit rides in.
4
+ *
5
+ * The lane treats it as POISON: step over the frame, advance the cursor, never re-read. The
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.
11
+ *
12
+ * 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.
15
+ */ export function isMissingLedgerEntries(error) {
16
+ return error instanceof Error && error.name === 'MissingLedgerEntriesError';
17
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The hub hands a peer two kinds of position, both a bare `string`:
3
+ *
4
+ * - A **log position** is a place in a *topic's log*: `fetchTopic`'s `after`, `head`,
5
+ * `oldest`. Every reader of the topic sees the same log in the same order.
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
8
+ * recipient's own frames, and is emptied by acking.
9
+ *
10
+ * Different sequences, different frames, different orders. Crossing them silently mis-pages
11
+ * (skipped or re-read commits) with no type error, since both are strings. Branded so a
12
+ * delivery position cannot be assigned where a log position is expected, and minting either
13
+ * requires saying which you mean.
14
+ */
15
+ declare const logPositionBrand: unique symbol;
16
+ declare const deliveryPositionBrand: unique symbol;
17
+ /** A position in a topic's log. Read it from a `fetchTopic` result or a log publish. */
18
+ export type LogPosition = string & {
19
+ readonly [logPositionBrand]: true;
20
+ };
21
+ /** A position in a recipient's delivery queue. Read it from a pushed message. */
22
+ export type DeliveryPosition = string & {
23
+ readonly [deliveryPositionBrand]: true;
24
+ };
25
+ /**
26
+ * Name a sequenceID as a position in a topic's log. Legitimate sources: the entries,
27
+ * `head` and `oldest` of a `fetchTopic` result, and the sequenceID a `retain: 'log'`
28
+ * publish returns. A sequenceID from a *pushed* message is NOT one of them.
29
+ */
30
+ export declare function asLogPosition(sequenceID: string): LogPosition;
31
+ /** Name a sequenceID as a position in this recipient's delivery queue (i.e. an ack). */
32
+ export declare function asDeliveryPosition(sequenceID: string): DeliveryPosition;
33
+ export {};
package/lib/cursor.js ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The hub hands a peer two kinds of position, both a bare `string`:
3
+ *
4
+ * - A **log position** is a place in a *topic's log*: `fetchTopic`'s `after`, `head`,
5
+ * `oldest`. Every reader of the topic sees the same log in the same order.
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
8
+ * recipient's own frames, and is emptied by acking.
9
+ *
10
+ * Different sequences, different frames, different orders. Crossing them silently mis-pages
11
+ * (skipped or re-read commits) with no type error, since both are strings. Branded so a
12
+ * delivery position cannot be assigned where a log position is expected, and minting either
13
+ * requires saying which you mean.
14
+ */ // Nominal brand keys: `declare const … : unique symbol` mints a fresh type-only tag with no runtime
15
+ // value — the declaration IS the definition, nothing to import. Each tags one string type below so
16
+ // the two cannot be assigned to each other.
17
+ /**
18
+ * Name a sequenceID as a position in a topic's log. Legitimate sources: the entries,
19
+ * `head` and `oldest` of a `fetchTopic` result, and the sequenceID a `retain: 'log'`
20
+ * publish returns. A sequenceID from a *pushed* message is NOT one of them.
21
+ */ export function asLogPosition(sequenceID) {
22
+ return sequenceID;
23
+ }
24
+ /** Name a sequenceID as a position in this recipient's delivery queue (i.e. an ack). */ export function asDeliveryPosition(sequenceID) {
25
+ return sequenceID;
26
+ }
@@ -1,17 +1,17 @@
1
1
  import type { ByteTransform, Unwrap } from '@kumiai/broadcast';
2
- import type { HubLike } from '@kumiai/hub-tunnel';
2
+ import type { MailboxHub } from '@kumiai/hub-tunnel';
3
3
  export type SealDirectedHubParams = {
4
- hub: HubLike;
4
+ hub: MailboxHub;
5
5
  wrap: ByteTransform;
6
6
  unwrap: Unwrap;
7
7
  /** When set, inbound frames whose recovered senderDID != this are dropped. */
8
8
  expectedSenderDID?: string;
9
9
  };
10
10
  /**
11
- * Wrap a HubLike so directed frames are sealed with `wrap` on publish and opened
11
+ * Wrap a MailboxHub so directed frames are sealed with `wrap` on publish and opened
12
12
  * with `unwrap` on receive. The recovered MLS `senderDID` replaces the
13
13
  * hub-asserted one (a lying hub cannot forge it); frames that fail to open,
14
14
  * that unwrap without a recovered sender, or whose recovered sender !=
15
15
  * `expectedSenderDID`, are dropped.
16
16
  */
17
- export declare function sealDirectedHub(params: SealDirectedHubParams): HubLike;
17
+ export declare function sealDirectedHub(params: SealDirectedHubParams): MailboxHub;
@@ -4,7 +4,7 @@ function normalizeUnwrap(result) {
4
4
  } : result;
5
5
  }
6
6
  /**
7
- * Wrap a HubLike so directed frames are sealed with `wrap` on publish and opened
7
+ * Wrap a MailboxHub so directed frames are sealed with `wrap` on publish and opened
8
8
  * with `unwrap` on receive. The recovered MLS `senderDID` replaces the
9
9
  * hub-asserted one (a lying hub cannot forge it); frames that fail to open,
10
10
  * that unwrap without a recovered sender, or whose recovered sender !=
package/lib/directed.d.ts CHANGED
@@ -33,12 +33,11 @@ export type InboxAcceptorParams<Protocol extends ProtocolDefinition> = {
33
33
  unwrap: Unwrap;
34
34
  };
35
35
  /**
36
- * Accept directed RPC. A single sealed drain of `selfInboxTopic` opens each
37
- * inbound frame with `unwrap`, binds every session to the MLS-authenticated
38
- * sender recovered from the ciphertext, and feeds decrypted frame bytes into a
39
- * per-session in-memory transport whose replies are sealed with `wrap`. Frames
40
- * whose recovered sender does not match the session binding are dropped, so a
41
- * malicious hub can neither read the lane nor forge/splice a sender.
36
+ * Accept directed RPC. A single sealed drain of `selfInboxTopic` opens each inbound frame with
37
+ * `unwrap`, binds every session to the MLS-authenticated sender recovered from the ciphertext,
38
+ * and feeds decrypted bytes into a per-session in-memory transport whose replies are sealed
39
+ * with `wrap`. Frames whose recovered sender does not match the session binding are dropped, so
40
+ * a malicious hub can neither read the lane nor forge/splice a sender.
42
41
  */
43
42
  export declare function createInboxAcceptor<Protocol extends ProtocolDefinition>(params: InboxAcceptorParams<Protocol>): {
44
43
  dispose: () => Promise<void>;
package/lib/directed.js CHANGED
@@ -13,7 +13,7 @@ import { inboxTopic } from './topic.js';
13
13
  // Replies are authored by `memberDID`; drop anything a lying hub injects under
14
14
  // a different MLS sender.
15
15
  const sealedHub = sealDirectedHub({
16
- hub: mux.hubLike,
16
+ hub: mux.mailbox,
17
17
  wrap,
18
18
  unwrap,
19
19
  expectedSenderDID: memberDID
@@ -42,12 +42,11 @@ function normalizeUnwrap(result) {
42
42
  } : result;
43
43
  }
44
44
  /**
45
- * Accept directed RPC. A single sealed drain of `selfInboxTopic` opens each
46
- * inbound frame with `unwrap`, binds every session to the MLS-authenticated
47
- * sender recovered from the ciphertext, and feeds decrypted frame bytes into a
48
- * per-session in-memory transport whose replies are sealed with `wrap`. Frames
49
- * whose recovered sender does not match the session binding are dropped, so a
50
- * malicious hub can neither read the lane nor forge/splice a sender.
45
+ * Accept directed RPC. A single sealed drain of `selfInboxTopic` opens each inbound frame with
46
+ * `unwrap`, binds every session to the MLS-authenticated sender recovered from the ciphertext,
47
+ * and feeds decrypted bytes into a per-session in-memory transport whose replies are sealed
48
+ * with `wrap`. Frames whose recovered sender does not match the session binding are dropped, so
49
+ * a malicious hub can neither read the lane nor forge/splice a sender.
51
50
  */ export function createInboxAcceptor(params) {
52
51
  const { mux, localDID, selfInboxTopic, resolveSendTopic, protocol, handlers, wrap, unwrap } = params;
53
52
  const server = new Server({
@@ -63,7 +62,7 @@ function normalizeUnwrap(result) {
63
62
  const sessionHub = {
64
63
  async publish (publishParams) {
65
64
  const sealed = await wrap(publishParams.payload);
66
- return mux.hubLike.publish({
65
+ return mux.mailbox.publish({
67
66
  senderDID: publishParams.senderDID,
68
67
  topicID: publishParams.topicID,
69
68
  payload: sealed
@@ -166,11 +165,9 @@ function normalizeUnwrap(result) {
166
165
  }
167
166
  };
168
167
  };
169
- // Serialize inbound processing: `unwrap` is async (real MLS decrypt has
170
- // variable latency), so independent concurrent tasks could resolve out of
171
- // dispatch order — racing to double-create a session, or feeding frames to a
172
- // tunnel out of wire order (which drops them as stale seq). Chaining each
173
- // message onto a running tail keeps processing in arrival order.
168
+ // Serialize inbound processing: `unwrap` is async with variable latency, so concurrent
169
+ // tasks could resolve out of dispatch order — double-creating a session, or feeding a tunnel
170
+ // out of wire order (dropped as stale seq). Chaining onto a running tail keeps arrival order.
174
171
  let inboundTail = Promise.resolve();
175
172
  const unsubscribe = mux.onInbound(selfInboxTopic, (message)=>{
176
173
  inboundTail = inboundTail.then(async ()=>{
@@ -1,13 +1,12 @@
1
1
  /**
2
- * Framing for the raw MLS-handshake lane. Unlike application protocols, this
3
- * lane carries un-`wrap`ped bytes on a single non-rotating topic and multiplexes
4
- * three message kinds. Each frame is self-identifying:
2
+ * Framing for the raw MLS control lanes: un-`wrap`ped bytes on non-rotating topics (Commits on
3
+ * the commit topic, recovery request/reply on the rendezvous topic). Self-identifying, so a
4
+ * frame on the wrong lane is dropped rather than mis-read:
5
5
  *
6
6
  * [ MAGIC(2) | VERSION(1) | KIND(1) | payload... ]
7
7
  *
8
- * The magic marks the bytes as a handshake frame (fail-fast on garbage or a
9
- * mis-routed payload); the version allows the wire format to evolve without an
10
- * ambiguous unversioned migration; the kind discriminates the three messages.
8
+ * Magic: fail-fast on garbage or a mis-routed payload. Version: evolve the wire format without
9
+ * an ambiguous unversioned migration. Kind: discriminate the messages.
11
10
  */
12
11
  /** Leading marker identifying a handshake frame ("EK"). */
13
12
  export declare const HANDSHAKE_MAGIC: Uint8Array<ArrayBuffer>;
@@ -21,6 +20,14 @@ export declare const HANDSHAKE_KIND: {
21
20
  readonly recoveryRequest: 1;
22
21
  /** A member's reply carrying the state needed to re-sync. */
23
22
  readonly recoveryReply: 2;
23
+ /**
24
+ * A rejoined peer asking for the group's WHOLE ordered ledger. A GroupInfo carries an
25
+ * authenticated ledger head (a chain digest) and no entries, so a peer that rejoined by
26
+ * external commit cannot ask for "the ids it is missing" — nothing enumerates them.
27
+ */
28
+ readonly ledgerRequest: 3;
29
+ /** A member's reply carrying its whole ordered ledger, for the requester to head-verify. */
30
+ readonly ledgerReply: 4;
24
31
  };
25
32
  export type HandshakeKind = (typeof HANDSHAKE_KIND)[keyof typeof HANDSHAKE_KIND];
26
33
  /** Wrap a payload with the magic + version + kind header. */
package/lib/handshake.js CHANGED
@@ -1,13 +1,12 @@
1
1
  /**
2
- * Framing for the raw MLS-handshake lane. Unlike application protocols, this
3
- * lane carries un-`wrap`ped bytes on a single non-rotating topic and multiplexes
4
- * three message kinds. Each frame is self-identifying:
2
+ * Framing for the raw MLS control lanes: un-`wrap`ped bytes on non-rotating topics (Commits on
3
+ * the commit topic, recovery request/reply on the rendezvous topic). Self-identifying, so a
4
+ * frame on the wrong lane is dropped rather than mis-read:
5
5
  *
6
6
  * [ MAGIC(2) | VERSION(1) | KIND(1) | payload... ]
7
7
  *
8
- * The magic marks the bytes as a handshake frame (fail-fast on garbage or a
9
- * mis-routed payload); the version allows the wire format to evolve without an
10
- * ambiguous unversioned migration; the kind discriminates the three messages.
8
+ * Magic: fail-fast on garbage or a mis-routed payload. Version: evolve the wire format without
9
+ * an ambiguous unversioned migration. Kind: discriminate the messages.
11
10
  */ /** Leading marker identifying a handshake frame ("EK"). */ export const HANDSHAKE_MAGIC = Uint8Array.from([
12
11
  0x45,
13
12
  0x4b
@@ -17,7 +16,13 @@ const HEADER_LENGTH = HANDSHAKE_MAGIC.length + 2;
17
16
  /** The message kinds carried on the handshake lane. */ export const HANDSHAKE_KIND = {
18
17
  /** An MLS Commit fanned out to advance every member's epoch. */ commit: 0,
19
18
  /** A stranded peer asking the group for current state. */ recoveryRequest: 1,
20
- /** A member's reply carrying the state needed to re-sync. */ recoveryReply: 2
19
+ /** A member's reply carrying the state needed to re-sync. */ recoveryReply: 2,
20
+ /**
21
+ * A rejoined peer asking for the group's WHOLE ordered ledger. A GroupInfo carries an
22
+ * authenticated ledger head (a chain digest) and no entries, so a peer that rejoined by
23
+ * external commit cannot ask for "the ids it is missing" — nothing enumerates them.
24
+ */ ledgerRequest: 3,
25
+ /** A member's reply carrying its whole ordered ledger, for the requester to head-verify. */ ledgerReply: 4
21
26
  };
22
27
  const KINDS = new Set(Object.values(HANDSHAKE_KIND));
23
28
  function isHandshakeKind(value) {
package/lib/hub-mux.d.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import type { BroadcastBus } from '@kumiai/broadcast';
2
2
  import type { StoredMessage } from '@kumiai/hub-protocol';
3
- import type { HubLike } from '@kumiai/hub-tunnel';
3
+ import type { HubFetchTopicResult, HubSubscribeOptions, LogHub, MailboxHub } from '@kumiai/hub-tunnel';
4
4
  export type HubMuxParams = {
5
- hub: HubLike;
5
+ /** The real hub. It must serve a log: the commit lane reads one. */
6
+ hub: LogHub;
6
7
  /** Authenticated DID used to drain `hub.receive` and stamp bus publishes. */
7
8
  localDID: string;
8
9
  };
@@ -12,21 +13,59 @@ export type HubMuxParams = {
12
13
  * (e.g. an idempotent app consumer) may ignore it.
13
14
  */
14
15
  export type InboundListener = (message: StoredMessage, ack: () => void) => void;
16
+ export type MuxPublishParams = {
17
+ topicID: string;
18
+ payload: Uint8Array;
19
+ /** Retention class. Absent: 'mailbox'. Only a 'log' publish moves the topic's head. */
20
+ retain?: 'log' | 'mailbox';
21
+ /**
22
+ * Compare-and-set on the topic's head. Absent: append unconditionally. `null`: append
23
+ * only while the topic has never had a log publish. A loser gets HeadMismatchError and
24
+ * the store is left exactly as it was found.
25
+ */
26
+ expectedHead?: string | null;
27
+ /** Idempotency key: a republish of an accepted one returns its sequenceID and appends nothing. */
28
+ publishID?: string;
29
+ };
30
+ export type MuxFetchTopicParams = {
31
+ topicID: string;
32
+ /** Exclusive cursor: entries after this log position. Absent: from the oldest retained. */
33
+ after?: string;
34
+ limit?: number;
35
+ };
15
36
  export type HubMux = {
16
37
  readonly bus: BroadcastBus;
17
- readonly hubLike: HubLike;
18
- onInbound: (topicID: string, listener: InboundListener) => () => void;
38
+ /** A mailbox-shaped view of the drain, for the directed tunnels. It carries no log. */
39
+ readonly mailbox: MailboxHub;
40
+ publish: (params: MuxPublishParams) => Promise<{
41
+ sequenceID: string;
42
+ }>;
43
+ /** Pull a topic's log as the local DID. */
44
+ fetchTopic: (params: MuxFetchTopicParams) => Promise<HubFetchTopicResult>;
45
+ onInbound: (topicID: string, listener: InboundListener, options?: HubSubscribeOptions) => () => void;
46
+ /**
47
+ * Stop the drain and drop every local listener. It does NOT unsubscribe: see the note on
48
+ * {@link createHubMux}. The member stays a subscriber of everything it was subscribed to,
49
+ * and the hub keeps holding its mail.
50
+ */
19
51
  dispose: () => Promise<void>;
20
52
  };
21
53
  /**
22
- * Multiplex a single hub `receive` drain into a BroadcastBus view, a HubLike
23
- * view (for directed tunnels), and an onInbound hook (for lazy directed-server
24
- * accept).
54
+ * Multiplex a single hub `receive` drain into a BroadcastBus view, a mailbox-hub view (for
55
+ * directed tunnels), and an onInbound hook (for lazy directed-server accept).
56
+ *
57
+ * Per inbound message, in order: (1) fire `onInbound` listeners for the topic, then (2) push
58
+ * to every `mailbox.receive` sink — so a listener may create a directed tunnel synchronously
59
+ * and still receive the triggering frame. Topics are refcounted across all three views; the
60
+ * first registration subscribes on the hub.
25
61
  *
26
- * Per inbound message, in order: (1) fire `onInbound` listeners for the topic,
27
- * then (2) push to every `hubLike.receive` sink — so a listener may create a
28
- * directed tunnel synchronously and still receive the triggering frame. Topics
29
- * are refcounted across all three views: the first registration subscribes on
30
- * the hub, the last removal unsubscribes.
62
+ * **The refcount tracks LOCAL LISTENERS and never unsubscribes.** A subscription is a durable
63
+ * member-topic relationship, not a session: the hub holds a subscriber's undelivered frames,
64
+ * and `unsubscribe` tells the store to drop them and free any mailbox frame it was the last
65
+ * reader of. So no local lifecycle event may unsubscribe — dropping a listener, rotating an
66
+ * epoch, disposing the mux all mean "not listening", never "I have read my mail, discard the
67
+ * rest". Only an explicit leave-the-group would unsubscribe, and nothing here does. That
68
+ * outliving subscription is what lets a member return and find its mail; disposing the peer is
69
+ * what backgrounding a mobile app calls.
31
70
  */
32
71
  export declare function createHubMux(params: HubMuxParams): HubMux;