@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/README.md +120 -0
- package/lib/anchor.d.ts +27 -0
- package/lib/anchor.js +18 -0
- package/lib/app-cursor.d.ts +63 -0
- package/lib/app-cursor.js +44 -0
- package/lib/app-lane.d.ts +78 -0
- package/lib/app-lane.js +401 -0
- package/lib/bus-server.d.ts +6 -6
- package/lib/bus-server.js +3 -9
- package/lib/classify.d.ts +94 -44
- package/lib/classify.js +35 -19
- package/lib/commit-frame.d.ts +40 -4
- package/lib/commit-frame.js +60 -13
- package/lib/crypto.d.ts +275 -115
- package/lib/crypto.js +5 -6
- package/lib/cursor.d.ts +1 -1
- package/lib/cursor.js +1 -1
- package/lib/directed.d.ts +44 -5
- package/lib/directed.js +135 -60
- package/lib/handshake.d.ts +41 -4
- package/lib/handshake.js +40 -7
- package/lib/hub-mux.d.ts +94 -1
- package/lib/hub-mux.js +254 -11
- package/lib/index.d.ts +10 -6
- package/lib/index.js +6 -5
- package/lib/ledger-entries.d.ts +52 -8
- package/lib/ledger-entries.js +59 -23
- package/lib/open-once.d.ts +46 -0
- package/lib/open-once.js +63 -0
- package/lib/peer.d.ts +122 -54
- package/lib/peer.js +664 -306
- package/lib/protocol.d.ts +52 -0
- package/lib/protocol.js +22 -0
- package/lib/roster.d.ts +22 -0
- package/lib/roster.js +29 -0
- package/lib/topic.d.ts +20 -3
- package/lib/topic.js +20 -4
- package/package.json +17 -13
- package/lib/directed-crypto.d.ts +0 -17
- package/lib/directed-crypto.js +0 -80
package/lib/hub-mux.js
CHANGED
|
@@ -1,4 +1,79 @@
|
|
|
1
|
+
import { RetentionExceededError } from '@kumiai/hub-protocol';
|
|
2
|
+
import { getLogger, isSetup } from '@sozai/log';
|
|
1
3
|
import { asDeliveryPosition } from './cursor.js';
|
|
4
|
+
/**
|
|
5
|
+
* Backoff for a TRANSIENT subscribe failure, in ms. Short enough that an ordinary reconnect blip
|
|
6
|
+
* heals before the first lane operation, bounded so a hub that is answering "no" in a shape this
|
|
7
|
+
* code cannot classify is not asked forever.
|
|
8
|
+
*/ const DEFAULT_SUBSCRIBE_RETRY_DELAYS_MS = [
|
|
9
|
+
100,
|
|
10
|
+
500,
|
|
11
|
+
2_000,
|
|
12
|
+
10_000
|
|
13
|
+
];
|
|
14
|
+
/**
|
|
15
|
+
* The logger these fall back to. `['kumiai', 'rpc']` — an app routing this category sees them
|
|
16
|
+
* with everything else it collects.
|
|
17
|
+
*/ const logger = getLogger([
|
|
18
|
+
'kumiai',
|
|
19
|
+
'rpc'
|
|
20
|
+
]);
|
|
21
|
+
/**
|
|
22
|
+
* THE FALLBACK, used when a host wires no handler: say it out loud rather than nowhere.
|
|
23
|
+
*
|
|
24
|
+
* Both conditions leave a peer that looks healthy and is not — every call still succeeds, and
|
|
25
|
+
* the group simply appears to have gone quiet. A host that has not wired the notice is exactly
|
|
26
|
+
* the host that will not otherwise find out, so the default has to be loud rather than tidy.
|
|
27
|
+
*
|
|
28
|
+
* AT ERROR LEVEL, not warn, and that is not emphasis: `@sozai/log`'s own default configuration
|
|
29
|
+
* admits `error` and drops `warn`, so a warning would be discarded by the very setup most apps
|
|
30
|
+
* start from. A condition that silently loses every message this peer is sent belongs above that
|
|
31
|
+
* line anyway.
|
|
32
|
+
*
|
|
33
|
+
* AND CONSOLE WHEN LOGGING IS NOT CONFIGURED, because logtape with no configuration discards
|
|
34
|
+
* records — which would put this back exactly where it started. `isSetup()` is the difference
|
|
35
|
+
* between "the app collects this" and "nobody will ever see it".
|
|
36
|
+
*
|
|
37
|
+
* KNOWN GAP, filed in `docs/agents/plans/next/2026-07-19-logging-reaches-a-sink.md`: `isSetup()`
|
|
38
|
+
* answers whether logging is configured, not whether THIS category reaches a sink. An app calling
|
|
39
|
+
* `@sozai/log`'s `setup()` with no argument gets a config covering `['sozai']` and nothing else,
|
|
40
|
+
* so these records are dropped while the console fallback stays out of the way. Fixing it means
|
|
41
|
+
* choosing between logtape's own emit check, a root sink in the shared default, and a documented
|
|
42
|
+
* requirement — a decision that belongs to the logging story rather than to this file.
|
|
43
|
+
*
|
|
44
|
+
* Only these two conditions. `rpc/src` swallows failures in twenty-odd other places and every one
|
|
45
|
+
* of them is ordinary control flow on a shared log — a frame sealed for another epoch, a host
|
|
46
|
+
* handler that threw, a retry that ran out. Logging those would be constant noise, and a warning
|
|
47
|
+
* nobody can afford to read is worth no more than silence.
|
|
48
|
+
*/ const report = (message, error)=>{
|
|
49
|
+
if (isSetup()) {
|
|
50
|
+
logger.error(message, {
|
|
51
|
+
error
|
|
52
|
+
});
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
// Last resort: no logging configured, so the app has nowhere to collect this.
|
|
56
|
+
console.error(`[@kumiai/rpc] ${message}`, error);
|
|
57
|
+
};
|
|
58
|
+
const warnSubscribeFailed = (failure)=>{
|
|
59
|
+
report(`hub refused the subscription to ${failure.topicID}` + `${failure.permanent ? ' (permanently)' : ' (after exhausting retries)'}. ` + 'This peer receives nothing on that topic and cannot pull it; every publish and fetch on ' + 'it now throws. Wire `onSubscribeFailed` to handle this.', failure.error);
|
|
60
|
+
};
|
|
61
|
+
const warnReceiveEnded = (ended)=>{
|
|
62
|
+
report('the hub push lane ended and will not restart on its own. This peer will receive nothing ' + 'further — no error, and every call keeps succeeding — until the host reconnects and ' + 'builds a new peer. Wire `onReceiveEnded` to handle this.', ended.error);
|
|
63
|
+
};
|
|
64
|
+
/**
|
|
65
|
+
* Permanent means the hub has ANSWERED, not that it failed. A retention above the operator's cap
|
|
66
|
+
* is a settled fact about this request: retrying it is a busy loop against an answer that will
|
|
67
|
+
* never change, and the peer's only route out is the host changing what it asks for. Anything
|
|
68
|
+
* else — a socket that dropped, a hub mid-restart — is assumed transient and retried, because the
|
|
69
|
+
* cost of retrying a failure that was really permanent is a bounded schedule, while the cost of
|
|
70
|
+
* NOT retrying one that was really transient is a peer that never comes back.
|
|
71
|
+
*/ function isPermanentSubscribeFailure(error) {
|
|
72
|
+
// Name as well as instance: a hub reached over the tunnel rebuilds the error from its wire code
|
|
73
|
+
// (`hubErrorFromCode`), and a host bundling two copies of hub-protocol would break `instanceof`
|
|
74
|
+
// alone — turning a permanent refusal back into a retry loop, silently.
|
|
75
|
+
return error instanceof RetentionExceededError || error instanceof Error && error.name === 'RetentionExceededError';
|
|
76
|
+
}
|
|
2
77
|
/**
|
|
3
78
|
* Multiplex a single hub `receive` drain into a BroadcastBus view, a mailbox-hub view (for
|
|
4
79
|
* directed tunnels), and an onInbound hook (for lazy directed-server accept).
|
|
@@ -8,6 +83,35 @@ import { asDeliveryPosition } from './cursor.js';
|
|
|
8
83
|
* and still receive the triggering frame. Topics are refcounted across all three views; the
|
|
9
84
|
* first registration subscribes on the hub.
|
|
10
85
|
*
|
|
86
|
+
* ## A subscribe the hub refuses
|
|
87
|
+
*
|
|
88
|
+
* The hub may say no — `RetentionExceededError` when a host asks to hold a log longer than the
|
|
89
|
+
* operator allows, refused rather than clamped on purpose. A peer that is not a subscriber of a
|
|
90
|
+
* topic is pushed nothing on it and cannot pull it: no commit applies, no app frame arrives. That
|
|
91
|
+
* failure has to be impossible to miss, and there are three candidate surfaces:
|
|
92
|
+
*
|
|
93
|
+
* - **Retry with backoff** answers a dropped socket and nothing else. Retrying a settled refusal
|
|
94
|
+
* is a busy loop against an answer that will not change, so it is the answer for TRANSIENT
|
|
95
|
+
* failures only. Used, bounded, and never for a permanent one.
|
|
96
|
+
* - **Raising into the caller** cannot be the whole answer: `retainTopic` is called for its effect
|
|
97
|
+
* and returns before the hub has answered, and the callers that would catch it (the commit-lane
|
|
98
|
+
* seed, the app-segment load) are the ones already written to swallow.
|
|
99
|
+
* - **A host callback** is optional by nature, and an optional notice cannot be the guarantee: an
|
|
100
|
+
* unwired host would be exactly as blind as today.
|
|
101
|
+
*
|
|
102
|
+
* So the guarantee is a LATCH, and the callback is a convenience on top of it. A refused topic is
|
|
103
|
+
* recorded as refused, and every `publish`, `bus.publish`, `mailbox.publish` and `fetchTopic` on it
|
|
104
|
+
* throws the hub's own error. A peer that cannot receive on a topic does not go on transmitting
|
|
105
|
+
* there as though it were whole — it fails at the first operation that touches the topic, with the
|
|
106
|
+
* reason rather than the `NotSubscribedError` symptom. That is what makes it impossible for a peer
|
|
107
|
+
* whose subscribe was refused to report itself healthy, whatever the host wired.
|
|
108
|
+
*
|
|
109
|
+
* `onSubscribeFailed` exists on top because a peer that only READS a topic calls nothing that
|
|
110
|
+
* could throw. The latch cannot reach it; the notice can.
|
|
111
|
+
*
|
|
112
|
+
* A refused topic is not held, so the next `retain` asks again — a host that lowered its retention
|
|
113
|
+
* recovers on the next rotation without restarting.
|
|
114
|
+
*
|
|
11
115
|
* **The refcount tracks LOCAL LISTENERS and never unsubscribes.** A subscription is a durable
|
|
12
116
|
* member-topic relationship, not a session: the hub holds a subscriber's undelivered frames,
|
|
13
117
|
* and `unsubscribe` tells the store to drop them and free any mailbox frame it was the last
|
|
@@ -18,14 +122,112 @@ import { asDeliveryPosition } from './cursor.js';
|
|
|
18
122
|
* what backgrounding a mobile app calls.
|
|
19
123
|
*/ export function createHubMux(params) {
|
|
20
124
|
const { hub, localDID } = params;
|
|
125
|
+
const onSubscribeFailed = params.onSubscribeFailed ?? warnSubscribeFailed;
|
|
126
|
+
const onReceiveEnded = params.onReceiveEnded ?? warnReceiveEnded;
|
|
127
|
+
const retryDelaysMs = params.subscribeRetryDelaysMs ?? DEFAULT_SUBSCRIBE_RETRY_DELAYS_MS;
|
|
21
128
|
const listeners = new Map();
|
|
22
129
|
const refcount = new Map();
|
|
130
|
+
const subscriptions = new Map();
|
|
23
131
|
const sinks = new Set();
|
|
24
132
|
let disposed = false;
|
|
133
|
+
/**
|
|
134
|
+
* Retry backoffs currently sleeping, each as the function that ends its sleep early.
|
|
135
|
+
*
|
|
136
|
+
* A timer nobody can reach still holds the process open, so a `dispose` that only sets a flag
|
|
137
|
+
* leaves the caller waiting out the longest backoff for work already abandoned. Cancelling ENDS
|
|
138
|
+
* the sleep rather than dropping it: clearing the timeout alone would leave the awaiting retry
|
|
139
|
+
* suspended on a promise that can never settle, trading a held timer for a leaked one.
|
|
140
|
+
*/ const sleeping = new Set();
|
|
141
|
+
const sleep = (ms)=>{
|
|
142
|
+
return new Promise((resolve)=>{
|
|
143
|
+
const wake = ()=>{
|
|
144
|
+
clearTimeout(timer);
|
|
145
|
+
sleeping.delete(wake);
|
|
146
|
+
resolve();
|
|
147
|
+
};
|
|
148
|
+
const timer = setTimeout(wake, ms);
|
|
149
|
+
sleeping.add(wake);
|
|
150
|
+
});
|
|
151
|
+
};
|
|
152
|
+
const reportFailure = (failure)=>{
|
|
153
|
+
try {
|
|
154
|
+
onSubscribeFailed?.(failure);
|
|
155
|
+
} catch {
|
|
156
|
+
// a host's notice handler must not break the mux
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
/**
|
|
160
|
+
* Ask the hub, once, and record what it said. Runs to the first `await` SYNCHRONOUSLY, so a hub
|
|
161
|
+
* whose `subscribe` registers synchronously is registered by the time `retain` returns — the
|
|
162
|
+
* subscribe-then-pull ordering the commit lane depends on is unchanged.
|
|
163
|
+
*/ const attemptSubscribe = async (topicID, options, attempt)=>{
|
|
164
|
+
subscriptions.set(topicID, {
|
|
165
|
+
kind: 'asking'
|
|
166
|
+
});
|
|
167
|
+
try {
|
|
168
|
+
// Inside the try, and awaited: `subscribe` may reject OR throw synchronously (the type
|
|
169
|
+
// allows `void`), and the old code's `Promise.resolve(...).catch()` caught only the first.
|
|
170
|
+
await hub.subscribe(localDID, topicID, options);
|
|
171
|
+
if (disposed) return;
|
|
172
|
+
subscriptions.set(topicID, {
|
|
173
|
+
kind: 'held'
|
|
174
|
+
});
|
|
175
|
+
return;
|
|
176
|
+
} catch (error) {
|
|
177
|
+
if (disposed) return;
|
|
178
|
+
const permanent = isPermanentSubscribeFailure(error);
|
|
179
|
+
const delay = retryDelaysMs[attempt];
|
|
180
|
+
if (permanent || delay === undefined) {
|
|
181
|
+
// The refusal is LATCHED, not just reported: see the note on `createHubMux` for why a
|
|
182
|
+
// notice a host may not have wired cannot be the whole answer.
|
|
183
|
+
subscriptions.set(topicID, {
|
|
184
|
+
kind: 'refused',
|
|
185
|
+
error,
|
|
186
|
+
permanent,
|
|
187
|
+
retention: options?.retention
|
|
188
|
+
});
|
|
189
|
+
reportFailure({
|
|
190
|
+
topicID,
|
|
191
|
+
error,
|
|
192
|
+
permanent
|
|
193
|
+
});
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
await sleep(delay);
|
|
197
|
+
if (disposed) return;
|
|
198
|
+
await attemptSubscribe(topicID, options, attempt + 1);
|
|
199
|
+
}
|
|
200
|
+
};
|
|
25
201
|
const retain = (topicID, options)=>{
|
|
26
|
-
|
|
27
|
-
refcount.
|
|
28
|
-
|
|
202
|
+
refcount.set(topicID, (refcount.get(topicID) ?? 0) + 1);
|
|
203
|
+
// Gated on the SUBSCRIPTION, never on the refcount. A topic held, or currently being asked
|
|
204
|
+
// for, is not asked for again. A refused one may be: the hub said no, so this peer does not
|
|
205
|
+
// hold it, and the data structure must not pretend otherwise.
|
|
206
|
+
const state = subscriptions.get(topicID);
|
|
207
|
+
if (state == null) {
|
|
208
|
+
void attemptSubscribe(topicID, options, 0);
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
if (state.kind !== 'refused') return;
|
|
212
|
+
// A PERMANENT refusal is an answer to a specific request, and is re-asked only under a
|
|
213
|
+
// different one. In particular a retain carrying NO retention does not clear it: a caller with
|
|
214
|
+
// no opinion about the window must not overrule the one that had an opinion and was refused —
|
|
215
|
+
// subscribing anyway would land the peer on the hub's default and quietly deliver the silent
|
|
216
|
+
// downgrade the hub refused to perform, which is worse than the refusal it replaces.
|
|
217
|
+
//
|
|
218
|
+
// A retry-exhausted failure carries no answer, so any retain re-asks.
|
|
219
|
+
if (state.permanent && (options?.retention == null || options.retention === state.retention)) {
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
void attemptSubscribe(topicID, options, 0);
|
|
223
|
+
};
|
|
224
|
+
/**
|
|
225
|
+
* The enforcement half. A topic the hub refused is one this peer cannot read, so it does not go
|
|
226
|
+
* on transmitting there as a full participant either: every publish and every fetch on it
|
|
227
|
+
* rejects with the hub's own error.
|
|
228
|
+
*/ const assertSubscribable = (topicID)=>{
|
|
229
|
+
const state = subscriptions.get(topicID);
|
|
230
|
+
if (state?.kind === 'refused') throw state.error;
|
|
29
231
|
};
|
|
30
232
|
// Drops a local listener's reference, and NOTHING at the hub. The subscription stands: the
|
|
31
233
|
// frames this member has been sent and not read are its own, and a caller that has merely
|
|
@@ -57,15 +259,33 @@ import { asDeliveryPosition } from './cursor.js';
|
|
|
57
259
|
};
|
|
58
260
|
const subscription = hub.receive(localDID);
|
|
59
261
|
const iterator = subscription[Symbol.asyncIterator]();
|
|
262
|
+
// Reported once, and only for an ending nobody asked for. `dispose` ends the drain too, and a
|
|
263
|
+
// host being told its lane died in response to its own teardown is noise that trains hosts to
|
|
264
|
+
// ignore the notice.
|
|
265
|
+
const reportEnded = (ended)=>{
|
|
266
|
+
if (disposed) return;
|
|
267
|
+
try {
|
|
268
|
+
onReceiveEnded?.(ended);
|
|
269
|
+
} catch {
|
|
270
|
+
// a host's notice handler must not break the mux
|
|
271
|
+
}
|
|
272
|
+
};
|
|
60
273
|
void (async ()=>{
|
|
61
274
|
while(true){
|
|
62
275
|
let result;
|
|
63
276
|
try {
|
|
64
277
|
result = await iterator.next();
|
|
65
|
-
} catch
|
|
278
|
+
} catch (error) {
|
|
279
|
+
reportEnded({
|
|
280
|
+
error
|
|
281
|
+
});
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
if (disposed) return;
|
|
285
|
+
if (result.done) {
|
|
286
|
+
reportEnded({});
|
|
66
287
|
return;
|
|
67
288
|
}
|
|
68
|
-
if (disposed || result.done) return;
|
|
69
289
|
const message = result.value;
|
|
70
290
|
const ack = ()=>{
|
|
71
291
|
// An ack names a place in THIS recipient's delivery queue, not in the topic's
|
|
@@ -87,15 +307,21 @@ import { asDeliveryPosition } from './cursor.js';
|
|
|
87
307
|
}
|
|
88
308
|
})();
|
|
89
309
|
const bus = {
|
|
90
|
-
publish: (topicID, payload)=>
|
|
310
|
+
publish: async (topicID, payload)=>{
|
|
311
|
+
assertSubscribable(topicID);
|
|
312
|
+
await hub.publish({
|
|
91
313
|
senderDID: localDID,
|
|
92
314
|
topicID,
|
|
93
315
|
payload
|
|
94
|
-
})
|
|
316
|
+
});
|
|
317
|
+
},
|
|
95
318
|
subscribe: (topicID, onMessage)=>onInbound(topicID, (message)=>onMessage(message.payload))
|
|
96
319
|
};
|
|
97
320
|
const mailbox = {
|
|
98
|
-
publish: (publishParams)=>
|
|
321
|
+
publish: async (publishParams)=>{
|
|
322
|
+
assertSubscribable(publishParams.topicID);
|
|
323
|
+
return await hub.publish(publishParams);
|
|
324
|
+
},
|
|
99
325
|
subscribe: (_subscriberDID, topicID)=>{
|
|
100
326
|
retain(topicID);
|
|
101
327
|
},
|
|
@@ -169,7 +395,9 @@ import { asDeliveryPosition } from './cursor.js';
|
|
|
169
395
|
};
|
|
170
396
|
}
|
|
171
397
|
};
|
|
172
|
-
const publish = (params)=>
|
|
398
|
+
const publish = async (params)=>{
|
|
399
|
+
assertSubscribable(params.topicID);
|
|
400
|
+
return await Promise.resolve(hub.publish({
|
|
173
401
|
senderDID: localDID,
|
|
174
402
|
topicID: params.topicID,
|
|
175
403
|
payload: params.payload,
|
|
@@ -186,9 +414,15 @@ import { asDeliveryPosition } from './cursor.js';
|
|
|
186
414
|
publishID: params.publishID
|
|
187
415
|
} : {}
|
|
188
416
|
}));
|
|
189
|
-
|
|
417
|
+
};
|
|
418
|
+
const fetchTopic = async (params)=>{
|
|
419
|
+
// A fetch of a refused topic would die of `NotSubscribedError` — the SYMPTOM, naming the mux's
|
|
420
|
+
// own failure to subscribe as if it were the caller's mistake. The latched refusal is raised
|
|
421
|
+
// instead, so what reaches the host is the reason.
|
|
422
|
+
assertSubscribable(params.topicID);
|
|
423
|
+
// Called on `hub`, not through a detached reference: a LogHub is often a class, and
|
|
190
424
|
// an unbound method loses its receiver.
|
|
191
|
-
Promise.resolve(hub.fetchTopic({
|
|
425
|
+
return await Promise.resolve(hub.fetchTopic({
|
|
192
426
|
subscriberDID: localDID,
|
|
193
427
|
topicID: params.topicID,
|
|
194
428
|
...params.after != null ? {
|
|
@@ -198,15 +432,24 @@ import { asDeliveryPosition } from './cursor.js';
|
|
|
198
432
|
limit: params.limit
|
|
199
433
|
} : {}
|
|
200
434
|
}));
|
|
435
|
+
};
|
|
201
436
|
return {
|
|
202
437
|
bus,
|
|
203
438
|
mailbox,
|
|
204
439
|
publish,
|
|
440
|
+
retainTopic: (topicID, options)=>{
|
|
441
|
+
retain(topicID, options);
|
|
442
|
+
},
|
|
205
443
|
fetchTopic,
|
|
206
444
|
onInbound,
|
|
207
445
|
dispose: async ()=>{
|
|
208
446
|
if (disposed) return;
|
|
209
447
|
disposed = true;
|
|
448
|
+
// Before anything else: a retry sleeping out its backoff is work already abandoned, and
|
|
449
|
+
// every path it could wake into checks `disposed` and returns.
|
|
450
|
+
for (const wake of [
|
|
451
|
+
...sleeping
|
|
452
|
+
])wake();
|
|
210
453
|
for (const sink of [
|
|
211
454
|
...sinks
|
|
212
455
|
])sink.close();
|
package/lib/index.d.ts
CHANGED
|
@@ -3,14 +3,18 @@
|
|
|
3
3
|
*
|
|
4
4
|
* @module rpc
|
|
5
5
|
*/
|
|
6
|
-
export {
|
|
7
|
-
export
|
|
6
|
+
export type { Anchor, AnchorStore } from './anchor.js';
|
|
7
|
+
export type { AppCursorStore, AppWindowPruned } from './app-cursor.js';
|
|
8
|
+
export { type CommitClassifierState, type CommitDisposition, type CommitFrameEvidence, classifyCommit, UNKNOWN_FRAME_VERSION, } from './classify.js';
|
|
8
9
|
export { CommitDeadlineError, type CommitJournal, type CommitKind, isHeadMismatch, type JournalEntry, JournalEpochError, type LaneResult, type LostCommit, type PendingCommit, RecoveryRequiredError, } from './commit.js';
|
|
9
|
-
export { type CommitFrame, decodeCommitFrame, encodeCommitFrame, } from './commit-frame.js';
|
|
10
|
-
export { type CommitContext, type CommitHeader, type GroupCrypto, type GroupMLS, isMissingLedgerEntries, type PendingRecovery, } from './crypto.js';
|
|
10
|
+
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';
|
|
11
12
|
export { asDeliveryPosition, asLogPosition, type DeliveryPosition, type LogPosition, } from './cursor.js';
|
|
12
13
|
export { decodeHandshakeFrame, encodeHandshakeFrame, HANDSHAKE_KIND, HANDSHAKE_MAGIC, HANDSHAKE_VERSION, type HandshakeKind, } from './handshake.js';
|
|
13
|
-
export {
|
|
14
|
+
export type { ReceiveLaneEnded, SubscribeFailure } from './hub-mux.js';
|
|
15
|
+
export { createLedgerEntryResolver, decodeLedgerEntries, encodeLedgerEntries, LEDGER_ENTRIES_VERSION, } from './ledger-entries.js';
|
|
14
16
|
export { createGroupPeer, type GroupPeer, type GroupPeerMLSParams, type GroupPeerParams, type ProtocolSurface, } from './peer.js';
|
|
17
|
+
export { defineGroupProtocol, type GroupProcedureDefinition, type GroupProtocolDefinition, type RetainableEventProcedureDefinition, type Retention, retentionOf, } from './protocol.js';
|
|
15
18
|
export { decodeLedgerReply, decodeLedgerRequest, decodeRecoveryReply, decodeRecoveryRequest, encodeLedgerReply, encodeLedgerRequest, encodeRecoveryReply, encodeRecoveryRequest, } from './recovery.js';
|
|
16
|
-
export {
|
|
19
|
+
export { detectRosterChange } from './roster.js';
|
|
20
|
+
export { APP_TOPIC_LABEL, COMMIT_LABEL, commitTopic, discoveryTopic, INBOX_LABEL, inboxTopic, protocolTopic, RENDEZVOUS_LABEL, rendezvousTopic, } from './topic.js';
|
package/lib/index.js
CHANGED
|
@@ -2,14 +2,15 @@
|
|
|
2
2
|
* High-level MLS-aware group RPC for Enkaku.
|
|
3
3
|
*
|
|
4
4
|
* @module rpc
|
|
5
|
-
*/ export {
|
|
6
|
-
export { classifyCommit } from './classify.js';
|
|
5
|
+
*/ export { classifyCommit, UNKNOWN_FRAME_VERSION } from './classify.js';
|
|
7
6
|
export { CommitDeadlineError, isHeadMismatch, JournalEpochError, RecoveryRequiredError } from './commit.js';
|
|
8
|
-
export { decodeCommitFrame, encodeCommitFrame } from './commit-frame.js';
|
|
7
|
+
export { COMMIT_FRAME_VERSION, decodeCommitFrame, encodeCommitFrame, isUnsupportedCommitFrameVersion, UnsupportedCommitFrameVersionError } from './commit-frame.js';
|
|
9
8
|
export { isMissingLedgerEntries } from './crypto.js';
|
|
10
9
|
export { asDeliveryPosition, asLogPosition } from './cursor.js';
|
|
11
10
|
export { decodeHandshakeFrame, encodeHandshakeFrame, HANDSHAKE_KIND, HANDSHAKE_MAGIC, HANDSHAKE_VERSION } from './handshake.js';
|
|
12
|
-
export { createLedgerEntryResolver, decodeLedgerEntries, encodeLedgerEntries } from './ledger-entries.js';
|
|
11
|
+
export { createLedgerEntryResolver, decodeLedgerEntries, encodeLedgerEntries, LEDGER_ENTRIES_VERSION } from './ledger-entries.js';
|
|
13
12
|
export { createGroupPeer } from './peer.js';
|
|
13
|
+
export { defineGroupProtocol, retentionOf } from './protocol.js';
|
|
14
14
|
export { decodeLedgerReply, decodeLedgerRequest, decodeRecoveryReply, decodeRecoveryRequest, encodeLedgerReply, encodeLedgerRequest, encodeRecoveryReply, encodeRecoveryRequest } from './recovery.js';
|
|
15
|
-
export {
|
|
15
|
+
export { detectRosterChange } from './roster.js';
|
|
16
|
+
export { APP_TOPIC_LABEL, COMMIT_LABEL, commitTopic, discoveryTopic, INBOX_LABEL, inboxTopic, protocolTopic, RENDEZVOUS_LABEL, rendezvousTopic } from './topic.js';
|
package/lib/ledger-entries.d.ts
CHANGED
|
@@ -1,7 +1,33 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { GroupCrypto } from './crypto.js';
|
|
2
|
+
/**
|
|
3
|
+
* The blob a commit frame carries: the signed control-ledger tokens the Commit enacts, sealed
|
|
4
|
+
* with `GroupCrypto.sealEntries` under a key derived from the epoch the Commit is framed at (the
|
|
5
|
+
* epoch every peer that can apply it holds). The hub sees only the sealed bytes, never a body.
|
|
6
|
+
*
|
|
7
|
+
* [ VERSION(1) | count(2, LE) | (tokenLength(4, LE) | token utf8)... ]
|
|
8
|
+
*
|
|
9
|
+
* This module is the ONLY place a commit frame's blob is opened, via a resolver that runs only
|
|
10
|
+
* when the MLS port asks for the bodies of a commit it is applying. Opening is a consequence
|
|
11
|
+
* of "I can apply this frame", never a precondition of reading it.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Current ledger-entry blob format version.
|
|
15
|
+
*
|
|
16
|
+
* Unversioned, this format degrades tolerably only by ACCIDENT: the resolver's `catch` turns a
|
|
17
|
+
* mis-parse into an empty answer, which the lane files as poison. That is an accident and not a
|
|
18
|
+
* contract — nothing stops a later layout from parsing as a plausible token list under today's
|
|
19
|
+
* rules — so the version byte makes the refusal a decision instead of a lucky one.
|
|
20
|
+
*
|
|
21
|
+
* An unknown version is REFUSED here, distinguishably. It does not heal: the blob rides INSIDE a
|
|
22
|
+
* commit frame, and it is the handshake header the lane reads first that carries the heal rule.
|
|
23
|
+
*/
|
|
24
|
+
export declare const LEDGER_ENTRIES_VERSION = 1;
|
|
2
25
|
/** Encode the signed tokens a Commit enacts, for sealing into its frame. */
|
|
3
26
|
export declare function encodeLedgerEntries(tokens: Array<string>): Uint8Array;
|
|
4
|
-
/**
|
|
27
|
+
/**
|
|
28
|
+
* Decode the signed tokens sealed into a commit frame. Throws on bytes that are not a list, and
|
|
29
|
+
* on a version this build does not know.
|
|
30
|
+
*/
|
|
5
31
|
export declare function decodeLedgerEntries(bytes: Uint8Array): Array<string>;
|
|
6
32
|
/**
|
|
7
33
|
* A ledger-entry resolver over the blob of the commit frame being applied. The MLS port calls
|
|
@@ -13,10 +39,28 @@ export declare function decodeLedgerEntries(bytes: Uint8Array): Array<string>;
|
|
|
13
39
|
* content-addressed, so the caller binds each body to its id by digesting, and an unrequested
|
|
14
40
|
* body is ignored. A responder can fail to answer, never inject.
|
|
15
41
|
*
|
|
16
|
-
* A blob this peer cannot open yields NO entries, not an error: the commit fails to resolve
|
|
17
|
-
* the port raises missing-entries,
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
42
|
+
* A blob this peer cannot open yields NO entries, not an error: the commit fails to resolve and
|
|
43
|
+
* the port raises missing-entries, never corruption. THE OPEN GETS EXACTLY ONE ATTEMPT — the lane
|
|
44
|
+
* files that commit as poison, advances the cursor over it and never re-reads it (`peer.ts`, the
|
|
45
|
+
* `isMissingLedgerEntries` branch of the walk). So this must not be used to absorb a failure that
|
|
46
|
+
* a retry would fix: there is no retry. In practice it should not arise at all on the apply path,
|
|
47
|
+
* since the port asks only for a commit it is applying, framed at this peer's epoch, which is the
|
|
48
|
+
* epoch the blob is sealed under.
|
|
49
|
+
*
|
|
50
|
+
* The `catch` is deliberately narrow about what it means and deliberately blind to which of three
|
|
51
|
+
* things happened: the AEAD refused the bytes, the plaintext did not decode as an entry list, or
|
|
52
|
+
* the blob genuinely lacked the ids. Only the first is reachable by TAMPERING — a hub that flips
|
|
53
|
+
* one byte turns that commit into poison for the targeted peer, silently and unattributably. The
|
|
54
|
+
* cost is bounded and known: the peer skips the commit, the next one is framed ahead of it, and
|
|
55
|
+
* the `ahead` disposition strands it into a rejoin that re-gathers the ledger. Nothing is
|
|
56
|
+
* injected, because bodies are content-addressed and signature-verified downstream. But the
|
|
57
|
+
* poison rule's justification — "a blob this peer cannot open is one no member at this epoch can"
|
|
58
|
+
* — holds only for an honest hub, and this is where that assumption is spent.
|
|
59
|
+
*
|
|
60
|
+
* Opened with {@link GroupCrypto.openEntries} and NOT with `unwrap`, because this runs INSIDE the
|
|
61
|
+
* MLS port's apply of the commit it is resolving for. `unwrap` consumes a ratchet generation and
|
|
62
|
+
* mutates the handle; an open that does either is unsound while the handle is mid-apply, whatever
|
|
63
|
+
* order it is scheduled in. `openEntries` derives its key from the epoch's exporter secret, so it
|
|
64
|
+
* is pure and re-entrant and this resolver may be called from anywhere the epoch is right.
|
|
21
65
|
*/
|
|
22
|
-
export declare function createLedgerEntryResolver(sealedEntries: Uint8Array,
|
|
66
|
+
export declare function createLedgerEntryResolver(sealedEntries: Uint8Array, openEntries: GroupCrypto['openEntries']): (ids: Array<string>) => Promise<Array<string>>;
|
package/lib/ledger-entries.js
CHANGED
|
@@ -1,23 +1,37 @@
|
|
|
1
1
|
import { fromUTF, toUTF } from '@sozai/codec';
|
|
2
2
|
/**
|
|
3
3
|
* The blob a commit frame carries: the signed control-ledger tokens the Commit enacts, sealed
|
|
4
|
-
* with `GroupCrypto.
|
|
5
|
-
* that can apply it holds). The hub sees only the sealed bytes, never a body.
|
|
4
|
+
* with `GroupCrypto.sealEntries` under a key derived from the epoch the Commit is framed at (the
|
|
5
|
+
* epoch every peer that can apply it holds). The hub sees only the sealed bytes, never a body.
|
|
6
6
|
*
|
|
7
|
-
* [ count(2, LE) | (tokenLength(4, LE) | token utf8)... ]
|
|
7
|
+
* [ VERSION(1) | count(2, LE) | (tokenLength(4, LE) | token utf8)... ]
|
|
8
8
|
*
|
|
9
9
|
* This module is the ONLY place a commit frame's blob is opened, via a resolver that runs only
|
|
10
|
-
* when the MLS port asks for the bodies of a commit it is applying.
|
|
10
|
+
* when the MLS port asks for the bodies of a commit it is applying. Opening is a consequence
|
|
11
11
|
* of "I can apply this frame", never a precondition of reading it.
|
|
12
|
-
*/
|
|
12
|
+
*/ /**
|
|
13
|
+
* Current ledger-entry blob format version.
|
|
14
|
+
*
|
|
15
|
+
* Unversioned, this format degrades tolerably only by ACCIDENT: the resolver's `catch` turns a
|
|
16
|
+
* mis-parse into an empty answer, which the lane files as poison. That is an accident and not a
|
|
17
|
+
* contract — nothing stops a later layout from parsing as a plausible token list under today's
|
|
18
|
+
* rules — so the version byte makes the refusal a decision instead of a lucky one.
|
|
19
|
+
*
|
|
20
|
+
* An unknown version is REFUSED here, distinguishably. It does not heal: the blob rides INSIDE a
|
|
21
|
+
* commit frame, and it is the handshake header the lane reads first that carries the heal rule.
|
|
22
|
+
*/ export const LEDGER_ENTRIES_VERSION = 1;
|
|
23
|
+
const VERSION_BYTES = 1;
|
|
24
|
+
const COUNT_BYTES = 2;
|
|
25
|
+
const HEADER_BYTES = VERSION_BYTES + COUNT_BYTES;
|
|
13
26
|
const LENGTH_BYTES = 4;
|
|
14
27
|
/** Encode the signed tokens a Commit enacts, for sealing into its frame. */ export function encodeLedgerEntries(tokens) {
|
|
15
28
|
const encoded = tokens.map((token)=>fromUTF(token));
|
|
16
|
-
const size = encoded.reduce((total, bytes)=>total + LENGTH_BYTES + bytes.length,
|
|
29
|
+
const size = encoded.reduce((total, bytes)=>total + LENGTH_BYTES + bytes.length, HEADER_BYTES);
|
|
17
30
|
const out = new Uint8Array(size);
|
|
18
31
|
const view = new DataView(out.buffer);
|
|
19
|
-
|
|
20
|
-
|
|
32
|
+
out[0] = LEDGER_ENTRIES_VERSION;
|
|
33
|
+
view.setUint16(VERSION_BYTES, encoded.length, true);
|
|
34
|
+
let offset = HEADER_BYTES;
|
|
21
35
|
for (const bytes of encoded){
|
|
22
36
|
view.setUint32(offset, bytes.length, true);
|
|
23
37
|
out.set(bytes, offset + LENGTH_BYTES);
|
|
@@ -25,14 +39,21 @@ const LENGTH_BYTES = 4;
|
|
|
25
39
|
}
|
|
26
40
|
return out;
|
|
27
41
|
}
|
|
28
|
-
/**
|
|
29
|
-
|
|
42
|
+
/**
|
|
43
|
+
* Decode the signed tokens sealed into a commit frame. Throws on bytes that are not a list, and
|
|
44
|
+
* on a version this build does not know.
|
|
45
|
+
*/ export function decodeLedgerEntries(bytes) {
|
|
46
|
+
if (bytes.length < HEADER_BYTES) {
|
|
30
47
|
throw new Error('ledger entry blob is too short');
|
|
31
48
|
}
|
|
49
|
+
const version = bytes[0];
|
|
50
|
+
if (version !== LEDGER_ENTRIES_VERSION) {
|
|
51
|
+
throw new Error(`unsupported ledger entry blob version: ${version}`);
|
|
52
|
+
}
|
|
32
53
|
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
33
|
-
const count = view.getUint16(
|
|
54
|
+
const count = view.getUint16(VERSION_BYTES, true);
|
|
34
55
|
const tokens = [];
|
|
35
|
-
let offset =
|
|
56
|
+
let offset = HEADER_BYTES;
|
|
36
57
|
for(let i = 0; i < count; i++){
|
|
37
58
|
if (offset + LENGTH_BYTES > bytes.length) {
|
|
38
59
|
throw new Error('ledger entry blob is truncated');
|
|
@@ -57,20 +78,35 @@ const LENGTH_BYTES = 4;
|
|
|
57
78
|
* content-addressed, so the caller binds each body to its id by digesting, and an unrequested
|
|
58
79
|
* body is ignored. A responder can fail to answer, never inject.
|
|
59
80
|
*
|
|
60
|
-
* A blob this peer cannot open yields NO entries, not an error: the commit fails to resolve
|
|
61
|
-
* the port raises missing-entries,
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
|
|
81
|
+
* A blob this peer cannot open yields NO entries, not an error: the commit fails to resolve and
|
|
82
|
+
* the port raises missing-entries, never corruption. THE OPEN GETS EXACTLY ONE ATTEMPT — the lane
|
|
83
|
+
* files that commit as poison, advances the cursor over it and never re-reads it (`peer.ts`, the
|
|
84
|
+
* `isMissingLedgerEntries` branch of the walk). So this must not be used to absorb a failure that
|
|
85
|
+
* a retry would fix: there is no retry. In practice it should not arise at all on the apply path,
|
|
86
|
+
* since the port asks only for a commit it is applying, framed at this peer's epoch, which is the
|
|
87
|
+
* epoch the blob is sealed under.
|
|
88
|
+
*
|
|
89
|
+
* The `catch` is deliberately narrow about what it means and deliberately blind to which of three
|
|
90
|
+
* things happened: the AEAD refused the bytes, the plaintext did not decode as an entry list, or
|
|
91
|
+
* the blob genuinely lacked the ids. Only the first is reachable by TAMPERING — a hub that flips
|
|
92
|
+
* one byte turns that commit into poison for the targeted peer, silently and unattributably. The
|
|
93
|
+
* cost is bounded and known: the peer skips the commit, the next one is framed ahead of it, and
|
|
94
|
+
* the `ahead` disposition strands it into a rejoin that re-gathers the ledger. Nothing is
|
|
95
|
+
* injected, because bodies are content-addressed and signature-verified downstream. But the
|
|
96
|
+
* poison rule's justification — "a blob this peer cannot open is one no member at this epoch can"
|
|
97
|
+
* — holds only for an honest hub, and this is where that assumption is spent.
|
|
98
|
+
*
|
|
99
|
+
* Opened with {@link GroupCrypto.openEntries} and NOT with `unwrap`, because this runs INSIDE the
|
|
100
|
+
* MLS port's apply of the commit it is resolving for. `unwrap` consumes a ratchet generation and
|
|
101
|
+
* mutates the handle; an open that does either is unsound while the handle is mid-apply, whatever
|
|
102
|
+
* order it is scheduled in. `openEntries` derives its key from the epoch's exporter secret, so it
|
|
103
|
+
* is pure and re-entrant and this resolver may be called from anywhere the epoch is right.
|
|
104
|
+
*/ export function createLedgerEntryResolver(sealedEntries, openEntries) {
|
|
66
105
|
return async (_ids)=>{
|
|
67
106
|
try {
|
|
68
|
-
const opened = await unwrap(sealedEntries);
|
|
69
|
-
const payload = opened instanceof Uint8Array ? opened : opened.payload;
|
|
70
107
|
// Body trust comes from the token's own signature + content-address, which the caller
|
|
71
|
-
// re-verifies — not from the seal, which only buys confidentiality from the hub.
|
|
72
|
-
|
|
73
|
-
return decodeLedgerEntries(payload);
|
|
108
|
+
// re-verifies — not from the seal, which only buys confidentiality from the hub.
|
|
109
|
+
return decodeLedgerEntries(await openEntries(sealedEntries));
|
|
74
110
|
} catch {
|
|
75
111
|
return [];
|
|
76
112
|
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { Unwrap, UnwrapResult } from '@kumiai/broadcast';
|
|
2
|
+
import type { StoredMessage } from '@kumiai/hub-protocol';
|
|
3
|
+
import type { HubMux } from './hub-mux.js';
|
|
4
|
+
export type OpenOncePathParams<Opened> = {
|
|
5
|
+
mux: HubMux;
|
|
6
|
+
topicID: string;
|
|
7
|
+
unwrap: Unwrap;
|
|
8
|
+
/**
|
|
9
|
+
* Turn an opened frame into what this lane's consumers receive. Returning `undefined` drops
|
|
10
|
+
* the frame — the open has already happened either way, so a lane rejects here rather than
|
|
11
|
+
* leaving each consumer to decide.
|
|
12
|
+
*/
|
|
13
|
+
project: (message: StoredMessage, opened: UnwrapResult) => Opened | undefined;
|
|
14
|
+
/** Called with the raw message BEFORE the open, for anything that must be recorded at the
|
|
15
|
+
* epoch the frame is about to be opened against. */
|
|
16
|
+
note?: (message: StoredMessage) => void;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* ONE INBOUND PATH PER TOPIC, shared by every consumer built on it.
|
|
20
|
+
*
|
|
21
|
+
* OPENING IS A CONSUMING OPERATION. `unwrap` spends the frame's own per-message ratchet key on
|
|
22
|
+
* the handle it opens against, so the same bytes open exactly once and every later open of them
|
|
23
|
+
* fails — not because the frame is bad, but because its key is gone. The port says so (see
|
|
24
|
+
* {@link GroupCrypto.unwrap}); it cannot be duplicated, and a lane that gave two consumers an
|
|
25
|
+
* `unwrap` each would have them race for one key with the loser silently dropping the frame.
|
|
26
|
+
*
|
|
27
|
+
* So the frame is opened HERE, once, and the opened result is fanned out over plaintext.
|
|
28
|
+
*
|
|
29
|
+
* EVERY multi-consumer topic goes through this, not just the app lane. The self-inbox topic has
|
|
30
|
+
* the most consumers of any — an acceptor per protocol, plus one directed client per member being
|
|
31
|
+
* spoken to — and each holding its own `unwrap` is exactly why a directed request went unanswered
|
|
32
|
+
* over real MLS while the XOR fake, which could open the same bytes twice, stayed green.
|
|
33
|
+
*
|
|
34
|
+
* Opens are chained rather than launched per message, so frames are opened in arrival order.
|
|
35
|
+
* `unwrap` is async with variable latency, and a lane whose opens resolved out of order would
|
|
36
|
+
* feed a tunnel out of wire order — dropped as a stale seq — or double-create a session.
|
|
37
|
+
*
|
|
38
|
+
* Subscribed through the mux's raw inbound path rather than its bus view, because the bus view
|
|
39
|
+
* hands on the payload alone and a frame's log position is the one thing a lane could not
|
|
40
|
+
* otherwise write down.
|
|
41
|
+
*
|
|
42
|
+
* The mux subscription is held for as long as a consumer wants it and released with the last one,
|
|
43
|
+
* which is what keeps a rotation's teardown from leaving a listener behind on a topic the group
|
|
44
|
+
* has left.
|
|
45
|
+
*/
|
|
46
|
+
export declare function createOpenOncePath<Opened>(params: OpenOncePathParams<Opened>): (onOpened: (value: Opened) => void) => () => void;
|