@kumiai/rpc 0.9.1 → 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/README.md +115 -13
- package/lib/app-aad.d.ts +8 -0
- package/lib/app-aad.js +28 -0
- package/lib/app-lane.d.ts +33 -20
- package/lib/app-lane.js +331 -66
- package/lib/commit-frame.js +3 -0
- package/lib/crypto.d.ts +106 -31
- package/lib/crypto.js +49 -7
- package/lib/cursor.d.ts +4 -0
- package/lib/cursor.js +10 -0
- package/lib/directed.d.ts +3 -4
- package/lib/directed.js +9 -3
- package/lib/handlers.d.ts +12 -1
- package/lib/handlers.js +6 -2
- package/lib/handshake.d.ts +3 -6
- package/lib/handshake.js +13 -6
- package/lib/host-notice.d.ts +1 -0
- package/lib/host-notice.js +12 -0
- package/lib/index.d.ts +5 -2
- package/lib/index.js +3 -2
- package/lib/open-once.d.ts +11 -9
- package/lib/open-once.js +18 -12
- package/lib/peer.d.ts +46 -4
- package/lib/peer.js +755 -303
- package/package.json +9 -9
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()`
|
|
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
|
|
20
|
-
*
|
|
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):
|
|
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
|
-
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
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):
|
|
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
|
|
186
|
-
*
|
|
187
|
-
*
|
|
188
|
-
* would anchor where it booted while the group stayed put — so the
|
|
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
|
|
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
|
|
260
|
-
* carrying both an Add and a Remove
|
|
261
|
-
*
|
|
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
|
|
264
|
-
*
|
|
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
|
-
|
|
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
|
|
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()`
|
|
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
|
|
20
|
-
*
|
|
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:
|
|
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:
|
|
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:
|
|
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, (
|
|
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') {
|
package/lib/handshake.d.ts
CHANGED
|
@@ -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
|
|
41
|
-
*
|
|
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
|
|
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
|
|
42
|
-
*
|
|
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
|
|
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/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';
|
package/lib/index.js
CHANGED
|
@@ -2,10 +2,11 @@
|
|
|
2
2
|
* High-level MLS-aware group RPC for Enkaku.
|
|
3
3
|
*
|
|
4
4
|
* @module rpc
|
|
5
|
-
*/ export {
|
|
5
|
+
*/ export { decodeAppAAD, encodeAppAAD } from './app-aad.js';
|
|
6
|
+
export { classifyCommit, digestAppliedCommit, UNKNOWN_FRAME_VERSION } from './classify.js';
|
|
6
7
|
export { CommitDeadlineError, isHeadMismatch, JournalEpochError, RecoveryRequiredError } from './commit.js';
|
|
7
8
|
export { COMMIT_FRAME_VERSION, decodeCommitFrame, encodeCommitFrame, isUnsupportedCommitFrameVersion, UnsupportedCommitFrameVersionError } from './commit-frame.js';
|
|
8
|
-
export { isMissingLedgerEntries } from './crypto.js';
|
|
9
|
+
export { AppFrameStorageError, FrameEpochError, isAppFrameStorageError, isMissingLedgerEntries, sortPendingAppFrames } from './crypto.js';
|
|
9
10
|
export { asDeliveryPosition, asLogPosition } from './cursor.js';
|
|
10
11
|
export { PeerDisposedError } from './errors.js';
|
|
11
12
|
export { decodeHandshakeFrame, encodeHandshakeFrame, HANDSHAKE_KIND, HANDSHAKE_MAGIC, HANDSHAKE_VERSION } from './handshake.js';
|
package/lib/open-once.d.ts
CHANGED
|
@@ -1,27 +1,29 @@
|
|
|
1
|
-
import type { Unwrap, UnwrapResult } from '@kumiai/broadcast';
|
|
2
1
|
import type { StoredMessage } from '@kumiai/hub-protocol';
|
|
2
|
+
import type { GroupUnwrapResult } from './crypto.js';
|
|
3
3
|
import type { HubMux } from './hub-mux.js';
|
|
4
4
|
export type OpenOncePathParams<Opened> = {
|
|
5
5
|
mux: HubMux;
|
|
6
6
|
topicID: string;
|
|
7
|
-
unwrap:
|
|
7
|
+
unwrap: (bytes: Uint8Array) => GroupUnwrapResult | Promise<GroupUnwrapResult>;
|
|
8
8
|
/**
|
|
9
9
|
* Turn an opened frame into what this lane's consumers receive. Returning `undefined` drops
|
|
10
10
|
* the frame — the open has already happened either way, so a lane rejects here rather than
|
|
11
11
|
* leaving each consumer to decide.
|
|
12
12
|
*/
|
|
13
|
-
project: (message: StoredMessage, opened:
|
|
14
|
-
/** Called with the raw message
|
|
15
|
-
*
|
|
16
|
-
note?: (message: StoredMessage) => void;
|
|
13
|
+
project: (message: StoredMessage, opened: GroupUnwrapResult) => Opened | undefined;
|
|
14
|
+
/** Called with the raw message once its open settles: `undefined` when it opened, else the
|
|
15
|
+
* throw. The throw carries the handle's locked answer ({@link "crypto".FrameEpochError}). */
|
|
16
|
+
note?: (message: StoredMessage, failure: unknown) => void;
|
|
17
|
+
/** A live push that only asks its owner to read the retained log. */
|
|
18
|
+
wakeup?: (message: StoredMessage) => boolean;
|
|
17
19
|
/**
|
|
18
20
|
* Consulted when the open fails (any throw in the chain — `unwrap`, `project`, or a listener).
|
|
19
21
|
* Answering `true` withholds the ack: the frame is sealed at an epoch this handle has not reached
|
|
20
22
|
* yet (the window between a commit landing and this peer applying it) and must survive for a later
|
|
21
|
-
* reconnect. Every other failure acks
|
|
22
|
-
*
|
|
23
|
+
* reconnect. Every other failure acks. See `app-lane.ts`'s `note` for the same distinction against
|
|
24
|
+
* a live push.
|
|
23
25
|
*/
|
|
24
|
-
retainOnFailure?: (message: StoredMessage) => boolean;
|
|
26
|
+
retainOnFailure?: (message: StoredMessage, error: unknown) => boolean;
|
|
25
27
|
};
|
|
26
28
|
/**
|
|
27
29
|
* ONE INBOUND PATH PER TOPIC, shared by every consumer built on it.
|