@ping-app/ping-openmls-sdk 0.0.0-stage → 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 +94 -2
- package/dist/index.cjs +2782 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1229 -0
- package/dist/index.d.ts +1229 -0
- package/dist/index.js +2715 -0
- package/dist/index.js.map +1 -0
- package/dist/notification-preview.cjs +137 -0
- package/dist/notification-preview.cjs.map +1 -0
- package/dist/notification-preview.d.cts +85 -0
- package/dist/notification-preview.d.ts +85 -0
- package/dist/notification-preview.js +98 -0
- package/dist/notification-preview.js.map +1 -0
- package/dist/storage/indexeddb.cjs +153 -0
- package/dist/storage/indexeddb.cjs.map +1 -0
- package/dist/storage/indexeddb.d.cts +21 -0
- package/dist/storage/indexeddb.d.ts +21 -0
- package/dist/storage/indexeddb.js +128 -0
- package/dist/storage/indexeddb.js.map +1 -0
- package/dist/transport/websocket.cjs +121 -0
- package/dist/transport/websocket.cjs.map +1 -0
- package/dist/transport/websocket.d.cts +23 -0
- package/dist/transport/websocket.d.ts +23 -0
- package/dist/transport/websocket.js +94 -0
- package/dist/transport/websocket.js.map +1 -0
- package/dist/types-B1GFwNXa.d.cts +535 -0
- package/dist/types-B1GFwNXa.d.ts +535 -0
- package/dist/worker.cjs +841 -0
- package/dist/worker.cjs.map +1 -0
- package/dist/worker.d.cts +2 -0
- package/dist/worker.d.ts +2 -0
- package/dist/worker.js +848 -0
- package/dist/worker.js.map +1 -0
- package/package.json +61 -4
- package/wasm/package.json +17 -0
- package/wasm/ping_wasm.d.ts +909 -0
- package/wasm/ping_wasm.js +3028 -0
- package/wasm/ping_wasm_bg.wasm +0 -0
- package/wasm/ping_wasm_bg.wasm.d.ts +112 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,2715 @@
|
|
|
1
|
+
// src/fanout.ts
|
|
2
|
+
function errorKind(e) {
|
|
3
|
+
if (e instanceof Error) return e.name;
|
|
4
|
+
return typeof e;
|
|
5
|
+
}
|
|
6
|
+
var MessageFanout = class {
|
|
7
|
+
messageHandlers = /* @__PURE__ */ new Set();
|
|
8
|
+
batchHandlers = /* @__PURE__ */ new Set();
|
|
9
|
+
onMessage(handler) {
|
|
10
|
+
this.messageHandlers.add(handler);
|
|
11
|
+
return () => this.messageHandlers.delete(handler);
|
|
12
|
+
}
|
|
13
|
+
onMessageBatch(handler) {
|
|
14
|
+
this.batchHandlers.add(handler);
|
|
15
|
+
return () => this.batchHandlers.delete(handler);
|
|
16
|
+
}
|
|
17
|
+
get hasBatchHandlers() {
|
|
18
|
+
return this.batchHandlers.size > 0;
|
|
19
|
+
}
|
|
20
|
+
/** One message from the legacy per-envelope path. */
|
|
21
|
+
deliverOne(m) {
|
|
22
|
+
for (const h of this.messageHandlers) {
|
|
23
|
+
try {
|
|
24
|
+
h(m);
|
|
25
|
+
} catch (e) {
|
|
26
|
+
if (typeof console !== "undefined") {
|
|
27
|
+
console.debug("[ping-sdk] onMessage handler threw:", errorKind(e));
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* One batch or page result. An empty result is not delivered: there is
|
|
34
|
+
* nothing to persist, and the caller already has the result value.
|
|
35
|
+
*/
|
|
36
|
+
deliverBatch(messages, meta) {
|
|
37
|
+
if (messages.length === 0) return;
|
|
38
|
+
if (this.batchHandlers.size === 0) {
|
|
39
|
+
for (const m of messages) this.deliverOne(m);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
for (const h of this.batchHandlers) {
|
|
43
|
+
try {
|
|
44
|
+
h(messages, meta);
|
|
45
|
+
} catch (e) {
|
|
46
|
+
if (typeof console !== "undefined") {
|
|
47
|
+
console.debug("[ping-sdk] onMessageBatch handler threw:", errorKind(e));
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
// src/gap-fill.ts
|
|
55
|
+
var GapFiller = class {
|
|
56
|
+
lanes = /* @__PURE__ */ new Map();
|
|
57
|
+
/**
|
|
58
|
+
* Fill the gap for `key`. `stepOnce` applies ONE page and resolves `true`
|
|
59
|
+
* while the server may hold more. Resolves when the loop (and any rerun a
|
|
60
|
+
* concurrent request asked for) has finished; rejects with the first step
|
|
61
|
+
* error, which ends that loop.
|
|
62
|
+
*/
|
|
63
|
+
fill(key, stepOnce) {
|
|
64
|
+
const running = this.lanes.get(key);
|
|
65
|
+
if (running !== void 0) {
|
|
66
|
+
running.again = true;
|
|
67
|
+
return running.run;
|
|
68
|
+
}
|
|
69
|
+
const lane = { run: Promise.resolve(), again: false };
|
|
70
|
+
lane.run = (async () => {
|
|
71
|
+
try {
|
|
72
|
+
do {
|
|
73
|
+
lane.again = false;
|
|
74
|
+
let more = true;
|
|
75
|
+
while (more) more = await stepOnce();
|
|
76
|
+
} while (lane.again);
|
|
77
|
+
} finally {
|
|
78
|
+
if (this.lanes.get(key) === lane) this.lanes.delete(key);
|
|
79
|
+
}
|
|
80
|
+
})();
|
|
81
|
+
this.lanes.set(key, lane);
|
|
82
|
+
return lane.run;
|
|
83
|
+
}
|
|
84
|
+
/** Conversations with a fill loop running (diagnostics / tests). */
|
|
85
|
+
get inFlight() {
|
|
86
|
+
return this.lanes.size;
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
// src/inbound-coalescer.ts
|
|
91
|
+
var InboundCoalescer = class {
|
|
92
|
+
/**
|
|
93
|
+
* @param apply Applies one batch. A rejection settles the promises of the
|
|
94
|
+
* frames in that batch with the error and the lane moves on to whatever
|
|
95
|
+
* queued meanwhile, so one bad batch cannot wedge a conversation.
|
|
96
|
+
* @param maxBatch Upper bound on frames per batch. A burst larger than
|
|
97
|
+
* this goes out as consecutive batches of at most `maxBatch`, so a
|
|
98
|
+
* flood cannot turn into one unbounded wasm call.
|
|
99
|
+
*/
|
|
100
|
+
constructor(apply, maxBatch = 256) {
|
|
101
|
+
this.apply = apply;
|
|
102
|
+
this.maxBatch = maxBatch;
|
|
103
|
+
}
|
|
104
|
+
apply;
|
|
105
|
+
maxBatch;
|
|
106
|
+
lanes = /* @__PURE__ */ new Map();
|
|
107
|
+
/**
|
|
108
|
+
* Queue a frame. Resolves when the batch that carried it has been applied
|
|
109
|
+
* (rejects if that batch failed), so a transport that awaits the dispatch
|
|
110
|
+
* to ack a watermark still sees the truth.
|
|
111
|
+
*/
|
|
112
|
+
push(key, item) {
|
|
113
|
+
const lane = this.lanes.get(key);
|
|
114
|
+
if (lane !== void 0) {
|
|
115
|
+
return new Promise((resolve, reject) => {
|
|
116
|
+
lane.queued.push(item);
|
|
117
|
+
lane.waiters.push({ resolve, reject });
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
const fresh = { queued: [], waiters: [] };
|
|
121
|
+
this.lanes.set(key, fresh);
|
|
122
|
+
return this.run(key, fresh, [item], []);
|
|
123
|
+
}
|
|
124
|
+
/** Conversations with a batch in flight (diagnostics / tests). */
|
|
125
|
+
get inFlight() {
|
|
126
|
+
return this.lanes.size;
|
|
127
|
+
}
|
|
128
|
+
run(key, lane, items, waiters) {
|
|
129
|
+
let attempt;
|
|
130
|
+
try {
|
|
131
|
+
attempt = this.apply(key, items);
|
|
132
|
+
} catch (e) {
|
|
133
|
+
attempt = Promise.reject(e);
|
|
134
|
+
}
|
|
135
|
+
attempt.then(
|
|
136
|
+
() => {
|
|
137
|
+
for (const w of waiters) w.resolve();
|
|
138
|
+
},
|
|
139
|
+
(e) => {
|
|
140
|
+
for (const w of waiters) w.reject(e);
|
|
141
|
+
}
|
|
142
|
+
);
|
|
143
|
+
void attempt.then(
|
|
144
|
+
() => this.drain(key, lane),
|
|
145
|
+
() => this.drain(key, lane)
|
|
146
|
+
);
|
|
147
|
+
return attempt;
|
|
148
|
+
}
|
|
149
|
+
drain(key, lane) {
|
|
150
|
+
if (lane.queued.length === 0) {
|
|
151
|
+
if (this.lanes.get(key) === lane) this.lanes.delete(key);
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
const items = lane.queued.splice(0, this.maxBatch);
|
|
155
|
+
const waiters = lane.waiters.splice(0, items.length);
|
|
156
|
+
void this.run(key, lane, items, waiters).catch(() => void 0);
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
// src/storage/scope.ts
|
|
161
|
+
function scopeStorage(storage, accountNamespace) {
|
|
162
|
+
const scope = (ns) => `${accountNamespace} ${ns}`;
|
|
163
|
+
const scoped = {
|
|
164
|
+
get: (ns, key) => storage.get(scope(ns), key),
|
|
165
|
+
put: (ns, key, value) => storage.put(scope(ns), key, value),
|
|
166
|
+
del: (ns, key) => storage.del(scope(ns), key),
|
|
167
|
+
listKeys: (ns, prefix) => storage.listKeys(scope(ns), prefix)
|
|
168
|
+
};
|
|
169
|
+
const hostApplyBatch = storage.applyBatch;
|
|
170
|
+
if (typeof hostApplyBatch === "function") {
|
|
171
|
+
scoped.applyBatch = (ns, puts, deletes) => hostApplyBatch.call(storage, scope(ns), puts, deletes);
|
|
172
|
+
}
|
|
173
|
+
const hostListEntries = storage.listEntries;
|
|
174
|
+
if (typeof hostListEntries === "function") {
|
|
175
|
+
scoped.listEntries = (ns, prefix) => hostListEntries.call(storage, scope(ns), prefix);
|
|
176
|
+
}
|
|
177
|
+
return scoped;
|
|
178
|
+
}
|
|
179
|
+
function storageFeaturesOf(storage) {
|
|
180
|
+
return {
|
|
181
|
+
applyBatch: typeof storage.applyBatch === "function",
|
|
182
|
+
listEntries: typeof storage.listEntries === "function"
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// src/sequenced.ts
|
|
187
|
+
function isSequencedFrame(frame) {
|
|
188
|
+
return typeof frame === "object" && frame !== null && "envelope" in frame && typeof frame.envelope === "object" && frame.envelope !== null;
|
|
189
|
+
}
|
|
190
|
+
function sequencedToWire(item) {
|
|
191
|
+
return { envelope: item.envelope, server_seq: item.serverSeq };
|
|
192
|
+
}
|
|
193
|
+
function logPositionFromWire(p) {
|
|
194
|
+
return {
|
|
195
|
+
conversationId: p.conversation_id,
|
|
196
|
+
epoch: p.epoch,
|
|
197
|
+
serverSeq: p.server_seq,
|
|
198
|
+
anchored: p.anchored
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
function logHeadToWire(h) {
|
|
202
|
+
return {
|
|
203
|
+
conversation_id: h.conversationId,
|
|
204
|
+
head_server_seq: h.headServerSeq,
|
|
205
|
+
head_epoch: h.headEpoch
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
function logGapFromWire(g) {
|
|
209
|
+
return {
|
|
210
|
+
conversationId: g.conversation_id,
|
|
211
|
+
appliedServerSeq: g.applied_server_seq,
|
|
212
|
+
firstBufferedServerSeq: g.first_buffered_server_seq
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
function conversationUpdateFromWire(u) {
|
|
216
|
+
return { conversationId: u.conversation_id, epoch: u.epoch };
|
|
217
|
+
}
|
|
218
|
+
function variant(name) {
|
|
219
|
+
return name.charAt(0).toLowerCase() + name.slice(1);
|
|
220
|
+
}
|
|
221
|
+
function conversationRemovalFromWire(r) {
|
|
222
|
+
return {
|
|
223
|
+
conversationId: r.conversation_id,
|
|
224
|
+
serverSeq: r.server_seq,
|
|
225
|
+
epoch: r.epoch,
|
|
226
|
+
readmitted: r.readmitted
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
function welcomeFailureFromWire(w) {
|
|
230
|
+
return {
|
|
231
|
+
conversationId: w.conversation_id,
|
|
232
|
+
serverSeq: w.server_seq,
|
|
233
|
+
reason: variant(w.reason)
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
function strandedConversationFromWire(s) {
|
|
237
|
+
return {
|
|
238
|
+
conversationId: s.conversation_id,
|
|
239
|
+
serverSeq: s.server_seq,
|
|
240
|
+
epoch: s.epoch,
|
|
241
|
+
reason: variant(s.reason)
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
function bufferOverflowFromWire(o) {
|
|
245
|
+
return {
|
|
246
|
+
conversationId: o.conversation_id,
|
|
247
|
+
reason: variant(o.reason),
|
|
248
|
+
dropped: o.dropped
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
function outcomesFromWire(r) {
|
|
252
|
+
return {
|
|
253
|
+
removed: (r.removed ?? []).map(conversationRemovalFromWire),
|
|
254
|
+
welcomeFailures: (r.welcome_failures ?? []).map(welcomeFailureFromWire),
|
|
255
|
+
stranded: (r.stranded ?? []).map(strandedConversationFromWire),
|
|
256
|
+
proposalsPending: r.proposals_pending ?? [],
|
|
257
|
+
overflow: (r.overflow ?? []).map(bufferOverflowFromWire)
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
function applyBatchResultFromWire(r) {
|
|
261
|
+
return {
|
|
262
|
+
messages: r.messages,
|
|
263
|
+
applied: r.applied,
|
|
264
|
+
duplicates: r.duplicates,
|
|
265
|
+
buffered: r.buffered,
|
|
266
|
+
failed: r.failed,
|
|
267
|
+
gaps: r.gaps.map(logGapFromWire),
|
|
268
|
+
joined: r.joined,
|
|
269
|
+
updated: r.updated.map(conversationUpdateFromWire),
|
|
270
|
+
...outcomesFromWire(r)
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
function syncStepResultFromWire(r) {
|
|
274
|
+
return {
|
|
275
|
+
messages: r.messages,
|
|
276
|
+
hasMore: r.has_more,
|
|
277
|
+
fetched: r.fetched,
|
|
278
|
+
position: logPositionFromWire(r.position),
|
|
279
|
+
updated: r.updated.map(conversationUpdateFromWire),
|
|
280
|
+
joined: r.joined ?? [],
|
|
281
|
+
...outcomesFromWire(r)
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
function addMembersReportFromWire(r) {
|
|
285
|
+
return {
|
|
286
|
+
verdicts: r.verdicts.map((v) => ({
|
|
287
|
+
deviceId: v.device_id,
|
|
288
|
+
status: variant(v.status),
|
|
289
|
+
leafIndex: v.leaf_index ?? null
|
|
290
|
+
})),
|
|
291
|
+
epoch: r.epoch ?? null
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
function commitInDoubtFromWire(c) {
|
|
295
|
+
return {
|
|
296
|
+
conversationId: c.conversation_id,
|
|
297
|
+
attempts: c.attempts,
|
|
298
|
+
nextAttemptAtMs: c.next_attempt_at_ms
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// src/storage/indexeddb.ts
|
|
303
|
+
var DB_NAME = "ping-sdk";
|
|
304
|
+
var DB_VERSION = 1;
|
|
305
|
+
var STORE = "kv";
|
|
306
|
+
function open() {
|
|
307
|
+
return new Promise((resolve, reject) => {
|
|
308
|
+
const req = indexedDB.open(DB_NAME, DB_VERSION);
|
|
309
|
+
req.onupgradeneeded = () => {
|
|
310
|
+
const db = req.result;
|
|
311
|
+
if (!db.objectStoreNames.contains(STORE)) {
|
|
312
|
+
const os = db.createObjectStore(STORE, { keyPath: ["ns", "key"] });
|
|
313
|
+
os.createIndex("ns", "ns", { unique: false });
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
req.onsuccess = () => resolve(req.result);
|
|
317
|
+
req.onerror = () => reject(req.error);
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
var IndexedDbStorage = class {
|
|
321
|
+
dbPromise;
|
|
322
|
+
constructor() {
|
|
323
|
+
this.dbPromise = open();
|
|
324
|
+
}
|
|
325
|
+
async get(namespace, key) {
|
|
326
|
+
const db = await this.dbPromise;
|
|
327
|
+
return new Promise((resolve, reject) => {
|
|
328
|
+
const tx = db.transaction(STORE, "readonly");
|
|
329
|
+
const r = tx.objectStore(STORE).get([namespace, key]);
|
|
330
|
+
r.onsuccess = () => resolve(r.result?.value ?? null);
|
|
331
|
+
r.onerror = () => reject(r.error);
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
async put(namespace, key, value) {
|
|
335
|
+
const db = await this.dbPromise;
|
|
336
|
+
return new Promise((resolve, reject) => {
|
|
337
|
+
const tx = db.transaction(STORE, "readwrite");
|
|
338
|
+
tx.objectStore(STORE).put({ ns: namespace, key, value });
|
|
339
|
+
tx.oncomplete = () => resolve();
|
|
340
|
+
tx.onerror = () => reject(tx.error);
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
async del(namespace, key) {
|
|
344
|
+
const db = await this.dbPromise;
|
|
345
|
+
return new Promise((resolve, reject) => {
|
|
346
|
+
const tx = db.transaction(STORE, "readwrite");
|
|
347
|
+
tx.objectStore(STORE).delete([namespace, key]);
|
|
348
|
+
tx.oncomplete = () => resolve();
|
|
349
|
+
tx.onerror = () => reject(tx.error);
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* One `readwrite` transaction for the whole batch. Every request is issued
|
|
354
|
+
* synchronously inside it (an await on anything else would let the
|
|
355
|
+
* transaction auto-commit), so a failure or a crash mid-way aborts all of
|
|
356
|
+
* it: the per-row MLS store relies on that to keep a checkpoint atomic.
|
|
357
|
+
*/
|
|
358
|
+
async applyBatch(namespace, puts, deletes) {
|
|
359
|
+
if (puts.length === 0 && deletes.length === 0) return;
|
|
360
|
+
const db = await this.dbPromise;
|
|
361
|
+
return new Promise((resolve, reject) => {
|
|
362
|
+
const tx = db.transaction(STORE, "readwrite");
|
|
363
|
+
let settled = false;
|
|
364
|
+
const fail = (e) => {
|
|
365
|
+
if (settled) return;
|
|
366
|
+
settled = true;
|
|
367
|
+
reject(e instanceof Error ? e : new Error(String(e)));
|
|
368
|
+
};
|
|
369
|
+
tx.oncomplete = () => {
|
|
370
|
+
if (!settled) {
|
|
371
|
+
settled = true;
|
|
372
|
+
resolve();
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
tx.onerror = () => fail(tx.error);
|
|
376
|
+
tx.onabort = () => fail(tx.error ?? new Error("applyBatch aborted"));
|
|
377
|
+
try {
|
|
378
|
+
const os = tx.objectStore(STORE);
|
|
379
|
+
for (const [key, value] of puts) os.put({ ns: namespace, key, value });
|
|
380
|
+
for (const key of deletes) os.delete([namespace, key]);
|
|
381
|
+
} catch (e) {
|
|
382
|
+
try {
|
|
383
|
+
tx.abort();
|
|
384
|
+
} catch {
|
|
385
|
+
}
|
|
386
|
+
fail(e);
|
|
387
|
+
}
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
/** Every `[key, value]` under `namespace` with the prefix, in one read. */
|
|
391
|
+
async listEntries(namespace, prefix) {
|
|
392
|
+
const db = await this.dbPromise;
|
|
393
|
+
return new Promise((resolve, reject) => {
|
|
394
|
+
const tx = db.transaction(STORE, "readonly");
|
|
395
|
+
const idx = tx.objectStore(STORE).index("ns");
|
|
396
|
+
const req = idx.openCursor(IDBKeyRange.only(namespace));
|
|
397
|
+
const out = [];
|
|
398
|
+
req.onsuccess = () => {
|
|
399
|
+
const cur = req.result;
|
|
400
|
+
if (!cur) return resolve(out);
|
|
401
|
+
const row = cur.value;
|
|
402
|
+
if (!prefix || row.key.startsWith(prefix)) out.push([row.key, row.value]);
|
|
403
|
+
cur.continue();
|
|
404
|
+
};
|
|
405
|
+
req.onerror = () => reject(req.error);
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
async listKeys(namespace, prefix) {
|
|
409
|
+
const db = await this.dbPromise;
|
|
410
|
+
return new Promise((resolve, reject) => {
|
|
411
|
+
const tx = db.transaction(STORE, "readonly");
|
|
412
|
+
const idx = tx.objectStore(STORE).index("ns");
|
|
413
|
+
const req = idx.openCursor(IDBKeyRange.only(namespace));
|
|
414
|
+
const out = [];
|
|
415
|
+
req.onsuccess = () => {
|
|
416
|
+
const cur = req.result;
|
|
417
|
+
if (!cur) return resolve(out);
|
|
418
|
+
const row = cur.value;
|
|
419
|
+
if (!prefix || row.key.startsWith(prefix)) out.push(row.key);
|
|
420
|
+
cur.continue();
|
|
421
|
+
};
|
|
422
|
+
req.onerror = () => reject(req.error);
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
};
|
|
426
|
+
|
|
427
|
+
// src/wire-contract.ts
|
|
428
|
+
var PING_WIRE_CONTRACT_VERSION = 2;
|
|
429
|
+
var WIRE_VERSION_MIN_ACCEPTED = 1;
|
|
430
|
+
var CONTENT_TYPE_CBOR = "application/vnd.ping.wire.v2+cbor";
|
|
431
|
+
var CONTENT_TYPE_JSON = "application/vnd.ping.wire.v2+json";
|
|
432
|
+
var CONTENT_TYPE_CBOR_LEGACY_V1 = "application/vnd.ping.wire.v1+cbor";
|
|
433
|
+
var CONTENT_TYPE_JSON_LEGACY_V1 = "application/vnd.ping.wire.v1+json";
|
|
434
|
+
var PING_WIRE_CONTRACT_HEADER = "X-Ping-Wire-Contract";
|
|
435
|
+
var PING_WIRE_CONTRACT_HEADER_VALUE = `ping/${PING_WIRE_CONTRACT_VERSION}`;
|
|
436
|
+
var ValidationError = class extends Error {
|
|
437
|
+
constructor(kind, message) {
|
|
438
|
+
super(message);
|
|
439
|
+
this.kind = kind;
|
|
440
|
+
this.name = "PingWireContractValidationError";
|
|
441
|
+
}
|
|
442
|
+
kind;
|
|
443
|
+
};
|
|
444
|
+
var KIND_DISCRIMINANT = {
|
|
445
|
+
Application: 1,
|
|
446
|
+
Commit: 2,
|
|
447
|
+
Welcome: 3,
|
|
448
|
+
Proposal: 4,
|
|
449
|
+
KeyPackage: 5
|
|
450
|
+
};
|
|
451
|
+
async function sha256(bytes) {
|
|
452
|
+
const ab = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
453
|
+
const hash = await crypto.subtle.digest("SHA-256", ab);
|
|
454
|
+
return new Uint8Array(hash);
|
|
455
|
+
}
|
|
456
|
+
function bytesEqual(a, b) {
|
|
457
|
+
if (a.length !== b.length) return false;
|
|
458
|
+
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
|
459
|
+
return true;
|
|
460
|
+
}
|
|
461
|
+
async function validate(env) {
|
|
462
|
+
if (env.v < WIRE_VERSION_MIN_ACCEPTED || env.v > PING_WIRE_CONTRACT_VERSION) {
|
|
463
|
+
throw new ValidationError(
|
|
464
|
+
"UnsupportedVersion",
|
|
465
|
+
`unsupported wire-contract version: envelope says v=${env.v}, expected v\u2208[${WIRE_VERSION_MIN_ACCEPTED}, ${PING_WIRE_CONTRACT_VERSION}]`
|
|
466
|
+
);
|
|
467
|
+
}
|
|
468
|
+
if (env.conversation_id.length !== 16) {
|
|
469
|
+
throw new ValidationError(
|
|
470
|
+
"BadConversationIdLen",
|
|
471
|
+
`conversation_id must be 16 bytes (ULID), got ${env.conversation_id.length}`
|
|
472
|
+
);
|
|
473
|
+
}
|
|
474
|
+
if (env.sender_device.length !== 32) {
|
|
475
|
+
throw new ValidationError(
|
|
476
|
+
"BadSenderDeviceLen",
|
|
477
|
+
`sender_device must be 32 bytes, got ${env.sender_device.length}`
|
|
478
|
+
);
|
|
479
|
+
}
|
|
480
|
+
if (env.v >= 2 && env.kind === "Application") {
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
const buf = new Uint8Array(1 + env.payload.length);
|
|
484
|
+
buf[0] = KIND_DISCRIMINANT[env.kind];
|
|
485
|
+
buf.set(env.payload, 1);
|
|
486
|
+
const computed = await sha256(buf);
|
|
487
|
+
if (!bytesEqual(computed, env.content_hash)) {
|
|
488
|
+
throw new ValidationError(
|
|
489
|
+
"ContentHashMismatch",
|
|
490
|
+
"content_hash mismatch: envelope is forged, corrupted, or built by a non-conformant sender"
|
|
491
|
+
);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
async function verifyApplicationContentHash(env, plaintext) {
|
|
495
|
+
if (env.v < 2 || env.kind !== "Application") return;
|
|
496
|
+
const computed = await sha256(plaintext);
|
|
497
|
+
if (!bytesEqual(computed, env.content_hash)) {
|
|
498
|
+
throw new ValidationError(
|
|
499
|
+
"ContentHashMismatch",
|
|
500
|
+
"v=2 application content_hash mismatch against decrypted plaintext"
|
|
501
|
+
);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
function negotiates(contentType) {
|
|
505
|
+
if (!contentType) return false;
|
|
506
|
+
const primary = contentType.split(";")[0]?.trim().toLowerCase() ?? "";
|
|
507
|
+
return primary === CONTENT_TYPE_CBOR || primary === CONTENT_TYPE_JSON || primary === CONTENT_TYPE_CBOR_LEGACY_V1 || primary === CONTENT_TYPE_JSON_LEGACY_V1;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
// src/transport/websocket.ts
|
|
511
|
+
var WebSocketTransport = class {
|
|
512
|
+
constructor(cfg) {
|
|
513
|
+
this.cfg = cfg;
|
|
514
|
+
this.fetchImpl = cfg.fetchImpl ?? globalThis.fetch.bind(globalThis);
|
|
515
|
+
this.openSocket();
|
|
516
|
+
}
|
|
517
|
+
cfg;
|
|
518
|
+
ws = null;
|
|
519
|
+
liveHandlers = /* @__PURE__ */ new Set();
|
|
520
|
+
fetchImpl;
|
|
521
|
+
openSocket() {
|
|
522
|
+
if (typeof WebSocket === "undefined") return;
|
|
523
|
+
const url = `${this.cfg.baseUrl.replace(/^http/, "ws")}/stream`;
|
|
524
|
+
this.ws = new WebSocket(url);
|
|
525
|
+
this.ws.onmessage = (ev) => {
|
|
526
|
+
const text = typeof ev.data === "string" ? ev.data : new TextDecoder().decode(ev.data);
|
|
527
|
+
try {
|
|
528
|
+
const env = JSON.parse(text, reviver);
|
|
529
|
+
for (const h of this.liveHandlers) h(env);
|
|
530
|
+
} catch (e) {
|
|
531
|
+
if (typeof console !== "undefined") console.debug("[ping-sdk] WS frame parse error:", e);
|
|
532
|
+
}
|
|
533
|
+
};
|
|
534
|
+
this.ws.onclose = () => setTimeout(() => this.openSocket(), 1e3);
|
|
535
|
+
}
|
|
536
|
+
async send(envelope) {
|
|
537
|
+
const res = await this.fetchImpl(`${this.cfg.baseUrl}/send`, {
|
|
538
|
+
method: "POST",
|
|
539
|
+
headers: {
|
|
540
|
+
"content-type": CONTENT_TYPE_JSON,
|
|
541
|
+
[PING_WIRE_CONTRACT_HEADER]: PING_WIRE_CONTRACT_HEADER_VALUE,
|
|
542
|
+
...this.cfg.authHeader ? { authorization: this.cfg.authHeader } : {}
|
|
543
|
+
},
|
|
544
|
+
body: JSON.stringify(envelope, replacer)
|
|
545
|
+
});
|
|
546
|
+
if (res.status === 409) throw new Error("EpochOccupied");
|
|
547
|
+
if (!res.ok) throw new Error(`transport send failed: ${res.status}`);
|
|
548
|
+
}
|
|
549
|
+
async fetchSince(conversationId, cursor, limit) {
|
|
550
|
+
const url = new URL(`${this.cfg.baseUrl}/sync`);
|
|
551
|
+
url.searchParams.set("conv", toHex(conversationId));
|
|
552
|
+
url.searchParams.set("cursor", btoaUrl(cursor));
|
|
553
|
+
url.searchParams.set("limit", String(limit));
|
|
554
|
+
const res = await this.fetchImpl(url.toString(), {
|
|
555
|
+
headers: { ...this.cfg.authHeader ? { authorization: this.cfg.authHeader } : {} }
|
|
556
|
+
});
|
|
557
|
+
if (!res.ok) throw new Error(`transport fetch failed: ${res.status}`);
|
|
558
|
+
const text = await res.text();
|
|
559
|
+
return JSON.parse(text, reviver);
|
|
560
|
+
}
|
|
561
|
+
subscribe(onEvent) {
|
|
562
|
+
this.liveHandlers.add(onEvent);
|
|
563
|
+
return { unsubscribe: () => this.liveHandlers.delete(onEvent) };
|
|
564
|
+
}
|
|
565
|
+
async discoverDevices(userId) {
|
|
566
|
+
const res = await this.fetchImpl(`${this.cfg.baseUrl}/devices/${toHex(userId)}`, {
|
|
567
|
+
headers: { ...this.cfg.authHeader ? { authorization: this.cfg.authHeader } : {} }
|
|
568
|
+
});
|
|
569
|
+
if (!res.ok) throw new Error(`device discovery failed: ${res.status}`);
|
|
570
|
+
const text = await res.text();
|
|
571
|
+
return JSON.parse(text, reviver);
|
|
572
|
+
}
|
|
573
|
+
};
|
|
574
|
+
function replacer(_k, v) {
|
|
575
|
+
if (v instanceof Uint8Array) return { _bytes: Array.from(v) };
|
|
576
|
+
return v;
|
|
577
|
+
}
|
|
578
|
+
function reviver(_k, v) {
|
|
579
|
+
if (v && typeof v === "object" && Array.isArray(v._bytes)) {
|
|
580
|
+
return new Uint8Array(v._bytes);
|
|
581
|
+
}
|
|
582
|
+
return v;
|
|
583
|
+
}
|
|
584
|
+
function toHex(b) {
|
|
585
|
+
let s = "";
|
|
586
|
+
for (const v of b) s += v.toString(16).padStart(2, "0");
|
|
587
|
+
return s;
|
|
588
|
+
}
|
|
589
|
+
function btoaUrl(b) {
|
|
590
|
+
let s = "";
|
|
591
|
+
for (const v of b) s += String.fromCharCode(v);
|
|
592
|
+
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
// src/wasm-memory.ts
|
|
596
|
+
var RESERVE_MIB_TARGETS = [192, 128, 64, 32];
|
|
597
|
+
var WASM_PAGE_BYTES = 64 * 1024;
|
|
598
|
+
var reserved = /* @__PURE__ */ new WeakSet();
|
|
599
|
+
function reserveLinearMemory(memory) {
|
|
600
|
+
if (reserved.has(memory)) return;
|
|
601
|
+
reserved.add(memory);
|
|
602
|
+
for (const mib of RESERVE_MIB_TARGETS) {
|
|
603
|
+
try {
|
|
604
|
+
memory.grow(mib * 1024 * 1024 / WASM_PAGE_BYTES);
|
|
605
|
+
return;
|
|
606
|
+
} catch {
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
// src/notification-preview.ts
|
|
612
|
+
async function openNotificationPreview(opts) {
|
|
613
|
+
const now = opts.now ?? (() => Date.now());
|
|
614
|
+
const scoped = opts.accountNamespace !== void 0 && opts.accountNamespace.length > 0 ? scopeStorage(opts.storage, opts.accountNamespace) : opts.storage;
|
|
615
|
+
const storage = readOnlyStorage(scoped);
|
|
616
|
+
const wasm = await import("../wasm/ping_wasm");
|
|
617
|
+
const out = await wasm.default(
|
|
618
|
+
opts.wasmModuleOrPath === void 0 ? void 0 : { module_or_path: opts.wasmModuleOrPath }
|
|
619
|
+
);
|
|
620
|
+
reserveLinearMemory(out.memory);
|
|
621
|
+
const client = await wasm.PingClient.openReadOnly(
|
|
622
|
+
opts.identityExport,
|
|
623
|
+
// Label is unused on the read-only path (no LocalDevice is ever minted).
|
|
624
|
+
"notification-preview",
|
|
625
|
+
storage,
|
|
626
|
+
silentTransport(),
|
|
627
|
+
now()
|
|
628
|
+
);
|
|
629
|
+
let closed = false;
|
|
630
|
+
return {
|
|
631
|
+
async previewEnvelope(envelope) {
|
|
632
|
+
if (closed) throw new Error("notification-preview session is closed");
|
|
633
|
+
const result = client.previewEnvelope(envelope, now());
|
|
634
|
+
return result ?? null;
|
|
635
|
+
},
|
|
636
|
+
close() {
|
|
637
|
+
if (closed) return;
|
|
638
|
+
closed = true;
|
|
639
|
+
client.free();
|
|
640
|
+
}
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
function readOnlyStorage(storage) {
|
|
644
|
+
const refuse = (op) => Promise.reject(
|
|
645
|
+
new Error(`notification-preview storage is read-only (attempted ${op})`)
|
|
646
|
+
);
|
|
647
|
+
const readOnly = {
|
|
648
|
+
get: (ns, key) => storage.get(ns, key),
|
|
649
|
+
put: (_ns, _key, _value) => refuse("put"),
|
|
650
|
+
del: (_ns, _key) => refuse("del"),
|
|
651
|
+
listKeys: (ns, prefix) => storage.listKeys(ns, prefix)
|
|
652
|
+
};
|
|
653
|
+
const hostListEntries = storage.listEntries;
|
|
654
|
+
if (typeof hostListEntries === "function") {
|
|
655
|
+
readOnly.listEntries = (ns, prefix) => hostListEntries.call(storage, ns, prefix);
|
|
656
|
+
}
|
|
657
|
+
return readOnly;
|
|
658
|
+
}
|
|
659
|
+
function silentTransport() {
|
|
660
|
+
return {
|
|
661
|
+
send: () => Promise.reject(new Error("notification-preview cannot send")),
|
|
662
|
+
fetchSince: () => Promise.resolve([]),
|
|
663
|
+
discoverDevices: () => Promise.resolve([]),
|
|
664
|
+
setNextWelcomeRecipients: () => Promise.resolve()
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
// src/index.ts
|
|
669
|
+
var MessagingClient = class _MessagingClient {
|
|
670
|
+
worker;
|
|
671
|
+
nextId = 1;
|
|
672
|
+
pending = /* @__PURE__ */ new Map();
|
|
673
|
+
storage;
|
|
674
|
+
transport;
|
|
675
|
+
now;
|
|
676
|
+
/** `onMessage` / `onMessageBatch` handlers and the guarded delivery to them. */
|
|
677
|
+
fanout = new MessageFanout();
|
|
678
|
+
conversationHandlers = /* @__PURE__ */ new Set();
|
|
679
|
+
subscription = null;
|
|
680
|
+
/**
|
|
681
|
+
* This client's copy of each conversation's metadata, keyed by lowercase-hex
|
|
682
|
+
* conversation id: what a conversation handle's `name`, `epoch` and `meta()`
|
|
683
|
+
* answer from.
|
|
684
|
+
*
|
|
685
|
+
* It is never older than what the host has been told. The worker attaches a
|
|
686
|
+
* conversation's metadata to every change it reports, and {@link handleWorker}
|
|
687
|
+
* stores it before it calls a listener or settles a call; an entry whose
|
|
688
|
+
* conversation changed with no metadata attached is dropped, never kept.
|
|
689
|
+
* Bounded by the conversations the client holds: an entry goes when its
|
|
690
|
+
* conversation is left, dropped or removed, and `listConversations()`
|
|
691
|
+
* replaces the whole map.
|
|
692
|
+
*/
|
|
693
|
+
metaCache = /* @__PURE__ */ new Map();
|
|
694
|
+
/**
|
|
695
|
+
* Per-conversation batching of sequenced live frames: the first frame goes
|
|
696
|
+
* to the worker at once, frames that arrive while that batch is in flight
|
|
697
|
+
* go out as ONE `processSequencedBatch` when it returns. See
|
|
698
|
+
* {@link dispatchIncoming}.
|
|
699
|
+
*/
|
|
700
|
+
coalescer = new InboundCoalescer(
|
|
701
|
+
(_key, items) => this.applyLiveBatch(items)
|
|
702
|
+
);
|
|
703
|
+
/** Single-flight gap fills, one `syncConversationStep` loop per conversation. */
|
|
704
|
+
gapFiller = new GapFiller();
|
|
705
|
+
/** Set by {@link close}: every later call rejects instead of hanging. */
|
|
706
|
+
closed = false;
|
|
707
|
+
// Cached at init() so dispatchIncoming can skip envelopes we sent ourselves — the relay
|
|
708
|
+
// broadcasts to all WS subscribers including the sender, and re-applying our own already-
|
|
709
|
+
// merged commits would error with "epoch differs".
|
|
710
|
+
ownDeviceId = null;
|
|
711
|
+
/**
|
|
712
|
+
* Per-conversation dispatch chains. See {@link dispatchIncoming}.
|
|
713
|
+
*
|
|
714
|
+
* Keyed by lowercase-hex conversation id. Bounded: a chain is deleted the
|
|
715
|
+
* moment it settles and is still the tail, so an account with thousands of
|
|
716
|
+
* conversations holds at most one entry per conversation with work IN FLIGHT,
|
|
717
|
+
* not one per conversation it has ever seen.
|
|
718
|
+
*/
|
|
719
|
+
dispatchChains = /* @__PURE__ */ new Map();
|
|
720
|
+
constructor(cfg, worker) {
|
|
721
|
+
this.worker = worker;
|
|
722
|
+
this.storage = cfg.accountNamespace !== void 0 && cfg.accountNamespace.length > 0 ? scopeStorage(cfg.storage, cfg.accountNamespace) : cfg.storage;
|
|
723
|
+
this.transport = cfg.transport;
|
|
724
|
+
this.now = cfg.now ?? (() => Date.now());
|
|
725
|
+
this.worker.onmessage = (ev) => this.handleWorker(ev.data);
|
|
726
|
+
this.worker.onerror = () => this.failPending(new MessagingClientClosedError("worker-error"));
|
|
727
|
+
}
|
|
728
|
+
/** Generate a fresh identity. The returned bytes are a secret — store them encrypted. */
|
|
729
|
+
static async generateIdentity() {
|
|
730
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
731
|
+
kind: "generateIdentity",
|
|
732
|
+
id: 1
|
|
733
|
+
});
|
|
734
|
+
}
|
|
735
|
+
/**
|
|
736
|
+
* HPKE-seal a `LinkingTicket` for delivery to a new device ([CR-3]).
|
|
737
|
+
*
|
|
738
|
+
* Returns CBOR-encoded bytes safe to relay through an untrusted inbox. The new device's
|
|
739
|
+
* X25519 public key (`newDevicePub`) is exchanged out-of-band — typically as part of a
|
|
740
|
+
* QR-encoded handshake on the linking screen. Pure function; runs in an ephemeral
|
|
741
|
+
* worker so no live `MessagingClient` is required on the sender side.
|
|
742
|
+
*
|
|
743
|
+
* Suite: `DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, AES-128-GCM` (matches MLS).
|
|
744
|
+
*/
|
|
745
|
+
static async sealLinkingTicket(ticket, newDevicePub) {
|
|
746
|
+
if (newDevicePub.length !== 32) {
|
|
747
|
+
throw new Error("sealLinkingTicket: newDevicePub must be 32 bytes");
|
|
748
|
+
}
|
|
749
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
750
|
+
kind: "sealLinkingTicket",
|
|
751
|
+
id: 1,
|
|
752
|
+
ticket,
|
|
753
|
+
newDevicePub
|
|
754
|
+
});
|
|
755
|
+
}
|
|
756
|
+
/**
|
|
757
|
+
* HPKE-open a sealed `LinkingTicket` on the new device ([CR-3]).
|
|
758
|
+
*
|
|
759
|
+
* The receiving device hasn't booted a `MessagingClient` yet — it only has its X25519
|
|
760
|
+
* ephemeral keypair. This static method runs the open in an ephemeral worker, returning
|
|
761
|
+
* the cleartext ticket which the host then feeds to `init()` + `consumeLinkingTicket()`.
|
|
762
|
+
*
|
|
763
|
+
* On failure the error message is deliberately generic (no discriminator between "wrong
|
|
764
|
+
* key" vs "tampered ciphertext") so a probing attacker can't tell the new device's key
|
|
765
|
+
* was the issue.
|
|
766
|
+
*/
|
|
767
|
+
static async openLinkingTicket(sealed, newDevicePriv) {
|
|
768
|
+
if (newDevicePriv.length !== 32) {
|
|
769
|
+
throw new Error("openLinkingTicket: newDevicePriv must be 32 bytes");
|
|
770
|
+
}
|
|
771
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
772
|
+
kind: "openLinkingTicket",
|
|
773
|
+
id: 1,
|
|
774
|
+
sealed,
|
|
775
|
+
newDevicePriv
|
|
776
|
+
});
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* Generic HPKE-Base seal of arbitrary bytes to `recipientPub` (32-byte X25519)
|
|
780
|
+
* under a caller-supplied `info`. One shared HPKE implementation so app layers
|
|
781
|
+
* (e.g. the device-linking auth envelope) stop hand-rolling per-platform HPKE
|
|
782
|
+
* that drifts and breaks cross-platform. Runs in an ephemeral worker.
|
|
783
|
+
*/
|
|
784
|
+
static async hpkeSeal(plaintext, recipientPub, info) {
|
|
785
|
+
if (recipientPub.length !== 32) {
|
|
786
|
+
throw new Error("hpkeSeal: recipientPub must be 32 bytes");
|
|
787
|
+
}
|
|
788
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
789
|
+
kind: "hpkeSeal",
|
|
790
|
+
id: 1,
|
|
791
|
+
plaintext,
|
|
792
|
+
recipientPub,
|
|
793
|
+
info
|
|
794
|
+
});
|
|
795
|
+
}
|
|
796
|
+
/** Generic HPKE-Base open — inverse of {@link hpkeSeal}. `info` must match the sender. */
|
|
797
|
+
static async hpkeOpen(sealed, recipientPriv, info) {
|
|
798
|
+
if (recipientPriv.length !== 32) {
|
|
799
|
+
throw new Error("hpkeOpen: recipientPriv must be 32 bytes");
|
|
800
|
+
}
|
|
801
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
802
|
+
kind: "hpkeOpen",
|
|
803
|
+
id: 1,
|
|
804
|
+
sealed,
|
|
805
|
+
recipientPriv,
|
|
806
|
+
info
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* HPKE-Base seal in the RFC 9180 CANONICAL layout, `enc || ct||tag`, with no
|
|
811
|
+
* CBOR wrapper.
|
|
812
|
+
*
|
|
813
|
+
* Use this, not {@link hpkeSeal}, for anything the app layers already speak.
|
|
814
|
+
* `hpkeSeal` wraps its output in CBOR `{v, enc, ct}` for the linking ticket,
|
|
815
|
+
* and because that could not read the RFC layout, iOS, Android, web and the
|
|
816
|
+
* third-party `ping-notify` sender each ended up hand-composing their own
|
|
817
|
+
* HPKE for the same suite. This is the one they agree on.
|
|
818
|
+
*/
|
|
819
|
+
static async hpkeSealRaw(plaintext, recipientPub, info) {
|
|
820
|
+
if (recipientPub.length !== 32) {
|
|
821
|
+
throw new Error("hpkeSealRaw: recipientPub must be 32 bytes");
|
|
822
|
+
}
|
|
823
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
824
|
+
kind: "hpkeSealRaw",
|
|
825
|
+
id: 1,
|
|
826
|
+
plaintext,
|
|
827
|
+
recipientPub,
|
|
828
|
+
info
|
|
829
|
+
});
|
|
830
|
+
}
|
|
831
|
+
/**
|
|
832
|
+
* Inverse of {@link hpkeSealRaw}. `info` must match the sender's.
|
|
833
|
+
*
|
|
834
|
+
* Rejects with one uniform error whatever went wrong. This opens bytes from
|
|
835
|
+
* an unauthenticated inbox, so a caller that could tell "wrong key" from
|
|
836
|
+
* "tampered" from "truncated" would be an oracle for whoever wrote them.
|
|
837
|
+
*/
|
|
838
|
+
static async hpkeOpenRaw(sealed, recipientPriv, info) {
|
|
839
|
+
if (recipientPriv.length !== 32) {
|
|
840
|
+
throw new Error("hpkeOpenRaw: recipientPriv must be 32 bytes");
|
|
841
|
+
}
|
|
842
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
843
|
+
kind: "hpkeOpenRaw",
|
|
844
|
+
id: 1,
|
|
845
|
+
sealed,
|
|
846
|
+
recipientPriv,
|
|
847
|
+
info
|
|
848
|
+
});
|
|
849
|
+
}
|
|
850
|
+
/**
|
|
851
|
+
* A fresh X25519 keypair for the suite.
|
|
852
|
+
*
|
|
853
|
+
* Exposed so a caller minting a recipient key (a Ping Notify inbox, a linking
|
|
854
|
+
* handshake) does not reach for WebCrypto to do it, which is the same problem
|
|
855
|
+
* one layer down.
|
|
856
|
+
*/
|
|
857
|
+
static async hpkeGenerateKeypair() {
|
|
858
|
+
const both = await _MessagingClient.ephemeralWorkerCall({
|
|
859
|
+
kind: "hpkeGenerateKeypair",
|
|
860
|
+
id: 1
|
|
861
|
+
});
|
|
862
|
+
if (both.length !== 64) {
|
|
863
|
+
throw new Error("hpkeGenerateKeypair: expected 64 bytes");
|
|
864
|
+
}
|
|
865
|
+
return { publicKey: both.slice(0, 32), privateKey: both.slice(32) };
|
|
866
|
+
}
|
|
867
|
+
// ---- Post-quantum HPKE (X-Wing), docs/POST_QUANTUM.md phase 2 ----
|
|
868
|
+
//
|
|
869
|
+
// The `Pq` twins of the functions above: HPKE with KEM X-Wing draft-06
|
|
870
|
+
// (ML-KEM-768 + X25519), HKDF-SHA256, AES-128-GCM. A public key is
|
|
871
|
+
// {@link HPKE_PQ_PUBLIC_KEY_BYTES} bytes, `enc` {@link HPKE_PQ_ENC_BYTES}, the
|
|
872
|
+
// private key a 32-byte seed. These are what the pairing, link-auth,
|
|
873
|
+
// history-transfer and app-inbox flows use from phase 2 on; the classical
|
|
874
|
+
// forms stay for app inboxes created with a 32-byte key before the roll. A
|
|
875
|
+
// classical private key and an X-Wing seed are both 32 bytes but are NOT
|
|
876
|
+
// interchangeable: the host knows which family a stored key belongs to.
|
|
877
|
+
/**
|
|
878
|
+
* HPKE-seal a `LinkingTicket` under the new device's X-Wing public key
|
|
879
|
+
* ([CR-3], post-quantum). CBOR `{v: 2, enc, ct}` under `ping/link/v2`; the
|
|
880
|
+
* classical {@link openLinkingTicket} refuses it and {@link openLinkingTicketPq}
|
|
881
|
+
* refuses a `v: 1` blob, so there is no downgrade in either direction.
|
|
882
|
+
*/
|
|
883
|
+
static async sealLinkingTicketPq(ticket, newDevicePub) {
|
|
884
|
+
if (newDevicePub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {
|
|
885
|
+
throw new Error(`sealLinkingTicketPq: newDevicePub must be ${HPKE_PQ_PUBLIC_KEY_BYTES} bytes`);
|
|
886
|
+
}
|
|
887
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
888
|
+
kind: "sealLinkingTicketPq",
|
|
889
|
+
id: 1,
|
|
890
|
+
ticket,
|
|
891
|
+
newDevicePub
|
|
892
|
+
});
|
|
893
|
+
}
|
|
894
|
+
/**
|
|
895
|
+
* HPKE-open a sealed `v: 2` ticket with the new device's 32-byte X-Wing seed
|
|
896
|
+
* ([CR-3], post-quantum). The error is deliberately generic, like
|
|
897
|
+
* {@link openLinkingTicket}.
|
|
898
|
+
*/
|
|
899
|
+
static async openLinkingTicketPq(sealed, newDevicePriv) {
|
|
900
|
+
if (newDevicePriv.length !== 32) {
|
|
901
|
+
throw new Error("openLinkingTicketPq: newDevicePriv must be 32 bytes");
|
|
902
|
+
}
|
|
903
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
904
|
+
kind: "openLinkingTicketPq",
|
|
905
|
+
id: 1,
|
|
906
|
+
sealed,
|
|
907
|
+
newDevicePriv
|
|
908
|
+
});
|
|
909
|
+
}
|
|
910
|
+
/** Post-quantum {@link hpkeSeal}: CBOR-wrapped (`v: 2`), `recipientPub` is 1216 bytes. */
|
|
911
|
+
static async hpkeSealPq(plaintext, recipientPub, info) {
|
|
912
|
+
if (recipientPub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {
|
|
913
|
+
throw new Error(`hpkeSealPq: recipientPub must be ${HPKE_PQ_PUBLIC_KEY_BYTES} bytes`);
|
|
914
|
+
}
|
|
915
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
916
|
+
kind: "hpkeSealPq",
|
|
917
|
+
id: 1,
|
|
918
|
+
plaintext,
|
|
919
|
+
recipientPub,
|
|
920
|
+
info
|
|
921
|
+
});
|
|
922
|
+
}
|
|
923
|
+
/** Inverse of {@link hpkeSealPq}. `recipientPriv` is the 32-byte seed; `info` must match. */
|
|
924
|
+
static async hpkeOpenPq(sealed, recipientPriv, info) {
|
|
925
|
+
if (recipientPriv.length !== 32) {
|
|
926
|
+
throw new Error("hpkeOpenPq: recipientPriv must be 32 bytes");
|
|
927
|
+
}
|
|
928
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
929
|
+
kind: "hpkeOpenPq",
|
|
930
|
+
id: 1,
|
|
931
|
+
sealed,
|
|
932
|
+
recipientPriv,
|
|
933
|
+
info
|
|
934
|
+
});
|
|
935
|
+
}
|
|
936
|
+
/**
|
|
937
|
+
* Post-quantum {@link hpkeSealRaw}: RFC 9180 canonical `enc(1120) || ct || tag`.
|
|
938
|
+
* The `v2` form of every app-layer envelope (`ping/link-auth/v2`,
|
|
939
|
+
* `ping/app-inbox/v2`).
|
|
940
|
+
*/
|
|
941
|
+
static async hpkeSealRawPq(plaintext, recipientPub, info) {
|
|
942
|
+
if (recipientPub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {
|
|
943
|
+
throw new Error(`hpkeSealRawPq: recipientPub must be ${HPKE_PQ_PUBLIC_KEY_BYTES} bytes`);
|
|
944
|
+
}
|
|
945
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
946
|
+
kind: "hpkeSealRawPq",
|
|
947
|
+
id: 1,
|
|
948
|
+
plaintext,
|
|
949
|
+
recipientPub,
|
|
950
|
+
info
|
|
951
|
+
});
|
|
952
|
+
}
|
|
953
|
+
/** Inverse of {@link hpkeSealRawPq}. One uniform error, as for {@link hpkeOpenRaw}. */
|
|
954
|
+
static async hpkeOpenRawPq(sealed, recipientPriv, info) {
|
|
955
|
+
if (recipientPriv.length !== 32) {
|
|
956
|
+
throw new Error("hpkeOpenRawPq: recipientPriv must be 32 bytes");
|
|
957
|
+
}
|
|
958
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
959
|
+
kind: "hpkeOpenRawPq",
|
|
960
|
+
id: 1,
|
|
961
|
+
sealed,
|
|
962
|
+
recipientPriv,
|
|
963
|
+
info
|
|
964
|
+
});
|
|
965
|
+
}
|
|
966
|
+
/**
|
|
967
|
+
* A fresh X-Wing keypair: `publicKey` is {@link HPKE_PQ_PUBLIC_KEY_BYTES} bytes,
|
|
968
|
+
* `privateKey` the 32-byte seed. Persist only the seed and recompute the public
|
|
969
|
+
* half with {@link hpkePublicKeyFromSeed}; wipe both buffers when done.
|
|
970
|
+
*/
|
|
971
|
+
static async hpkeGenerateKeypairPq() {
|
|
972
|
+
const both = await _MessagingClient.ephemeralWorkerCall({
|
|
973
|
+
kind: "hpkeGenerateKeypairPq",
|
|
974
|
+
id: 1
|
|
975
|
+
});
|
|
976
|
+
if (both.length !== HPKE_PQ_PUBLIC_KEY_BYTES + 32) {
|
|
977
|
+
throw new Error(`hpkeGenerateKeypairPq: expected ${HPKE_PQ_PUBLIC_KEY_BYTES + 32} bytes`);
|
|
978
|
+
}
|
|
979
|
+
return {
|
|
980
|
+
publicKey: both.slice(0, HPKE_PQ_PUBLIC_KEY_BYTES),
|
|
981
|
+
privateKey: both.slice(HPKE_PQ_PUBLIC_KEY_BYTES)
|
|
982
|
+
};
|
|
983
|
+
}
|
|
984
|
+
/**
|
|
985
|
+
* The X-Wing public key for a stored 32-byte seed. Deterministic: the pairing
|
|
986
|
+
* code carries SHA-256 of exactly these bytes, so what a device advertises
|
|
987
|
+
* always matches what it will open with.
|
|
988
|
+
*/
|
|
989
|
+
static async hpkePublicKeyFromSeed(seed) {
|
|
990
|
+
if (seed.length !== 32) {
|
|
991
|
+
throw new Error("hpkePublicKeyFromSeed: seed must be 32 bytes");
|
|
992
|
+
}
|
|
993
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
994
|
+
kind: "hpkePublicKeyFromSeed",
|
|
995
|
+
id: 1,
|
|
996
|
+
seed
|
|
997
|
+
});
|
|
998
|
+
}
|
|
999
|
+
/**
|
|
1000
|
+
* The id of an account's DeviceGroup (the private sync group of the
|
|
1001
|
+
* account's own devices), derived by the SDK core from the account's MLS
|
|
1002
|
+
* user id: `userId` is `client.userId()` (32 bytes), NOT the server's
|
|
1003
|
+
* account id. Deterministic: every device of the account derives the same
|
|
1004
|
+
* id, so a host recognises the DeviceGroup without copying the derivation.
|
|
1005
|
+
* Stateless (no client needed); bytes that are not an MLS user id derive an
|
|
1006
|
+
* id no device uses.
|
|
1007
|
+
*/
|
|
1008
|
+
static async deviceGroupIdFor(userId) {
|
|
1009
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
1010
|
+
kind: "deviceGroupIdFor",
|
|
1011
|
+
id: 1,
|
|
1012
|
+
userId
|
|
1013
|
+
});
|
|
1014
|
+
}
|
|
1015
|
+
/** The 32-byte X25519 public key for a stored classical private key. */
|
|
1016
|
+
static async hpkePublicKeyFromPrivate(privateKey) {
|
|
1017
|
+
if (privateKey.length !== 32) {
|
|
1018
|
+
throw new Error("hpkePublicKeyFromPrivate: privateKey must be 32 bytes");
|
|
1019
|
+
}
|
|
1020
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
1021
|
+
kind: "hpkePublicKeyFromPrivate",
|
|
1022
|
+
id: 1,
|
|
1023
|
+
privateKey
|
|
1024
|
+
});
|
|
1025
|
+
}
|
|
1026
|
+
/**
|
|
1027
|
+
* Answer a device re-authentication challenge (`POST /v1/auth/device/challenge`) with
|
|
1028
|
+
* the device signing key, so a device whose session tokens are gone or dead gets fresh
|
|
1029
|
+
* ones for the SAME device without a code (`POST /v1/auth/device/verify`).
|
|
1030
|
+
*
|
|
1031
|
+
* The SDK builds the signed bytes itself (`"ping/device-reauth/v1" || challengeId ||
|
|
1032
|
+
* nonce || deviceId || accountId || audience`), so this cannot sign anything else with
|
|
1033
|
+
* the device key. `deviceSigningSecretKey` is the 32-byte secret the host passes as
|
|
1034
|
+
* `deviceSigningSecretKey` to {@link init}; `challengeId` (16 bytes) and `nonce`
|
|
1035
|
+
* (32 bytes) come from the challenge response. `accountId` (16 bytes) is the account
|
|
1036
|
+
* the host stored with its session; the server refuses a proof for any other account,
|
|
1037
|
+
* so send the same id with the proof. `audience` is the canonical origin of the API
|
|
1038
|
+
* THIS host is configured to reach (`new URL(apiBase).origin`, for example
|
|
1039
|
+
* `https://api-prod.ping.live`), never the value the server returned: that is what
|
|
1040
|
+
* makes a challenge relayed from another deployment useless there. The returned
|
|
1041
|
+
* `deviceId` is SHA-256 of the key's public half; send it with the signature.
|
|
1042
|
+
*
|
|
1043
|
+
* Rejects wrong widths and a non-canonical audience. Runs in an ephemeral worker.
|
|
1044
|
+
*/
|
|
1045
|
+
static async signDeviceReauth(params) {
|
|
1046
|
+
const { deviceSigningSecretKey, challengeId, nonce, accountId, audience } = params;
|
|
1047
|
+
if (deviceSigningSecretKey.length !== 32) {
|
|
1048
|
+
throw new Error("signDeviceReauth: deviceSigningSecretKey must be 32 bytes");
|
|
1049
|
+
}
|
|
1050
|
+
if (challengeId.length !== 16) {
|
|
1051
|
+
throw new Error("signDeviceReauth: challengeId must be 16 bytes");
|
|
1052
|
+
}
|
|
1053
|
+
if (nonce.length !== 32) {
|
|
1054
|
+
throw new Error("signDeviceReauth: nonce must be 32 bytes");
|
|
1055
|
+
}
|
|
1056
|
+
if (accountId.length !== 16) {
|
|
1057
|
+
throw new Error("signDeviceReauth: accountId must be 16 bytes");
|
|
1058
|
+
}
|
|
1059
|
+
const both = await _MessagingClient.ephemeralWorkerCall({
|
|
1060
|
+
kind: "signDeviceReauth",
|
|
1061
|
+
id: 1,
|
|
1062
|
+
deviceSigningSecretKey,
|
|
1063
|
+
challengeId,
|
|
1064
|
+
nonce,
|
|
1065
|
+
accountId,
|
|
1066
|
+
audience
|
|
1067
|
+
});
|
|
1068
|
+
if (both.length !== 96) {
|
|
1069
|
+
throw new Error("signDeviceReauth: expected 96 bytes");
|
|
1070
|
+
}
|
|
1071
|
+
return { deviceId: both.slice(0, 32), signature: both.slice(32) };
|
|
1072
|
+
}
|
|
1073
|
+
/**
|
|
1074
|
+
* Link verification v2, on the APPROVING device: approve ONE new device on ONE
|
|
1075
|
+
* server link session (`POST /v1/auth/link/sessions` returned `approvalSessionId`)
|
|
1076
|
+
* with this device's signing key. The new device sends the result with its own
|
|
1077
|
+
* {@link signDeviceLinkPossession} proof to `POST /v1/auth/link/verify`.
|
|
1078
|
+
*
|
|
1079
|
+
* The SDK builds the signed bytes itself (`"ping/device-link-approve/v1" ||
|
|
1080
|
+
* approvalSessionId || accountId || approverDeviceId || newDeviceId ||
|
|
1081
|
+
* newDevicePubkey || audience`, see docs/DEVICE_LINK_V2_VECTORS.md) and derives
|
|
1082
|
+
* both device ids from the keys, so this cannot sign anything else with the device
|
|
1083
|
+
* key. `deviceSigningSecretKey` is the 32-byte seed the host holds for THIS device
|
|
1084
|
+
* (the one registered as its device signing key); `accountId` (16 bytes) is the
|
|
1085
|
+
* account stored with this device's session; `newDevicePubkey` (32 bytes) is the
|
|
1086
|
+
* new device's key from its handshake; `audience` is the canonical origin of the API
|
|
1087
|
+
* THIS host is configured to reach (`new URL(apiBase).origin`), as for
|
|
1088
|
+
* {@link signDeviceReauth}.
|
|
1089
|
+
*
|
|
1090
|
+
* Rejects wrong widths, a non-canonical audience, a new key that is not a canonical
|
|
1091
|
+
* Ed25519 point outside the small-order subgroup, and this device's own key. Runs in
|
|
1092
|
+
* an ephemeral worker.
|
|
1093
|
+
*/
|
|
1094
|
+
static async signDeviceLinkApproval(params) {
|
|
1095
|
+
const { deviceSigningSecretKey, approvalSessionId, accountId, newDevicePubkey, audience } = params;
|
|
1096
|
+
if (deviceSigningSecretKey.length !== 32) {
|
|
1097
|
+
throw new Error("signDeviceLinkApproval: deviceSigningSecretKey must be 32 bytes");
|
|
1098
|
+
}
|
|
1099
|
+
if (approvalSessionId.length !== 16) {
|
|
1100
|
+
throw new Error("signDeviceLinkApproval: approvalSessionId must be 16 bytes");
|
|
1101
|
+
}
|
|
1102
|
+
if (accountId.length !== 16) {
|
|
1103
|
+
throw new Error("signDeviceLinkApproval: accountId must be 16 bytes");
|
|
1104
|
+
}
|
|
1105
|
+
if (newDevicePubkey.length !== 32) {
|
|
1106
|
+
throw new Error("signDeviceLinkApproval: newDevicePubkey must be 32 bytes");
|
|
1107
|
+
}
|
|
1108
|
+
const all = await _MessagingClient.ephemeralWorkerCall({
|
|
1109
|
+
kind: "signDeviceLinkApproval",
|
|
1110
|
+
id: 1,
|
|
1111
|
+
deviceSigningSecretKey,
|
|
1112
|
+
approvalSessionId,
|
|
1113
|
+
accountId,
|
|
1114
|
+
newDevicePubkey,
|
|
1115
|
+
audience
|
|
1116
|
+
});
|
|
1117
|
+
if (all.length !== 128) {
|
|
1118
|
+
throw new Error("signDeviceLinkApproval: expected 128 bytes");
|
|
1119
|
+
}
|
|
1120
|
+
return {
|
|
1121
|
+
approverDeviceId: all.slice(0, 32),
|
|
1122
|
+
newDeviceId: all.slice(32, 64),
|
|
1123
|
+
signature: all.slice(64)
|
|
1124
|
+
};
|
|
1125
|
+
}
|
|
1126
|
+
/**
|
|
1127
|
+
* Link verification v2, on the NEW device: prove that this device holds the key the
|
|
1128
|
+
* link session names (`"ping/device-link-possess/v1" || approvalSessionId ||
|
|
1129
|
+
* accountId || deviceId || audience`). `deviceSigningSecretKey` is this device's own
|
|
1130
|
+
* 32-byte seed (the key its handshake advertised); `approvalSessionId` and
|
|
1131
|
+
* `accountId` come from the approving device's sealed envelope; `audience` as for
|
|
1132
|
+
* {@link signDeviceReauth}. Check `approval.newDeviceId` equals the returned
|
|
1133
|
+
* `deviceId` before verifying: a substituted handshake is refused locally.
|
|
1134
|
+
*
|
|
1135
|
+
* Rejects wrong widths and a non-canonical audience. Runs in an ephemeral worker.
|
|
1136
|
+
*/
|
|
1137
|
+
static async signDeviceLinkPossession(params) {
|
|
1138
|
+
const { deviceSigningSecretKey, approvalSessionId, accountId, audience } = params;
|
|
1139
|
+
if (deviceSigningSecretKey.length !== 32) {
|
|
1140
|
+
throw new Error("signDeviceLinkPossession: deviceSigningSecretKey must be 32 bytes");
|
|
1141
|
+
}
|
|
1142
|
+
if (approvalSessionId.length !== 16) {
|
|
1143
|
+
throw new Error("signDeviceLinkPossession: approvalSessionId must be 16 bytes");
|
|
1144
|
+
}
|
|
1145
|
+
if (accountId.length !== 16) {
|
|
1146
|
+
throw new Error("signDeviceLinkPossession: accountId must be 16 bytes");
|
|
1147
|
+
}
|
|
1148
|
+
const both = await _MessagingClient.ephemeralWorkerCall({
|
|
1149
|
+
kind: "signDeviceLinkPossession",
|
|
1150
|
+
id: 1,
|
|
1151
|
+
deviceSigningSecretKey,
|
|
1152
|
+
approvalSessionId,
|
|
1153
|
+
accountId,
|
|
1154
|
+
audience
|
|
1155
|
+
});
|
|
1156
|
+
if (both.length !== 96) {
|
|
1157
|
+
throw new Error("signDeviceLinkPossession: expected 96 bytes");
|
|
1158
|
+
}
|
|
1159
|
+
return { deviceId: both.slice(0, 32), signature: both.slice(32) };
|
|
1160
|
+
}
|
|
1161
|
+
// Spawn-call-terminate helper for stateless WASM functions exposed at module scope (no
|
|
1162
|
+
// PingClient required). Each call gets a fresh worker; the cost is acceptable because
|
|
1163
|
+
// these are one-shot, off-the-hot-path operations (identity gen, linking ticket seal/open).
|
|
1164
|
+
//
|
|
1165
|
+
// The returned promise ALWAYS settles and the worker is ALWAYS terminated: on its
|
|
1166
|
+
// result, on a worker `error` (the script failed to load or import, or threw at top
|
|
1167
|
+
// level), on a `messageerror` (a reply that could not be deserialised), and when the
|
|
1168
|
+
// worker cannot be created or the request cannot be posted. Only `onmessage` used to be
|
|
1169
|
+
// wired, so a worker that failed to load left `generateIdentity()` pending forever and
|
|
1170
|
+
// the worker alive.
|
|
1171
|
+
static ephemeralWorkerCall(req) {
|
|
1172
|
+
let w;
|
|
1173
|
+
try {
|
|
1174
|
+
w = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
|
|
1175
|
+
} catch {
|
|
1176
|
+
return Promise.reject(new EphemeralWorkerError("spawn"));
|
|
1177
|
+
}
|
|
1178
|
+
return new Promise((resolve, reject) => {
|
|
1179
|
+
let settled = false;
|
|
1180
|
+
const settle = (finish) => {
|
|
1181
|
+
if (settled) return;
|
|
1182
|
+
settled = true;
|
|
1183
|
+
w.onmessage = null;
|
|
1184
|
+
w.onerror = null;
|
|
1185
|
+
w.onmessageerror = null;
|
|
1186
|
+
w.terminate();
|
|
1187
|
+
finish();
|
|
1188
|
+
};
|
|
1189
|
+
w.onmessage = (ev) => {
|
|
1190
|
+
const msg = ev.data;
|
|
1191
|
+
if (msg.kind === "result" && msg.id === req.id) {
|
|
1192
|
+
settle(() => msg.ok ? resolve(msg.value) : reject(new Error(msg.error)));
|
|
1193
|
+
}
|
|
1194
|
+
};
|
|
1195
|
+
w.onerror = () => settle(() => reject(new EphemeralWorkerError("error")));
|
|
1196
|
+
w.onmessageerror = () => settle(() => reject(new EphemeralWorkerError("messageerror")));
|
|
1197
|
+
try {
|
|
1198
|
+
w.postMessage(req);
|
|
1199
|
+
} catch {
|
|
1200
|
+
settle(() => reject(new EphemeralWorkerError("post")));
|
|
1201
|
+
}
|
|
1202
|
+
});
|
|
1203
|
+
}
|
|
1204
|
+
static async init(cfg) {
|
|
1205
|
+
const worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
|
|
1206
|
+
const client = new _MessagingClient(cfg, worker);
|
|
1207
|
+
const transportFeatures = {
|
|
1208
|
+
fetchLogSince: typeof cfg.transport.fetchLogSince === "function",
|
|
1209
|
+
fetchLogHeads: typeof cfg.transport.fetchLogHeads === "function"
|
|
1210
|
+
};
|
|
1211
|
+
const storageFeatures = storageFeaturesOf(client.storage);
|
|
1212
|
+
await client.call({
|
|
1213
|
+
kind: "init",
|
|
1214
|
+
id: client.nextId++,
|
|
1215
|
+
identityExport: cfg.identityExport,
|
|
1216
|
+
deviceLabel: cfg.deviceLabel,
|
|
1217
|
+
nowMs: client.now(),
|
|
1218
|
+
...cfg.deviceSigningSecretKey ? { deviceSigningSecretKey: cfg.deviceSigningSecretKey } : {},
|
|
1219
|
+
...cfg.expectedOwners ? { expectedOwners: cfg.expectedOwners } : {},
|
|
1220
|
+
transportFeatures,
|
|
1221
|
+
storageFeatures
|
|
1222
|
+
});
|
|
1223
|
+
client.ownDeviceId = await client.deviceId();
|
|
1224
|
+
client.subscription = cfg.transport.subscribe(
|
|
1225
|
+
(frame) => client.dispatchIncoming(frame)
|
|
1226
|
+
);
|
|
1227
|
+
return client;
|
|
1228
|
+
}
|
|
1229
|
+
/**
|
|
1230
|
+
* Internal: route an inbound envelope to the right handler, IN ARRIVAL ORDER
|
|
1231
|
+
* PER CONVERSATION.
|
|
1232
|
+
*
|
|
1233
|
+
* ## Why the ordering is load-bearing
|
|
1234
|
+
*
|
|
1235
|
+
* A group invitation arrives as a Welcome immediately followed by the
|
|
1236
|
+
* inviter's hydration Application messages (group title, roster, avatar id).
|
|
1237
|
+
* `joinConversation` is asynchronous — it is several round trips to the WASM
|
|
1238
|
+
* worker — so a naive `void dispatchIncoming(...)` per frame let the
|
|
1239
|
+
* Applications reach `processEnvelope` while the join was still in flight.
|
|
1240
|
+
* The conversation did not exist yet, so every one of them was dropped with
|
|
1241
|
+
* "envelope drop: unknown conversation".
|
|
1242
|
+
*
|
|
1243
|
+
* That loss is PERMANENT and silent: MLS ratchets forward, the transport has
|
|
1244
|
+
* already marked the frames seen and advanced its cursor, and the server will
|
|
1245
|
+
* not resend them. The visible symptom was an invitation landing as an
|
|
1246
|
+
* unnamed "New chat" with no avatar and no roster, and — for the same reason —
|
|
1247
|
+
* a rename, avatar change, member add/remove or role change being lost
|
|
1248
|
+
* whenever it happened to land while a join or another commit for that group
|
|
1249
|
+
* was still being applied.
|
|
1250
|
+
*
|
|
1251
|
+
* Chaining PER CONVERSATION (not globally) is deliberate: MLS state is
|
|
1252
|
+
* per-group, so that is the granularity correctness actually requires, and a
|
|
1253
|
+
* busy conversation must not be able to head-of-line block every other one.
|
|
1254
|
+
* The chain is built synchronously on entry, so chain order is exactly frame
|
|
1255
|
+
* arrival order.
|
|
1256
|
+
*
|
|
1257
|
+
* ## Sequenced frames
|
|
1258
|
+
*
|
|
1259
|
+
* A frame that carries its server position (`{ envelope, serverSeq }`,
|
|
1260
|
+
* `serverSeq > 0`) does not need the chain: the core applies it at its
|
|
1261
|
+
* position, holds it ahead of a hole and drops it at or below what was
|
|
1262
|
+
* applied, whatever order it arrived in. What it needs is BATCHING: one
|
|
1263
|
+
* MLS checkpoint and one host transaction per burst instead of one per
|
|
1264
|
+
* frame. So the first frame for a conversation goes to the worker at once
|
|
1265
|
+
* as a batch of one, and frames that arrive while that batch is in flight
|
|
1266
|
+
* accumulate and go out as ONE `processSequencedBatch` when it returns; no
|
|
1267
|
+
* timer ever delays a frame. Own-device echoes are NOT dropped on this
|
|
1268
|
+
* path: the core advances the position past them without touching MLS,
|
|
1269
|
+
* and dropping one would leave a hole the next frame reports as a gap. A
|
|
1270
|
+
* sequenced frame at `serverSeq` 0 is a legacy frame in a wrapper and
|
|
1271
|
+
* takes the legacy path unchanged.
|
|
1272
|
+
*/
|
|
1273
|
+
dispatchIncoming(frame) {
|
|
1274
|
+
if (isSequencedFrame(frame)) {
|
|
1275
|
+
if (frame.serverSeq > 0) {
|
|
1276
|
+
return this.coalescer.push(hexOf(frame.envelope.conversation_id), frame);
|
|
1277
|
+
}
|
|
1278
|
+
return this.dispatchLegacy(frame.envelope);
|
|
1279
|
+
}
|
|
1280
|
+
return this.dispatchLegacy(frame);
|
|
1281
|
+
}
|
|
1282
|
+
/** The legacy per-envelope path: own-device drop, then the per-conversation chain. */
|
|
1283
|
+
dispatchLegacy(envelope) {
|
|
1284
|
+
if (this.ownDeviceId && sameBytesU8(envelope.sender_device, this.ownDeviceId)) {
|
|
1285
|
+
return Promise.resolve();
|
|
1286
|
+
}
|
|
1287
|
+
const key = hexOf(envelope.conversation_id);
|
|
1288
|
+
const prior = this.dispatchChains.get(key) ?? Promise.resolve();
|
|
1289
|
+
const next = prior.catch(() => void 0).then(() => this.dispatchIncomingOrdered(envelope));
|
|
1290
|
+
const tail = next.catch(() => void 0).finally(() => {
|
|
1291
|
+
if (this.dispatchChains.get(key) === tail) this.dispatchChains.delete(key);
|
|
1292
|
+
});
|
|
1293
|
+
this.dispatchChains.set(key, tail);
|
|
1294
|
+
return next;
|
|
1295
|
+
}
|
|
1296
|
+
/** The actual routing, run inside the per-conversation chain. */
|
|
1297
|
+
async dispatchIncomingOrdered(envelope) {
|
|
1298
|
+
if (envelope.kind === "Welcome") {
|
|
1299
|
+
try {
|
|
1300
|
+
const known = await this.listConversations();
|
|
1301
|
+
const already = known.some((m) => sameBytesU8(m.id, envelope.conversation_id));
|
|
1302
|
+
if (already) {
|
|
1303
|
+
const stranded = await this.strandedConversations();
|
|
1304
|
+
const isStranded = stranded.some((id) => sameBytesU8(id, envelope.conversation_id));
|
|
1305
|
+
if (!isStranded) return;
|
|
1306
|
+
}
|
|
1307
|
+
await this.joinConversation(envelope);
|
|
1308
|
+
} catch (e) {
|
|
1309
|
+
if (typeof console !== "undefined") console.debug("[ping-sdk] welcome ignored:", e);
|
|
1310
|
+
}
|
|
1311
|
+
return;
|
|
1312
|
+
}
|
|
1313
|
+
try {
|
|
1314
|
+
await this.processEnvelope(envelope);
|
|
1315
|
+
} catch (e) {
|
|
1316
|
+
if (typeof console !== "undefined") console.debug("[ping-sdk] envelope deferred:", e);
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
/**
|
|
1320
|
+
* One coalesced batch of live frames. Errors are logged at debug and
|
|
1321
|
+
* swallowed, exactly as the legacy path treats a failed envelope: the
|
|
1322
|
+
* dispatch promise a transport may await resolves either way, and the
|
|
1323
|
+
* core retains anything it could not apply yet.
|
|
1324
|
+
*/
|
|
1325
|
+
async applyLiveBatch(items) {
|
|
1326
|
+
try {
|
|
1327
|
+
await this.processSequencedBatch(items);
|
|
1328
|
+
} catch (e) {
|
|
1329
|
+
if (typeof console !== "undefined") console.debug("[ping-sdk] sequenced batch failed:", errorKind(e));
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
/** Start a fill for every gap a batch reported; each is single-flight. */
|
|
1333
|
+
scheduleGapFills(result) {
|
|
1334
|
+
for (const gap of result.gaps) {
|
|
1335
|
+
void this.fillGap(gap.conversationId).catch((e) => {
|
|
1336
|
+
if (typeof console !== "undefined") console.debug("[ping-sdk] gap fill failed:", errorKind(e));
|
|
1337
|
+
});
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
/** One page, delivered as a page, on the requested lane. */
|
|
1341
|
+
async stepConversation(id, stepped) {
|
|
1342
|
+
const raw = await this.call({
|
|
1343
|
+
kind: "syncConversationStep",
|
|
1344
|
+
id: this.nextId++,
|
|
1345
|
+
conv: id,
|
|
1346
|
+
nowMs: this.now(),
|
|
1347
|
+
...stepped ? { stepped: true } : {}
|
|
1348
|
+
});
|
|
1349
|
+
const result = syncStepResultFromWire(raw);
|
|
1350
|
+
this.fanout.deliverBatch(result.messages, { source: "page" });
|
|
1351
|
+
return result;
|
|
1352
|
+
}
|
|
1353
|
+
// ------------------------ Public API ------------------------
|
|
1354
|
+
async userId() {
|
|
1355
|
+
return await this.call({ kind: "userId", id: this.nextId++ });
|
|
1356
|
+
}
|
|
1357
|
+
/**
|
|
1358
|
+
* Export the account identity seed (CBOR-wrapped Ed25519, **SECRET**).
|
|
1359
|
+
* Transfer to a newly-linked device over the sealed linking channel so all of
|
|
1360
|
+
* an account's devices share one `userId` — the basis for cross-device
|
|
1361
|
+
* self-attribution (`IncomingMessage.sender_user_id === userId()`). Never log
|
|
1362
|
+
* or persist in cleartext.
|
|
1363
|
+
*/
|
|
1364
|
+
async exportIdentity() {
|
|
1365
|
+
return await this.call({ kind: "exportIdentity", id: this.nextId++ });
|
|
1366
|
+
}
|
|
1367
|
+
/**
|
|
1368
|
+
* RETIRED (2026-11-03): always rejects (`Invalid`) and changes nothing.
|
|
1369
|
+
*
|
|
1370
|
+
* It moved every conversation's own leaf to a new account identity with a
|
|
1371
|
+
* credential-changing Commit, the way out of `409 mls_identity_conflict`.
|
|
1372
|
+
* Every Ping client now refuses a Commit that changes a member's leaf
|
|
1373
|
+
* credential (a hostile linked device could otherwise move its leaf to a
|
|
1374
|
+
* peer's identity and escape the account's removal), so a rotation would
|
|
1375
|
+
* strand every conversation it touched. The way out of an identity conflict
|
|
1376
|
+
* is to link this device again, or sign out and in. Kept so no caller
|
|
1377
|
+
* breaks. See `docs/MULTIDEVICE.md` "Identity rotation".
|
|
1378
|
+
*
|
|
1379
|
+
* @deprecated Retired: always rejects. Link this device again instead.
|
|
1380
|
+
*/
|
|
1381
|
+
async rotateIdentity(newIdentityExport, nowMs = this.now()) {
|
|
1382
|
+
return await this.call({
|
|
1383
|
+
kind: "rotateIdentity",
|
|
1384
|
+
id: this.nextId++,
|
|
1385
|
+
newIdentityExport,
|
|
1386
|
+
nowMs
|
|
1387
|
+
});
|
|
1388
|
+
}
|
|
1389
|
+
/**
|
|
1390
|
+
* RETIRED with [[rotateIdentity]]: always rejects (`Invalid`).
|
|
1391
|
+
*
|
|
1392
|
+
* @deprecated Retired: always rejects.
|
|
1393
|
+
*/
|
|
1394
|
+
async rotateIdentityRetry(conv, nowMs = this.now()) {
|
|
1395
|
+
await this.call({ kind: "rotateIdentityRetry", id: this.nextId++, conv, nowMs });
|
|
1396
|
+
}
|
|
1397
|
+
async deviceId() {
|
|
1398
|
+
return await this.call({ kind: "deviceId", id: this.nextId++ });
|
|
1399
|
+
}
|
|
1400
|
+
/**
|
|
1401
|
+
* Release every file lock the MLS store holds so the host process can be
|
|
1402
|
+
* suspended. Resolves `true` when the locks are genuinely gone.
|
|
1403
|
+
*
|
|
1404
|
+
* Present on web for API parity, and a no-op returning `true` here: this build
|
|
1405
|
+
* persists through the host's `Storage` (IndexedDB by default), which holds no
|
|
1406
|
+
* file locks and has nothing to release. It is load-bearing on the native
|
|
1407
|
+
* bindings, where iOS kills a backgrounded process that still holds a lock on
|
|
1408
|
+
* a file in an App Group container. Exposed on every platform so a host
|
|
1409
|
+
* sharing code across web and native does not have to branch on it.
|
|
1410
|
+
*
|
|
1411
|
+
* Pair with `resumeStorage()`.
|
|
1412
|
+
*/
|
|
1413
|
+
async suspendStorage() {
|
|
1414
|
+
return await this.call({ kind: "suspendStorage", id: this.nextId++ });
|
|
1415
|
+
}
|
|
1416
|
+
/** Undo `suspendStorage()`. Idempotent. */
|
|
1417
|
+
async resumeStorage() {
|
|
1418
|
+
await this.call({ kind: "resumeStorage", id: this.nextId++ });
|
|
1419
|
+
}
|
|
1420
|
+
async freshKeyPackage() {
|
|
1421
|
+
return await this.call({ kind: "freshKeyPackage", id: this.nextId++ });
|
|
1422
|
+
}
|
|
1423
|
+
/**
|
|
1424
|
+
* Generate a fresh LAST-RESORT KeyPackage (RFC 9420 §10). Publish exactly one
|
|
1425
|
+
* per device so the server can serve it repeatedly as a fallback when the
|
|
1426
|
+
* single-use pool empties — invites then never hard-fail purely because the
|
|
1427
|
+
* peer ran out of KeyPackages.
|
|
1428
|
+
*/
|
|
1429
|
+
async freshLastResortKeyPackage() {
|
|
1430
|
+
return await this.call({ kind: "freshLastResortKeyPackage", id: this.nextId++ });
|
|
1431
|
+
}
|
|
1432
|
+
async createConversation(opts = {}) {
|
|
1433
|
+
const idBytes = await this.call({
|
|
1434
|
+
kind: "createConversation",
|
|
1435
|
+
id: this.nextId++,
|
|
1436
|
+
name: opts.name ?? null,
|
|
1437
|
+
nowMs: this.now()
|
|
1438
|
+
});
|
|
1439
|
+
return this.conversationProxy(idBytes);
|
|
1440
|
+
}
|
|
1441
|
+
/**
|
|
1442
|
+
* Create an ephemeral per-call MLS group. Identical to {@link createConversation}
|
|
1443
|
+
* except the id carries the `0xFF 0xCC` call-group sentinel, so every device
|
|
1444
|
+
* recognises it structurally (by id alone — no name, no registry) and keeps it
|
|
1445
|
+
* out of the chat list. Hosts MUST use this for call groups.
|
|
1446
|
+
*/
|
|
1447
|
+
async createCallConversation(opts = {}) {
|
|
1448
|
+
const idBytes = await this.call({
|
|
1449
|
+
kind: "createCallConversation",
|
|
1450
|
+
id: this.nextId++,
|
|
1451
|
+
name: opts.name ?? null,
|
|
1452
|
+
nowMs: this.now()
|
|
1453
|
+
});
|
|
1454
|
+
return this.conversationProxy(idBytes);
|
|
1455
|
+
}
|
|
1456
|
+
async joinConversation(welcome) {
|
|
1457
|
+
const idBytes = await this.call({
|
|
1458
|
+
kind: "joinConversation",
|
|
1459
|
+
id: this.nextId++,
|
|
1460
|
+
welcome,
|
|
1461
|
+
nowMs: this.now()
|
|
1462
|
+
});
|
|
1463
|
+
return this.conversationProxy(idBytes);
|
|
1464
|
+
}
|
|
1465
|
+
/**
|
|
1466
|
+
* Get a `Conversation` proxy for an already-known conversation. Use this when you have a
|
|
1467
|
+
* conversation id (e.g., from `listConversations()`) and want to send/addMembers without
|
|
1468
|
+
* re-creating it. Throws if the id isn't known to the worker — call `listConversations()`
|
|
1469
|
+
* first to verify membership.
|
|
1470
|
+
*/
|
|
1471
|
+
getConversation(id) {
|
|
1472
|
+
return this.conversationProxy(id);
|
|
1473
|
+
}
|
|
1474
|
+
async listConversations() {
|
|
1475
|
+
const metas = await this.call({ kind: "listConversations", id: this.nextId++ });
|
|
1476
|
+
this.metaCache.clear();
|
|
1477
|
+
for (const m of metas) this.metaCache.set(hex(m.id), m);
|
|
1478
|
+
return metas;
|
|
1479
|
+
}
|
|
1480
|
+
/**
|
|
1481
|
+
* ONE conversation's metadata as the group holds it now: the same record as
|
|
1482
|
+
* its element of {@link listConversations}, without listing the others.
|
|
1483
|
+
* Resolves `null` when this client does not hold the conversation (unknown,
|
|
1484
|
+
* dropped, removed, or left). A pure read of local state: nothing is
|
|
1485
|
+
* fetched. Rejects for an id that is not 16 bytes.
|
|
1486
|
+
*
|
|
1487
|
+
* It also brings the conversation handle's `name`, `epoch` and `meta()` to
|
|
1488
|
+
* the answer, though they do not need it to be fresh: the client replaces
|
|
1489
|
+
* its copy of a conversation's metadata
|
|
1490
|
+
* - before any {@link onConversationUpdated} listener is told the
|
|
1491
|
+
* conversation changed (a Commit from another member, a join, a page of
|
|
1492
|
+
* a catch-up), and
|
|
1493
|
+
* - before this device's own call that changed it resolves (a rename, a
|
|
1494
|
+
* roles or membership change, a creation, a leave).
|
|
1495
|
+
* Use this read for a conversation nothing has reported yet in this
|
|
1496
|
+
* session, or to learn that a conversation is no longer held.
|
|
1497
|
+
*/
|
|
1498
|
+
async readConversationMeta(id) {
|
|
1499
|
+
const meta = await this.call({
|
|
1500
|
+
kind: "conversationMeta",
|
|
1501
|
+
id: this.nextId++,
|
|
1502
|
+
conv: id
|
|
1503
|
+
});
|
|
1504
|
+
this.storeMeta(id, meta);
|
|
1505
|
+
return meta ?? null;
|
|
1506
|
+
}
|
|
1507
|
+
/**
|
|
1508
|
+
* Conversations detected as STRANDED during catch-up — a Commit was missed
|
|
1509
|
+
* and the group can no longer advance from local state, so new messages stop
|
|
1510
|
+
* arriving. Poll after a sync and recover each (re-Welcome / state-snapshot
|
|
1511
|
+
* import). Returns 16-byte conversation ids; the set self-clears as a
|
|
1512
|
+
* conversation makes progress or is re-joined.
|
|
1513
|
+
*/
|
|
1514
|
+
async strandedConversations() {
|
|
1515
|
+
return await this.call({ kind: "strandedConversations", id: this.nextId++ });
|
|
1516
|
+
}
|
|
1517
|
+
/**
|
|
1518
|
+
* Conversations this device asked to leave and is still a member of:
|
|
1519
|
+
* the leave is OWED. The SDK holds their state and proposes the leave
|
|
1520
|
+
* again by itself; the host only keeps delivering their rows (live
|
|
1521
|
+
* frames and catch-up pages). An id leaves the list when the leave has
|
|
1522
|
+
* completed: this device processed its own removal and the state is
|
|
1523
|
+
* deleted. Sorted 16-byte conversation ids.
|
|
1524
|
+
*/
|
|
1525
|
+
async conversationsLeaving() {
|
|
1526
|
+
return await this.call({ kind: "conversationsLeaving", id: this.nextId++ });
|
|
1527
|
+
}
|
|
1528
|
+
/**
|
|
1529
|
+
* The leaving conversations whose leave has STALLED: 8 sends of it
|
|
1530
|
+
* FAILED and this device is still a member, or this device can no longer
|
|
1531
|
+
* follow the group. Nothing more is proposed for them. The host may call
|
|
1532
|
+
* {@link leaveConversation} again (the count starts over) or give up with
|
|
1533
|
+
* {@link dropConversationLocal}, which leaves this device's leaf in the group
|
|
1534
|
+
* until somebody removes it. Sorted 16-byte conversation ids.
|
|
1535
|
+
*/
|
|
1536
|
+
async conversationsLeaveStalled() {
|
|
1537
|
+
return await this.call({ kind: "conversationsLeaveStalled", id: this.nextId++ });
|
|
1538
|
+
}
|
|
1539
|
+
/**
|
|
1540
|
+
* Conversations this device was just torn down from by a SELF-RE-ADD Commit
|
|
1541
|
+
* — a peer's `reAdmitDevice` of this device — whose Welcome for the new
|
|
1542
|
+
* leaf is expected within seconds. Treat these as "re-admission in flight",
|
|
1543
|
+
* not stranded or evicted: no repair advertise, no delivery-key rotation,
|
|
1544
|
+
* no KeyPackage-pool replace, until the join lands or the entry ages out
|
|
1545
|
+
* (ten minutes). Returns 16-byte conversation ids.
|
|
1546
|
+
*/
|
|
1547
|
+
async readmitPendingConversations(nowMs = Date.now()) {
|
|
1548
|
+
return await this.call({
|
|
1549
|
+
kind: "readmitPendingConversations",
|
|
1550
|
+
id: this.nextId++,
|
|
1551
|
+
nowMs
|
|
1552
|
+
});
|
|
1553
|
+
}
|
|
1554
|
+
/**
|
|
1555
|
+
* How many inbound envelopes are currently RETAINED awaiting replay, across
|
|
1556
|
+
* all conversations.
|
|
1557
|
+
*
|
|
1558
|
+
* An envelope that cannot be applied yet — its Welcome has not been processed,
|
|
1559
|
+
* or a Commit that advances the epoch is missing — is buffered and replayed on
|
|
1560
|
+
* join / epoch advance / catch-up sync rather than dropped (see
|
|
1561
|
+
* docs/INVITE_HARDENING.md §S6).
|
|
1562
|
+
*
|
|
1563
|
+
* A non-zero count means "delivered but not yet applicable", which is
|
|
1564
|
+
* materially different from "not delivered" and is the distinction a host
|
|
1565
|
+
* needs to explain a chat that looks incomplete. Expected to be 0 at rest; a
|
|
1566
|
+
* value that stays high points at a conversation whose handshake never
|
|
1567
|
+
* arrived.
|
|
1568
|
+
*/
|
|
1569
|
+
async undeliverableCount() {
|
|
1570
|
+
return await this.call({ kind: "undeliverableCount", id: this.nextId++ });
|
|
1571
|
+
}
|
|
1572
|
+
/**
|
|
1573
|
+
* Leave a conversation: broadcasts a self-Remove PROPOSAL (MLS forbids
|
|
1574
|
+
* committing your own removal: a remaining member commits it via
|
|
1575
|
+
* `commitPendingProposals`) and answers at once. From then on the conversation is
|
|
1576
|
+
* LEFT for the host: it is no longer listed, every call that names it
|
|
1577
|
+
* answers `UnknownConversation`, and nothing of it is surfaced again.
|
|
1578
|
+
*
|
|
1579
|
+
* Do NOT delete it locally afterwards ({@link dropConversationLocal}). The SDK keeps the
|
|
1580
|
+
* group's state, follows its Commits, and proposes the leave again after
|
|
1581
|
+
* each Commit that did not carry it (a Commit built before the proposal
|
|
1582
|
+
* arrived voids it), until this device is removed; then it deletes the
|
|
1583
|
+
* state itself. Keep delivering the conversation's rows to the client
|
|
1584
|
+
* while {@link conversationsLeaving} lists it. The bound is 8 FAILED sends;
|
|
1585
|
+
* after that {@link conversationsLeaveStalled} lists the conversation and calling
|
|
1586
|
+
* this again starts over.
|
|
1587
|
+
*
|
|
1588
|
+
* The group's OWNER hands over first: this call commits the successor (the
|
|
1589
|
+
* one every device computes when the owner's last leaf goes) and only then
|
|
1590
|
+
* proposes the leave. If that Commit cannot be made the call fails with the
|
|
1591
|
+
* Commit's error and nothing is marked: call it again. Nothing is handed
|
|
1592
|
+
* over when the owner's account keeps another device in the group or when
|
|
1593
|
+
* no other member could take over.
|
|
1594
|
+
*/
|
|
1595
|
+
async leaveConversation(id, nowMs = this.now()) {
|
|
1596
|
+
await this.call({ kind: "leaveConversation", id: this.nextId++, conv: id, nowMs });
|
|
1597
|
+
}
|
|
1598
|
+
/**
|
|
1599
|
+
* Drop a conversation's local state with NO network side effect. Unlike
|
|
1600
|
+
* {@link leaveConversation} (which broadcasts a self-Remove proposal), this
|
|
1601
|
+
* sends nothing — use it for a group the SERVER does not back: an invite that
|
|
1602
|
+
* minted the MLS group locally but never completed server-side, so the backend
|
|
1603
|
+
* 404s `fetchSince` / 403s the member roster for it. Deletes the OpenMLS group
|
|
1604
|
+
* state + the on-disk snapshot rows so the dead group stops rehydrating on the
|
|
1605
|
+
* next restart (and re-materialising as a ghost "New chat"). Idempotent — safe
|
|
1606
|
+
* on an unknown/already-dropped id.
|
|
1607
|
+
*/
|
|
1608
|
+
async dropConversationLocal(id) {
|
|
1609
|
+
await this.call({ kind: "dropConversationLocal", id: this.nextId++, conv: id });
|
|
1610
|
+
}
|
|
1611
|
+
/**
|
|
1612
|
+
* Conversations with buffered pending proposals (e.g. a peer's leave). Poll
|
|
1613
|
+
* after a sync; if you're the designated committer, call
|
|
1614
|
+
* `commitPendingProposals` to evict the leaver.
|
|
1615
|
+
*/
|
|
1616
|
+
async conversationsWithPendingProposals() {
|
|
1617
|
+
return await this.call({
|
|
1618
|
+
kind: "conversationsWithPendingProposals",
|
|
1619
|
+
id: this.nextId++
|
|
1620
|
+
});
|
|
1621
|
+
}
|
|
1622
|
+
/**
|
|
1623
|
+
* Commit buffered pending proposals for a conversation (evicts a peer who
|
|
1624
|
+
* left). No-op if nothing is pending; on an epoch-advanced rejection re-sync
|
|
1625
|
+
* (another member already committed). Call it on receipt (a batch or page
|
|
1626
|
+
* result's `proposalsPending`), elected with
|
|
1627
|
+
* {@link pendingProposalsCommitRank}. A `send` commits pending proposals
|
|
1628
|
+
* itself first, so a proposal never blocks a message.
|
|
1629
|
+
*/
|
|
1630
|
+
async commitPendingProposals(id, nowMs = this.now()) {
|
|
1631
|
+
await this.call({ kind: "commitPendingProposals", id: this.nextId++, conv: id, nowMs });
|
|
1632
|
+
}
|
|
1633
|
+
/**
|
|
1634
|
+
* This device's rank in the deterministic election of who commits a
|
|
1635
|
+
* conversation's pending proposals: members by leaf index, excluding any
|
|
1636
|
+
* leaf a pending proposal removes; identical on every member. `0` means
|
|
1637
|
+
* commit now; rank `n` means wait `n` intervals (a few seconds each), then
|
|
1638
|
+
* commit if the proposals are still pending. `null` when nothing is pending
|
|
1639
|
+
* or this device is not eligible.
|
|
1640
|
+
*/
|
|
1641
|
+
async pendingProposalsCommitRank(id) {
|
|
1642
|
+
const rank = await this.call({
|
|
1643
|
+
kind: "pendingProposalsCommitRank",
|
|
1644
|
+
id: this.nextId++,
|
|
1645
|
+
conv: id
|
|
1646
|
+
});
|
|
1647
|
+
return rank ?? null;
|
|
1648
|
+
}
|
|
1649
|
+
/**
|
|
1650
|
+
* The Commits this device holds in doubt: a Commit whose send got no
|
|
1651
|
+
* definite answer (no response, a 5xx) is neither merged nor discarded; the
|
|
1652
|
+
* SDK settles it on a capped exponential backoff, and every operation in
|
|
1653
|
+
* that conversation fails with `commit in doubt` until it settles. Retry
|
|
1654
|
+
* such an operation at `nextAttemptAtMs`.
|
|
1655
|
+
*/
|
|
1656
|
+
async commitsInDoubt() {
|
|
1657
|
+
const raw = await this.call({ kind: "commitsInDoubt", id: this.nextId++ });
|
|
1658
|
+
return raw.map(commitInDoubtFromWire);
|
|
1659
|
+
}
|
|
1660
|
+
/**
|
|
1661
|
+
* Member roster for a conversation, recovered locally from the MLS
|
|
1662
|
+
* group's leaf credentials (no network, no out-of-band message). Returns
|
|
1663
|
+
* one entry per device leaf — a multi-device user appears multiple times,
|
|
1664
|
+
* so dedup by `user_id` for a per-user roster. Empty for an unknown id.
|
|
1665
|
+
*/
|
|
1666
|
+
async members(conv) {
|
|
1667
|
+
return await this.call({ kind: "members", id: this.nextId++, conv });
|
|
1668
|
+
}
|
|
1669
|
+
/**
|
|
1670
|
+
* A conversation's credential policy (account-signed device credentials,
|
|
1671
|
+
* 2026-11-04): whether every leaf must carry a credential the account key signed
|
|
1672
|
+
* (`credentialsRequired`; a KeyPackage without one gets the add verdict
|
|
1673
|
+
* `credentialMissing`), the roles once the policy records them (round 2), and
|
|
1674
|
+
* `incapableMembers`, the accounts with a member on an app too old for this
|
|
1675
|
+
* group, which is what blocks the upgrade. Rejects for a conversation this client
|
|
1676
|
+
* does not hold. No host action is needed for the credentials themselves: the SDK
|
|
1677
|
+
* signs and verifies them internally.
|
|
1678
|
+
*/
|
|
1679
|
+
async conversationPolicy(conv) {
|
|
1680
|
+
return await this.call({ kind: "conversationPolicy", id: this.nextId++, conv });
|
|
1681
|
+
}
|
|
1682
|
+
/**
|
|
1683
|
+
* Whether a Commit of THIS device that re-admits or adds the device `deviceId` of
|
|
1684
|
+
* the account `identity` would pass the membership rules of the conversation in
|
|
1685
|
+
* its state now, without building or sending anything (2026-11-18). True when
|
|
1686
|
+
* this device may add a leaf of that account (the owner, an admin, or a device of
|
|
1687
|
+
* that same account; a device of the OWNER only when this device is the owner's)
|
|
1688
|
+
* and, if `deviceId` holds a leaf there, may also remove that leaf. Always true in
|
|
1689
|
+
* a conversation without roles. Ask it BEFORE leasing a re-admission request or
|
|
1690
|
+
* claiming a KeyPackage: a device that is not privileged never claims another
|
|
1691
|
+
* account's KeyPackage. Advisory: the Commit is judged again when it is built and
|
|
1692
|
+
* by every receiver. Rejects for a conversation this client does not hold.
|
|
1693
|
+
*/
|
|
1694
|
+
async mayReadmit(conv, identity, deviceId) {
|
|
1695
|
+
return await this.call({ kind: "mayReadmit", id: this.nextId++, conv, identity, deviceId });
|
|
1696
|
+
}
|
|
1697
|
+
/**
|
|
1698
|
+
* The identity (the account's user id) a KeyPackage's credential CLAIMS, read
|
|
1699
|
+
* without changing anything (2026-11-18, rule R13). `null` for a credential that
|
|
1700
|
+
* is not the project's. Rejects for bytes that are not a valid KeyPackage: the
|
|
1701
|
+
* checks OpenMLS runs on a KeyPackage an add carries run first (both signatures
|
|
1702
|
+
* under the leaf's own key, the version, the init key, the extensions against the
|
|
1703
|
+
* capabilities, the lifetime: an expired KeyPackage rejects).
|
|
1704
|
+
*
|
|
1705
|
+
* Before adding ANOTHER account's device, read it and compare it with the account
|
|
1706
|
+
* you meant to add, byte for byte; a different answer, or `null`, is enough to
|
|
1707
|
+
* refuse the KeyPackage the server handed out, before any Commit.
|
|
1708
|
+
*
|
|
1709
|
+
* The read runs the SAME credential verdict the add runs (the device
|
|
1710
|
+
* credential, then the leaf-ready check) and rejects for a claim the add
|
|
1711
|
+
* would refuse, so an identity answered is one the account's key vouched
|
|
1712
|
+
* for (rulings part 13, ruling 1; until then the answer was a bare claim).
|
|
1713
|
+
*/
|
|
1714
|
+
async keyPackageIdentity(keyPackage) {
|
|
1715
|
+
const identity = await this.call({
|
|
1716
|
+
kind: "keyPackageIdentity",
|
|
1717
|
+
id: this.nextId++,
|
|
1718
|
+
keyPackage
|
|
1719
|
+
});
|
|
1720
|
+
return identity ?? null;
|
|
1721
|
+
}
|
|
1722
|
+
/**
|
|
1723
|
+
* Replace the owners this client expects first roles writes to name
|
|
1724
|
+
* (2026-11-04, round 2; see `ClientConfig.expectedOwners`).
|
|
1725
|
+
*/
|
|
1726
|
+
async setExpectedOwners(entries) {
|
|
1727
|
+
await this.call({ kind: "setExpectedOwners", id: this.nextId++, entries });
|
|
1728
|
+
}
|
|
1729
|
+
/**
|
|
1730
|
+
* Record a group's roles in its policy (2026-11-04, round 2): `owner` and
|
|
1731
|
+
* `admins` as MLS user ids (map account ids through the roster). One
|
|
1732
|
+
* GroupContextExtensions Commit, no Welcome, send-then-merge. Rejects with
|
|
1733
|
+
* "not permitted ..." before anything is sent when this device's role does not
|
|
1734
|
+
* allow the change, when a member's app is too old for roles
|
|
1735
|
+
* (`conversationPolicy().incapableMembers` names it), or in the DeviceGroup.
|
|
1736
|
+
* The same call as `getConversation(id).setConversationRoles`.
|
|
1737
|
+
*/
|
|
1738
|
+
async setConversationRoles(conv, owner, admins) {
|
|
1739
|
+
await this.call({
|
|
1740
|
+
kind: "setConversationRoles",
|
|
1741
|
+
id: this.nextId++,
|
|
1742
|
+
conv,
|
|
1743
|
+
owner,
|
|
1744
|
+
admins,
|
|
1745
|
+
nowMs: this.now()
|
|
1746
|
+
});
|
|
1747
|
+
}
|
|
1748
|
+
/**
|
|
1749
|
+
* Whole-account catch-up. The worker runs it one conversation at a time and
|
|
1750
|
+
* lets every other request (a `send` the user is waiting on, a live frame)
|
|
1751
|
+
* run between conversations, so a pass over many conversations never parks
|
|
1752
|
+
* an interactive call behind all of them. Resolves when every conversation
|
|
1753
|
+
* held at the start of the pass (plus any joined while it ran) has been
|
|
1754
|
+
* paged, with the decrypted application messages in apply order.
|
|
1755
|
+
*/
|
|
1756
|
+
async syncConversations() {
|
|
1757
|
+
return await this.call({
|
|
1758
|
+
kind: "syncConversations",
|
|
1759
|
+
id: this.nextId++,
|
|
1760
|
+
nowMs: this.now()
|
|
1761
|
+
});
|
|
1762
|
+
}
|
|
1763
|
+
/**
|
|
1764
|
+
* Catch-up for ONE conversation: the unit `syncConversations` is built from.
|
|
1765
|
+
* Use it to bring the conversation the user is looking at up to date ahead
|
|
1766
|
+
* of the rest (a message must be encrypted at the epoch the group is really
|
|
1767
|
+
* at, so a host calls this before the first send after a reconnect), or to
|
|
1768
|
+
* step a pass in an order of its own. Rejects with the SDK's
|
|
1769
|
+
* `unknown conversation` error for an id this client does not hold.
|
|
1770
|
+
*/
|
|
1771
|
+
async syncConversation(id) {
|
|
1772
|
+
return await this.call({
|
|
1773
|
+
kind: "syncConversation",
|
|
1774
|
+
id: this.nextId++,
|
|
1775
|
+
conv: id,
|
|
1776
|
+
nowMs: this.now()
|
|
1777
|
+
});
|
|
1778
|
+
}
|
|
1779
|
+
async processEnvelope(envelope) {
|
|
1780
|
+
return await this.call({
|
|
1781
|
+
kind: "processEnvelope",
|
|
1782
|
+
id: this.nextId++,
|
|
1783
|
+
envelope,
|
|
1784
|
+
nowMs: this.now()
|
|
1785
|
+
});
|
|
1786
|
+
}
|
|
1787
|
+
// ------------------------ Sequenced log sync ------------------------
|
|
1788
|
+
// See docs/SYNC_PROTOCOL.md "Sequenced log sync". The subscribe path feeds
|
|
1789
|
+
// these itself for a transport that hands over sequenced frames; they are
|
|
1790
|
+
// public for hosts that drive their own socket.
|
|
1791
|
+
/**
|
|
1792
|
+
* Apply a batch of live frames, each with its server log position, and
|
|
1793
|
+
* checkpoint once per touched conversation. Per conversation: the next
|
|
1794
|
+
* position applies, one ahead of a hole is held and reported in `gaps`,
|
|
1795
|
+
* one at or below the applied position is a duplicate. Welcomes are routed
|
|
1796
|
+
* to a join inside the SDK (a join anchors the new conversation at the
|
|
1797
|
+
* Welcome's position); own-device echoes advance the position without
|
|
1798
|
+
* touching MLS, so pass them through. Frames at `serverSeq` 0 take the
|
|
1799
|
+
* legacy per-sender path.
|
|
1800
|
+
*
|
|
1801
|
+
* The decrypted messages are returned AND delivered: to `onMessageBatch`
|
|
1802
|
+
* handlers as one call (source `live`) when any is registered, else per
|
|
1803
|
+
* message to `onMessage` handlers. `onConversationUpdated` fires once per
|
|
1804
|
+
* entry of `updated`. A reported gap starts {@link fillGap} for that
|
|
1805
|
+
* conversation.
|
|
1806
|
+
*/
|
|
1807
|
+
async processSequencedBatch(items) {
|
|
1808
|
+
const raw = await this.call({
|
|
1809
|
+
kind: "processSequencedBatch",
|
|
1810
|
+
id: this.nextId++,
|
|
1811
|
+
items: items.map(sequencedToWire),
|
|
1812
|
+
nowMs: this.now()
|
|
1813
|
+
});
|
|
1814
|
+
const result = applyBatchResultFromWire(raw);
|
|
1815
|
+
this.fanout.deliverBatch(result.messages, { source: "live" });
|
|
1816
|
+
this.scheduleGapFills(result);
|
|
1817
|
+
return result;
|
|
1818
|
+
}
|
|
1819
|
+
/**
|
|
1820
|
+
* ONE page of a conversation's server log through `Transport.fetchLogSince`,
|
|
1821
|
+
* applied in order and checkpointed once, then whatever held frames the
|
|
1822
|
+
* page made contiguous. `hasMore` means step again. Same delivery as
|
|
1823
|
+
* {@link processSequencedBatch}, with source `page`. An ordinary request:
|
|
1824
|
+
* it runs ahead of any background pass, so a host can bring the open chat
|
|
1825
|
+
* current first. Rejects with the SDK's `unknown conversation` error for an
|
|
1826
|
+
* id this client does not hold; the durable cursor is unchanged on a
|
|
1827
|
+
* transport failure.
|
|
1828
|
+
*/
|
|
1829
|
+
async syncConversationStep(id) {
|
|
1830
|
+
return this.stepConversation(id, false);
|
|
1831
|
+
}
|
|
1832
|
+
/**
|
|
1833
|
+
* Fill a conversation's gap: run {@link syncConversationStep} until
|
|
1834
|
+
* `hasMore` is false, single-flight per conversation, on the worker's
|
|
1835
|
+
* stepped lane so a send posted meanwhile goes between pages. The SDK
|
|
1836
|
+
* starts this itself for every gap a batch reports; hosts call it for the
|
|
1837
|
+
* heads a socket `resume_ack` shows above the local position. A call
|
|
1838
|
+
* while a fill is running rides on it (and the loop runs once more after,
|
|
1839
|
+
* in case the running one ended before the new gap's rows were appended).
|
|
1840
|
+
*/
|
|
1841
|
+
fillGap(conversationId) {
|
|
1842
|
+
return this.gapFiller.fill(hexOf(conversationId), async () => {
|
|
1843
|
+
const page = await this.stepConversation(conversationId, true);
|
|
1844
|
+
return page.hasMore;
|
|
1845
|
+
});
|
|
1846
|
+
}
|
|
1847
|
+
/**
|
|
1848
|
+
* This device's applied position in every conversation it holds, sorted by
|
|
1849
|
+
* conversation id: what a host puts in its socket resume frame and
|
|
1850
|
+
* compares against the server's heads.
|
|
1851
|
+
*/
|
|
1852
|
+
async logPositions() {
|
|
1853
|
+
const raw = await this.call({ kind: "logPositions", id: this.nextId++ });
|
|
1854
|
+
return raw.map(logPositionFromWire);
|
|
1855
|
+
}
|
|
1856
|
+
/** This device's applied position in one conversation; `null` when not held. */
|
|
1857
|
+
async logPosition(id) {
|
|
1858
|
+
const raw = await this.call({ kind: "logPosition", id: this.nextId++, conv: id });
|
|
1859
|
+
return raw === null || raw === void 0 ? null : logPositionFromWire(raw);
|
|
1860
|
+
}
|
|
1861
|
+
/**
|
|
1862
|
+
* Anchor a conversation whose cursor predates positions at the
|
|
1863
|
+
* `(epoch, serverSeq)` the host had recorded for it, so an existing install
|
|
1864
|
+
* does not page its whole current epoch again. Resolves `false` (a no-op)
|
|
1865
|
+
* when the conversation is already anchored; the MLS epoch is never
|
|
1866
|
+
* touched. Call it once at start-up for every conversation the host's own
|
|
1867
|
+
* cursor store holds a position for.
|
|
1868
|
+
*/
|
|
1869
|
+
async adoptLogPosition(id, epoch, serverSeq) {
|
|
1870
|
+
return await this.call({
|
|
1871
|
+
kind: "adoptLogPosition",
|
|
1872
|
+
id: this.nextId++,
|
|
1873
|
+
conv: id,
|
|
1874
|
+
epoch,
|
|
1875
|
+
serverSeq
|
|
1876
|
+
});
|
|
1877
|
+
}
|
|
1878
|
+
/**
|
|
1879
|
+
* Conversations the server's heads show this device is behind on: not
|
|
1880
|
+
* anchored yet, a head above the applied position, or frames held in the
|
|
1881
|
+
* reorder buffer. Sorted by id. A held conversation absent from `heads` is
|
|
1882
|
+
* not listed.
|
|
1883
|
+
*/
|
|
1884
|
+
async conversationsBehind(heads) {
|
|
1885
|
+
return await this.call({
|
|
1886
|
+
kind: "conversationsBehind",
|
|
1887
|
+
id: this.nextId++,
|
|
1888
|
+
heads: heads.map(logHeadToWire)
|
|
1889
|
+
});
|
|
1890
|
+
}
|
|
1891
|
+
/** Frames held in reorder buffers right now (diagnostics). */
|
|
1892
|
+
async heldFrameCount() {
|
|
1893
|
+
return await this.call({ kind: "heldFrameCount", id: this.nextId++ });
|
|
1894
|
+
}
|
|
1895
|
+
/**
|
|
1896
|
+
* {@link joinConversation} at the Welcome's log position, so the new
|
|
1897
|
+
* conversation is anchored there and its first live frame applies without
|
|
1898
|
+
* a page. Pass `null` (or omit) when the position is unknown.
|
|
1899
|
+
*/
|
|
1900
|
+
async joinConversationAt(welcome, position = null) {
|
|
1901
|
+
const idBytes = await this.call({
|
|
1902
|
+
kind: "joinConversationAt",
|
|
1903
|
+
id: this.nextId++,
|
|
1904
|
+
welcome,
|
|
1905
|
+
position,
|
|
1906
|
+
nowMs: this.now()
|
|
1907
|
+
});
|
|
1908
|
+
return this.conversationProxy(idBytes);
|
|
1909
|
+
}
|
|
1910
|
+
/**
|
|
1911
|
+
* The Welcome routing rule at a known position: joins when the conversation
|
|
1912
|
+
* is unknown or held stranded and resolves to it, resolves `null` when it
|
|
1913
|
+
* is held healthy (a relay duplicate), rejects when the Welcome is not
|
|
1914
|
+
* addressed to this device.
|
|
1915
|
+
*/
|
|
1916
|
+
async processWelcomeAt(welcome, position = null) {
|
|
1917
|
+
const idBytes = await this.call({
|
|
1918
|
+
kind: "processWelcomeAt",
|
|
1919
|
+
id: this.nextId++,
|
|
1920
|
+
welcome,
|
|
1921
|
+
position,
|
|
1922
|
+
nowMs: this.now()
|
|
1923
|
+
});
|
|
1924
|
+
return idBytes === null || idBytes === void 0 ? null : this.conversationProxy(idBytes);
|
|
1925
|
+
}
|
|
1926
|
+
/**
|
|
1927
|
+
* [D27] Decrypted-but-unconfirmed messages surviving in the pending-apply
|
|
1928
|
+
* journal, oldest first.
|
|
1929
|
+
*
|
|
1930
|
+
* The MLS ratchet advances at decrypt, BEFORE the host persists its own row
|
|
1931
|
+
* for the message; a crash inside that gap used to lose the message for good
|
|
1932
|
+
* (the server re-delivers, but MLS cannot re-decrypt a consumed generation).
|
|
1933
|
+
* The SDK now journals every decrypt in the same checkpoint that persists
|
|
1934
|
+
* the ratchet advance.
|
|
1935
|
+
*
|
|
1936
|
+
* CRASH-RECOVERY CONTRACT: on boot, BEFORE advancing any sync cursor or
|
|
1937
|
+
* sending any delivery ack, drain this list through the normal ingest —
|
|
1938
|
+
* dedup by `content_hash` / envelope identity exactly as for a redelivered
|
|
1939
|
+
* envelope — persist each message, then {@link confirmApplied} the drained
|
|
1940
|
+
* ids. Reading does not consume; unconfirmed entries survive further
|
|
1941
|
+
* restarts (bounded: 512 entries / 4 MiB, oldest evicted). See
|
|
1942
|
+
* docs/PENDING_APPLIES.md.
|
|
1943
|
+
*/
|
|
1944
|
+
async pendingApplies() {
|
|
1945
|
+
return await this.call({ kind: "pendingApplies", id: this.nextId++ });
|
|
1946
|
+
}
|
|
1947
|
+
/**
|
|
1948
|
+
* [D27] Delete journal entries whose messages the host has durably
|
|
1949
|
+
* persisted (`IncomingMessage.journal_id` from live processing, or
|
|
1950
|
+
* `PendingApply.journal_id` from a boot drain), and checkpoint so the
|
|
1951
|
+
* deletion survives a reload. Unknown ids are ignored (idempotent).
|
|
1952
|
+
*/
|
|
1953
|
+
async confirmApplied(journalIds) {
|
|
1954
|
+
if (journalIds.length === 0) return;
|
|
1955
|
+
await this.call({ kind: "confirmApplied", id: this.nextId++, journalIds });
|
|
1956
|
+
}
|
|
1957
|
+
/**
|
|
1958
|
+
* Build a `LinkingTicket` for a new device.
|
|
1959
|
+
*
|
|
1960
|
+
* [CR-13] `lastAppEvents` is host-supplied per-conversation "what you missed" data
|
|
1961
|
+
* (decrypted AppEvent bytes the new device will render before sync catches up).
|
|
1962
|
+
* Pass `[]` to suppress catchup data — the new device will see an empty conversation
|
|
1963
|
+
* list until normal sync runs.
|
|
1964
|
+
*
|
|
1965
|
+
* Caller is responsible for HPKE-sealing the returned ticket via
|
|
1966
|
+
* `MessagingClient.sealLinkingTicket` before transmitting (CR-3).
|
|
1967
|
+
*
|
|
1968
|
+
* Rejects (`Invalid`), before anything is sent, a KeyPackage that claims the
|
|
1969
|
+
* identity of another account this client knows: a new device links under an
|
|
1970
|
+
* identity of its own, or the account's.
|
|
1971
|
+
*/
|
|
1972
|
+
async buildLinkingTicket(newDeviceId, newDeviceKp, lastAppEvents = []) {
|
|
1973
|
+
return await this.call({
|
|
1974
|
+
kind: "buildLinkingTicket",
|
|
1975
|
+
id: this.nextId++,
|
|
1976
|
+
newDeviceId,
|
|
1977
|
+
newDeviceKp,
|
|
1978
|
+
lastAppEvents,
|
|
1979
|
+
nowMs: this.now()
|
|
1980
|
+
});
|
|
1981
|
+
}
|
|
1982
|
+
/**
|
|
1983
|
+
* Decode a `LinkingTicket.catchup_snapshot` blob ([CR-13]).
|
|
1984
|
+
*
|
|
1985
|
+
* Pure WASM — runs in an ephemeral worker so the new device can call this before
|
|
1986
|
+
* `MessagingClient.init()` completes (just like `openLinkingTicket`). Returns the
|
|
1987
|
+
* structured view: per-conversation metas + last-known AppEvent bytes.
|
|
1988
|
+
*
|
|
1989
|
+
* Throws on malformed or oversized inputs. Empty bytes return `null` — that's the
|
|
1990
|
+
* "no catchup data" case (sender passed `[]` to buildLinkingTicket).
|
|
1991
|
+
*/
|
|
1992
|
+
static async decodeCatchupSnapshot(snapshotBytes) {
|
|
1993
|
+
if (snapshotBytes.length === 0) return null;
|
|
1994
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
1995
|
+
kind: "decodeCatchupSnapshot",
|
|
1996
|
+
id: 1,
|
|
1997
|
+
snapshotBytes
|
|
1998
|
+
});
|
|
1999
|
+
}
|
|
2000
|
+
async consumeLinkingTicket(ticket) {
|
|
2001
|
+
await this.call({
|
|
2002
|
+
kind: "consumeLinkingTicket",
|
|
2003
|
+
id: this.nextId++,
|
|
2004
|
+
ticket,
|
|
2005
|
+
nowMs: this.now()
|
|
2006
|
+
});
|
|
2007
|
+
}
|
|
2008
|
+
// ------------------------ Recovery (account backup) ------------------------
|
|
2009
|
+
// All static + stateless: they run on an ephemeral worker, so the recovery screen can
|
|
2010
|
+
// call them before any client is initialised. Same Argon2id/AES-256-GCM IdentityBackup
|
|
2011
|
+
// wire format as the iOS/Android FFI bindings — backups are portable across platforms.
|
|
2012
|
+
/** Generate a fresh 12-word BIP39 mnemonic, returned as its canonical phrase string. */
|
|
2013
|
+
static async generateMnemonicPhrase() {
|
|
2014
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
2015
|
+
kind: "generateMnemonicPhrase",
|
|
2016
|
+
id: 1
|
|
2017
|
+
});
|
|
2018
|
+
}
|
|
2019
|
+
/** Validate + canonicalise a user-entered phrase (BIP39 wordlist + checksum). Rejects
|
|
2020
|
+
* malformed input. Use on the recovery screen before calling `decryptBackup`. */
|
|
2021
|
+
static async normalizeMnemonicPhrase(phrase) {
|
|
2022
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
2023
|
+
kind: "normalizeMnemonicPhrase",
|
|
2024
|
+
id: 1,
|
|
2025
|
+
phrase
|
|
2026
|
+
});
|
|
2027
|
+
}
|
|
2028
|
+
/** Encrypt an IdentityBackup for `POST /v1/recovery/blobs`. `deviceGroupSnapshot` may be
|
|
2029
|
+
* empty (Conservative path) or the DeviceGroup's `exportConversationStateSnapshot`. */
|
|
2030
|
+
static async encryptBackup(args) {
|
|
2031
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
2032
|
+
kind: "encryptBackup",
|
|
2033
|
+
id: 1,
|
|
2034
|
+
mnemonicPhrase: args.mnemonicPhrase,
|
|
2035
|
+
accountId: args.accountId,
|
|
2036
|
+
identityExport: args.identityExport,
|
|
2037
|
+
deviceGroupSnapshot: args.deviceGroupSnapshot,
|
|
2038
|
+
conversationSnapshots: args.conversationSnapshots ?? [],
|
|
2039
|
+
createdAtMs: args.createdAtMs
|
|
2040
|
+
});
|
|
2041
|
+
}
|
|
2042
|
+
/** Decrypt a recovery blob from `GET /v1/recovery/blobs`. Throws on wrong mnemonic or a
|
|
2043
|
+
* tampered blob. The returned `identity_export` is the secret seed for `init`. */
|
|
2044
|
+
static async decryptBackup(blob, mnemonicPhrase) {
|
|
2045
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
2046
|
+
kind: "decryptBackup",
|
|
2047
|
+
id: 1,
|
|
2048
|
+
blob,
|
|
2049
|
+
mnemonicPhrase
|
|
2050
|
+
});
|
|
2051
|
+
}
|
|
2052
|
+
// ------------------------ Peer-assisted history transfer ------------------------
|
|
2053
|
+
// Authenticated (sign-then-encrypt) device-to-device history used by linking and
|
|
2054
|
+
// post-recovery peer re-add. Confidential to the recipient's ephemeral X25519 key AND
|
|
2055
|
+
// signed by the account identity key, so the receiver proves the sender. Plaintext-only
|
|
2056
|
+
// share — preserves forward secrecy (no MLS keys leave the device).
|
|
2057
|
+
/** Seal+sign a `HistoryBundle` for a recipient device. `recipientPub` (X25519, 32B) is the
|
|
2058
|
+
* recipient's ephemeral pubkey from the linking QR; `senderIdentitySecret` (Ed25519 seed,
|
|
2059
|
+
* 32B) is this account's identity key. Returns the blob to POST to /v1/history-transfers. */
|
|
2060
|
+
static async sealHistoryBundle(bundle, recipientPub, senderIdentitySecret) {
|
|
2061
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
2062
|
+
kind: "sealHistoryBundle",
|
|
2063
|
+
id: 1,
|
|
2064
|
+
bundle,
|
|
2065
|
+
recipientPub,
|
|
2066
|
+
senderIdentitySecret
|
|
2067
|
+
});
|
|
2068
|
+
}
|
|
2069
|
+
/** Open+verify a sealed history bundle. `recipientPriv` (X25519, 32B) is this device's
|
|
2070
|
+
* ephemeral private key; `senderIdentityPub` (Ed25519, 32B) is the account identity pubkey
|
|
2071
|
+
* from the linking handshake. Throws if the signature doesn't verify. */
|
|
2072
|
+
static async openHistoryBundle(sealed, recipientPriv, senderIdentityPub) {
|
|
2073
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
2074
|
+
kind: "openHistoryBundle",
|
|
2075
|
+
id: 1,
|
|
2076
|
+
sealed,
|
|
2077
|
+
recipientPriv,
|
|
2078
|
+
senderIdentityPub
|
|
2079
|
+
});
|
|
2080
|
+
}
|
|
2081
|
+
/**
|
|
2082
|
+
* Post-quantum {@link sealHistoryBundle}: `recipientPub` is the recipient's
|
|
2083
|
+
* X-Wing public key ({@link HPKE_PQ_PUBLIC_KEY_BYTES} bytes). Wrapper `v: 2`;
|
|
2084
|
+
* the classical open refuses it and vice versa.
|
|
2085
|
+
*/
|
|
2086
|
+
static async sealHistoryBundlePq(bundle, recipientPub, senderIdentitySecret) {
|
|
2087
|
+
if (recipientPub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {
|
|
2088
|
+
throw new Error(`sealHistoryBundlePq: recipientPub must be ${HPKE_PQ_PUBLIC_KEY_BYTES} bytes`);
|
|
2089
|
+
}
|
|
2090
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
2091
|
+
kind: "sealHistoryBundlePq",
|
|
2092
|
+
id: 1,
|
|
2093
|
+
bundle,
|
|
2094
|
+
recipientPub,
|
|
2095
|
+
senderIdentitySecret
|
|
2096
|
+
});
|
|
2097
|
+
}
|
|
2098
|
+
/** Post-quantum {@link openHistoryBundle}: `recipientPriv` is the 32-byte X-Wing seed. */
|
|
2099
|
+
static async openHistoryBundlePq(sealed, recipientPriv, senderIdentityPub) {
|
|
2100
|
+
if (recipientPriv.length !== 32) {
|
|
2101
|
+
throw new Error("openHistoryBundlePq: recipientPriv must be 32 bytes");
|
|
2102
|
+
}
|
|
2103
|
+
return _MessagingClient.ephemeralWorkerCall({
|
|
2104
|
+
kind: "openHistoryBundlePq",
|
|
2105
|
+
id: 1,
|
|
2106
|
+
sealed,
|
|
2107
|
+
recipientPriv,
|
|
2108
|
+
senderIdentityPub
|
|
2109
|
+
});
|
|
2110
|
+
}
|
|
2111
|
+
/**
|
|
2112
|
+
* Admit a freshly-linked device to every chat in `entries` — one MLS
|
|
2113
|
+
* Commit + Welcome per chat, with the Welcome's `?recipient=` priming
|
|
2114
|
+
* handled inside the SDK. This is the post-link reconciliation step
|
|
2115
|
+
* that follows `consumeLinkingTicket`: the new device has the
|
|
2116
|
+
* DeviceGroup (from the ticket) and metadata for external chats (from
|
|
2117
|
+
* the catchup snapshot), but its leaf is not yet in any external
|
|
2118
|
+
* MLS group. The host on the EXISTING device calls this once the
|
|
2119
|
+
* new device shows up in `/v1/auth/sessions` and has uploaded its
|
|
2120
|
+
* KeyPackage batch, passing one freshly-claimed KP per chat.
|
|
2121
|
+
*
|
|
2122
|
+
* Per-chat failures (stale KP, transport error, unknown chat) are
|
|
2123
|
+
* captured in the returned outcomes rather than aborting — one bad
|
|
2124
|
+
* chat shouldn't lose the user access to all the others.
|
|
2125
|
+
*
|
|
2126
|
+
* Each KeyPackage must carry this account's identity (a linked device
|
|
2127
|
+
* adopts it with the link): one that claims any other identity fails its
|
|
2128
|
+
* chat and nothing is sent there.
|
|
2129
|
+
*/
|
|
2130
|
+
async admitDeviceToChats(deviceId, entries) {
|
|
2131
|
+
return await this.call({
|
|
2132
|
+
kind: "admitDeviceToChats",
|
|
2133
|
+
id: this.nextId++,
|
|
2134
|
+
deviceId,
|
|
2135
|
+
entries,
|
|
2136
|
+
nowMs: this.now()
|
|
2137
|
+
});
|
|
2138
|
+
}
|
|
2139
|
+
/**
|
|
2140
|
+
* `admitDeviceToChats` with up to `concurrency` admissions in flight at
|
|
2141
|
+
* once. Same input, same per-chat outcomes in INPUT order whatever order
|
|
2142
|
+
* the sends finish in; `concurrency` 1 is exactly `admitDeviceToChats`,
|
|
2143
|
+
* 0 is treated as 1. Safe because every admission is its own conversation
|
|
2144
|
+
* (one Commit + Welcome per chat, the conversation lock is never held
|
|
2145
|
+
* across the send), so two admissions never touch the same epoch.
|
|
2146
|
+
*
|
|
2147
|
+
* This is the ONLY way to overlap admissions on web: the worker runs one
|
|
2148
|
+
* call at a time, so several `admitDeviceToChats` calls issued together
|
|
2149
|
+
* still run one after another. The overlap happens inside this one call.
|
|
2150
|
+
*/
|
|
2151
|
+
async admitDeviceToChatsConcurrent(deviceId, entries, concurrency) {
|
|
2152
|
+
const lanes = Number.isFinite(concurrency) ? Math.min(4294967295, Math.max(1, Math.floor(concurrency))) : 1;
|
|
2153
|
+
return await this.call({
|
|
2154
|
+
kind: "admitDeviceToChatsConcurrent",
|
|
2155
|
+
id: this.nextId++,
|
|
2156
|
+
deviceId,
|
|
2157
|
+
entries,
|
|
2158
|
+
nowMs: this.now(),
|
|
2159
|
+
concurrency: lanes
|
|
2160
|
+
});
|
|
2161
|
+
}
|
|
2162
|
+
/**
|
|
2163
|
+
* Revoke a device ([CR-2]).
|
|
2164
|
+
*
|
|
2165
|
+
* Removes `deviceId`'s leaf from every conversation where this client locally
|
|
2166
|
+
* tracked the device→leaf mapping (i.e. conversations where this client itself
|
|
2167
|
+
* admitted the device via `addMembers`, or where this client is the device being
|
|
2168
|
+
* revoked). The SDK has already broadcast each Commit envelope via
|
|
2169
|
+
* `transport.send`; the returned array is for any additional host-side handling
|
|
2170
|
+
* (audit logs, UI). An empty array is a valid outcome — the device wasn't locally
|
|
2171
|
+
* known anywhere.
|
|
2172
|
+
*
|
|
2173
|
+
* **Scope note.** Conversations where a peer admitted the device on this client's
|
|
2174
|
+
* behalf are silently skipped — the leaf index isn't locally known. Host can fall
|
|
2175
|
+
* back to `transport.discoverDevices` + a manual `remove_members(leafIndex)` for
|
|
2176
|
+
* those, or wait for the affected user to revoke from a device that did the admit.
|
|
2177
|
+
* See `docs/architecture/multi-device.md §Device removal`.
|
|
2178
|
+
*/
|
|
2179
|
+
async revokeDevice(deviceId) {
|
|
2180
|
+
return await this.call({
|
|
2181
|
+
kind: "revokeDevice",
|
|
2182
|
+
id: this.nextId++,
|
|
2183
|
+
deviceId,
|
|
2184
|
+
nowMs: this.now()
|
|
2185
|
+
});
|
|
2186
|
+
}
|
|
2187
|
+
/**
|
|
2188
|
+
* Remove one of THIS account's devices from every group this client is in, the
|
|
2189
|
+
* DeviceGroup included, without stopping at a failure, and report where it stands.
|
|
2190
|
+
*
|
|
2191
|
+
* Unlike {@link revokeDevice}, the device's leaf is read from each ratchet tree (the
|
|
2192
|
+
* leaf whose key hashes to the id), so this reaches leaves a sibling or a peer
|
|
2193
|
+
* admitted. The id is the server's word that the device is this account's; outside
|
|
2194
|
+
* the DeviceGroup a leaf is removed only when its credential names this account, or
|
|
2195
|
+
* when the device was seen in the account's DeviceGroup and its credential names no
|
|
2196
|
+
* other account this client knows (docs/MULTIDEVICE.md, "Which leaf"). An id that
|
|
2197
|
+
* names no leaf of this account is rejected before anything is sent. Every held
|
|
2198
|
+
* conversation is checked: a Commit of this device in doubt is settled first, and
|
|
2199
|
+
* the log is read to its end before the device is reported absent (what that read
|
|
2200
|
+
* applies comes with the next batch or page); a conversation that failed to load
|
|
2201
|
+
* is a failure with reason `Unloadable`. The DeviceGroup goes first, then the
|
|
2202
|
+
* conversations, a few at a time, each a send-then-merge Commit. Persist the report
|
|
2203
|
+
* and call again until `failed` is empty and `deviceGroup !== "failed"`. A
|
|
2204
|
+
* `CommitInDoubt` reason settles on its own backoff ({@link commitsInDoubt});
|
|
2205
|
+
* `NotOwnAccount` and `RefusedCommit` never resolve by retrying (for
|
|
2206
|
+
* `RefusedCommit`, offer to recreate the conversation). Groups this device joins
|
|
2207
|
+
* later are checked for the device too.
|
|
2208
|
+
*
|
|
2209
|
+
* MLS only: revoke the device on the server yourself. Rejects for this device's own
|
|
2210
|
+
* id (leave a conversation with `leaveConversation` instead) and for a device that
|
|
2211
|
+
* is not this account's.
|
|
2212
|
+
*/
|
|
2213
|
+
async removeDeviceEverywhere(deviceId, nowMs = this.now()) {
|
|
2214
|
+
return await this.call({
|
|
2215
|
+
kind: "removeDeviceEverywhere",
|
|
2216
|
+
id: this.nextId++,
|
|
2217
|
+
deviceId,
|
|
2218
|
+
nowMs
|
|
2219
|
+
});
|
|
2220
|
+
}
|
|
2221
|
+
/**
|
|
2222
|
+
* Remove every other device of THIS account from every group this client is in,
|
|
2223
|
+
* except the devices in `keep` and this device: the "secure my account" sweep.
|
|
2224
|
+
*
|
|
2225
|
+
* `listed` is the server's list of this account's devices to remove (a reset's
|
|
2226
|
+
* `revoked_device_ids`). In the DeviceGroup every leaf but this device's and the
|
|
2227
|
+
* kept ones goes. Elsewhere a leaf goes when its credential names this client's
|
|
2228
|
+
* account (no device id has to match, so a device that moved its leaf to another
|
|
2229
|
+
* signature key is still reached), or when its device is in `listed` and was seen in
|
|
2230
|
+
* the account's DeviceGroup, whatever identity its leaf claims. A leaf the sweep
|
|
2231
|
+
* leaves although one of those two says it may be the account's (seen but not
|
|
2232
|
+
* listed, or listed but not seen) is reported: its conversation fails with
|
|
2233
|
+
* `NotOwnAccount`, so the report is never complete over it. Same pass and report as
|
|
2234
|
+
* {@link removeDeviceEverywhere}; call again until it is complete. MLS only.
|
|
2235
|
+
*/
|
|
2236
|
+
async removeOwnDevicesExcept(keep, listed, nowMs = this.now()) {
|
|
2237
|
+
return await this.call({
|
|
2238
|
+
kind: "removeOwnDevicesExcept",
|
|
2239
|
+
id: this.nextId++,
|
|
2240
|
+
keep,
|
|
2241
|
+
listed,
|
|
2242
|
+
nowMs
|
|
2243
|
+
});
|
|
2244
|
+
}
|
|
2245
|
+
/**
|
|
2246
|
+
* Export a portable MLS state snapshot for one conversation ([CR-7]).
|
|
2247
|
+
*
|
|
2248
|
+
* Returned bytes can be embedded in a recovery blob or shipped through a
|
|
2249
|
+
* linking ticket so another device of the same user identity can re-attach to
|
|
2250
|
+
* the group via [[importStateSnapshot]]. The bytes contain past epoch secrets;
|
|
2251
|
+
* never log, never persist unencrypted, wipe (`.fill(0)`) after use.
|
|
2252
|
+
*/
|
|
2253
|
+
async exportConversationStateSnapshot(conv) {
|
|
2254
|
+
return await this.call({
|
|
2255
|
+
kind: "exportConversationStateSnapshot",
|
|
2256
|
+
id: this.nextId++,
|
|
2257
|
+
conv,
|
|
2258
|
+
nowMs: this.now()
|
|
2259
|
+
});
|
|
2260
|
+
}
|
|
2261
|
+
/**
|
|
2262
|
+
* Import a `GroupStateSnapshot` from another device of the same user identity
|
|
2263
|
+
* ([CR-7]).
|
|
2264
|
+
*
|
|
2265
|
+
* On success, the conversation appears in [[listConversations]] and decryption
|
|
2266
|
+
* of subsequent peer-originated traffic works against the imported state. For
|
|
2267
|
+
* full multi-device participation, the recovered device SHOULD then issue an
|
|
2268
|
+
* MLS Update Proposal to rotate onto a fresh leaf (post-v1 follow-up — see
|
|
2269
|
+
* `docs/design/CR4_CR7_PERSISTENCE.md` open question #3).
|
|
2270
|
+
*/
|
|
2271
|
+
async importStateSnapshot(snapshotBytes) {
|
|
2272
|
+
return await this.call({
|
|
2273
|
+
kind: "importStateSnapshot",
|
|
2274
|
+
id: this.nextId++,
|
|
2275
|
+
snapshotBytes,
|
|
2276
|
+
nowMs: this.now()
|
|
2277
|
+
});
|
|
2278
|
+
}
|
|
2279
|
+
/**
|
|
2280
|
+
* Export a derived secret from a conversation's MLS exporter ([CR-8]).
|
|
2281
|
+
*
|
|
2282
|
+
* Used to seed the ephemeral channel (`ping/ephemeral`), call-media keys
|
|
2283
|
+
* (`ping/calls/media/<call_id>`), and call-ephemeral framer keys
|
|
2284
|
+
* (`ping/calls/ephemeral/<call_id>`). The returned bytes are a secret — never log,
|
|
2285
|
+
* persist only encrypted, and call `bytes.fill(0)` after use to wipe the typed array.
|
|
2286
|
+
*
|
|
2287
|
+
* Same `(conversationId, current_epoch, label, context, length)` produces the same
|
|
2288
|
+
* bytes across every binding (Rust core, native UniFFI, WASM/JS). Cross-platform
|
|
2289
|
+
* byte-equality is enforced by `protocol/conformance/export_secret/`.
|
|
2290
|
+
*/
|
|
2291
|
+
async exportConversationSecret(conv, label, context, length) {
|
|
2292
|
+
if (length <= 0 || length > 1024) {
|
|
2293
|
+
throw new Error("exportConversationSecret: length must be 1..=1024");
|
|
2294
|
+
}
|
|
2295
|
+
return await this.call({
|
|
2296
|
+
kind: "exportConversationSecret",
|
|
2297
|
+
id: this.nextId++,
|
|
2298
|
+
conv,
|
|
2299
|
+
label,
|
|
2300
|
+
context,
|
|
2301
|
+
length
|
|
2302
|
+
});
|
|
2303
|
+
}
|
|
2304
|
+
/**
|
|
2305
|
+
* Subscribe to decrypted application messages, one call per message. A
|
|
2306
|
+
* batch or page result (the sequenced paths) is fanned out here per
|
|
2307
|
+
* message only while no {@link onMessageBatch} handler is registered.
|
|
2308
|
+
*/
|
|
2309
|
+
onMessage(handler) {
|
|
2310
|
+
return this.fanout.onMessage(handler);
|
|
2311
|
+
}
|
|
2312
|
+
/**
|
|
2313
|
+
* Subscribe to decrypted messages one BATCH at a time: one call per
|
|
2314
|
+
* `processSequencedBatch` result (source `live`) or per page of the server
|
|
2315
|
+
* log (source `page`: a gap fill, or the whole-account catch-up), so the
|
|
2316
|
+
* host persists the batch in one store transaction. While at least one
|
|
2317
|
+
* batch handler is registered, batch and page results go ONLY here, never
|
|
2318
|
+
* per message to `onMessage`; the legacy per-envelope path still delivers
|
|
2319
|
+
* per message. An empty result is not delivered.
|
|
2320
|
+
*/
|
|
2321
|
+
onMessageBatch(handler) {
|
|
2322
|
+
return this.fanout.onMessageBatch(handler);
|
|
2323
|
+
}
|
|
2324
|
+
/** Fired after every state-changing event for a conversation (Commit, member changes). */
|
|
2325
|
+
/**
|
|
2326
|
+
* Fires after every conversation state change — joining via Welcome, processing a Commit,
|
|
2327
|
+
* etc. `sender` carries the device id of whoever triggered the event when known (e.g. the
|
|
2328
|
+
* inviter's device on auto-join), so the host can label peers in its UI.
|
|
2329
|
+
*/
|
|
2330
|
+
onConversationUpdated(handler) {
|
|
2331
|
+
this.conversationHandlers.add(handler);
|
|
2332
|
+
return () => this.conversationHandlers.delete(handler);
|
|
2333
|
+
}
|
|
2334
|
+
/**
|
|
2335
|
+
* Stop the live subscription and terminate the worker. Every call still in
|
|
2336
|
+
* flight rejects with a {@link MessagingClientClosedError} (reason
|
|
2337
|
+
* `closed`), and every later call rejects the same way instead of waiting
|
|
2338
|
+
* on a worker that no longer exists. Idempotent.
|
|
2339
|
+
*/
|
|
2340
|
+
async close() {
|
|
2341
|
+
if (this.closed) return;
|
|
2342
|
+
this.closed = true;
|
|
2343
|
+
this.subscription?.unsubscribe();
|
|
2344
|
+
this.worker.terminate();
|
|
2345
|
+
this.failPending(new MessagingClientClosedError("closed"));
|
|
2346
|
+
}
|
|
2347
|
+
/** Reject every pending call with `error` and forget them. */
|
|
2348
|
+
failPending(error) {
|
|
2349
|
+
const slots = [...this.pending.values()];
|
|
2350
|
+
this.pending.clear();
|
|
2351
|
+
for (const slot of slots) slot.reject(error);
|
|
2352
|
+
}
|
|
2353
|
+
// ------------------------ Internals ------------------------
|
|
2354
|
+
conversationProxy(id) {
|
|
2355
|
+
const self = this;
|
|
2356
|
+
return {
|
|
2357
|
+
id,
|
|
2358
|
+
async send(plaintext) {
|
|
2359
|
+
const heldEpoch = self.metaCache.get(hex(id))?.epoch;
|
|
2360
|
+
return await self.call({
|
|
2361
|
+
kind: "send",
|
|
2362
|
+
id: self.nextId++,
|
|
2363
|
+
conv: id,
|
|
2364
|
+
plaintext,
|
|
2365
|
+
nowMs: self.now(),
|
|
2366
|
+
...heldEpoch !== void 0 ? { heldEpoch } : {}
|
|
2367
|
+
});
|
|
2368
|
+
},
|
|
2369
|
+
async addMembers(entries) {
|
|
2370
|
+
await self.call({
|
|
2371
|
+
kind: "addMembers",
|
|
2372
|
+
id: self.nextId++,
|
|
2373
|
+
conv: id,
|
|
2374
|
+
entries,
|
|
2375
|
+
nowMs: self.now()
|
|
2376
|
+
});
|
|
2377
|
+
},
|
|
2378
|
+
async addMembersWithVerdicts(entries) {
|
|
2379
|
+
const raw = await self.call({
|
|
2380
|
+
kind: "addMembersWithVerdicts",
|
|
2381
|
+
id: self.nextId++,
|
|
2382
|
+
conv: id,
|
|
2383
|
+
entries,
|
|
2384
|
+
nowMs: self.now()
|
|
2385
|
+
});
|
|
2386
|
+
return addMembersReportFromWire(raw);
|
|
2387
|
+
},
|
|
2388
|
+
async reAdmitDevice(entry) {
|
|
2389
|
+
const replaced = await self.call({
|
|
2390
|
+
kind: "reAdmitDevice",
|
|
2391
|
+
id: self.nextId++,
|
|
2392
|
+
conv: id,
|
|
2393
|
+
entry,
|
|
2394
|
+
nowMs: self.now()
|
|
2395
|
+
});
|
|
2396
|
+
return replaced ?? null;
|
|
2397
|
+
},
|
|
2398
|
+
async removeOwnOtherLeaves() {
|
|
2399
|
+
return await self.call({
|
|
2400
|
+
kind: "removeOwnOtherLeaves",
|
|
2401
|
+
id: self.nextId++,
|
|
2402
|
+
conv: id,
|
|
2403
|
+
nowMs: self.now()
|
|
2404
|
+
});
|
|
2405
|
+
},
|
|
2406
|
+
async removeMembersByIdentity(identities) {
|
|
2407
|
+
return await self.call({
|
|
2408
|
+
kind: "removeMembersByIdentity",
|
|
2409
|
+
id: self.nextId++,
|
|
2410
|
+
conv: id,
|
|
2411
|
+
identities,
|
|
2412
|
+
nowMs: self.now()
|
|
2413
|
+
});
|
|
2414
|
+
},
|
|
2415
|
+
async removeMembers(leaves) {
|
|
2416
|
+
await self.call({
|
|
2417
|
+
kind: "removeMembers",
|
|
2418
|
+
id: self.nextId++,
|
|
2419
|
+
conv: id,
|
|
2420
|
+
leaves,
|
|
2421
|
+
nowMs: self.now()
|
|
2422
|
+
});
|
|
2423
|
+
},
|
|
2424
|
+
async setConversationName(name) {
|
|
2425
|
+
await self.call({
|
|
2426
|
+
kind: "setConversationName",
|
|
2427
|
+
id: self.nextId++,
|
|
2428
|
+
conv: id,
|
|
2429
|
+
name,
|
|
2430
|
+
nowMs: self.now()
|
|
2431
|
+
});
|
|
2432
|
+
},
|
|
2433
|
+
async setConversationRoles(owner, admins) {
|
|
2434
|
+
await self.call({
|
|
2435
|
+
kind: "setConversationRoles",
|
|
2436
|
+
id: self.nextId++,
|
|
2437
|
+
conv: id,
|
|
2438
|
+
owner,
|
|
2439
|
+
admins,
|
|
2440
|
+
nowMs: self.now()
|
|
2441
|
+
});
|
|
2442
|
+
},
|
|
2443
|
+
/**
|
|
2444
|
+
* The conversation's MLS GroupContext name as the group holds it now, or
|
|
2445
|
+
* `undefined` when it has none or the client holds no metadata for it.
|
|
2446
|
+
*
|
|
2447
|
+
* This accessor did not exist, and hosts reasonably assumed it did:
|
|
2448
|
+
* `getConversation(id).name` read `undefined` on every call, which
|
|
2449
|
+
* silently disabled any host logic driven by group state — group titles,
|
|
2450
|
+
* rosters, avatars and roles carried in the GroupContext all appeared
|
|
2451
|
+
* absent, so a group would materialise unnamed until a best-effort
|
|
2452
|
+
* broadcast happened to arrive.
|
|
2453
|
+
*
|
|
2454
|
+
* A getter rather than a snapshot, so it reflects the client's copy at
|
|
2455
|
+
* read time. That copy used to be refilled by `listConversations()`
|
|
2456
|
+
* only, and this answered the name from BEFORE a rename until the host
|
|
2457
|
+
* listed again; it is now replaced with every change the worker reports
|
|
2458
|
+
* (see `metaCache`).
|
|
2459
|
+
*/
|
|
2460
|
+
get name() {
|
|
2461
|
+
return self.metaCache.get(hex(id))?.name ?? void 0;
|
|
2462
|
+
},
|
|
2463
|
+
/** The conversation's current MLS epoch, or `undefined` when the client
|
|
2464
|
+
* holds no metadata for it. */
|
|
2465
|
+
get epoch() {
|
|
2466
|
+
return self.metaCache.get(hex(id))?.epoch;
|
|
2467
|
+
},
|
|
2468
|
+
meta() {
|
|
2469
|
+
const cached = self.metaCache.get(hex(id));
|
|
2470
|
+
if (!cached) {
|
|
2471
|
+
throw new Error("conversation meta not loaded; call readConversationMeta(id) or listConversations() first");
|
|
2472
|
+
}
|
|
2473
|
+
return cached;
|
|
2474
|
+
}
|
|
2475
|
+
};
|
|
2476
|
+
}
|
|
2477
|
+
/** Replace this client's copy of one conversation's metadata with what the
|
|
2478
|
+
* worker read; no metadata means the copy is dropped, so the handle answers
|
|
2479
|
+
* "not held" instead of what the group held before. */
|
|
2480
|
+
storeMeta(id, meta) {
|
|
2481
|
+
if (meta === null || meta === void 0) this.metaCache.delete(hex(id));
|
|
2482
|
+
else this.metaCache.set(hex(id), meta);
|
|
2483
|
+
}
|
|
2484
|
+
call(req) {
|
|
2485
|
+
if (this.closed) return Promise.reject(new MessagingClientClosedError("closed"));
|
|
2486
|
+
return new Promise((resolve, reject) => {
|
|
2487
|
+
this.pending.set(req.id, { resolve, reject });
|
|
2488
|
+
this.worker.postMessage(req);
|
|
2489
|
+
});
|
|
2490
|
+
}
|
|
2491
|
+
/** Dispatch a worker-side transport proxy call onto the host transport.
|
|
2492
|
+
* `sendBatch` is the one method the worker proxy always declares but a
|
|
2493
|
+
* host may not implement: emulate it with sequential sends and report a
|
|
2494
|
+
* partial delivery with the sentinel the wasm bridge maps to
|
|
2495
|
+
* `TransportPartial`, so the SDK still learns the Commit landed while the
|
|
2496
|
+
* Welcome did not (and surfaces `WelcomeUndelivered`). The two
|
|
2497
|
+
* sequenced-log methods cross in the wasm's wire shape and are converted
|
|
2498
|
+
* to the public shape here, both ways; the worker only asks for them when
|
|
2499
|
+
* the host declared them at `init`. */
|
|
2500
|
+
async callTransportMethod(method, args) {
|
|
2501
|
+
const t = this.transport;
|
|
2502
|
+
if (method === "sendBatch" && typeof t.sendBatch !== "function") {
|
|
2503
|
+
await emulateSendBatch(this.transport, args[0] ?? []);
|
|
2504
|
+
return void 0;
|
|
2505
|
+
}
|
|
2506
|
+
if (method === "fetchLogSince") {
|
|
2507
|
+
if (typeof this.transport.fetchLogSince !== "function") return null;
|
|
2508
|
+
const [position, limit] = args;
|
|
2509
|
+
const rows = await this.transport.fetchLogSince(logPositionFromWire(position), limit);
|
|
2510
|
+
return rows === null || rows === void 0 ? null : rows.map(sequencedToWire);
|
|
2511
|
+
}
|
|
2512
|
+
if (method === "fetchLogHeads") {
|
|
2513
|
+
if (typeof this.transport.fetchLogHeads !== "function") return null;
|
|
2514
|
+
const heads = await this.transport.fetchLogHeads();
|
|
2515
|
+
return heads === null || heads === void 0 ? null : heads.map(logHeadToWire);
|
|
2516
|
+
}
|
|
2517
|
+
return await t[method]?.(...args);
|
|
2518
|
+
}
|
|
2519
|
+
async handleWorker(msg) {
|
|
2520
|
+
switch (msg.kind) {
|
|
2521
|
+
case "result": {
|
|
2522
|
+
const slot = this.pending.get(msg.id);
|
|
2523
|
+
if (!slot) return;
|
|
2524
|
+
this.pending.delete(msg.id);
|
|
2525
|
+
msg.ok ? slot.resolve(msg.value) : slot.reject(errorFromWorker(msg.error));
|
|
2526
|
+
return;
|
|
2527
|
+
}
|
|
2528
|
+
case "event.message": {
|
|
2529
|
+
this.fanout.deliverOne(msg.msg);
|
|
2530
|
+
return;
|
|
2531
|
+
}
|
|
2532
|
+
case "event.batch": {
|
|
2533
|
+
this.fanout.deliverBatch(msg.messages, { source: msg.source });
|
|
2534
|
+
return;
|
|
2535
|
+
}
|
|
2536
|
+
case "event.conversation": {
|
|
2537
|
+
this.storeMeta(msg.id, msg.meta);
|
|
2538
|
+
for (const h of this.conversationHandlers) {
|
|
2539
|
+
try {
|
|
2540
|
+
h(msg.id, msg.epoch, msg.sender);
|
|
2541
|
+
} catch (e) {
|
|
2542
|
+
if (typeof console !== "undefined") {
|
|
2543
|
+
console.debug("[ping-sdk] onConversationUpdated handler threw:", errorKind(e));
|
|
2544
|
+
}
|
|
2545
|
+
}
|
|
2546
|
+
}
|
|
2547
|
+
return;
|
|
2548
|
+
}
|
|
2549
|
+
case "cache.conversations": {
|
|
2550
|
+
for (const meta of msg.held) this.storeMeta(meta.id, meta);
|
|
2551
|
+
for (const id of msg.dropped) this.storeMeta(id, null);
|
|
2552
|
+
return;
|
|
2553
|
+
}
|
|
2554
|
+
case "storage.call": {
|
|
2555
|
+
try {
|
|
2556
|
+
const method = this.storage[msg.method];
|
|
2557
|
+
if (typeof method !== "function") {
|
|
2558
|
+
throw new Error(`storage.${String(msg.method)} is not implemented by the host storage`);
|
|
2559
|
+
}
|
|
2560
|
+
const v = await method.apply(this.storage, msg.args);
|
|
2561
|
+
this.worker.postMessage({ kind: "storage.reply", id: msg.id, ok: true, value: v });
|
|
2562
|
+
} catch (e) {
|
|
2563
|
+
this.worker.postMessage({
|
|
2564
|
+
kind: "storage.reply",
|
|
2565
|
+
id: msg.id,
|
|
2566
|
+
ok: false,
|
|
2567
|
+
error: String(e)
|
|
2568
|
+
});
|
|
2569
|
+
}
|
|
2570
|
+
return;
|
|
2571
|
+
}
|
|
2572
|
+
case "transport.call": {
|
|
2573
|
+
try {
|
|
2574
|
+
const v = await this.callTransportMethod(msg.method, msg.args);
|
|
2575
|
+
this.worker.postMessage({ kind: "transport.reply", id: msg.id, ok: true, value: v });
|
|
2576
|
+
} catch (e) {
|
|
2577
|
+
this.worker.postMessage({
|
|
2578
|
+
kind: "transport.reply",
|
|
2579
|
+
id: msg.id,
|
|
2580
|
+
ok: false,
|
|
2581
|
+
error: describeTransportError(e)
|
|
2582
|
+
});
|
|
2583
|
+
}
|
|
2584
|
+
return;
|
|
2585
|
+
}
|
|
2586
|
+
}
|
|
2587
|
+
}
|
|
2588
|
+
};
|
|
2589
|
+
var EphemeralWorkerError = class extends Error {
|
|
2590
|
+
reason;
|
|
2591
|
+
constructor(reason) {
|
|
2592
|
+
super(`ping-openmls-sdk: one-shot worker failed (${reason})`);
|
|
2593
|
+
this.name = "EphemeralWorkerError";
|
|
2594
|
+
this.reason = reason;
|
|
2595
|
+
}
|
|
2596
|
+
};
|
|
2597
|
+
var MessagingClientClosedError = class extends Error {
|
|
2598
|
+
reason;
|
|
2599
|
+
constructor(reason) {
|
|
2600
|
+
super(reason === "closed" ? "MessagingClient is closed" : "MessagingClient worker error");
|
|
2601
|
+
this.name = "MessagingClientClosedError";
|
|
2602
|
+
this.reason = reason;
|
|
2603
|
+
}
|
|
2604
|
+
};
|
|
2605
|
+
var HPKE_PQ_PUBLIC_KEY_BYTES = 1216;
|
|
2606
|
+
var HPKE_PQ_ENC_BYTES = 1120;
|
|
2607
|
+
var BATCH_PARTIAL_PREFIX = "batch partial after ";
|
|
2608
|
+
var NOT_PERMITTED_PREFIX = "not permitted: ";
|
|
2609
|
+
var NotPermittedError = class extends Error {
|
|
2610
|
+
/** The rule that was broken: fixed text, no id, safe to log. */
|
|
2611
|
+
rule;
|
|
2612
|
+
constructor(message) {
|
|
2613
|
+
super(message);
|
|
2614
|
+
this.name = "NotPermittedError";
|
|
2615
|
+
this.rule = message.startsWith(NOT_PERMITTED_PREFIX) ? message.slice(NOT_PERMITTED_PREFIX.length) : message;
|
|
2616
|
+
}
|
|
2617
|
+
};
|
|
2618
|
+
function notPermittedRule(e) {
|
|
2619
|
+
const text = typeof e === "string" ? e : e !== null && typeof e === "object" && typeof e.message === "string" ? e.message : null;
|
|
2620
|
+
return text !== null && text.startsWith(NOT_PERMITTED_PREFIX) ? text.slice(NOT_PERMITTED_PREFIX.length) : null;
|
|
2621
|
+
}
|
|
2622
|
+
function isNotPermittedError(e) {
|
|
2623
|
+
return notPermittedRule(e) !== null;
|
|
2624
|
+
}
|
|
2625
|
+
var SENDER_MISMATCH_PREFIX = "sender mismatch: ";
|
|
2626
|
+
var SenderMismatchError = class extends Error {
|
|
2627
|
+
constructor(message) {
|
|
2628
|
+
super(message);
|
|
2629
|
+
this.name = "SenderMismatchError";
|
|
2630
|
+
}
|
|
2631
|
+
};
|
|
2632
|
+
function isSenderMismatchError(e) {
|
|
2633
|
+
const text = typeof e === "string" ? e : e !== null && typeof e === "object" && typeof e.message === "string" ? e.message : null;
|
|
2634
|
+
return text !== null && text.startsWith(SENDER_MISMATCH_PREFIX);
|
|
2635
|
+
}
|
|
2636
|
+
function errorFromWorker(text) {
|
|
2637
|
+
if (text.startsWith(NOT_PERMITTED_PREFIX)) return new NotPermittedError(text);
|
|
2638
|
+
if (text.startsWith(SENDER_MISMATCH_PREFIX)) return new SenderMismatchError(text);
|
|
2639
|
+
return new Error(text);
|
|
2640
|
+
}
|
|
2641
|
+
async function emulateSendBatch(transport, envelopes) {
|
|
2642
|
+
let delivered = 0;
|
|
2643
|
+
for (const envelope of envelopes) {
|
|
2644
|
+
try {
|
|
2645
|
+
await transport.send(envelope);
|
|
2646
|
+
} catch (e) {
|
|
2647
|
+
if (delivered === 0) throw e;
|
|
2648
|
+
throw new Error(`${BATCH_PARTIAL_PREFIX}${delivered}: ${describeTransportError(e)}`);
|
|
2649
|
+
}
|
|
2650
|
+
delivered += 1;
|
|
2651
|
+
}
|
|
2652
|
+
}
|
|
2653
|
+
function describeTransportError(e) {
|
|
2654
|
+
if (e && typeof e === "object") {
|
|
2655
|
+
const rec = e;
|
|
2656
|
+
const status = typeof rec.status === "number" ? rec.status : void 0;
|
|
2657
|
+
const message = typeof rec.message === "string" ? rec.message : String(e);
|
|
2658
|
+
if (message.startsWith(BATCH_PARTIAL_PREFIX)) return message;
|
|
2659
|
+
const parts = [];
|
|
2660
|
+
if (typeof rec.name === "string" && rec.name) parts.push(`${rec.name}:`);
|
|
2661
|
+
parts.push(message);
|
|
2662
|
+
if (status !== void 0 && !message.includes(`http ${status}`)) parts.push(`(http ${status})`);
|
|
2663
|
+
if (typeof rec.serverError === "string" && rec.serverError) parts.push(`[${rec.serverError}]`);
|
|
2664
|
+
return parts.join(" ");
|
|
2665
|
+
}
|
|
2666
|
+
return String(e);
|
|
2667
|
+
}
|
|
2668
|
+
function hex(b) {
|
|
2669
|
+
let s = "";
|
|
2670
|
+
for (const v of b) s += v.toString(16).padStart(2, "0");
|
|
2671
|
+
return s;
|
|
2672
|
+
}
|
|
2673
|
+
function hexOf(bytes) {
|
|
2674
|
+
let out = "";
|
|
2675
|
+
for (let i = 0; i < bytes.length; i++) out += bytes[i].toString(16).padStart(2, "0");
|
|
2676
|
+
return out;
|
|
2677
|
+
}
|
|
2678
|
+
function sameBytesU8(a, b) {
|
|
2679
|
+
if (a.length !== b.length) return false;
|
|
2680
|
+
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
|
2681
|
+
return true;
|
|
2682
|
+
}
|
|
2683
|
+
export {
|
|
2684
|
+
BATCH_PARTIAL_PREFIX,
|
|
2685
|
+
CONTENT_TYPE_CBOR,
|
|
2686
|
+
CONTENT_TYPE_CBOR_LEGACY_V1,
|
|
2687
|
+
CONTENT_TYPE_JSON,
|
|
2688
|
+
CONTENT_TYPE_JSON_LEGACY_V1,
|
|
2689
|
+
EphemeralWorkerError,
|
|
2690
|
+
HPKE_PQ_ENC_BYTES,
|
|
2691
|
+
HPKE_PQ_PUBLIC_KEY_BYTES,
|
|
2692
|
+
IndexedDbStorage,
|
|
2693
|
+
MessagingClient,
|
|
2694
|
+
MessagingClientClosedError,
|
|
2695
|
+
NOT_PERMITTED_PREFIX,
|
|
2696
|
+
NotPermittedError,
|
|
2697
|
+
PING_WIRE_CONTRACT_HEADER,
|
|
2698
|
+
PING_WIRE_CONTRACT_HEADER_VALUE,
|
|
2699
|
+
PING_WIRE_CONTRACT_VERSION,
|
|
2700
|
+
SENDER_MISMATCH_PREFIX,
|
|
2701
|
+
SenderMismatchError,
|
|
2702
|
+
ValidationError,
|
|
2703
|
+
WIRE_VERSION_MIN_ACCEPTED,
|
|
2704
|
+
WebSocketTransport,
|
|
2705
|
+
describeTransportError,
|
|
2706
|
+
emulateSendBatch,
|
|
2707
|
+
isNotPermittedError,
|
|
2708
|
+
isSenderMismatchError,
|
|
2709
|
+
negotiates,
|
|
2710
|
+
notPermittedRule,
|
|
2711
|
+
openNotificationPreview,
|
|
2712
|
+
validate,
|
|
2713
|
+
verifyApplicationContentHash
|
|
2714
|
+
};
|
|
2715
|
+
//# sourceMappingURL=index.js.map
|