@koralabs/handle-chat-sdk 0.0.13 → 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 (82) hide show
  1. package/LICENSE +6 -0
  2. package/README.md +97 -0
  3. package/assets/libsignal_bg.wasm +0 -0
  4. package/examples/guardian-flow.mjs +88 -0
  5. package/examples/quickstart.mjs +74 -0
  6. package/lib/libsignal-wasm/pkg/handle_libsignal_wasm.d.ts +207 -0
  7. package/lib/libsignal-wasm/pkg/handle_libsignal_wasm.js +945 -0
  8. package/lib/src/chat/ChatService.d.ts +117 -0
  9. package/lib/src/chat/ChatService.js +922 -0
  10. package/lib/src/chat/anchor.d.ts +17 -0
  11. package/lib/src/chat/anchor.js +43 -0
  12. package/lib/src/chat/blob.d.ts +55 -0
  13. package/lib/src/chat/blob.js +247 -0
  14. package/lib/src/chat/chainDirectory.d.ts +24 -0
  15. package/lib/src/chat/chainDirectory.js +93 -0
  16. package/lib/src/chat/demeter.d.ts +3 -0
  17. package/lib/src/chat/demeter.js +8 -0
  18. package/lib/src/chat/directory.d.ts +24 -0
  19. package/lib/src/chat/directory.js +37 -0
  20. package/lib/src/chat/guardian.d.ts +75 -0
  21. package/lib/src/chat/guardian.js +67 -0
  22. package/lib/src/chat/guardianHistory.d.ts +3 -0
  23. package/lib/src/chat/guardianHistory.js +36 -0
  24. package/lib/src/chat/httpRateLimit.d.ts +5 -0
  25. package/lib/src/chat/httpRateLimit.js +54 -0
  26. package/lib/src/chat/identity.d.ts +28 -0
  27. package/lib/src/chat/identity.js +61 -0
  28. package/lib/src/chat/invite.d.ts +19 -0
  29. package/lib/src/chat/invite.js +73 -0
  30. package/lib/src/chat/mesh/b2b.d.ts +17 -0
  31. package/lib/src/chat/mesh/b2b.js +50 -0
  32. package/lib/src/chat/mesh/client.d.ts +28 -0
  33. package/lib/src/chat/mesh/client.js +209 -0
  34. package/lib/src/chat/mesh/node.d.ts +12 -0
  35. package/lib/src/chat/mesh/node.js +46 -0
  36. package/lib/src/chat/mesh/presenceAuth.d.ts +19 -0
  37. package/lib/src/chat/mesh/presenceAuth.js +46 -0
  38. package/lib/src/chat/mesh/protocol.d.ts +92 -0
  39. package/lib/src/chat/mesh/protocol.js +19 -0
  40. package/lib/src/chat/mesh/webrtcAddr.d.ts +3 -0
  41. package/lib/src/chat/mesh/webrtcAddr.js +14 -0
  42. package/lib/src/chat/mesh/wire.d.ts +5 -0
  43. package/lib/src/chat/mesh/wire.js +36 -0
  44. package/lib/src/chat/message.d.ts +28 -0
  45. package/lib/src/chat/message.js +92 -0
  46. package/lib/src/chat/publish.d.ts +6 -0
  47. package/lib/src/chat/publish.js +33 -0
  48. package/lib/src/chat/qr.d.ts +9 -0
  49. package/lib/src/chat/qr.js +25 -0
  50. package/lib/src/chat/receipt.d.ts +17 -0
  51. package/lib/src/chat/receipt.js +22 -0
  52. package/lib/src/chat/sessionStore.d.ts +74 -0
  53. package/lib/src/chat/sessionStore.js +183 -0
  54. package/lib/src/chat/transport.d.ts +51 -0
  55. package/lib/src/chat/transport.js +139 -0
  56. package/lib/src/index.d.ts +19 -0
  57. package/lib/src/index.js +18 -0
  58. package/lib/src/memory.d.ts +18 -0
  59. package/lib/src/memory.js +44 -0
  60. package/lib/src/signal/SignalEngine.d.ts +73 -0
  61. package/lib/src/signal/SignalEngine.js +131 -0
  62. package/package.json +44 -19
  63. package/index.d.ts +0 -8
  64. package/index.js +0 -8
  65. package/interfaces/Chat.d.ts +0 -33
  66. package/interfaces/Chat.js +0 -1
  67. package/interfaces/Directory.d.ts +0 -27
  68. package/interfaces/Directory.js +0 -1
  69. package/interfaces/SessionMessage.d.ts +0 -15
  70. package/interfaces/SessionMessage.js +0 -1
  71. package/interfaces/Store.d.ts +0 -29
  72. package/interfaces/Store.js +0 -1
  73. package/lib/SignalDirectory.d.ts +0 -23
  74. package/lib/SignalDirectory.js +0 -157
  75. package/lib/SignalProtocolStore.d.ts +0 -46
  76. package/lib/SignalProtocolStore.js +0 -195
  77. package/lib/helper.d.ts +0 -2
  78. package/lib/helper.js +0 -17
  79. package/lib/helper.test.d.ts +0 -1
  80. package/lib/helper.test.js +0 -10
  81. package/lib/message-helper.d.ts +0 -20
  82. package/lib/message-helper.js +0 -53
@@ -0,0 +1,922 @@
1
+ import { SignalEngine } from "../signal/SignalEngine.js";
2
+ import { deriveIdentity } from "./identity.js";
3
+ import { EncryptedIdbVault } from "./sessionStore.js";
4
+ import { encodeMessage, decodeMessage, textMessage, mediaMessage, messageText } from "./message.js";
5
+ import { receiptMessage, parseReceipt } from "./receipt.js";
6
+ import { buildBlobMessages, BlobAssembler, isBlobPart } from "./blob.js";
7
+ import { retainedHistory } from "./guardianHistory.js";
8
+ import { presenceEpoch } from "./mesh/presenceAuth.js";
9
+ import { pairwiseMailbox, pairwiseRoutingTopic } from "./mesh/protocol.js";
10
+ // Anti-DoS bounds.
11
+ const MAX_QUEUE = 1000; // cap the offline send queue — drop oldest beyond this
12
+ const MAX_SENT_STATE = 2000; // cap the per-message status map (LRU) so a long session can't leak it
13
+ const MAX_ENVELOPE_BYTES = 256 * 1024; // reject oversized inbound envelopes before decrypting (legit: inline ≤32KB, chunk ≤16KB + sealing)
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;
23
+ // Abuse gate: cold first-contacts from UN-anchored senders (the spam vector) are rate-limited. Anchored
24
+ // senders cost ada per identity (Handle + on-chain anchor) and are chain-verified, so they're unlimited;
25
+ // known contacts (we initiated, or already accepted) are unlimited too.
26
+ export const UNVERIFIED_FIRST_CONTACT_LIMIT = 8;
27
+ const UNVERIFIED_WINDOW_MS = 60_000;
28
+ // Sent-message status is monotonic — it only advances. A late/out-of-order receipt must never regress it.
29
+ const SEND_STATE_RANK = { queued: 0, sent: 1, delivered: 2, read: 3 };
30
+ // Re-derive + re-subscribe to my rotating routing labels this often. Just needs to be < the rotation
31
+ // period (the ±1-epoch neighbour coverage means no message is missed as long as we refresh within it).
32
+ const TOPIC_REFRESH_MS = 30 * 60 * 1000;
33
+ const bytesEqual = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
34
+ // The sealed-sender certificate's handle field is SELF-SIGNED + free-form, so an inbound `sender` is
35
+ // attacker-controlled until chain-as-CA verifies it. Constrain it before it touches any state or the DOM —
36
+ // defense in depth behind output-escaping (which is the real fix). A DENYLIST (not an ASCII allowlist) so
37
+ // legitimate unicode/emoji handles still work: reject HTML-special, quote, whitespace, and control chars.
38
+ const HANDLE_RE = /^\$[^\s<>"'&]{1,100}$/;
39
+ const isValidHandle = (h) => HANDLE_RE.test(h);
40
+ const toB64 = (b) => {
41
+ let s = "";
42
+ for (const x of b)
43
+ s += String.fromCharCode(x);
44
+ return btoa(s);
45
+ };
46
+ const fromB64 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
47
+ const toHex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
48
+ const fromHex = (h) => {
49
+ const o = new Uint8Array(h.length / 2);
50
+ for (let i = 0; i < o.length; i++)
51
+ o[i] = parseInt(h.slice(i * 2, i * 2 + 2), 16);
52
+ return o;
53
+ };
54
+ // Copy into a fresh ArrayBuffer — WASM-memory-backed views can't be passed to crypto.subtle directly.
55
+ const ab = (x) => {
56
+ const out = new Uint8Array(x.byteLength);
57
+ out.set(x);
58
+ return out;
59
+ };
60
+ // Content fingerprint of a sealed envelope body, for inbound dedup (SHA-256 → base64). Identical for the
61
+ // two copies of the same message (direct + mailbox); distinct ciphertexts seal to distinct bodies.
62
+ const envelopeFp = async (body) => toB64(new Uint8Array(await crypto.subtle.digest("SHA-256", ab(body))));
63
+ const toStored = (m) => ({ from: m.from, mime: m.content.mime, body: toB64(m.content.body), meta: m.content.meta, ts: m.ts });
64
+ const fromStored = (s) => ({ from: s.from, content: { mime: s.mime, body: fromB64(s.body), meta: s.meta }, ts: s.ts });
65
+ /**
66
+ * Walk a serialized PQXDH bundle's length-prefixed fields — mirrors libsignal-wasm `createBundle`'s layout:
67
+ * regId, deviceId, spkId, spkPub, spkSig, kyberId, kyberPub, kyberSig, identityKey, presenceAuthPub.
68
+ * Returns the identity key and the presence-auth key (Tier 2 Stage 3; absent in older bundles → empty).
69
+ */
70
+ const parseBundle = (bundle) => {
71
+ const dv = new DataView(bundle.buffer, bundle.byteOffset, bundle.byteLength);
72
+ let i = 0;
73
+ const u32 = () => {
74
+ const v = dv.getUint32(i);
75
+ i += 4;
76
+ return v;
77
+ };
78
+ const bytes = () => {
79
+ const n = u32();
80
+ const b = bundle.subarray(i, i + n);
81
+ i += n;
82
+ return b;
83
+ };
84
+ u32(); // registration id
85
+ u32(); // device id
86
+ u32(); // signed-pre-key id
87
+ bytes(); // signed-pre-key pub
88
+ bytes(); // signed-pre-key sig
89
+ u32(); // kyber id
90
+ bytes(); // kyber pub
91
+ bytes(); // kyber sig
92
+ const identityKey = bytes();
93
+ const presenceAuthPub = i < bundle.byteLength ? bytes() : new Uint8Array(0);
94
+ return { identityKey, presenceAuthPub };
95
+ };
96
+ /** The identity key (chain-as-CA cross-check of a sealed sender's claimed key vs. what the handle publishes). */
97
+ export const bundleIdentityKey = (bundle) => parseBundle(bundle).identityKey;
98
+ /**
99
+ * Orchestrates one handle's chat: derive the wallet-rooted identity, provision the WASM Signal
100
+ * engine, publish the bundle to the directory, and send/receive E2E messages over the transport.
101
+ * Crypto = libsignal (WASM). Directory/transport are seams (demo: localStorage + BroadcastChannel).
102
+ */
103
+ export class ChatService {
104
+ handle;
105
+ directory;
106
+ transport;
107
+ now;
108
+ engine;
109
+ onMessageCb = null;
110
+ onReceiptCb = null;
111
+ onKeyChangeCb = null;
112
+ onSendUpdateCb = null;
113
+ /** State of my outbound messages by id: "queued" (offline) → "sent" → delivered/read (peer acks). */
114
+ #sentState = new Map();
115
+ /** Outbound messages sealed but not yet handed to the network (offline) — retried on reconnect. */
116
+ #queue = [];
117
+ #flushTimer = null;
118
+ #activeFlush = null;
119
+ #dispatchChain = Promise.resolve();
120
+ #onlineHandler = null;
121
+ /** My current rotating routing labels (prev/current/next epoch) + the timer that rolls them over. */
122
+ #topics = [];
123
+ #topicTimer = null;
124
+ /** Reassembles inbound streamed blobs (large media sent as ref + chunks). */
125
+ #assembler = new BlobAssembler();
126
+ /** Timestamps of recently-admitted cold first-contacts from un-anchored senders (sliding-window limit). */
127
+ #unverifiedAdmissions = [];
128
+ started = false;
129
+ #bundle = null;
130
+ #vault;
131
+ #useDefaultVault;
132
+ #contacts = new Set();
133
+ // Peers I've received from — they know me, so they subscribe to our pairwise label and I can address them
134
+ // there (Tier 2). Until then I deposit at their PUBLIC first-contact slot. Reconstructed from history on
135
+ // restore (any thread with an inbound message). [[tier2-session-bound-topics]]
136
+ #convReady = new Set();
137
+ // Tier 2 Stage 3: each contact's presence-auth public key (from their bundle), used to address their PUBLIC
138
+ // first-contact slot `HKDF(peerPA, epoch)`. Persisted in the snapshot.
139
+ #peerPA = new Map();
140
+ // Verify-once-then-warn (Tier 2): the identity key I verified for each conversation at first contact. I
141
+ // trust THIS key + the ratchet thereafter — NOT the live, mutable on-chain anchor — so an established
142
+ // conversation survives a handle re-anchor/transfer instead of being silently dropped. Reconstructed from
143
+ // the persisted session on restore (`engine.peerIdentityKey`). [[tier2-session-bound-topics]]
144
+ #trustedKey = new Map();
145
+ #persistChain = Promise.resolve();
146
+ #recvChain = Promise.resolve(); // serializes inbound processing in arrival order
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;
153
+ /** Decrypted conversation history (per remote), restored on start + appended on every message. */
154
+ #history = new Map();
155
+ #historyChain = Promise.resolve();
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
163
+ constructor(handle, directory, transport,
164
+ /** Where per-device session state persists. Omit for the default (wallet-encrypted IndexedDB);
165
+ * pass `null` to disable persistence; inject a custom vault in tests. */
166
+ vault,
167
+ /** Clock for topic-epoch derivation — injectable so tests can cross a rotation boundary. */
168
+ now = () => Date.now()) {
169
+ this.handle = handle;
170
+ this.directory = directory;
171
+ this.transport = transport;
172
+ this.now = now;
173
+ this.#vault = vault === undefined ? null : vault;
174
+ this.#useDefaultVault = vault === undefined;
175
+ }
176
+ /** Provision identity + Signal engine from the wallet seed, restore any persisted session, publish, receive. */
177
+ #stopped = false;
178
+ async start(seed) {
179
+ if (this.#stopped)
180
+ throw new Error("ChatService stopped");
181
+ if (this.started)
182
+ return;
183
+ const { priv, registrationId } = await deriveIdentity(seed, this.handle);
184
+ this.engine = await SignalEngine.create(this.handle, priv, registrationId);
185
+ // Persistence: default to the wallet-encrypted IndexedDB vault (re-derives its key from the seed).
186
+ if (this.#useDefaultVault)
187
+ this.#vault = await EncryptedIdbVault.create(seed);
188
+ // CRITICAL: the snapshot load must distinguish "no record" (null → genuine new user) from a transient
189
+ // read/decrypt error (throws). We must NOT catch-to-null here: doing so would treat a recoverable error
190
+ // as a fresh user and mint+persist a NEW identity over the intact snapshot, destroying the session,
191
+ // anchor binding, and history. On error we let start() throw so the caller can retry — never clobber.
192
+ const snapshot = this.#vault ? await this.#vault.load(this.handle) : null;
193
+ if (snapshot) {
194
+ // Resume: restore the ratchets/identities/pre-keys and re-publish the SAME bundle (so the
195
+ // on-chain anchor stays valid) — no re-handshake.
196
+ this.engine.importState(snapshot.state);
197
+ this.#bundle = snapshot.bundle;
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);
205
+ for (const [h, hex] of Object.entries(snapshot.peerPA ?? {}))
206
+ this.#peerPA.set(h, fromHex(hex)); // Tier 2 Stage 3
207
+ // Restore each conversation's decrypted history (encrypted at rest under the same wallet key).
208
+ for (const remote of this.#contacts) {
209
+ // Reconstruct the verify-once TRUSTED key from the restored session (NOT the live anchor, which may
210
+ // have since moved). This is what keeps an established conversation alive across a handle re-anchor.
211
+ const trusted = this.engine.peerIdentityKey(remote);
212
+ if (trusted)
213
+ this.#trustedKey.set(remote, trusted);
214
+ const stored = this.#vault ? await this.#vault.loadHistory(this.handle, remote) : null;
215
+ if (stored && stored.length) {
216
+ this.#history.set(remote, stored.map(fromStored));
217
+ // A thread with any INBOUND message means this peer has reached me → they know me → I can address
218
+ // them at our pairwise topic (Tier 2). A contact I only opened-but-never-heard-from stays public.
219
+ if (stored.some((m) => m.from === remote))
220
+ this.#convReady.add(remote);
221
+ }
222
+ }
223
+ // Restore the outbound queue (messages sealed while offline before a reload).
224
+ const queued = this.#vault ? await this.#vault.loadQueue(this.handle) : null;
225
+ if (queued && queued.length) {
226
+ this.#queue = queued;
227
+ for (const q of queued)
228
+ if (!this.#sentState.has(q.id))
229
+ this.#setSentState(q.id, "queued");
230
+ }
231
+ }
232
+ else {
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();
237
+ }
238
+ if (this.#stopped)
239
+ throw new Error("ChatService stopped");
240
+ this.directory.publish(this.handle, this.#bundle);
241
+ // Subscribe under our scrambled, ROTATING topics (prev/current/next epoch), not our handle — the relay
242
+ // routes by opaque labels that change over time, so it can't track us or who messages us. A timer rolls
243
+ // the set forward as epochs advance.
244
+ this.#topics = this.#myTopicSet();
245
+ this.transport.subscribe(this.#topics, (env) => this.receive(env), this.#sign, this.#receiveDurably);
246
+ this.#topicTimer = setInterval(() => this.#resubscribe(), TOPIC_REFRESH_MS);
247
+ this.started = true;
248
+ // Flush the outbound queue now and whenever connectivity returns.
249
+ if (typeof globalThis.addEventListener === "function") {
250
+ this.#onlineHandler = () => void this.flushQueue();
251
+ globalThis.addEventListener("online", this.#onlineHandler);
252
+ }
253
+ void this.flushQueue();
254
+ this.#scheduleFlush();
255
+ }
256
+ /** Serialize + encrypt the current session state to the vault. Serialized via a chain so concurrent
257
+ * mutations don't interleave writes. A mailbox consumer must await the transaction. */
258
+ persist() {
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();
264
+ const peerPA = {};
265
+ for (const [h, k] of this.#peerPA)
266
+ peerPA[h] = toHex(k);
267
+ const snap = { state: this.engine.exportState([...this.#contacts]), bundle: this.#bundle, contacts: [...this.#contacts], peerPA };
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;
291
+ }
292
+ /** Append a message to a conversation's history and persist that thread (capped, chained writes). */
293
+ record(remote, msg) {
294
+ const list = this.#history.get(remote) ?? [];
295
+ list.push(msg);
296
+ const retained = retainedHistory(list, this.handle, ChatService.MAX_HISTORY);
297
+ this.#history.set(remote, retained);
298
+ if (!this.#vault)
299
+ return;
300
+ const snapshot = retained.map(toStored);
301
+ if (this.#vault.commitInbound) {
302
+ this.#dirtyHistory.set(remote, snapshot);
303
+ return;
304
+ }
305
+ this.#historyChain = this.#historyChain.then(() => this.#vault?.saveHistory(this.handle, remote, snapshot)).catch(() => { });
306
+ }
307
+ /** Restored conversation history (per remote handle) — for the UI to seed its threads on reopen. */
308
+ loadedHistory() {
309
+ return this.#history;
310
+ }
311
+ /** Await any in-flight persistence (session state + history) — so a reopen reads the latest. */
312
+ async flush() {
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]);
317
+ }
318
+ /** Tear down timers + the global `online` listener, and stop the transport. Idempotent. Call before
319
+ * discarding the service (e.g. a wallet switch / re-provision) so nothing leaks or fires on a stale engine. */
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;
327
+ if (this.#flushTimer)
328
+ clearInterval(this.#flushTimer);
329
+ if (this.#topicTimer)
330
+ clearInterval(this.#topicTimer);
331
+ this.#flushTimer = null;
332
+ this.#topicTimer = null;
333
+ if (this.#onlineHandler && typeof globalThis.removeEventListener === "function") {
334
+ globalThis.removeEventListener("online", this.#onlineHandler);
335
+ }
336
+ this.#onlineHandler = null;
337
+ this.transport.stop();
338
+ }
339
+ /** This identity's publishable key-bundle — what goes in an invite (or the chain anchor). */
340
+ myBundle() {
341
+ if (!this.#bundle)
342
+ throw new Error("ChatService not started");
343
+ return this.#bundle;
344
+ }
345
+ /** My wallet-rooted identity public key (libsignal serialization: type byte + 32-byte Curve25519).
346
+ * SSR (secrets.handle.me) hands this out in a guardian-consent — "the key is handed over the medium". */
347
+ myIdentityKey() {
348
+ return bundleIdentityKey(this.myBundle());
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
+ }
354
+ /** Open an outbound session to a peer by resolving their published bundle (cold lookup). */
355
+ openChat(remote) {
356
+ if (!("resolve" in this.directory))
357
+ throw new Error("Use openChatAsync with an asynchronous directory");
358
+ const bundle = this.directory.resolve(remote);
359
+ if (!bundle)
360
+ return false;
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);
374
+ return true;
375
+ }
376
+ /** Open an outbound session from a bundle handed over directly (invite link / QR — no directory). */
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;
386
+ this.engine.processBundle(remote, bundle);
387
+ this.#contacts.add(remote);
388
+ this.#learnFromBundle(remote, bundle);
389
+ this.#resubscribe(); // listen on our pairwise label too, so the peer's reply on it reaches me
390
+ this.persist();
391
+ }
392
+ /** Record what a peer's bundle tells us: the verify-once trusted identity key, and (Tier 2 Stage 3) their
393
+ * presence-auth key so we can address their public first-contact slot. */
394
+ #learnFromBundle(remote, bundle) {
395
+ const { identityKey, presenceAuthPub } = parseBundle(bundle);
396
+ this.#trustedKey.set(remote, identityKey); // verify-once: trust the key I open the session with
397
+ if (presenceAuthPub.length)
398
+ this.#peerPA.set(remote, presenceAuthPub);
399
+ }
400
+ /** Send a plain-text message (convenience over {@link sendContent}). */
401
+ send(remote, text) {
402
+ this.sendContent(remote, textMessage(text));
403
+ }
404
+ /** Sealed-sender encrypt and send typed content (any MIME) to a peer (must have an open session). The
405
+ * wire envelope carries no sender label — the recipient recovers it from the seal. Returns the message
406
+ * id (stamped into `meta.id`), which delivery/read receipts reference. */
407
+ sendContent(remote, content) {
408
+ const id = content.meta?.id ?? crypto.randomUUID();
409
+ const stamped = content.meta?.id ? content : { ...content, meta: { ...content.meta, id } };
410
+ const ts = this.now();
411
+ const env = this.#seal(remote, stamped, ts); // sealed at the current epoch; a retry re-addresses
412
+ this.#setSentState(id, "queued"); // pending until the network takes it
413
+ this.record(remote, { from: this.handle, content: stamped, ts });
414
+ this.persist();
415
+ this.#emitSendUpdate();
416
+ void this.#dispatch(id, remote, env);
417
+ return id;
418
+ }
419
+ /** Seal + address an envelope. The relay sees only an opaque, rotating label. The `slot` tells the mesh
420
+ * which presence table to use: a first-contact message rides the PUBLIC slot, an established one the
421
+ * unguessable PAIRWISE slot (Tier 2 Stage 3). */
422
+ #seal(remote, content, ts) {
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 };
426
+ }
427
+ /** Authenticate a PUBLIC-slot presence registration (Tier 2 Stage 3): if `topic` is one of my current
428
+ * public first-contact labels, sign `topic‖addr‖epoch` so the helper accepts it. Returns null for a
429
+ * pairwise/unknown topic (registered unauthenticated — it's unguessable). Bound as a field so it can be
430
+ * handed to the transport as a callback. */
431
+ #sign = (topic, addr) => {
432
+ const now = this.now();
433
+ const e = presenceEpoch(now);
434
+ const idx = this.engine.publicSlotTopics(now).indexOf(topic); // [prev, cur, next]
435
+ if (idx < 0)
436
+ return null;
437
+ const epoch = [e - 1, e, e + 1][idx];
438
+ return { epoch, pub: this.engine.presenceAuthPub(), sig: this.engine.signPresence(fromHex(topic), addr, epoch) };
439
+ };
440
+ /** Where to deposit a message for `remote` (Tier 2). Once the peer has reached me they subscribe to our
441
+ * unguessable PAIRWISE label — use it (defeats the chain-watcher; survives a handle transfer). Before that
442
+ * (I'm initiating, no reply yet) the peer may not know me, so I deposit at their PUBLIC first-contact slot. */
443
+ #sendTopic(remote, ts) {
444
+ if (this.#convReady.has(remote)) {
445
+ try {
446
+ return pairwiseMailbox(this.engine.convSendTopic(remote, ts));
447
+ }
448
+ catch {
449
+ /* no session/identity — fall back to the public slot */
450
+ }
451
+ }
452
+ // Public first-contact slot = HKDF(peer's presence-auth pub, epoch), derived from their bundle (Stage 3).
453
+ const pa = this.#peerPA.get(remote);
454
+ if (pa)
455
+ return this.engine.publicSlotTopicFor(pa, ts);
456
+ return this.engine.peerTopic(remote, ts); // legacy fallback (peer bundle predates presence-auth)
457
+ }
458
+ /** My full subscription set: the PUBLIC first-contact slot (prev/cur/next), plus — for every known contact
459
+ * — the pairwise labels they deposit at FOR me (prev/cur/next). All rotate by epoch. */
460
+ #myTopicSet() {
461
+ const set = new Set(this.engine.publicSlotTopics(this.now())); // public first-contact slot (Stage 3)
462
+ for (const c of this.#contacts) {
463
+ try {
464
+ for (const t of this.engine.convRecvTopics(c, this.now()))
465
+ set.add(pairwiseMailbox(t));
466
+ }
467
+ catch {
468
+ /* no identity for this contact yet — only the public slot covers them */
469
+ }
470
+ }
471
+ return [...set];
472
+ }
473
+ /** Recompute the subscription set and re-subscribe if it changed (epoch rolled, or a new contact added a
474
+ * pairwise label). Idempotent. */
475
+ #resubscribe() {
476
+ if (!this.started)
477
+ return;
478
+ const next = this.#myTopicSet();
479
+ if (next.join() !== this.#topics.join()) {
480
+ this.#topics = next;
481
+ this.transport.subscribe(next, (env) => this.receive(env), this.#sign, this.#receiveDurably);
482
+ }
483
+ }
484
+ /** Hand an envelope to the network; queue it if we're offline or the network can't take it. `track`
485
+ * is false for blob chunks — reliable, but not a user-visible message whose status should change. */
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) {
495
+ // Offline OR a non-empty backlog → queue, so the queue is the sole ordering authority (a fresh send
496
+ // must not overtake messages still waiting to flush).
497
+ if (this.#offline() || this.#queue.length > 0)
498
+ return this.#enqueue(id, remote, env, track);
499
+ const ok = await this.transport.send(env).catch(() => false);
500
+ if (this.#stopped)
501
+ return;
502
+ if (ok) {
503
+ if (track)
504
+ this.#advanceSentState(id, "sent");
505
+ }
506
+ else {
507
+ this.#enqueue(id, remote, env, track);
508
+ }
509
+ }
510
+ #enqueue(id, remote, env, track = true) {
511
+ this.#queue.push({ id, remote, to: env.to, body: toB64(env.body), ts: env.ts, track });
512
+ if (this.#queue.length > MAX_QUEUE)
513
+ this.#queue.splice(0, this.#queue.length - MAX_QUEUE); // bound memory/storage
514
+ if (track) {
515
+ this.#setSentState(id, "queued");
516
+ this.#emitSendUpdate();
517
+ }
518
+ this.#persistQueue();
519
+ this.#scheduleFlush();
520
+ }
521
+ /** Set a sent-message status, bounding the map (LRU by insertion order) so a long session can't leak it. */
522
+ #setSentState(id, state) {
523
+ this.#sentState.set(id, state);
524
+ if (this.#sentState.size > MAX_SENT_STATE) {
525
+ const oldest = this.#sentState.keys().next().value;
526
+ if (oldest !== undefined && oldest !== id)
527
+ this.#sentState.delete(oldest);
528
+ }
529
+ }
530
+ #offline() {
531
+ return typeof navigator !== "undefined" && navigator.onLine === false;
532
+ }
533
+ /** Sliding-window rate limit for cold first-contacts from un-anchored senders. */
534
+ #admitUnverified() {
535
+ const now = Date.now();
536
+ this.#unverifiedAdmissions = this.#unverifiedAdmissions.filter((t) => now - t < UNVERIFIED_WINDOW_MS);
537
+ if (this.#unverifiedAdmissions.length >= UNVERIFIED_FIRST_CONTACT_LIMIT)
538
+ return false;
539
+ this.#unverifiedAdmissions.push(now);
540
+ return true;
541
+ }
542
+ /** Retry queued envelopes in order, stopping at the first the network still won't take (preserves order). */
543
+ async flushQueue() {
544
+ await this.#dispatchChain;
545
+ if (this.#offline() || this.#stopped || this.#queue.length === 0)
546
+ return;
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 */
563
+ }
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");
573
+ }
574
+ this.#persistQueue();
575
+ if (this.#queue.length === 0 && this.#flushTimer) {
576
+ clearInterval(this.#flushTimer);
577
+ this.#flushTimer = null;
578
+ }
579
+ }
580
+ #scheduleFlush() {
581
+ if (this.#flushTimer || this.#queue.length === 0)
582
+ return;
583
+ this.#flushTimer = setInterval(() => void this.flushQueue(), 3000);
584
+ }
585
+ #persistQueue() {
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(() => { });
591
+ }
592
+ #emitSendUpdate() {
593
+ this.onSendUpdateCb?.();
594
+ }
595
+ /** Send a control message (receipt) — best-effort, never queued. */
596
+ #sendRaw(remote, content, ts) {
597
+ void this.transport.send(this.#seal(remote, content, ts)).catch(() => { });
598
+ }
599
+ /** Mark a received message read — sends a "read" receipt to its sender. */
600
+ markRead(remote, messageId) {
601
+ this.#sendRaw(remote, receiptMessage(messageId, "read"), Date.now());
602
+ this.persist();
603
+ }
604
+ /** Advance a sent message's status, never regressing it (out-of-order delivered/read acks are common). */
605
+ #advanceSentState(id, state) {
606
+ const cur = this.#sentState.get(id);
607
+ if (cur && SEND_STATE_RANK[cur] >= SEND_STATE_RANK[state])
608
+ return;
609
+ this.#setSentState(id, state);
610
+ this.#emitSendUpdate();
611
+ }
612
+ /** Current delivery state of one of my sent messages ("queued"/"sent" until the peer acks). */
613
+ sentState(messageId) {
614
+ return this.#sentState.get(messageId);
615
+ }
616
+ onReceipt(cb) {
617
+ this.onReceiptCb = cb;
618
+ }
619
+ /** Register a handler for a conversation's identity key changing after first contact (verify-once-then-warn
620
+ * — the handle was re-anchored / may have changed hands, or a different key tried to claim it). */
621
+ onKeyChange(cb) {
622
+ this.onKeyChangeCb = cb;
623
+ }
624
+ /** Fires when any sent-message state changes (queued/sent/delivered/read) — for the UI to refresh ticks. */
625
+ onSendUpdate(cb) {
626
+ this.onSendUpdateCb = cb;
627
+ }
628
+ /** Send a large blob (image/audio/video/…) by STREAMING it: encrypt + chunk + content-address, then
629
+ * send a small `blob-ref` (tracked, carries the message id) + raw `blob-chunk` messages (reliable, but
630
+ * untracked). The recipient reassembles + verifies + decrypts. Returns the message id. The caller still
631
+ * echoes the full media locally (the sender already has the bytes). */
632
+ async sendBlob(remote, mime, bytes, name) {
633
+ const id = crypto.randomUUID();
634
+ this.#setSentState(id, "queued");
635
+ this.record(remote, { from: this.handle, content: mediaMessage(mime, bytes, { name: name ?? "", id }), ts: Date.now() });
636
+ this.persist();
637
+ this.#emitSendUpdate();
638
+ const { ref, chunks } = await buildBlobMessages(id, mime, bytes, name);
639
+ if (this.#stopped)
640
+ throw new Error("ChatService stopped");
641
+ this.#reliableSend(remote, ref, id, true); // the ref's delivery flips the blob's status
642
+ for (const c of chunks)
643
+ this.#reliableSend(remote, c, `chunk:${crypto.randomUUID()}`, false);
644
+ return id;
645
+ }
646
+ /** Reliable (queue-aware) send that does NOT record in history — for blob ref/chunk transport messages. */
647
+ #reliableSend(remote, content, id, track) {
648
+ void this.#dispatch(id, remote, this.#seal(remote, content, Date.now()), track);
649
+ }
650
+ onMessage(cb) {
651
+ this.onMessageCb = cb;
652
+ }
653
+ /** Serialize inbound processing: each envelope fully completes (incl. async blob reassembly) before the
654
+ * next, so app-level ordering of history/UI is preserved even when a blob await interleaves. */
655
+ receive(env) {
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();
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) {
743
+ this.#seenEnvelopes.add(fp);
744
+ if (this.#seenEnvelopes.size > MAX_SEEN_ENVELOPES) {
745
+ const oldest = this.#seenEnvelopes.values().next().value;
746
+ if (oldest !== undefined)
747
+ this.#seenEnvelopes.delete(oldest);
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;
810
+ try {
811
+ const { sender, identityKey, body } = this.engine.sealedReceive(env.body);
812
+ if (sender !== hint.sender || !bytesEqual(identityKey, hint.identityKey))
813
+ return;
814
+ if (trusted) {
815
+ // Established conversation: trust the key I verified at first contact + the ratchet — do NOT re-check
816
+ // the live anchor per message (that's what silently broke a conversation when its handle was
817
+ // re-anchored / sold). A DIFFERENT key claiming this conversation is a key change I never verified:
818
+ // warn and DROP (the app must explicitly re-verify before trusting it).
819
+ if (!bytesEqual(trusted, identityKey)) {
820
+ this.onKeyChangeCb?.({ handle: sender, knownKey: trusted, newKey: identityKey, anchorDiverged: false });
821
+ return;
822
+ }
823
+ }
824
+ else {
825
+ // First contact: chain-as-CA if the handle is anchored (the claimed key MUST match the on-chain
826
+ // anchor, else it's an impersonator → drop); otherwise TOFU (invite/out-of-band bundle). Record the
827
+ // verified key as this conversation's trusted identity.
828
+ if (anchorKey && !bytesEqual(anchorKey, identityKey))
829
+ return;
830
+ }
831
+ // Abuse gate. Always admit a KNOWN contact (we initiated, or already accepted) or an ANCHORED sender
832
+ // (chain-verified above; an anchor + Handle cost ada per identity → Sybil-resistant). A cold
833
+ // first-contact from an UN-anchored sender is the spam vector — rate-limit it. (An invitee holds our
834
+ // bundle by our consent and gets through within the budget, then is known and unlimited thereafter.)
835
+ if (!trusted)
836
+ this.#trustedKey.set(sender, identityKey);
837
+ // The sender reached me → they know me and subscribe to our pairwise label, so address them there from
838
+ // now on (Tier 2). A receipt counts too. If this is a newly-known contact, re-subscribe so I also listen
839
+ // on the pairwise label they'll deposit at.
840
+ this.#convReady.add(sender);
841
+ if (!this.#contacts.has(sender)) {
842
+ this.#contacts.add(sender);
843
+ this.#resubscribe();
844
+ }
845
+ const content = decodeMessage(body);
846
+ // Receipts are control, not content: update my sent-message state and surface to the UI, never record.
847
+ const receipt = parseReceipt(content);
848
+ if (receipt) {
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();
859
+ this.onReceiptCb?.({ from: sender, ref: receipt.ref, state: receipt.state });
860
+ } : undefined);
861
+ return;
862
+ }
863
+ // Streamed blob: ref/chunk parts are control until the blob completes — then surface the full media.
864
+ let visible = content;
865
+ if (isBlobPart(content)) {
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
+ }
882
+ }
883
+ const notify = visible ? this.#prepareIncoming(sender, visible, env.ts) : undefined;
884
+ await this.#finishReceipt(fp, notify);
885
+ }
886
+ catch {
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.
889
+ }
890
+ }
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) {
906
+ this.record(sender, { from: sender, content, ts });
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
+ };
921
+ }
922
+ }