@koralabs/handle-chat-sdk 1.0.1 → 1.1.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.
Files changed (38) hide show
  1. package/assets/libsignal_bg.wasm +0 -0
  2. package/lib/libsignal-wasm/pkg/handle_libsignal_wasm.d.ts +20 -0
  3. package/lib/libsignal-wasm/pkg/handle_libsignal_wasm.js +85 -0
  4. package/lib/src/chat/ChatService.d.ts +13 -9
  5. package/lib/src/chat/ChatService.js +384 -105
  6. package/lib/src/chat/anchor.d.ts +2 -2
  7. package/lib/src/chat/anchor.js +2 -2
  8. package/lib/src/chat/blob.d.ts +14 -0
  9. package/lib/src/chat/blob.js +107 -6
  10. package/lib/src/chat/chainDirectory.d.ts +14 -19
  11. package/lib/src/chat/chainDirectory.js +73 -31
  12. package/lib/src/chat/demeter.d.ts +3 -0
  13. package/lib/src/chat/demeter.js +8 -0
  14. package/lib/src/chat/directory.d.ts +12 -2
  15. package/lib/src/chat/directory.js +23 -0
  16. package/lib/src/chat/guardian.d.ts +6 -4
  17. package/lib/src/chat/guardian.js +17 -5
  18. package/lib/src/chat/guardianHistory.d.ts +3 -0
  19. package/lib/src/chat/guardianHistory.js +36 -0
  20. package/lib/src/chat/httpRateLimit.d.ts +5 -0
  21. package/lib/src/chat/httpRateLimit.js +54 -0
  22. package/lib/src/chat/identity.d.ts +1 -1
  23. package/lib/src/chat/identity.js +8 -2
  24. package/lib/src/chat/invite.d.ts +7 -0
  25. package/lib/src/chat/invite.js +18 -0
  26. package/lib/src/chat/mesh/client.d.ts +6 -3
  27. package/lib/src/chat/mesh/client.js +89 -13
  28. package/lib/src/chat/mesh/protocol.d.ts +35 -0
  29. package/lib/src/chat/mesh/protocol.js +11 -0
  30. package/lib/src/chat/publish.d.ts +1 -1
  31. package/lib/src/chat/publish.js +13 -2
  32. package/lib/src/chat/sessionStore.d.ts +10 -1
  33. package/lib/src/chat/sessionStore.js +52 -7
  34. package/lib/src/chat/transport.d.ts +2 -2
  35. package/lib/src/chat/transport.js +66 -6
  36. package/lib/src/signal/SignalEngine.d.ts +5 -0
  37. package/lib/src/signal/SignalEngine.js +10 -0
  38. package/package.json +3 -2
@@ -4,12 +4,22 @@ import { EncryptedIdbVault } from "./sessionStore.js";
4
4
  import { encodeMessage, decodeMessage, textMessage, mediaMessage, messageText } from "./message.js";
5
5
  import { receiptMessage, parseReceipt } from "./receipt.js";
6
6
  import { buildBlobMessages, BlobAssembler, isBlobPart } from "./blob.js";
7
+ import { retainedHistory } from "./guardianHistory.js";
7
8
  import { presenceEpoch } from "./mesh/presenceAuth.js";
9
+ import { pairwiseMailbox, pairwiseRoutingTopic } from "./mesh/protocol.js";
8
10
  // Anti-DoS bounds.
9
11
  const MAX_QUEUE = 1000; // cap the offline send queue — drop oldest beyond this
10
12
  const MAX_SENT_STATE = 2000; // cap the per-message status map (LRU) so a long session can't leak it
11
13
  const MAX_ENVELOPE_BYTES = 256 * 1024; // reject oversized inbound envelopes before decrypting (legit: inline ≤32KB, chunk ≤16KB + sealing)
12
14
  const MAX_SEEN_ENVELOPES = 4000; // cap the inbound dedup set (LRU) — bounds memory while covering live + mailbox copies
15
+ // Cover the helper's entire retention window. Do not evict an unexpired acknowledgement to admit new mail.
16
+ const RECEIPT_TTL_MS = 24 * 60 * 60 * 1000;
17
+ const MAX_MAILBOX_RECEIPTS = 10_000;
18
+ const MAX_PENDING_AUTH = 32;
19
+ const MAX_PENDING_AUTH_BYTES = 512 * 1024;
20
+ const AUTH_RETRY_BASE_MS = 2_000;
21
+ const AUTH_RETRY_MAX_MS = 60_000;
22
+ const AUTH_PENDING_MAX_AGE_MS = 10 * 60_000;
13
23
  // Abuse gate: cold first-contacts from UN-anchored senders (the spam vector) are rate-limited. Anchored
14
24
  // senders cost ada per identity (Handle + on-chain anchor) and are chain-verified, so they're unlimited;
15
25
  // known contacts (we initiated, or already accepted) are unlimited too.
@@ -84,7 +94,7 @@ const parseBundle = (bundle) => {
84
94
  return { identityKey, presenceAuthPub };
85
95
  };
86
96
  /** The identity key (chain-as-CA cross-check of a sealed sender's claimed key vs. what the handle publishes). */
87
- const bundleIdentityKey = (bundle) => parseBundle(bundle).identityKey;
97
+ export const bundleIdentityKey = (bundle) => parseBundle(bundle).identityKey;
88
98
  /**
89
99
  * Orchestrates one handle's chat: derive the wallet-rooted identity, provision the WASM Signal
90
100
  * engine, publish the bundle to the directory, and send/receive E2E messages over the transport.
@@ -105,7 +115,8 @@ export class ChatService {
105
115
  /** Outbound messages sealed but not yet handed to the network (offline) — retried on reconnect. */
106
116
  #queue = [];
107
117
  #flushTimer = null;
108
- #flushing = false;
118
+ #activeFlush = null;
119
+ #dispatchChain = Promise.resolve();
109
120
  #onlineHandler = null;
110
121
  /** My current rotating routing labels (prev/current/next epoch) + the timer that rolls them over. */
111
122
  #topics = [];
@@ -134,10 +145,21 @@ export class ChatService {
134
145
  #persistChain = Promise.resolve();
135
146
  #recvChain = Promise.resolve(); // serializes inbound processing in arrival order
136
147
  #seenEnvelopes = new Set(); // content fingerprints of processed envelopes (LRU) — inbound dedup
148
+ #pendingAuth = [];
149
+ #pendingAuthBytes = 0;
150
+ #authRetryTimer = null;
151
+ #authRetryAt = 0;
152
+ #authFailures = 0;
137
153
  /** Decrypted conversation history (per remote), restored on start + appended on every message. */
138
154
  #history = new Map();
139
155
  #historyChain = Promise.resolve();
140
- static MAX_HISTORY = 500; // cap per thread — bound the at-rest blob + memory
156
+ // Atomic vaults keep dirty threads until a transaction containing them actually commits.
157
+ #dirtyHistory = new Map();
158
+ #received = new Map();
159
+ #pendingCommit;
160
+ #assembling = false;
161
+ #queueChain = Promise.resolve();
162
+ static MAX_HISTORY = 500; // rolling transcript; explicitly accepted guardian material is retained separately from this cap
141
163
  constructor(handle, directory, transport,
142
164
  /** Where per-device session state persists. Omit for the default (wallet-encrypted IndexedDB);
143
165
  * pass `null` to disable persistence; inject a custom vault in tests. */
@@ -152,14 +174,17 @@ export class ChatService {
152
174
  this.#useDefaultVault = vault === undefined;
153
175
  }
154
176
  /** Provision identity + Signal engine from the wallet seed, restore any persisted session, publish, receive. */
177
+ #stopped = false;
155
178
  async start(seed) {
179
+ if (this.#stopped)
180
+ throw new Error("ChatService stopped");
156
181
  if (this.started)
157
182
  return;
158
183
  const { priv, registrationId } = await deriveIdentity(seed, this.handle);
159
184
  this.engine = await SignalEngine.create(this.handle, priv, registrationId);
160
185
  // Persistence: default to the wallet-encrypted IndexedDB vault (re-derives its key from the seed).
161
186
  if (this.#useDefaultVault)
162
- this.#vault = await EncryptedIdbVault.create(seed).catch(() => null);
187
+ this.#vault = await EncryptedIdbVault.create(seed);
163
188
  // CRITICAL: the snapshot load must distinguish "no record" (null → genuine new user) from a transient
164
189
  // read/decrypt error (throws). We must NOT catch-to-null here: doing so would treat a recoverable error
165
190
  // as a fresh user and mint+persist a NEW identity over the intact snapshot, destroying the session,
@@ -171,6 +196,12 @@ export class ChatService {
171
196
  this.engine.importState(snapshot.state);
172
197
  this.#bundle = snapshot.bundle;
173
198
  this.#contacts = new Set(snapshot.contacts);
199
+ this.#received = new Map(snapshot.inbox?.receipts);
200
+ this.#expireMailboxReceipts();
201
+ for (const [id, status] of snapshot.inbox?.peerReceipts ?? [])
202
+ this.#setSentState(id, status);
203
+ if (snapshot.inbox?.blobs)
204
+ this.#assembler.restore(snapshot.inbox.blobs);
174
205
  for (const [h, hex] of Object.entries(snapshot.peerPA ?? {}))
175
206
  this.#peerPA.set(h, fromHex(hex)); // Tier 2 Stage 3
176
207
  // Restore each conversation's decrypted history (encrypted at rest under the same wallet key).
@@ -180,7 +211,7 @@ export class ChatService {
180
211
  const trusted = this.engine.peerIdentityKey(remote);
181
212
  if (trusted)
182
213
  this.#trustedKey.set(remote, trusted);
183
- const stored = this.#vault ? await this.#vault.loadHistory(this.handle, remote).catch(() => null) : null;
214
+ const stored = this.#vault ? await this.#vault.loadHistory(this.handle, remote) : null;
184
215
  if (stored && stored.length) {
185
216
  this.#history.set(remote, stored.map(fromStored));
186
217
  // A thread with any INBOUND message means this peer has reached me → they know me → I can address
@@ -190,26 +221,30 @@ export class ChatService {
190
221
  }
191
222
  }
192
223
  // Restore the outbound queue (messages sealed while offline before a reload).
193
- const queued = this.#vault ? await this.#vault.loadQueue(this.handle).catch(() => null) : null;
224
+ const queued = this.#vault ? await this.#vault.loadQueue(this.handle) : null;
194
225
  if (queued && queued.length) {
195
226
  this.#queue = queued;
196
227
  for (const q of queued)
197
- this.#setSentState(q.id, "queued");
228
+ if (!this.#sentState.has(q.id))
229
+ this.#setSentState(q.id, "queued");
198
230
  }
199
231
  }
200
232
  else {
201
233
  this.#bundle = this.engine.createBundle();
234
+ // Do not advertise prekeys that a crash could erase before the first mailbox delivery returns.
235
+ if (!this.#stopped)
236
+ await this.persist();
202
237
  }
238
+ if (this.#stopped)
239
+ throw new Error("ChatService stopped");
203
240
  this.directory.publish(this.handle, this.#bundle);
204
241
  // Subscribe under our scrambled, ROTATING topics (prev/current/next epoch), not our handle — the relay
205
242
  // routes by opaque labels that change over time, so it can't track us or who messages us. A timer rolls
206
243
  // the set forward as epochs advance.
207
244
  this.#topics = this.#myTopicSet();
208
- this.transport.subscribe(this.#topics, (env) => this.receive(env), this.#sign);
245
+ this.transport.subscribe(this.#topics, (env) => this.receive(env), this.#sign, this.#receiveDurably);
209
246
  this.#topicTimer = setInterval(() => this.#resubscribe(), TOPIC_REFRESH_MS);
210
247
  this.started = true;
211
- if (!snapshot)
212
- this.persist(); // persist the fresh bundle/pre-keys so a new identity survives a reopen
213
248
  // Flush the outbound queue now and whenever connectivity returns.
214
249
  if (typeof globalThis.addEventListener === "function") {
215
250
  this.#onlineHandler = () => void this.flushQueue();
@@ -219,26 +254,54 @@ export class ChatService {
219
254
  this.#scheduleFlush();
220
255
  }
221
256
  /** Serialize + encrypt the current session state to the vault. Serialized via a chain so concurrent
222
- * mutations don't interleave writes. Fire-and-forget; failures never block messaging. */
257
+ * mutations don't interleave writes. A mailbox consumer must await the transaction. */
223
258
  persist() {
224
- if (!this.#vault || !this.#bundle)
225
- return;
259
+ const vault = this.#vault;
260
+ // Completing a streamed attachment mutates the assembler across a WebCrypto await. Do not save a
261
+ // consumed ratchet without either its partial chunks or its completed history row during that gap.
262
+ if (!vault || !this.#bundle || this.#assembling)
263
+ return Promise.resolve();
226
264
  const peerPA = {};
227
265
  for (const [h, k] of this.#peerPA)
228
266
  peerPA[h] = toHex(k);
229
267
  const snap = { state: this.engine.exportState([...this.#contacts]), bundle: this.#bundle, contacts: [...this.#contacts], peerPA };
230
- this.#persistChain = this.#persistChain.then(() => this.#vault?.save(this.handle, snap)).catch(() => { });
268
+ const histories = new Map(this.#dirtyHistory);
269
+ const pending = this.#pendingCommit;
270
+ const inbox = vault.commitInbound ? {
271
+ receipts: [...this.#received], blobs: this.#assembler.snapshot(),
272
+ peerReceipts: [...this.#sentState].filter((entry) => entry[1] === "delivered" || entry[1] === "read"),
273
+ } : undefined;
274
+ const write = this.#persistChain.then(async () => {
275
+ if (!inbox || !vault.commitInbound)
276
+ return vault.save(this.handle, snap);
277
+ await vault.commitInbound(this.handle, { ...snap, inbox }, histories);
278
+ for (const [remote, rows] of histories) {
279
+ if (this.#dirtyHistory.get(remote) === rows)
280
+ this.#dirtyHistory.delete(remote);
281
+ }
282
+ if (pending && pending === this.#pendingCommit) {
283
+ this.#pendingCommit = undefined;
284
+ if (!this.#stopped)
285
+ pending.notify?.();
286
+ }
287
+ });
288
+ // Later writes may retry dirty state after an abort. Only callers of *write* receive proof of commit.
289
+ this.#persistChain = write.catch(() => { });
290
+ return write;
231
291
  }
232
292
  /** Append a message to a conversation's history and persist that thread (capped, chained writes). */
233
293
  record(remote, msg) {
234
294
  const list = this.#history.get(remote) ?? [];
235
295
  list.push(msg);
236
- if (list.length > ChatService.MAX_HISTORY)
237
- list.splice(0, list.length - ChatService.MAX_HISTORY);
238
- this.#history.set(remote, list);
296
+ const retained = retainedHistory(list, this.handle, ChatService.MAX_HISTORY);
297
+ this.#history.set(remote, retained);
239
298
  if (!this.#vault)
240
299
  return;
241
- const snapshot = list.map(toStored);
300
+ const snapshot = retained.map(toStored);
301
+ if (this.#vault.commitInbound) {
302
+ this.#dirtyHistory.set(remote, snapshot);
303
+ return;
304
+ }
242
305
  this.#historyChain = this.#historyChain.then(() => this.#vault?.saveHistory(this.handle, remote, snapshot)).catch(() => { });
243
306
  }
244
307
  /** Restored conversation history (per remote handle) — for the UI to seed its threads on reopen. */
@@ -247,11 +310,20 @@ export class ChatService {
247
310
  }
248
311
  /** Await any in-flight persistence (session state + history) — so a reopen reads the latest. */
249
312
  async flush() {
250
- await Promise.all([this.#persistChain, this.#historyChain]);
313
+ await this.#recvChain;
314
+ await this.#dispatchChain; // a failed in-flight send creates its queue write when it settles
315
+ await this.#activeFlush;
316
+ await Promise.all([this.#persistChain, this.#historyChain, this.#queueChain]);
251
317
  }
252
318
  /** Tear down timers + the global `online` listener, and stop the transport. Idempotent. Call before
253
319
  * discarding the service (e.g. a wallet switch / re-provision) so nothing leaks or fires on a stale engine. */
254
320
  stop() {
321
+ this.#stopped = true;
322
+ if (this.#authRetryTimer)
323
+ clearTimeout(this.#authRetryTimer);
324
+ this.#authRetryTimer = null;
325
+ this.#pendingAuth.length = 0;
326
+ this.#pendingAuthBytes = 0;
255
327
  if (this.#flushTimer)
256
328
  clearInterval(this.#flushTimer);
257
329
  if (this.#topicTimer)
@@ -275,20 +347,42 @@ export class ChatService {
275
347
  myIdentityKey() {
276
348
  return bundleIdentityKey(this.myBundle());
277
349
  }
350
+ /** The identity pinned to this conversation, not a fresh directory lookup or an identity claimed in a message body. */
351
+ pinnedIdentityKey(remote) {
352
+ return this.#trustedKey.get(remote)?.slice() ?? null;
353
+ }
278
354
  /** Open an outbound session to a peer by resolving their published bundle (cold lookup). */
279
355
  openChat(remote) {
356
+ if (!("resolve" in this.directory))
357
+ throw new Error("Use openChatAsync with an asynchronous directory");
280
358
  const bundle = this.directory.resolve(remote);
281
359
  if (!bundle)
282
360
  return false;
283
- this.engine.processBundle(remote, bundle);
284
- this.#contacts.add(remote);
285
- this.#learnFromBundle(remote, bundle);
286
- this.#resubscribe(); // listen on our pairwise label too, so the peer's reply on it reaches me
287
- this.persist();
361
+ this.openChatWithBundle(remote, bundle);
362
+ return true;
363
+ }
364
+ #lookup(remote) {
365
+ return "resolve" in this.directory ? this.directory.resolve(remote) : this.directory.resolveAsync(remote);
366
+ }
367
+ async openChatAsync(remote) {
368
+ const bundle = await this.#lookup(remote);
369
+ if (this.#stopped)
370
+ throw new Error("ChatService stopped");
371
+ if (!bundle)
372
+ return false;
373
+ this.openChatWithBundle(remote, bundle);
288
374
  return true;
289
375
  }
290
376
  /** Open an outbound session from a bundle handed over directly (invite link / QR — no directory). */
291
377
  openChatWithBundle(remote, bundle) {
378
+ const trusted = this.#trustedKey.get(remote);
379
+ const key = bundleIdentityKey(bundle);
380
+ if (trusted && !bytesEqual(trusted, key)) {
381
+ this.onKeyChangeCb?.({ handle: remote, knownKey: trusted, newKey: key, anchorDiverged: true });
382
+ throw new Error(`Identity key changed for ${remote}`);
383
+ }
384
+ if (trusted && this.engine.peerIdentityKey(remote))
385
+ return;
292
386
  this.engine.processBundle(remote, bundle);
293
387
  this.#contacts.add(remote);
294
388
  this.#learnFromBundle(remote, bundle);
@@ -326,8 +420,9 @@ export class ChatService {
326
420
  * which presence table to use: a first-contact message rides the PUBLIC slot, an established one the
327
421
  * unguessable PAIRWISE slot (Tier 2 Stage 3). */
328
422
  #seal(remote, content, ts) {
329
- const slot = this.#convReady.has(remote) ? "pairwise" : "public";
330
- return { to: this.#sendTopic(remote, ts), body: this.engine.sealedSend(remote, encodeMessage(content)), ts, slot };
423
+ const to = this.#sendTopic(remote, ts);
424
+ const slot = pairwiseRoutingTopic(to) ? "pairwise" : "public";
425
+ return { to, body: this.engine.sealedSend(remote, encodeMessage(content)), ts, slot };
331
426
  }
332
427
  /** Authenticate a PUBLIC-slot presence registration (Tier 2 Stage 3): if `topic` is one of my current
333
428
  * public first-contact labels, sign `topic‖addr‖epoch` so the helper accepts it. Returns null for a
@@ -348,7 +443,7 @@ export class ChatService {
348
443
  #sendTopic(remote, ts) {
349
444
  if (this.#convReady.has(remote)) {
350
445
  try {
351
- return this.engine.convSendTopic(remote, ts);
446
+ return pairwiseMailbox(this.engine.convSendTopic(remote, ts));
352
447
  }
353
448
  catch {
354
449
  /* no session/identity — fall back to the public slot */
@@ -367,7 +462,7 @@ export class ChatService {
367
462
  for (const c of this.#contacts) {
368
463
  try {
369
464
  for (const t of this.engine.convRecvTopics(c, this.now()))
370
- set.add(t);
465
+ set.add(pairwiseMailbox(t));
371
466
  }
372
467
  catch {
373
468
  /* no identity for this contact yet — only the public slot covers them */
@@ -383,17 +478,27 @@ export class ChatService {
383
478
  const next = this.#myTopicSet();
384
479
  if (next.join() !== this.#topics.join()) {
385
480
  this.#topics = next;
386
- this.transport.subscribe(next, (env) => this.receive(env), this.#sign);
481
+ this.transport.subscribe(next, (env) => this.receive(env), this.#sign, this.#receiveDurably);
387
482
  }
388
483
  }
389
484
  /** Hand an envelope to the network; queue it if we're offline or the network can't take it. `track`
390
485
  * is false for blob chunks — reliable, but not a user-visible message whose status should change. */
391
- async #dispatch(id, remote, env, track = true) {
486
+ #dispatch(id, remote, env, track = true) {
487
+ // Even online, concurrent sends can finish in reverse order. Let the first attempt decide whether
488
+ // there is a backlog before the next attempt is allowed to go directly to the network.
489
+ this.#dispatchChain = this.#dispatchChain.then(async () => {
490
+ if (!this.#stopped)
491
+ await this.#dispatchNext(id, remote, env, track);
492
+ });
493
+ }
494
+ async #dispatchNext(id, remote, env, track) {
392
495
  // Offline OR a non-empty backlog → queue, so the queue is the sole ordering authority (a fresh send
393
496
  // must not overtake messages still waiting to flush).
394
497
  if (this.#offline() || this.#queue.length > 0)
395
498
  return this.#enqueue(id, remote, env, track);
396
499
  const ok = await this.transport.send(env).catch(() => false);
500
+ if (this.#stopped)
501
+ return;
397
502
  if (ok) {
398
503
  if (track)
399
504
  this.#advanceSentState(id, "sent");
@@ -436,38 +541,40 @@ export class ChatService {
436
541
  }
437
542
  /** Retry queued envelopes in order, stopping at the first the network still won't take (preserves order). */
438
543
  async flushQueue() {
439
- if (this.#flushing || this.#offline())
544
+ await this.#dispatchChain;
545
+ if (this.#offline() || this.#stopped || this.#queue.length === 0)
440
546
  return;
441
- this.#flushing = true;
442
- try {
443
- while (this.#queue.length) {
444
- const item = this.#queue[0];
445
- // RE-ADDRESS to the recipient's CURRENT-epoch topic (topics rotate daily; a long-offline message's
446
- // frozen label is dead). Re-address only — the body was sealed once, so we don't re-encrypt.
447
- let to = item.to;
448
- if (item.remote) {
449
- try {
450
- to = this.#sendTopic(item.remote, this.now());
451
- }
452
- catch {
453
- /* no session for remote (shouldn't happen post-restore) — fall back to the frozen label */
454
- }
547
+ if (!this.#activeFlush)
548
+ this.#activeFlush = this.#drainQueue().finally(() => { this.#activeFlush = null; });
549
+ await this.#activeFlush;
550
+ }
551
+ async #drainQueue() {
552
+ while (!this.#stopped && this.#queue.length) {
553
+ const item = this.#queue[0];
554
+ // RE-ADDRESS to the recipient's CURRENT-epoch topic (topics rotate daily; a long-offline message's
555
+ // frozen label is dead). Re-address only — the body was sealed once, so we don't re-encrypt.
556
+ let to = item.to;
557
+ if (item.remote) {
558
+ try {
559
+ to = this.#sendTopic(item.remote, this.now());
560
+ }
561
+ catch {
562
+ /* no session for remote (shouldn't happen post-restore) — fall back to the frozen label */
455
563
  }
456
- const ok = await this.transport.send({ to, body: fromB64(item.body), ts: item.ts }).catch(() => false);
457
- if (!ok)
458
- break;
459
- this.#queue.shift();
460
- if (item.track !== false)
461
- this.#advanceSentState(item.id, "sent");
462
- }
463
- this.#persistQueue();
464
- if (this.#queue.length === 0 && this.#flushTimer) {
465
- clearInterval(this.#flushTimer);
466
- this.#flushTimer = null;
467
564
  }
565
+ const slot = pairwiseRoutingTopic(to) ? "pairwise" : "public";
566
+ const ok = await this.transport.send({ to, slot, body: fromB64(item.body), ts: item.ts }).catch(() => false);
567
+ if (this.#stopped || !ok)
568
+ break;
569
+ if (this.#queue[0] === item)
570
+ this.#queue.shift(); // cap eviction can remove this item during send
571
+ if (item.track !== false)
572
+ this.#advanceSentState(item.id, "sent");
468
573
  }
469
- finally {
470
- this.#flushing = false;
574
+ this.#persistQueue();
575
+ if (this.#queue.length === 0 && this.#flushTimer) {
576
+ clearInterval(this.#flushTimer);
577
+ this.#flushTimer = null;
471
578
  }
472
579
  }
473
580
  #scheduleFlush() {
@@ -476,8 +583,11 @@ export class ChatService {
476
583
  this.#flushTimer = setInterval(() => void this.flushQueue(), 3000);
477
584
  }
478
585
  #persistQueue() {
479
- if (this.#vault)
480
- void this.#vault.saveQueue(this.handle, [...this.#queue]).catch(() => { });
586
+ if (!this.#vault)
587
+ return;
588
+ const snapshot = [...this.#queue];
589
+ // Sealing each snapshot is asynchronous. An older write must never overwrite a newer enqueue or drain.
590
+ this.#queueChain = this.#queueChain.then(() => this.#vault?.saveQueue(this.handle, snapshot)).catch(() => { });
481
591
  }
482
592
  #emitSendUpdate() {
483
593
  this.onSendUpdateCb?.();
@@ -526,6 +636,8 @@ export class ChatService {
526
636
  this.persist();
527
637
  this.#emitSendUpdate();
528
638
  const { ref, chunks } = await buildBlobMessages(id, mime, bytes, name);
639
+ if (this.#stopped)
640
+ throw new Error("ChatService stopped");
529
641
  this.#reliableSend(remote, ref, id, true); // the ref's delivery flips the blob's status
530
642
  for (const c of chunks)
531
643
  this.#reliableSend(remote, c, `chunk:${crypto.randomUUID()}`, false);
@@ -541,32 +653,164 @@ export class ChatService {
541
653
  /** Serialize inbound processing: each envelope fully completes (incl. async blob reassembly) before the
542
654
  * next, so app-level ordering of history/UI is preserved even when a blob await interleaves. */
543
655
  receive(env) {
544
- this.#recvChain = this.#recvChain.then(() => this.#receiveInner(env)).catch(() => { });
545
- }
546
- async #receiveInner(env) {
547
- if (env.body.length > MAX_ENVELOPE_BYTES)
548
- return; // anti-DoS: drop oversized envelopes before decrypting
549
- // Dedup before decrypting: the same envelope now arrives via BOTH the direct dial and the mailbox
550
- // (send deposits to both — see MeshClient.send), and a relay may redeliver. Drop a repeat by its content
551
- // fingerprint so the redundant copy never advances the ratchet, double-records history, or re-emits.
552
- const fp = await envelopeFp(env.body);
553
- if (this.#seenEnvelopes.has(fp))
656
+ void this.#enqueueReceive(env, false);
657
+ }
658
+ #receiveDurably = (env) => this.#enqueueReceive(env, true);
659
+ #enqueueReceive(env, requireCommit) {
660
+ const task = this.#recvChain.then(async () => {
661
+ if (this.#stopped || env.body.length > MAX_ENVELOPE_BYTES)
662
+ return false;
663
+ const fp = await envelopeFp(env.body);
664
+ await this.#receiveInner(env, Date.now(), fp, requireCommit);
665
+ return !this.#stopped && !!this.#vault?.commitInbound && !this.#pendingCommit && this.#received.has(fp);
666
+ }).catch(() => false);
667
+ this.#recvChain = task.then(() => { });
668
+ return task;
669
+ }
670
+ #expireMailboxReceipts() {
671
+ // Map insertion order is receipt order. Use the recipient clock, never peer-provided timestamps.
672
+ const cutoff = Date.now() - RECEIPT_TTL_MS;
673
+ for (const [fp, at] of this.#received) {
674
+ if (at > cutoff)
675
+ break;
676
+ this.#received.delete(fp);
677
+ }
678
+ }
679
+ #queueAuth(message) {
680
+ if (this.#pendingAuth.some((pending) => pending.fingerprint === message.fingerprint))
681
+ return;
682
+ if (this.#pendingAuth.length >= MAX_PENDING_AUTH || this.#pendingAuthBytes + message.env.body.length > MAX_PENDING_AUTH_BYTES)
683
+ return;
684
+ this.#pendingAuth.push(message);
685
+ this.#pendingAuthBytes += message.env.body.length;
686
+ }
687
+ #scheduleAuthRetry(error) {
688
+ if (this.#stopped || !this.#pendingAuth.length || this.#authRetryTimer)
689
+ return;
690
+ const requested = typeof error === "object" && error !== null && "retryAfter" in error && typeof error.retryAfter === "number"
691
+ ? Math.max(0, error.retryAfter * 1000) : 0;
692
+ const delay = Math.max(requested, Math.min(AUTH_RETRY_MAX_MS, AUTH_RETRY_BASE_MS * 2 ** Math.min(this.#authFailures++, 10)));
693
+ this.#authRetryAt = Date.now() + delay;
694
+ this.#armAuthTimer();
695
+ }
696
+ #armAuthTimer() {
697
+ if (this.#stopped || this.#authRetryTimer || !this.#pendingAuth.length)
698
+ return;
699
+ const expiry = Math.min(...this.#pendingAuth.map((message) => message.receivedAt + AUTH_PENDING_MAX_AGE_MS));
700
+ const delay = Math.max(1, Math.min(this.#authRetryAt, expiry) - Date.now());
701
+ this.#authRetryTimer = setTimeout(() => {
702
+ this.#authRetryTimer = null;
703
+ void this.retryPendingContacts();
704
+ }, delay);
705
+ }
706
+ /** Retry in-memory first contacts after a directory outage; provider-imposed waits are never bypassed. */
707
+ async retryPendingContacts() {
708
+ if (this.#stopped)
709
+ return;
710
+ if (Date.now() < this.#authRetryAt) {
711
+ for (let i = this.#pendingAuth.length - 1; i >= 0; i--) {
712
+ if (Date.now() - this.#pendingAuth[i].receivedAt >= AUTH_PENDING_MAX_AGE_MS) {
713
+ this.#pendingAuthBytes -= this.#pendingAuth[i].env.body.length;
714
+ this.#pendingAuth.splice(i, 1);
715
+ }
716
+ }
717
+ this.#armAuthTimer();
554
718
  return;
719
+ }
720
+ this.#recvChain = this.#recvChain.then(async () => {
721
+ while (!this.#stopped && this.#pendingAuth.length) {
722
+ const message = this.#pendingAuth[0];
723
+ this.#pendingAuth.shift();
724
+ this.#pendingAuthBytes -= message.env.body.length;
725
+ if (Date.now() - message.receivedAt > AUTH_PENDING_MAX_AGE_MS)
726
+ continue;
727
+ await this.#receiveInner(message.env, message.receivedAt, message.fingerprint, message.requireCommit);
728
+ if (this.#authRetryTimer) {
729
+ const index = this.#pendingAuth.findIndex((item) => item.fingerprint === message.fingerprint);
730
+ if (index > 0)
731
+ this.#pendingAuth.unshift(...this.#pendingAuth.splice(index, 1));
732
+ return;
733
+ }
734
+ if (this.#stopped)
735
+ return;
736
+ }
737
+ this.#authFailures = 0;
738
+ this.#authRetryAt = 0;
739
+ }).catch(() => { });
740
+ await this.#recvChain;
741
+ }
742
+ #rememberEnvelope(fp) {
555
743
  this.#seenEnvelopes.add(fp);
556
744
  if (this.#seenEnvelopes.size > MAX_SEEN_ENVELOPES) {
557
745
  const oldest = this.#seenEnvelopes.values().next().value;
558
746
  if (oldest !== undefined)
559
747
  this.#seenEnvelopes.delete(oldest);
560
748
  }
749
+ }
750
+ async #receiveInner(env, receivedAt, fp, requireCommit) {
751
+ // Retry an aborted write, NOT decryption, before consuming another ratchet step. After restart
752
+ // either the whole checkpoint exists or the old ratchet can still decrypt the helper's redelivery.
753
+ if (this.#pendingCommit)
754
+ await this.persist();
755
+ this.#expireMailboxReceipts();
756
+ if (this.#received.has(fp) || this.#seenEnvelopes.has(fp) || (requireCommit && this.#received.size >= MAX_MAILBOX_RECEIPTS))
757
+ return;
758
+ let hint;
759
+ try {
760
+ hint = this.engine.sealedSenderHint(env.body);
761
+ }
762
+ catch {
763
+ this.#rememberEnvelope(fp);
764
+ return;
765
+ }
766
+ if (!isValidHandle(hint.sender)) {
767
+ this.#rememberEnvelope(fp);
768
+ return;
769
+ }
770
+ if (this.#stopped)
771
+ return;
772
+ const trusted = this.#trustedKey.get(hint.sender);
773
+ if (trusted && !bytesEqual(trusted, hint.identityKey)) {
774
+ this.#rememberEnvelope(fp);
775
+ this.onKeyChangeCb?.({ handle: hint.sender, knownKey: trusted, newKey: hint.identityKey, anchorDiverged: false });
776
+ return;
777
+ }
778
+ let bundle = null;
779
+ if (!trusted) {
780
+ if (Date.now() < this.#authRetryAt) {
781
+ this.#queueAuth({ fingerprint: fp, env, receivedAt, requireCommit });
782
+ this.#armAuthTimer();
783
+ return;
784
+ }
785
+ try {
786
+ bundle = await this.#lookup(hint.sender);
787
+ }
788
+ catch (error) {
789
+ if (!this.#stopped) {
790
+ this.#queueAuth({ fingerprint: fp, env, receivedAt, requireCommit });
791
+ this.#scheduleAuthRetry(error);
792
+ }
793
+ return;
794
+ }
795
+ }
796
+ if (this.#stopped)
797
+ return;
798
+ this.#rememberEnvelope(fp);
799
+ let anchorKey;
800
+ try {
801
+ anchorKey = bundle ? bundleIdentityKey(bundle) : null;
802
+ }
803
+ catch {
804
+ return;
805
+ }
806
+ if (anchorKey && !bytesEqual(anchorKey, hint.identityKey))
807
+ return;
808
+ if (!trusted && !this.#contacts.has(hint.sender) && !bundle && !this.#admitUnverified())
809
+ return;
561
810
  try {
562
811
  const { sender, identityKey, body } = this.engine.sealedReceive(env.body);
563
- if (!isValidHandle(sender))
564
- return; // drop malformed/forged sender handles before they touch state or the DOM
565
- // Verify-once-then-warn. The WASM already bound this cert key to the session-authenticated identity, so
566
- // `identityKey` is cryptographically the peer. The TRUST question is handle↔key:
567
- const bundle = this.directory.resolve(sender);
568
- const anchorKey = bundle ? bundleIdentityKey(bundle) : null;
569
- const trusted = this.#trustedKey.get(sender);
812
+ if (sender !== hint.sender || !bytesEqual(identityKey, hint.identityKey))
813
+ return;
570
814
  if (trusted) {
571
815
  // Established conversation: trust the key I verified at first contact + the ratchet — do NOT re-check
572
816
  // the live anchor per message (that's what silently broke a conversation when its handle was
@@ -576,11 +820,6 @@ export class ChatService {
576
820
  this.onKeyChangeCb?.({ handle: sender, knownKey: trusted, newKey: identityKey, anchorDiverged: false });
577
821
  return;
578
822
  }
579
- // Same trusted key, but the on-chain anchor has since moved → the handle was re-anchored (may have
580
- // changed hands). Surface it, but keep trusting the established session and accept the message.
581
- if (anchorKey && !bytesEqual(anchorKey, trusted)) {
582
- this.onKeyChangeCb?.({ handle: sender, knownKey: trusted, newKey: anchorKey, anchorDiverged: true });
583
- }
584
823
  }
585
824
  else {
586
825
  // First contact: chain-as-CA if the handle is anchored (the claimed key MUST match the on-chain
@@ -588,14 +827,13 @@ export class ChatService {
588
827
  // verified key as this conversation's trusted identity.
589
828
  if (anchorKey && !bytesEqual(anchorKey, identityKey))
590
829
  return;
591
- this.#trustedKey.set(sender, identityKey);
592
830
  }
593
831
  // Abuse gate. Always admit a KNOWN contact (we initiated, or already accepted) or an ANCHORED sender
594
832
  // (chain-verified above; an anchor + Handle cost ada per identity → Sybil-resistant). A cold
595
833
  // first-contact from an UN-anchored sender is the spam vector — rate-limit it. (An invitee holds our
596
834
  // bundle by our consent and gets through within the budget, then is known and unlimited thereafter.)
597
- if (!this.#contacts.has(sender) && !bundle && !this.#admitUnverified())
598
- return;
835
+ if (!trusted)
836
+ this.#trustedKey.set(sender, identityKey);
599
837
  // The sender reached me → they know me and subscribe to our pairwise label, so address them there from
600
838
  // now on (Tier 2). A receipt counts too. If this is a newly-known contact, re-subscribe so I also listen
601
839
  // on the pairwise label they'll deposit at.
@@ -608,36 +846,77 @@ export class ChatService {
608
846
  // Receipts are control, not content: update my sent-message state and surface to the UI, never record.
609
847
  const receipt = parseReceipt(content);
610
848
  if (receipt) {
611
- this.persist(); // the inbound receipt advanced the ratchet regardless
612
- // Only honor a receipt for a message we actually sent (a known id) — this prevents forged/arbitrary
613
- // refs from spoofing status or growing #sentState — and only advance, never regress, the status.
614
- if (this.#sentState.has(receipt.ref)) {
615
- this.#advanceSentState(receipt.ref, receipt.state);
849
+ // History also identifies our earlier sends after a restart, when queued/sent state is gone.
850
+ // Snapshot the control effect before allowing the helper to delete the receipt.
851
+ const prior = this.#sentState.get(receipt.ref);
852
+ const known = prior !== undefined || this.#history.get(sender)?.some(m => m.from === this.handle && m.content.meta?.id === receipt.ref);
853
+ const advance = known && (!prior || SEND_STATE_RANK[prior] < SEND_STATE_RANK[receipt.state]);
854
+ if (advance)
855
+ this.#setSentState(receipt.ref, receipt.state);
856
+ await this.#finishReceipt(fp, known ? () => {
857
+ if (advance)
858
+ this.#emitSendUpdate();
616
859
  this.onReceiptCb?.({ from: sender, ref: receipt.ref, state: receipt.state });
617
- }
860
+ } : undefined);
618
861
  return;
619
862
  }
620
863
  // Streamed blob: ref/chunk parts are control until the blob completes — then surface the full media.
864
+ let visible = content;
621
865
  if (isBlobPart(content)) {
622
- const media = await this.#assembler.accept(content);
623
- this.persist(); // the inbound part advanced the ratchet
624
- if (media)
625
- this.#surface(sender, media, env.ts);
626
- return;
866
+ this.#assembling = true;
867
+ try {
868
+ visible = await this.#assembler.accept(content);
869
+ }
870
+ catch {
871
+ visible = null;
872
+ }
873
+ finally {
874
+ this.#assembling = false;
875
+ }
876
+ if (this.#stopped)
877
+ return;
878
+ if (!visible && !this.#assembler.hasPart(content)) {
879
+ void this.persist(); // release any concurrent send's deferred checkpoint, but do not ACK the discarded part
880
+ return;
881
+ }
627
882
  }
628
- this.#surface(sender, content, env.ts);
629
- this.persist(); // inbound message + the delivery ack both advanced the ratchet
883
+ const notify = visible ? this.#prepareIncoming(sender, visible, env.ts) : undefined;
884
+ await this.#finishReceipt(fp, notify);
630
885
  }
631
886
  catch {
632
- // ignore undecryptable / unverifiable envelopes (not for us, or impersonation attempt)
887
+ // Authentication/decoding can reject the message; storage can abort after authentication. In
888
+ // neither case is this delivery ACKable. An aborted checkpoint stays pending for the next attempt.
633
889
  }
634
890
  }
635
- /** Record a received message, hand it to the app, and auto-acknowledge delivery to the sender. */
636
- #surface(sender, content, ts) {
891
+ async #finishReceipt(fp, notify) {
892
+ if (this.#vault?.commitInbound) {
893
+ if (this.#received.size < MAX_MAILBOX_RECEIPTS)
894
+ this.#received.set(fp, Date.now());
895
+ this.#pendingCommit = { notify };
896
+ await this.persist();
897
+ }
898
+ else {
899
+ notify?.();
900
+ void this.persist(); // legacy/ephemeral transport: never used as proof of durable receipt
901
+ }
902
+ }
903
+ /** Prepare the history and the ratchet change for the receipt in the same checkpoint. Notify the
904
+ * UI and send the peer's delivery receipt only after that checkpoint has committed. */
905
+ #prepareIncoming(sender, content, ts) {
637
906
  this.record(sender, { from: sender, content, ts });
638
- this.onMessageCb?.({ from: sender, content, text: messageText(content), ts });
639
- const id = content.meta?.id; // the inbound message gave us a usable return session for the ack
640
- if (id)
641
- this.#sendRaw(sender, receiptMessage(id, "delivered"), Date.now());
907
+ const id = content.meta?.id;
908
+ let ack;
909
+ // A best-effort peer receipt must not prevent the original message from being saved.
910
+ if (id) {
911
+ try {
912
+ ack = this.#seal(sender, receiptMessage(id, "delivered"), Date.now());
913
+ }
914
+ catch { /* no return session */ }
915
+ }
916
+ return () => {
917
+ if (ack)
918
+ void this.transport.send(ack).catch(() => { });
919
+ this.onMessageCb?.({ from: sender, content, text: messageText(content), ts });
920
+ };
642
921
  }
643
922
  }