@ping-app/ping-openmls-sdk 0.10.3 → 0.10.5

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/wasm-memory.ts","../src/worker.ts","../src/epoch-events.ts","../src/catch-up-pass.ts","../src/request-lanes.ts"],"sourcesContent":["// Linear-memory reservation shared by every realm that instantiates the wasm.\n\n/**\n * Linear-memory headroom the worker reserves from JavaScript right after\n * instantiation, largest first; a target the engine refuses (`RangeError`)\n * falls through to the next. Sized so the Argon2id recovery backup\n * (64 MiB of blocks in ONE allocation) and a large history bundle fit\n * inside memory the module already owns.\n *\n * Why from JS and not inside the module: Safari/JSC (macOS 26 / iOS 26,\n * IPInt) crashes the WebContent process when the wasm `memory.grow`\n * INSTRUCTION runs in a Worker while the Web Inspector is attached — the GC\n * it triggers walks the stack and dies on the wasm frame. The same grow\n * requested through `WebAssembly.Memory.prototype.grow` has only JS frames\n * on the stack and is fine. The module's allocator (`ping-wasm/src/alloc.rs`)\n * claims these pages before it would ever execute the instruction itself.\n * The pages are virtual until touched, so an idle worker costs nothing extra.\n */\nexport const RESERVE_MIB_TARGETS = [192, 128, 64, 32] as const;\nconst WASM_PAGE_BYTES = 64 * 1024;\n\n/** Memories already reserved: `init` is idempotent per realm and returns the\n * same instance, so a second open must not grow it again. */\nconst reserved = new WeakSet<WebAssembly.Memory>();\n\nexport function reserveLinearMemory(memory: WebAssembly.Memory): void {\n if (reserved.has(memory)) return;\n reserved.add(memory);\n for (const mib of RESERVE_MIB_TARGETS) {\n try {\n memory.grow((mib * 1024 * 1024) / WASM_PAGE_BYTES);\n return;\n } catch {\n // Over the engine's limit for this memory; try a smaller reservation.\n }\n }\n}\n\n","// Web Worker entry. Owns the WASM `PingClient` instance. Receives Requests from the main thread\n// and posts Responses back. Storage / Transport calls back to the main thread are tracked by id.\n//\n// The WASM module is loaded lazily on the first `init` so that ephemeral identity-only spawns\n// (used by `MessagingClient.generateIdentity()`) don't pay the cost.\n\n/// <reference lib=\"webworker\" />\n\nimport { reserveLinearMemory } from \"./wasm-memory\";\nimport init, {\n PingClient,\n sealLinkingTicket as wasmSealLinkingTicket,\n openLinkingTicket as wasmOpenLinkingTicket,\n hpkeSeal as wasmHpkeSeal,\n hpkeOpen as wasmHpkeOpen,\n hpkeSealRaw as wasmHpkeSealRaw,\n hpkeOpenRaw as wasmHpkeOpenRaw,\n hpkeGenerateKeypair as wasmHpkeGenerateKeypair,\n sealLinkingTicketPq as wasmSealLinkingTicketPq,\n openLinkingTicketPq as wasmOpenLinkingTicketPq,\n hpkeSealPq as wasmHpkeSealPq,\n hpkeOpenPq as wasmHpkeOpenPq,\n hpkeSealRawPq as wasmHpkeSealRawPq,\n hpkeOpenRawPq as wasmHpkeOpenRawPq,\n hpkeGenerateKeypairPq as wasmHpkeGenerateKeypairPq,\n deviceGroupIdFor as wasmDeviceGroupIdFor,\n hpkePublicKeyFromSeed as wasmHpkePublicKeyFromSeed,\n hpkePublicKeyFromPrivate as wasmHpkePublicKeyFromPrivate,\n signDeviceReauth as wasmSignDeviceReauth,\n signDeviceLinkApproval as wasmSignDeviceLinkApproval,\n signDeviceLinkPossession as wasmSignDeviceLinkPossession,\n decodeCatchupSnapshot as wasmDecodeCatchupSnapshot,\n generateMnemonicPhrase as wasmGenerateMnemonicPhrase,\n normalizeMnemonicPhrase as wasmNormalizeMnemonicPhrase,\n encryptBackup as wasmEncryptBackup,\n decryptBackup as wasmDecryptBackup,\n checkBackupPhrase as wasmCheckBackupPhrase,\n sealHistoryBundle as wasmSealHistoryBundle,\n openHistoryBundle as wasmOpenHistoryBundle,\n sealHistoryBundlePq as wasmSealHistoryBundlePq,\n openHistoryBundlePq as wasmOpenHistoryBundlePq,\n} from \"../wasm/ping_wasm\";\nimport { catchUpPass } from \"./catch-up-pass\";\nimport {\n advancedEpochs, changedHoldings, type ConversationEpoch, conversationKey, epochMap,\n} from \"./epoch-events\";\nimport type { Request, Response, StorageFeatures, TransportFeatures } from \"./protocol\";\nimport { RequestScheduler } from \"./request-lanes\";\nimport type {\n ApplyBatchResultWire,\n ConversationRemovalWire,\n ConversationUpdateWire,\n LogHeadWire,\n SequencedEnvelopeWire,\n SyncStepResultWire,\n} from \"./sequenced\";\nimport type { ConversationMeta, DeviceId, IncomingMessage, MessageEnvelope } from \"./types\";\n\ndeclare const self: DedicatedWorkerGlobalScope;\n\nlet client: PingClient | null = null;\nlet wasmReady: Promise<void> | null = null;\n\nconst pendingStorage = new Map<number, (r: { ok: boolean; value: unknown }) => void>();\nconst pendingTransport = new Map<number, (r: { ok: boolean; value: unknown }) => void>();\nlet nextStorageId = 1;\nlet nextTransportId = 1;\n/** Calls made to the host transport so far. The worker runs one request at a\n * time, so the difference around a request is what that request sent and\n * fetched (see `sendLeftCopyBehind`). */\nlet transportCalls = 0;\n\nconst proxyStorage = {\n get: (namespace: string, key: string) => callMain<Uint8Array | null>(\"storage\", \"get\", [namespace, key]),\n put: (namespace: string, key: string, value: Uint8Array) =>\n callMain<void>(\"storage\", \"put\", [namespace, key, value]),\n del: (namespace: string, key: string) => callMain<void>(\"storage\", \"del\", [namespace, key]),\n listKeys: (namespace: string, prefix: string) =>\n callMain<string[]>(\"storage\", \"listKeys\", [namespace, prefix]),\n};\n// The two optional methods are declared on the proxy ONLY when the host\n// storage has them: the wasm bridge decides by their presence whether to hand\n// the per-row MLS store's delta to the host as one atomic batch (and read the\n// rows in one call) or to take its own journalled row-by-row fallback.\nconst applyBatchProxy = (namespace: string, puts: Array<[string, Uint8Array]>, deletes: string[]) =>\n callMain<void>(\"storage\", \"applyBatch\", [namespace, puts, deletes]);\nconst listEntriesProxy = (namespace: string, prefix: string) =>\n callMain<Array<[string, Uint8Array]>>(\"storage\", \"listEntries\", [namespace, prefix]);\nfunction makeProxyStorage(features: StorageFeatures | undefined) {\n return {\n ...proxyStorage,\n ...(features?.applyBatch ? { applyBatch: applyBatchProxy } : {}),\n ...(features?.listEntries ? { listEntries: listEntriesProxy } : {}),\n };\n}\nconst proxyTransport = {\n send: (envelope: MessageEnvelope) => callMain<void>(\"transport\", \"send\", [envelope]),\n // Always declared here: the main-thread dispatch emulates it with\n // sequential sends when the host transport has no `sendBatch`, encoding a\n // partial delivery with the `batch partial after <n>:` sentinel the wasm\n // bridge understands (see index.ts `BATCH_PARTIAL_PREFIX`).\n sendBatch: (envelopes: MessageEnvelope[]) => callMain<void>(\"transport\", \"sendBatch\", [envelopes]),\n fetchSince: (conv: Uint8Array, cursor: Uint8Array, limit: number) =>\n callMain<MessageEnvelope[]>(\"transport\", \"fetchSince\", [conv, cursor, limit]),\n discoverDevices: (userId: Uint8Array) => callMain<unknown[]>(\"transport\", \"discoverDevices\", [userId]),\n // Optional on the host (see `Transport.setNextWelcomeRecipients` in types.ts).\n // The main-thread dispatch (index.ts `handleWorker → case \"transport.call\"`)\n // resolves `undefined` to a `transport.reply { ok: true, value: undefined }`\n // when the host hasn't implemented the method, which we treat as a no-op.\n setNextWelcomeRecipients: (conv: Uint8Array, recipients: Uint8Array[]) =>\n callMain<void>(\"transport\", \"setNextWelcomeRecipients\", [conv, recipients]),\n};\n\n/** What the host transport declared at `init`; read by the catch-up pass. */\nlet transportFeatures: TransportFeatures = { fetchLogSince: false, fetchLogHeads: false };\n\nconst fetchLogSinceProxy = (position: unknown, limit: number) =>\n callMain<SequencedEnvelopeWire[] | null>(\"transport\", \"fetchLogSince\", [position, limit]);\nconst fetchLogHeadsProxy = () =>\n callMain<LogHeadWire[] | null | undefined>(\"transport\", \"fetchLogHeads\", []);\n\n/**\n * The transport proxy the wasm sees. Unlike `setNextWelcomeRecipients`, the\n * two sequenced-log methods are NOT always declared: the wasm bridge decides\n * by their presence whether to call them or fall back to the core default\n * (`fetchSince` at position 0; no heads), and `fetchLogSince` has no\n * main-thread emulation because only the core can encode the legacy cursor.\n */\nfunction makeProxyTransport(features: TransportFeatures) {\n return {\n ...proxyTransport,\n ...(features.fetchLogSince ? { fetchLogSince: fetchLogSinceProxy } : {}),\n ...(features.fetchLogHeads ? { fetchLogHeads: fetchLogHeadsProxy } : {}),\n };\n}\n\nfunction callMain<T>(kind: \"storage\" | \"transport\", method: string, args: unknown[]): Promise<T> {\n return new Promise((resolve, reject) => {\n const id = kind === \"storage\" ? nextStorageId++ : nextTransportId++;\n const map = kind === \"storage\" ? pendingStorage : pendingTransport;\n if (kind === \"transport\") transportCalls += 1;\n map.set(id, ({ ok, value }) => ok ? resolve(value as T) : reject(new Error(String(value))));\n self.postMessage({ kind: `${kind}.call`, id, method, args } as Response);\n });\n}\n\nasync function ensureWasm() {\n if (wasmReady) return wasmReady;\n // The bundled wasm path is rewritten by the build script to be relative to `dist/`.\n wasmReady = init().then((out) => {\n reserveLinearMemory(out.memory);\n });\n return wasmReady;\n}\n\n// The WASM `PingClient` is SINGLE-THREADED (this one worker). Its async\n// methods hold internal locks across `.await` (e.g. a `conversations`\n// RwLock guard kept while `snapshot_to_storage` awaits IndexedDB). If we\n// let `onmessage` dispatch a SECOND top-level request while the first is\n// suspended at an await, the two WASM calls interleave on the single\n// thread, the second re-acquires a held lock, and `parking_lot`'s wasm\n// stub `panic!`s with \"Parking not supported on this platform\" — which\n// poisons the module (`RuntimeError: unreachable`) and breaks every\n// subsequent call. We therefore SERIALIZE top-level request dispatch:\n// one WASM call runs to completion before the next begins.\n//\n// ONE CALL AT A TIME IS NOT THE SAME AS FIRST COME, FIRST SERVED. A\n// whole-account `syncConversations` used to be one request: every\n// conversation paged inside a single turn, one network round trip each,\n// and a `send` posted while it ran started only after the last of them.\n// On a tab returning from an idle hour that was the whole visible cost of\n// the first message: the composer cleared, the bubble sat on a clock for\n// the length of the pass, and the second message went out at once. The\n// scheduler below keeps the one-call invariant but runs a whole-account\n// pass as a sequence of per-conversation steps (`syncConversation`) and\n// lets everything else queued run between steps. Ordinary requests stay\n// FIFO among themselves, so the inbound ordering that per-conversation\n// chaining on the main thread relies on is untouched; a host's own\n// `syncConversation` for the chat the user is looking at is an ordinary\n// request too, so it runs ahead of the background pass.\n//\n// CRUCIAL: `storage.reply` / `transport.reply` are NOT serialized — an\n// in-flight request awaits those replies (via `callMain`), so queuing\n// them behind the request would deadlock. They resolve pending callbacks\n// immediately, exactly as before.\nconst scheduler = new RequestScheduler();\n\n// Requests that can advance a conversation's MLS epoch WITHOUT an inbound\n// envelope to announce it.\n//\n// `event.conversation` was only ever emitted from `processEnvelope` and\n// `joinConversation`, so it announced exactly one of the three ways an epoch\n// moves: a Commit received from someone else. The other two were invisible to\n// every consumer:\n//\n// 1. A commit THIS device authored. `MessagingClient.dispatchIncoming` drops\n// envelopes whose `sender_device` is ours (the relay echoes our own\n// sends), so the author's own commit never reaches `processEnvelope`.\n// A host that re-derives exported secrets on epoch change — call media\n// keys are the load-bearing case — therefore kept using the PREVIOUS\n// epoch's secret after adding a member, and went silent against everyone\n// who had rotated. It is specifically the device that INVITES that breaks.\n// 2. A commit applied during catch-up. `syncConversations` fetches and\n// applies envelopes but posted nothing, so a client that reconnected after\n// missing a commit resumed on a stale secret.\n//\n// Rather than enumerate emissions per operation (and miss the next one added),\n// the epoch map is snapshotted around these requests and any conversation whose\n// epoch actually MOVED is announced. Conversations are only compared, never\n// created, so this can never invent an event: a freshly joined conversation is\n// already announced by `joinConversation`, and one that disappears (leave/drop)\n// is not an epoch change.\n//\n// `send` is deliberately absent from this set: it is the hot path. It must not\n// pay for two `listConversations` calls, and it reports no conversation event\n// of its own. A send is not only an application message, though: before it\n// encrypts, the core settles a Commit this device left in doubt there and\n// commits pending proposals, and after it the core refreshes this device's\n// leaf when that is due. Each of those moves the epoch, and the first can land\n// a rename. The core reports such a move with the next batch or page, and\n// that is where the host hears it, once. Here the main thread's copy of the\n// conversation is only kept level with the group, and a send that moved\n// nothing reads nothing (see `sendLeftCopyBehind`).\nconst EPOCH_ADVANCING_REQUESTS: ReadonlySet<string> = new Set([\n \"addMembers\",\n \"addMembersWithVerdicts\",\n \"reAdmitDevice\",\n \"removeMembers\",\n \"removeOwnOtherLeaves\",\n \"removeMembersByIdentity\",\n \"commitPendingProposals\",\n \"setConversationName\",\n \"setConversationRoles\",\n \"admitDeviceToChats\",\n \"admitDeviceToChatsConcurrent\",\n \"revokeDevice\",\n \"removeDeviceEverywhere\",\n \"removeOwnDevicesExcept\",\n \"syncConversations\",\n \"syncConversation\",\n \"consumeLinkingTicket\",\n \"importStateSnapshot\",\n]);\n\n// Requests that commit and whose epoch move is NOT announced to the host: it\n// never was, and a new host event is not what keeps a handle fresh. The\n// conversations are compared around them all the same, and the main thread's\n// copy of each one that moved is brought level with `cache.conversations`,\n// which calls no listener. `buildLinkingTicket` commits to the DeviceGroup.\nconst EPOCH_UPKEEP_REQUESTS: ReadonlySet<string> = new Set([\n \"buildLinkingTicket\",\n]);\n\n// THE MAIN THREAD'S COPY OF A CONVERSATION'S METADATA\n//\n// The main thread keeps one `ConversationMeta` per conversation so that a\n// conversation handle can answer `name`, `epoch` and `meta()` without a round\n// trip. That copy used to be refilled by `listConversations()` only, so after\n// any change of a group it kept answering the metadata from before the change:\n// a host that carries a group's title and picture id in the name rebuilt the\n// name from the stale read and lost the picture on a rename.\n//\n// The rule now: every message that tells the main thread a conversation\n// changed CARRIES the conversation's metadata as the group holds it at that\n// moment, and the main thread stores it before it calls any host listener. A\n// request that changes a conversation without reporting an event (a creation,\n// a leave, a call whose Commit did not move the epoch, a `send` or a\n// `buildLinkingTicket` that moved one) says so with a\n// `cache.conversations` message before its `result`. Nothing here lists every\n// conversation to do it: the one conversation is read (`conversationMeta`), or\n// the record comes from a listing the request already paid for.\n\n/** One conversation's metadata as the group holds it now. `null`: the client\n * does not hold it (unknown, dropped, removed, or left) or it could not be\n * read; either way the main thread must not keep answering for it. */\nfunction readMeta(id: Uint8Array): ConversationMeta | null {\n if (!client) return null;\n try {\n return (client.conversationMeta(id) as ConversationMeta | null | undefined) ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Past this many conversations, one listing is cheaper than reading them one\n * at a time. The single read walks the client's conversations inside the\n * wasm and hands over one record; a listing hands over all of them and costs\n * about twelve single reads at any account size (measured at 100, 500 and\n * 2000 conversations). So the cost of bringing any number of conversations\n * up to date is bounded by one listing.\n */\nconst SINGLE_READS_MAX = 8;\n\n/** The metadata of each of `ids` as the groups hold it now, by\n * `conversationKey`; `null` for one the client does not hold. */\nfunction readMetas(ids: readonly Uint8Array[]): Map<string, ConversationMeta | null> {\n const out = new Map<string, ConversationMeta | null>();\n for (const id of ids) out.set(conversationKey(id), null);\n if (out.size <= SINGLE_READS_MAX) {\n for (const id of ids) out.set(conversationKey(id), readMeta(id));\n return out;\n }\n if (!client) return out;\n try {\n for (const meta of client.listConversations() as unknown as ConversationMeta[]) {\n const key = conversationKey(meta.id);\n if (out.has(key)) out.set(key, meta);\n }\n } catch {\n // Unreadable: every one of them stays `null`, and the main thread drops\n // its copies instead of keeping the old ones.\n }\n return out;\n}\n\n/** Tell the main thread a conversation changed, with its metadata as the\n * group holds it now (`null`: it is not held any more). */\nfunction postConversationEvent(\n id: Uint8Array,\n epoch: number,\n sender: DeviceId | undefined,\n meta: ConversationMeta | null,\n): void {\n (self.postMessage as (m: Response) => void)({\n kind: \"event.conversation\",\n id,\n epoch,\n ...(sender !== undefined ? { sender } : {}),\n ...(meta !== null ? { meta } : {}),\n });\n}\n\n/** Cache upkeep with no host event: what the main thread must hold now and\n * what it must forget. Posts nothing when there is nothing to say. */\nfunction postCacheUpkeep(held: ConversationMeta[], dropped: Uint8Array[]): void {\n if (held.length === 0 && dropped.length === 0) return;\n (self.postMessage as (m: Response) => void)({ kind: \"cache.conversations\", held, dropped });\n}\n\n/** Read each of `ids` and post the upkeep for them as one message. */\nfunction refreshCached(ids: readonly Uint8Array[]): void {\n if (ids.length === 0) return;\n const metas = readMetas(ids);\n const held: ConversationMeta[] = [];\n const dropped: Uint8Array[] = [];\n const done = new Set<string>();\n for (const id of ids) {\n const key = conversationKey(id);\n if (done.has(key)) continue;\n done.add(key);\n const meta = metas.get(key) ?? null;\n if (meta !== null) held.push(meta);\n else dropped.push(id);\n }\n postCacheUpkeep(held, dropped);\n}\n\n/**\n * What a request is watched over: the epoch of every conversation the client\n * held before it ran (one listing), and how to list them again after it.\n * `announce` says what a moved epoch becomes: a host event (the requests in\n * `EPOCH_ADVANCING_REQUESTS`) or upkeep of the main thread's copy only (the\n * requests in `EPOCH_UPKEEP_REQUESTS`).\n */\ninterface EpochWatch {\n before: Map<string, number>;\n after(): ConversationMeta[];\n announce: boolean;\n}\n\n/** The watch for `msg`, or `null` when it needs none or the conversations\n * could not be read: no epoch change is reported for that request then, and\n * nothing is concluded from an absence. */\nfunction watchFor(msg: Request): EpochWatch | null {\n const held = client;\n if (!held) return null;\n const announce = EPOCH_ADVANCING_REQUESTS.has(msg.kind);\n if (!announce && !EPOCH_UPKEEP_REQUESTS.has(msg.kind)) return null;\n const list = (): ConversationMeta[] => held.listConversations() as unknown as ConversationMeta[];\n try {\n return { before: epochMap(list()), after: list, announce };\n } catch {\n // A client mid-teardown (or a storage read failure) is not a reason to\n // fail the request the caller actually made.\n return null;\n }\n}\n\n/**\n * Tell the main thread about every watched conversation whose epoch moved,\n * each with the metadata just read: as a host event when the watch announces,\n * as cache upkeep when it does not. The conversations the request brought in\n * or took away are cache upkeep either way. Returns the keys of every\n * conversation the main thread was told about, so the caller does not read\n * one of them a second time.\n */\nfunction emitEpochAdvances(watch: EpochWatch): Set<string> {\n const told = new Set<string>();\n let metas: ConversationMeta[];\n try {\n metas = watch.after();\n } catch {\n return told;\n }\n const advanced = advancedEpochs(watch.before, metas);\n for (const meta of advanced) {\n told.add(conversationKey(meta.id));\n if (watch.announce) postConversationEvent(meta.id, meta.epoch, undefined, meta);\n }\n const { appeared, disappeared } = changedHoldings(watch.before, metas);\n for (const meta of appeared) told.add(conversationKey(meta.id));\n for (const id of disappeared) told.add(conversationKey(id));\n postCacheUpkeep(watch.announce ? appeared : [...advanced, ...appeared], disappeared);\n return told;\n}\n\n/**\n * Whether the main thread's copy of the conversation a `send` named may be\n * behind the group now. Answered from what the worker already holds, so a\n * send that moved nothing reads nothing:\n *\n * - The envelope the send produced carries the epoch it was encrypted at,\n * and the main thread sent the epoch of its own copy with the request.\n * Everything the core does BEFORE it encrypts shows in that comparison:\n * settling a Commit this device left in doubt, committing pending\n * proposals, applying another member's Commits from the log.\n * - The one thing the core does AFTER it encrypts is the refresh of this\n * device's leaf: a Commit, merged only once the transport accepted it. A\n * send that moved nothing makes exactly one transport call, the message\n * itself, so any other count means something else was sent or fetched.\n *\n * A send that failed produced no envelope to compare, so the conversation is\n * read. In every case the cost is at most ONE read of the one conversation,\n * made after the send; never a listing, and never a host event.\n */\nfunction sendLeftCopyBehind(\n msg: Extract<Request, { kind: \"send\" }>,\n outcome: { ok: true; value: unknown } | { ok: false },\n calls: number,\n): boolean {\n if (!outcome.ok || calls !== 1) return true;\n const sentAt = (outcome.value as { epoch?: unknown } | null | undefined)?.epoch;\n return typeof sentAt !== \"number\" || sentAt !== msg.heldEpoch;\n}\n\n/**\n * Announce the conversations a batch or page moved. The sequenced paths\n * report `updated` exactly (the core lists every conversation whose epoch\n * moved or that was joined), so there is nothing to diff: one event per\n * entry, each with the conversation's metadata read at that moment.\n * `senders` labels a join with the inviter's device, as `joinConversation`\n * does. `removed` are the conversations the batch took this device out of:\n * no host event (the result reports them), but the main thread's copy of\n * each is brought to what the client holds now.\n */\nfunction announceUpdated(\n updated: ConversationUpdateWire[],\n senders: Map<string, DeviceId> = new Map(),\n removed: ConversationRemovalWire[] = [],\n): void {\n if (updated.length === 0 && removed.length === 0) return;\n const metas = readMetas([\n ...updated.map((u) => u.conversation_id),\n ...removed.map((r) => r.conversation_id),\n ]);\n const told = new Set<string>();\n for (const u of updated) {\n const key = conversationKey(u.conversation_id);\n told.add(key);\n postConversationEvent(u.conversation_id, u.epoch, senders.get(key), metas.get(key) ?? null);\n }\n const held: ConversationMeta[] = [];\n const dropped: Uint8Array[] = [];\n for (const r of removed) {\n const key = conversationKey(r.conversation_id);\n if (told.has(key)) continue;\n told.add(key);\n const meta = metas.get(key) ?? null;\n if (meta !== null) held.push(meta);\n else dropped.push(r.conversation_id);\n }\n postCacheUpkeep(held, dropped);\n}\n\n/** The inviter's device for every conversation a batch joined, from the\n * Welcome that joined it. */\nfunction welcomeSenders(items: SequencedEnvelopeWire[], joined: Uint8Array[]): Map<string, DeviceId> {\n const out = new Map<string, DeviceId>();\n if (joined.length === 0) return out;\n const wanted = new Set(joined.map((id) => conversationKey(id)));\n for (const item of items) {\n if (item.envelope.kind !== \"Welcome\") continue;\n const key = conversationKey(item.envelope.conversation_id);\n if (wanted.has(key) && !out.has(key)) out.set(key, item.envelope.sender_device);\n }\n return out;\n}\n\n// Requests after which ONE conversation's metadata on the main thread must be\n// what the group holds, whether or not an event said so: this device's own\n// calls on a conversation. When the call moved the epoch, the event above\n// already carried the metadata and nothing more is read. When it did not (the\n// call failed, its Commit is in doubt, the conversation is now left or\n// dropped), the one conversation is read once, here.\nconst CONVERSATION_REQUESTS: ReadonlySet<string> = new Set([\n \"addMembers\",\n \"addMembersWithVerdicts\",\n \"reAdmitDevice\",\n \"removeMembers\",\n \"removeOwnOtherLeaves\",\n \"removeMembersByIdentity\",\n \"commitPendingProposals\",\n \"setConversationName\",\n \"setConversationRoles\",\n \"syncConversation\",\n \"leaveConversation\",\n \"dropConversationLocal\",\n]);\n\n// Requests that resolve to the id of a conversation they brought in.\nconst CONVERSATION_RESULT_REQUESTS: ReadonlySet<string> = new Set([\n \"createConversation\",\n \"createCallConversation\",\n \"importStateSnapshot\",\n]);\n\n/** The conversation a finished request must leave fresh on the main thread. */\nfunction conversationTouched(msg: Request, value: unknown): Uint8Array | null {\n if (CONVERSATION_REQUESTS.has(msg.kind)) {\n const conv = (msg as { conv?: unknown }).conv;\n return conv instanceof Uint8Array ? conv : null;\n }\n if (CONVERSATION_RESULT_REQUESTS.has(msg.kind)) {\n return value instanceof Uint8Array ? value : null;\n }\n return null;\n}\n\n/**\n * The conversations a request that applies inbound frames named. When such a\n * request succeeds, the events it posted carried the metadata. When it\n * THROWS it posted nothing, yet the group may have moved before the throw (a\n * Commit merged, then the checkpoint failed), so each conversation it named\n * is read once and the main thread's copy follows. No host event: a failed\n * apply never announced one.\n */\nfunction conversationsOfFailedApply(msg: Request): Uint8Array[] {\n switch (msg.kind) {\n case \"processEnvelope\":\n return [msg.envelope.conversation_id];\n case \"joinConversation\":\n case \"joinConversationAt\":\n case \"processWelcomeAt\":\n return [msg.welcome.conversation_id];\n case \"syncConversationStep\":\n return [msg.conv];\n case \"processSequencedBatch\":\n return msg.items.map((item) => item.envelope.conversation_id);\n default:\n return [];\n }\n}\n\n/** Everything the main thread must know about conversations before it hears\n * the request's outcome. `calls` is how many transport calls the request\n * made. Never throws. */\nfunction reportConversations(\n msg: Request,\n watch: EpochWatch | null,\n outcome: { ok: true; value: unknown } | { ok: false },\n calls: number,\n): void {\n try {\n const told = watch ? emitEpochAdvances(watch) : new Set<string>();\n const touched = conversationTouched(msg, outcome.ok ? outcome.value : undefined);\n const owed = outcome.ok ? [] : conversationsOfFailedApply(msg);\n if (touched !== null) owed.push(touched);\n if (msg.kind === \"send\" && sendLeftCopyBehind(msg, outcome, calls)) owed.push(msg.conv);\n refreshCached(owed.filter((id) => id instanceof Uint8Array && !told.has(conversationKey(id))));\n } catch {\n // Reporting is never a reason to fail the request the caller made.\n }\n}\n\nasync function runRequest(msg: Request): Promise<void> {\n // Snapshot BEFORE the request and diff after, so a self-authored commit or a\n // catch-up-applied one is announced like any other epoch change.\n const watch = watchFor(msg);\n const callsBefore = transportCalls;\n try {\n const value = await dispatch(msg);\n // Announce the epoch change BEFORE resolving the caller, so a host that\n // awaits `addMembers` and then reads a derived secret cannot observe the\n // new epoch before being told about it. The same order is what makes the\n // conversation handle fresh when the call resolves.\n reportConversations(msg, watch, { ok: true, value }, transportCalls - callsBefore);\n (self.postMessage as (m: Response) => void)({ kind: \"result\", id: msg.id, ok: true, value });\n } catch (e) {\n // A failed request can still have advanced the epoch (a commit that merged\n // locally before a later step threw), so report the change either way.\n reportConversations(msg, watch, { ok: false }, transportCalls - callsBefore);\n (self.postMessage as (m: Response) => void)({\n kind: \"result\", id: msg.id, ok: false, error: e instanceof Error ? e.message : String(e),\n });\n }\n}\n\nself.onmessage = (ev: MessageEvent<Request>) => {\n const msg = ev.data;\n\n // Storage / transport responses from the main thread — handle\n // immediately (they unblock the in-flight request). Never queued.\n if (msg.kind === \"storage.reply\") {\n const slot = pendingStorage.get(msg.id);\n if (slot) {\n pendingStorage.delete(msg.id);\n msg.ok ? slot({ ok: true, value: msg.value })\n : slot({ ok: false, value: msg.error });\n }\n return;\n }\n if (msg.kind === \"transport.reply\") {\n const slot = pendingTransport.get(msg.id);\n if (slot) {\n pendingTransport.delete(msg.id);\n msg.ok ? slot({ ok: true, value: msg.value })\n : slot({ ok: false, value: msg.error });\n }\n return;\n }\n\n // Top-level client request. A whole-account catch-up becomes a stepped\n // pass the scheduler runs one conversation per turn, behind everything\n // else queued; every other request runs FIFO, one WASM call at a time.\n // `runRequest` and the pass stepper never reject (errors are posted as\n // results), so the scheduler can't wedge.\n if (msg.kind === \"syncConversations\") {\n scheduler.enqueueStepped(catchUpPassStepper(msg));\n return;\n }\n // The SDK's own gap fill: one page per turn on the stepped lane, so a\n // send posted while a long fill runs goes between pages.\n if (msg.kind === \"syncConversationStep\" && msg.stepped === true) {\n scheduler.enqueueStepped(async () => {\n await runRequest(msg);\n return false;\n });\n return;\n }\n scheduler.enqueue(() => runRequest(msg));\n};\n\n/**\n * One whole-account catch-up as a stepped job: ONE PAGE of one conversation\n * per scheduler turn (`catch-up-pass.ts` has the policy). The scheduler runs\n * queued ordinary requests between pages. When the host transport reports\n * the server's log heads, only the conversations that are behind are\n * stepped. Each page's messages are posted as an `event.batch` (source\n * `page`) and its conversation updates come from the core's exact `updated`\n * list, so nothing here diffs epochs. The result is posted once, when the\n * pass is complete, with every decrypted application message in apply\n * order, the same contract `syncConversations()` callers have always had.\n */\nfunction catchUpPassStepper(\n msg: Extract<Request, { kind: \"syncConversations\" }>,\n): () => Promise<boolean> {\n const post = (m: Response): void => (self.postMessage as (m: Response) => void)(m);\n let pass: (() => Promise<boolean>) | null = null;\n return async (): Promise<boolean> => {\n if (pass === null) {\n try {\n await ensureWasm();\n ensureClient();\n } catch (e) {\n post({\n kind: \"result\", id: msg.id, ok: false,\n error: e instanceof Error ? e.message : String(e),\n });\n return false;\n }\n pass = catchUpPass({\n listConversationIds: () =>\n (ensureClient().listConversations() as unknown as ConversationEpoch[]).map((meta) => meta.id),\n fetchHeads: async () =>\n transportFeatures.fetchLogHeads ? (await fetchLogHeadsProxy()) ?? null : null,\n conversationsBehind: (heads) =>\n ensureClient().conversationsBehind(heads) as unknown as Uint8Array[],\n step: async (id) => {\n try {\n return await (ensureClient().syncConversationStep(id, msg.nowMs) as unknown as Promise<SyncStepResultWire>);\n } catch (e) {\n // A page that threw announced nothing; the group may still have\n // moved before the throw (see `conversationsOfFailedApply`).\n refreshCached([id]);\n throw e;\n }\n },\n onPage: (page) => {\n announceUpdated(page.updated, undefined, page.removed);\n if (page.messages.length > 0) {\n post({ kind: \"event.batch\", messages: page.messages, source: \"page\" });\n }\n },\n finish: (ok, value) => {\n if (ok) {\n post({ kind: \"result\", id: msg.id, ok: true, value });\n } else {\n post({\n kind: \"result\", id: msg.id, ok: false,\n error: value instanceof Error ? value.message : String(value),\n });\n }\n },\n });\n }\n return pass();\n };\n}\n\nasync function dispatch(msg: Request): Promise<unknown> {\n await ensureWasm();\n switch (msg.kind) {\n case \"init\": {\n transportFeatures = msg.transportFeatures ?? { fetchLogSince: false, fetchLogHeads: false };\n client = await PingClient.init(\n msg.identityExport, msg.deviceLabel,\n makeProxyStorage(msg.storageFeatures) as unknown as never,\n makeProxyTransport(transportFeatures) as unknown as never,\n msg.nowMs,\n // Optional Ed25519 device signing secret — see protocol.ts\n // and ClientConfig.deviceSigningSecretKey. Forwarding `null`\n // explicitly when absent so the wasm-bindgen `Option<Vec<u8>>`\n // shape is matched correctly.\n msg.deviceSigningSecretKey ?? null,\n // The owner each conversation's FIRST roles write must name\n // (2026-11-04, round 2); `null` for none.\n msg.expectedOwners ?? null,\n );\n // Wire decrypted application-message callback back to the main thread.\n client.onMessage((m: unknown) => {\n (self.postMessage as (m: Response) => void)({ kind: \"event.message\", msg: m as never });\n });\n return null;\n }\n case \"openReadOnly\": {\n // No `onMessage` wiring here: a read-only client exists to answer one\n // question about one envelope, not to stream. Registering the callback\n // would also fire the tab's handlers from the worker.\n client = await PingClient.openReadOnly(\n msg.identityExport, msg.deviceLabel,\n makeProxyStorage(msg.storageFeatures) as unknown as never,\n proxyTransport as unknown as never,\n msg.nowMs,\n );\n return null;\n }\n\n case \"previewEnvelope\":\n return ensureClient().previewEnvelope(msg.envelope as unknown as never, msg.nowMs);\n case \"previewEnvelopeWithPrerequisites\":\n return ensureClient().previewEnvelopeWithPrerequisites(\n msg.prerequisites as unknown as never,\n msg.envelope as unknown as never,\n msg.nowMs,\n );\n\n case \"generateIdentity\":\n return PingClient.generateIdentity();\n case \"userId\": return ensureClient().userId();\n case \"exportIdentity\": return ensureClient().exportIdentity();\n case \"rotateIdentity\":\n // One self-update Commit per conversation moves the leaf credential to\n // the new user id; the device signing key and deviceId stay put. The\n // identity swaps even when some conversations end up in `failed`.\n return await ensureClient().rotateIdentity(msg.newIdentityExport, msg.nowMs);\n case \"rotateIdentityRetry\":\n return await ensureClient().rotateIdentityRetry(msg.conv, msg.nowMs);\n case \"deviceId\": return ensureClient().deviceId();\n case \"suspendStorage\": return ensureClient().suspendStorage();\n case \"resumeStorage\": return ensureClient().resumeStorage();\n case \"freshKeyPackage\": return ensureClient().freshKeyPackage();\n case \"freshLastResortKeyPackage\": return ensureClient().freshLastResortKeyPackage();\n case \"createConversation\":\n return await ensureClient().createConversation(msg.name ?? undefined, msg.nowMs);\n case \"createCallConversation\":\n return await ensureClient().createCallConversation(msg.name ?? undefined, msg.nowMs);\n case \"joinConversation\": {\n const id = await ensureClient().joinConversation(msg.welcome, msg.nowMs) as Uint8Array;\n // Notify the main thread that we just entered a new conversation. We forward the\n // Welcome's `sender_device` so the host can label \"joined chat with <inviter>\".\n postConversationEvent(id, 0, msg.welcome.sender_device, readMeta(id));\n return id;\n }\n case \"listConversations\":\n return ensureClient().listConversations();\n case \"conversationMeta\":\n // ONE conversation, read where the group lives: no listing crosses to\n // the main thread. `null` when the client does not hold it.\n return ensureClient().conversationMeta(msg.conv) ?? null;\n case \"strandedConversations\":\n return ensureClient().strandedConversations();\n case \"conversationsLeaving\":\n return ensureClient().conversationsLeaving();\n case \"conversationsLeaveStalled\":\n return ensureClient().conversationsLeaveStalled();\n case \"readmitPendingConversations\":\n return ensureClient().readmitPendingConversations(msg.nowMs);\n case \"undeliverableCount\":\n return ensureClient().undeliverableCount();\n case \"members\":\n return ensureClient().members(msg.conv);\n case \"conversationPolicy\":\n return ensureClient().conversationPolicy(msg.conv);\n case \"setExpectedOwners\":\n return ensureClient().setExpectedOwners(msg.entries);\n case \"setConversationRoles\":\n return await ensureClient().setConversationRoles(msg.conv, msg.owner, msg.admins, msg.nowMs);\n case \"send\":\n return await ensureClient().send(msg.conv, msg.plaintext, msg.nowMs);\n case \"addMembers\":\n // wasm-bindgen takes the entries as a plain array of {deviceId, keyPackage};\n // serde-wasm-bindgen on the Rust side deserialises into Vec<JsAddMemberEntry>.\n return await ensureClient().addMembers(msg.conv, msg.entries, msg.nowMs);\n case \"addMembersWithVerdicts\":\n // Per-entry verdicts; resolves to the serialised AddMembersReport.\n return await ensureClient().addMembersWithVerdicts(msg.conv, msg.entries, msg.nowMs);\n case \"reAdmitDevice\":\n // Re-admit one device that kept its key: the leaf with the KeyPackage's\n // own signature key goes and the fresh KeyPackage is added. Never an add:\n // with no such leaf it rejects \"not permitted: ...\", and so does a\n // committer the roles do not permit. Resolves to the device id of the\n // replaced leaf.\n return await ensureClient().reAdmitDevice(msg.conv, msg.entry, msg.nowMs);\n case \"mayReadmit\":\n // A pure query: would this device's Commit re-admitting or adding that\n // device pass the membership rules now. Nothing is built or sent.\n return ensureClient().mayReadmit(msg.conv, msg.identity, msg.deviceId);\n case \"keyPackageIdentity\":\n // A pure read: the identity the KeyPackage's credential claims, after the\n // KeyPackage was validated (signatures, lifetime). `undefined` for a\n // credential that is not the project's; throws for anything else.\n return ensureClient().keyPackageIdentity(msg.keyPackage);\n case \"setConversationName\":\n // GroupContextExtensions commit carrying the new conversation name — the\n // rename / avatar-id change propagates to every member via group state.\n return await ensureClient().setConversationName(msg.conv, msg.name ?? undefined, msg.nowMs);\n case \"admitDeviceToChats\":\n // Per-chat add for a newly-linked device. Returns Vec<JsAdmitChatOutcome>\n // — the host inspects per-entry status to decide whether to retry.\n return await ensureClient().admitDeviceToChats(msg.deviceId, msg.entries, msg.nowMs);\n case \"admitDeviceToChatsConcurrent\":\n // Same per-chat add with up to `concurrency` admissions in flight inside\n // this ONE wasm call (the worker still runs one call at a time; the\n // overlap is the core's, across conversations). Outcomes in input order.\n return await ensureClient().admitDeviceToChatsConcurrent(\n msg.deviceId,\n msg.entries,\n msg.nowMs,\n msg.concurrency,\n );\n case \"removeMembers\":\n // wasm-bindgen exposes Vec<u32> as Uint32Array; convert from the protocol's number[].\n return await ensureClient().removeMembers(msg.conv, new Uint32Array(msg.leaves), msg.nowMs);\n case \"removeOwnOtherLeaves\":\n // Every OTHER leaf of this account in one conversation; resolves to the count.\n return await ensureClient().removeOwnOtherLeaves(msg.conv, msg.nowMs);\n case \"removeMembersByIdentity\":\n // Every leaf whose credential verifies for one of `identities`; resolves to the count.\n return await ensureClient().removeMembersByIdentity(msg.conv, msg.identities, msg.nowMs);\n case \"leaveConversation\":\n return await ensureClient().leaveConversation(msg.conv, msg.nowMs);\n case \"dropConversationLocal\":\n return await ensureClient().dropConversationLocal(msg.conv);\n case \"conversationsWithPendingProposals\":\n return ensureClient().conversationsWithPendingProposals();\n case \"commitPendingProposals\":\n return await ensureClient().commitPendingProposals(msg.conv, msg.nowMs);\n case \"pendingProposalsCommitRank\":\n return ensureClient().pendingProposalsCommitRank(msg.conv) ?? null;\n case \"commitsInDoubt\":\n return ensureClient().commitsInDoubt();\n case \"revokeDevice\":\n // [CR-2] returns the array of Commit envelopes the SDK has already broadcast.\n return await ensureClient().revokeDevice(msg.deviceId, msg.nowMs);\n case \"removeDeviceEverywhere\":\n // Every group, DeviceGroup first, never stopping at a failure; resolves\n // to the report the host persists and retries from.\n return await ensureClient().removeDeviceEverywhere(msg.deviceId, msg.nowMs);\n case \"removeOwnDevicesExcept\":\n // The \"secure my account\" sweep: every other leaf of this account\n // except `keep` (by credential, or listed by the server); same report.\n return await ensureClient().removeOwnDevicesExcept(msg.keep, msg.listed, msg.nowMs);\n case \"processEnvelope\": {\n const result = await ensureClient().processEnvelope(msg.envelope, msg.nowMs);\n postConversationEvent(\n msg.envelope.conversation_id, msg.envelope.epoch, undefined,\n readMeta(msg.envelope.conversation_id),\n );\n return result;\n }\n case \"pendingApplies\":\n // [D27] Journal listing — reading does not consume.\n return ensureClient().pendingApplies();\n case \"confirmApplied\":\n // [D27] Removes + checkpoints; unknown ids are ignored (idempotent).\n return await ensureClient().confirmApplied(msg.journalIds);\n case \"syncConversations\":\n // Reached only if a caller bypasses `onmessage`; the scheduler turns\n // this kind into a stepped pass before it can get here.\n return await ensureClient().syncConversations(msg.nowMs);\n case \"syncConversation\":\n return await ensureClient().syncConversation(msg.conv, msg.nowMs);\n // Sequenced log sync. The batch and page results carry their messages\n // (the wasm does not fan them out through `onMessage`); the main thread\n // delivers them from the result. Conversation updates are announced from\n // the core's exact `updated` list, before the result resolves.\n case \"processSequencedBatch\": {\n const raw = await ensureClient().processSequencedBatch(msg.items, msg.nowMs) as unknown as ApplyBatchResultWire;\n announceUpdated(raw.updated, welcomeSenders(msg.items, raw.joined), raw.removed);\n return raw;\n }\n case \"syncConversationStep\": {\n const raw = await ensureClient().syncConversationStep(msg.conv, msg.nowMs) as unknown as SyncStepResultWire;\n announceUpdated(raw.updated, undefined, raw.removed);\n return raw;\n }\n case \"logPositions\":\n return ensureClient().logPositions();\n case \"logPosition\":\n return ensureClient().logPosition(msg.conv);\n case \"adoptLogPosition\":\n return await ensureClient().adoptLogPosition(msg.conv, msg.epoch, msg.serverSeq);\n case \"conversationsBehind\":\n return ensureClient().conversationsBehind(msg.heads);\n case \"heldFrameCount\":\n return ensureClient().heldFrameCount();\n case \"joinConversationAt\": {\n const id = await ensureClient().joinConversationAt(msg.welcome, msg.position, msg.nowMs) as Uint8Array;\n postConversationEvent(id, 0, msg.welcome.sender_device, readMeta(id));\n return id;\n }\n case \"processWelcomeAt\": {\n const id = await ensureClient().processWelcomeAt(msg.welcome, msg.position, msg.nowMs) as Uint8Array | null;\n if (id !== null && id !== undefined) {\n postConversationEvent(id, 0, msg.welcome.sender_device, readMeta(id));\n return id;\n }\n return null;\n }\n case \"buildLinkingTicket\":\n return await ensureClient().buildLinkingTicket(\n msg.newDeviceId, msg.newDeviceKp, msg.lastAppEvents, msg.nowMs,\n );\n case \"consumeLinkingTicket\":\n await ensureClient().consumeLinkingTicket(msg.ticket, msg.nowMs);\n return null;\n case \"decodeCatchupSnapshot\":\n // Pure WASM — no client state required. The new device may call this in an\n // ephemeral worker before init() completes.\n return wasmDecodeCatchupSnapshot(msg.snapshotBytes);\n case \"exportConversationSecret\":\n // wasm-bindgen returns a Uint8Array sized to `length`. The bytes are a secret —\n // the main thread is responsible for clearing the typed array when done.\n return ensureClient().exportConversationSecret(\n msg.conv, msg.label, msg.context, msg.length,\n );\n case \"exportConversationSecretWithEpoch\":\n // `{ epoch, secret }` from ONE read inside the core: the epoch is the one\n // the secret was exported at. Passed through as it is, never rebuilt from\n // a second read. The secret is the main thread's to clear when done.\n return ensureClient().exportConversationSecretWithEpoch(\n msg.conv, msg.label, msg.context, msg.length,\n );\n case \"sealLinkingTicket\":\n // Pure WASM call — no client state required. Lets a sender seal a ticket from an\n // ephemeral worker without standing up the full PingClient.\n return wasmSealLinkingTicket(msg.ticket, msg.newDevicePub);\n case \"openLinkingTicket\":\n // Same — runs without an initialised client, which is the receiving device's\n // pre-bootstrap state (it has the X25519 ephemeral key but no identity yet).\n return wasmOpenLinkingTicket(msg.sealed, msg.newDevicePriv);\n case \"hpkeSeal\":\n // Generic HPKE seal for app-layer envelopes (e.g. linking auth envelope).\n return wasmHpkeSeal(msg.plaintext, msg.recipientPub, msg.info);\n case \"hpkeOpen\":\n return wasmHpkeOpen(msg.sealed, msg.recipientPriv, msg.info);\n case \"hpkeSealRaw\":\n // The RFC 9180 canonical layout (`enc || ct`), which the app layers use.\n return wasmHpkeSealRaw(msg.plaintext, msg.recipientPub, msg.info);\n case \"hpkeOpenRaw\":\n return wasmHpkeOpenRaw(msg.sealed, msg.recipientPriv, msg.info);\n case \"hpkeGenerateKeypair\":\n return wasmHpkeGenerateKeypair();\n // Post-quantum (X-Wing) twins: all pure WASM, no client state required.\n case \"sealLinkingTicketPq\":\n return wasmSealLinkingTicketPq(msg.ticket, msg.newDevicePub);\n case \"openLinkingTicketPq\":\n return wasmOpenLinkingTicketPq(msg.sealed, msg.newDevicePriv);\n case \"hpkeSealPq\":\n return wasmHpkeSealPq(msg.plaintext, msg.recipientPub, msg.info);\n case \"hpkeOpenPq\":\n return wasmHpkeOpenPq(msg.sealed, msg.recipientPriv, msg.info);\n case \"hpkeSealRawPq\":\n return wasmHpkeSealRawPq(msg.plaintext, msg.recipientPub, msg.info);\n case \"hpkeOpenRawPq\":\n return wasmHpkeOpenRawPq(msg.sealed, msg.recipientPriv, msg.info);\n case \"hpkeGenerateKeypairPq\":\n return wasmHpkeGenerateKeypairPq();\n case \"hpkePublicKeyFromSeed\":\n return wasmHpkePublicKeyFromSeed(msg.seed);\n case \"deviceGroupIdFor\":\n // Pure: the core's DeviceGroup id derivation for an MLS user id.\n return wasmDeviceGroupIdFor(msg.userId);\n case \"hpkePublicKeyFromPrivate\":\n return wasmHpkePublicKeyFromPrivate(msg.privateKey);\n case \"signDeviceReauth\":\n // Pure WASM: the SDK builds the signed bytes, so this signs nothing else\n // with the device key. Returns `deviceId (32) || signature (64)`.\n return wasmSignDeviceReauth(msg.deviceSigningSecretKey, msg.challengeId, msg.nonce, msg.accountId, msg.audience);\n case \"signDeviceLinkApproval\":\n // Pure WASM, link verification v2: the SDK builds the signed bytes and\n // derives both ids. Returns `approverDeviceId (32) || newDeviceId (32) ||\n // signature (64)`.\n return wasmSignDeviceLinkApproval(msg.deviceSigningSecretKey, msg.approvalSessionId, msg.accountId, msg.newDevicePubkey, msg.audience);\n case \"signDeviceLinkPossession\":\n // Pure WASM. Returns `deviceId (32) || signature (64)`.\n return wasmSignDeviceLinkPossession(msg.deviceSigningSecretKey, msg.approvalSessionId, msg.accountId, msg.audience);\n case \"exportConversationStateSnapshot\":\n // [CR-7] state snapshot bytes are a secret (past epoch keys); the main thread\n // is responsible for clearing the typed array when done.\n return ensureClient().exportConversationStateSnapshot(msg.conv, msg.nowMs);\n case \"importStateSnapshot\":\n // [CR-7] returns the imported conversation id as a Uint8Array.\n return await ensureClient().importStateSnapshot(msg.snapshotBytes, msg.nowMs);\n // Recovery — all pure WASM; no client state required.\n case \"generateMnemonicPhrase\":\n return wasmGenerateMnemonicPhrase();\n case \"normalizeMnemonicPhrase\":\n return wasmNormalizeMnemonicPhrase(msg.phrase);\n case \"encryptBackup\":\n return wasmEncryptBackup(\n msg.mnemonicPhrase, msg.accountId, msg.identityExport,\n msg.deviceGroupSnapshot,\n // Map idiomatic camelCase → the snake_case keys serde expects on the\n // WASM boundary (matches the decrypt view's account_id / group_state_bytes).\n msg.conversationSnapshots.map((c) => ({\n conversation_id: c.conversationId,\n group_state_bytes: c.groupStateBytes,\n })),\n msg.createdAtMs,\n );\n case \"decryptBackup\":\n return wasmDecryptBackup(msg.blob, msg.mnemonicPhrase);\n case \"checkBackupPhrase\":\n // `{ outcome, reason? }`, the wasm's own codes, passed on untouched.\n return wasmCheckBackupPhrase(msg.blob, msg.mnemonicPhrase);\n case \"sealHistoryBundle\":\n return wasmSealHistoryBundle(msg.bundle, msg.recipientPub, msg.senderIdentitySecret);\n case \"openHistoryBundle\":\n return wasmOpenHistoryBundle(msg.sealed, msg.recipientPriv, msg.senderIdentityPub);\n case \"sealHistoryBundlePq\":\n return wasmSealHistoryBundlePq(msg.bundle, msg.recipientPub, msg.senderIdentitySecret);\n case \"openHistoryBundlePq\":\n return wasmOpenHistoryBundlePq(msg.sealed, msg.recipientPriv, msg.senderIdentityPub);\n default:\n throw new Error(`unknown request kind: ${(msg as { kind: string }).kind}`);\n }\n}\n\nfunction ensureClient(): PingClient {\n if (!client) throw new Error(\"client not initialised\");\n return client;\n}\n","// Which conversations' MLS epochs moved, and therefore which `event.conversation`\n// notifications the worker owes the main thread.\n//\n// This lives outside `worker.ts` purely so it is testable: importing the worker\n// module runs its top-level `self.onmessage` wiring, which needs a\n// `DedicatedWorkerGlobalScope`. The rule it encodes is small but load-bearing —\n// see `EPOCH_ADVANCING_REQUESTS` in the worker for why a self-authored or\n// catch-up-applied commit would otherwise be announced to nobody.\n\n/** The two fields of a `ConversationMeta` this comparison needs. */\nexport interface ConversationEpoch {\n id: Uint8Array;\n epoch: number;\n}\n\n/** Stable map key for a 16-byte conversation id. */\nexport function conversationKey(id: Uint8Array): string {\n let out = \"\";\n for (let i = 0; i < id.length; i += 1) out += (id[i] ?? 0).toString(16).padStart(2, \"0\");\n return out;\n}\n\n/** Epoch per conversation, keyed by `conversationKey`. */\nexport function epochMap(metas: readonly ConversationEpoch[]): Map<string, number> {\n const out = new Map<string, number>();\n for (const meta of metas) out.set(conversationKey(meta.id), meta.epoch);\n return out;\n}\n\n/**\n * Conversations whose epoch STRICTLY advanced between `before` and `after`.\n *\n * Only conversations present in both are considered:\n * - a conversation that is new since `before` was either just created by this\n * caller or just joined, and `joinConversation` already announces the\n * latter — announcing it here would double-fire;\n * - a conversation that has disappeared (left / dropped) has no epoch to\n * report;\n * - an epoch that did not move is not an event, however many times the\n * request that ran touched the group.\n *\n * The elements returned are the elements of `after` themselves, so a caller\n * that listed whole metadata records gets them back whole.\n */\nexport function advancedEpochs<T extends ConversationEpoch>(\n before: ReadonlyMap<string, number>,\n after: readonly T[],\n): T[] {\n const out: T[] = [];\n for (const meta of after) {\n const previous = before.get(conversationKey(meta.id));\n if (previous === undefined || meta.epoch <= previous) continue;\n out.push(meta);\n }\n return out;\n}\n\n/** The id a `conversationKey` was made from. */\nexport function conversationIdOf(key: string): Uint8Array {\n const out = new Uint8Array(key.length >> 1);\n for (let i = 0; i < out.length; i += 1) out[i] = Number.parseInt(key.slice(i * 2, i * 2 + 2), 16);\n return out;\n}\n\n/**\n * The conversations a request brought in or took away, which\n * {@link advancedEpochs} deliberately does not report.\n *\n * They are not host events (whoever joined or left already said so, or it is\n * not an epoch change at all), but the main thread's copy of a conversation's\n * metadata must still follow them: a conversation that `appeared` is held\n * now, one that `disappeared` is not, and a copy that kept answering for it\n * would be answering for a group this device no longer reads.\n */\nexport function changedHoldings<T extends ConversationEpoch>(\n before: ReadonlyMap<string, number>,\n after: readonly T[],\n): { appeared: T[]; disappeared: Uint8Array[] } {\n const appeared: T[] = [];\n const still = new Set<string>();\n for (const meta of after) {\n const key = conversationKey(meta.id);\n still.add(key);\n if (!before.has(key)) appeared.push(meta);\n }\n const disappeared: Uint8Array[] = [];\n for (const key of before.keys()) {\n if (!still.has(key)) disappeared.push(conversationIdOf(key));\n }\n return { appeared, disappeared };\n}\n","// The whole-account catch-up as a stepped job: one PAGE of one conversation\n// per scheduler turn.\n//\n// `syncConversations()` used to page each conversation to its end inside one\n// wasm call; a 2,000-message group backlog was eight pages behind which\n// every queued send waited. Each call of the returned step now applies ONE\n// page through `syncConversationStep` and yields, so the primary lane (a\n// send, a live batch, a host's own step) runs between pages as well as\n// between conversations. A conversation whose page was full stays at the\n// head of the queue and continues next turn.\n//\n// When the transport can report the server's log heads, only the\n// conversations `conversationsBehind` names are stepped: one request instead\n// of one page per conversation the account holds. A transport without\n// `fetchLogHeads` (or one that answers `null`: the relay has no heads route)\n// gets the whole-account walk, as before. A heads request that FAILS ends\n// the pass with that error instead: walking every conversation on a network\n// that just failed one request would fail N more times, and the host retries\n// the pass on its next trigger (reconnect, foreground, heartbeat), by which\n// time the socket's `resume_ack` has usually named what is behind anyway.\n//\n// The pass ends with one re-list so a conversation joined while it ran is\n// still covered, exactly as the core re-reads its map. Conversations already\n// evaluated (stepped, or present in the heads snapshot) are not re-stepped.\n//\n// Lives outside `worker.ts` so it is testable without a\n// `DedicatedWorkerGlobalScope`; the worker supplies the dependencies.\n\nimport { conversationKey } from \"./epoch-events\";\nimport type { LogHeadWire, SyncStepResultWire } from \"./sequenced\";\nimport type { IncomingMessage } from \"./types\";\n\nexport interface CatchUpPassDeps {\n /** Ids of every conversation the client holds right now. */\n listConversationIds(): Uint8Array[];\n /** The server's heads, or `null` when the transport cannot report them. */\n fetchHeads(): Promise<LogHeadWire[] | null>;\n /** The core's verdict on which of `heads` this device is behind on. */\n conversationsBehind(heads: LogHeadWire[]): Uint8Array[];\n /** Apply ONE page of one conversation. */\n step(id: Uint8Array): Promise<SyncStepResultWire>;\n /** Deliver a page: its conversation updates and its messages. */\n onPage(result: SyncStepResultWire): void;\n /** Post the pass result: every message in apply order, or the error. */\n finish(ok: boolean, value: IncomingMessage[] | unknown): void;\n}\n\n/**\n * Build the stepped job. Each call runs one step and resolves `true` while\n * the pass has more to do; it never rejects (errors are posted through\n * `finish`).\n */\nexport function catchUpPass(deps: CatchUpPassDeps): () => Promise<boolean> {\n const seen = new Set<string>();\n const delivered: IncomingMessage[] = [];\n let pending: Uint8Array[] | null = null;\n let relisted = false;\n\n const sortedUnseen = (ids: Uint8Array[]): Uint8Array[] =>\n ids\n .filter((id) => !seen.has(conversationKey(id)))\n .sort((a, b) => (conversationKey(a) < conversationKey(b) ? -1 : 1));\n\n const initial = async (): Promise<Uint8Array[]> => {\n // A rejection propagates to the caller, which posts it through `finish`.\n const heads = await deps.fetchHeads();\n if (heads === null) return sortedUnseen(deps.listConversationIds());\n // Every conversation the heads describe has been evaluated: the ones\n // that are current are not stepped now and not re-stepped by the re-list.\n for (const h of heads) seen.add(conversationKey(h.conversation_id));\n const behind = deps.conversationsBehind(heads);\n for (const id of behind) seen.delete(conversationKey(id));\n return sortedUnseen(behind);\n };\n\n return async (): Promise<boolean> => {\n try {\n if (pending === null) pending = await initial();\n if (pending.length === 0 && !relisted) {\n relisted = true;\n pending = sortedUnseen(deps.listConversationIds());\n }\n } catch (e) {\n deps.finish(false, e);\n return false;\n }\n const id = pending[0];\n if (id === undefined) {\n deps.finish(true, delivered);\n return false;\n }\n let more = false;\n try {\n const page = await deps.step(id);\n for (const m of page.messages) delivered.push(m);\n deps.onPage(page);\n more = page.has_more;\n } catch {\n // Dropped between the listing and this step (a wipe, a self-removal),\n // a transport failure, or a checkpoint failure: this conversation's\n // paging ends for this pass. The durable cursor is where the next\n // pass resumes, which is what the whole-account request did too.\n }\n if (!more) {\n seen.add(conversationKey(id));\n pending.shift();\n }\n return true;\n };\n}\n","// Request scheduling for the WASM worker: one call in flight at a time, in\n// two lanes.\n//\n// The worker may run only ONE WASM call at a time (see `worker.ts`), so every\n// request waits for the one before it. That is fine for the requests a user\n// is waiting on (a send, a live frame) — they are short. It was not fine for a\n// whole-account catch-up, which paged every conversation inside a single\n// request: a `send` posted while it ran started after all of them, and on a\n// tab returning from an idle hour that wait WAS the first message's latency.\n//\n// This scheduler keeps the one-call invariant and adds a second lane for\n// work that is allowed to be interrupted between its natural steps. An\n// ordinary request runs FIFO in the primary lane; a stepped job runs one\n// step per turn and only when the primary lane is empty, so anything queued\n// while a step ran goes next. Stepped jobs are FIFO among themselves and a\n// job's steps never interleave with another job's.\n//\n// Lives outside `worker.ts` so it is testable without a\n// `DedicatedWorkerGlobalScope` (the same reason `epoch-events.ts` exists).\n\n/** An ordinary request: runs to completion in one turn. Must not reject. */\nexport type LaneJob = () => Promise<void>;\n\n/**\n * A stepped job: each call runs ONE step and resolves `true` while more steps\n * remain. A rejected step ends the job (the scheduler treats it as `false`).\n */\nexport type SteppedJob = () => Promise<boolean>;\n\nexport class RequestScheduler {\n private readonly primary: LaneJob[] = [];\n private readonly stepped: SteppedJob[] = [];\n private pumping = false;\n\n /** Queue an ordinary request behind the ordinary requests before it. */\n enqueue(job: LaneJob): void {\n this.primary.push(job);\n void this.pump();\n }\n\n /** Queue a stepped job; its steps run whenever the primary lane is empty. */\n enqueueStepped(job: SteppedJob): void {\n this.stepped.push(job);\n void this.pump();\n }\n\n /** Requests waiting in the primary lane (diagnostics / tests). */\n get pendingPrimary(): number {\n return this.primary.length;\n }\n\n /** Stepped jobs not yet finished (diagnostics / tests). */\n get pendingStepped(): number {\n return this.stepped.length;\n }\n\n private async pump(): Promise<void> {\n if (this.pumping) return;\n this.pumping = true;\n try {\n for (;;) {\n const job = this.primary.shift();\n if (job !== undefined) {\n // A job posts its own error as a result; a rejection here would\n // only mean a bug in the job, and it must not stall the lane.\n await job().catch(() => undefined);\n continue;\n }\n const step = this.stepped[0];\n if (step === undefined) return;\n let more = false;\n try {\n more = await step();\n } catch {\n more = false;\n }\n if (!more) this.stepped.shift();\n }\n } finally {\n this.pumping = false;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAkBO,IAAM,sBAAsB,CAAC,KAAK,KAAK,IAAI,EAAE;AACpD,IAAM,kBAAkB,KAAK;AAI7B,IAAM,WAAW,oBAAI,QAA4B;AAE1C,SAAS,oBAAoB,QAAkC;AACpE,MAAI,SAAS,IAAI,MAAM,EAAG;AAC1B,WAAS,IAAI,MAAM;AACnB,aAAW,OAAO,qBAAqB;AACrC,QAAI;AACF,aAAO,KAAM,MAAM,OAAO,OAAQ,eAAe;AACjD;AAAA,IACF,QAAQ;AAAA,IAER;AAAA,EACF;AACF;;;AC3BA,uBAgCO;;;ACzBA,SAAS,gBAAgB,IAAwB;AACtD,MAAI,MAAM;AACV,WAAS,IAAI,GAAG,IAAI,GAAG,QAAQ,KAAK,EAAG,SAAQ,GAAG,CAAC,KAAK,GAAG,SAAS,EAAE,EAAE,SAAS,GAA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,oBAAoB,IAAI,eAAe,IAAI,KAAK;AAAA;AAAA,IAE9E,KAAK;AACH,iBAAO,iBAAAC,wBAA2B;AAAA,IACpC,KAAK;AACH,iBAAO,iBAAAC,yBAA4B,IAAI,MAAM;AAAA,IAC/C,KAAK;AACH,iBAAO,iBAAAC;AAAA,QACL,IAAI;AAAA,QAAgB,IAAI;AAAA,QAAW,IAAI;AAAA,QACvC,IAAI;AAAA;AAAA;AAAA,QAGJ,IAAI,sBAAsB,IAAI,CAAC,OAAO;AAAA,UACpC,iBAAiB,EAAE;AAAA,UACnB,mBAAmB,EAAE;AAAA,QACvB,EAAE;AAAA,QACF,IAAI;AAAA,MACN;AAAA,IACF,KAAK;AACH,iBAAO,iBAAAC,eAAkB,IAAI,MAAM,IAAI,cAAc;AAAA,IACvD,KAAK;AAEH,iBAAO,iBAAAC,mBAAsB,IAAI,MAAM,IAAI,cAAc;AAAA,IAC3D,KAAK;AACH,iBAAO,iBAAAC,mBAAsB,IAAI,QAAQ,IAAI,cAAc,IAAI,oBAAoB;AAAA,IACrF,KAAK;AACH,iBAAO,iBAAAC,mBAAsB,IAAI,QAAQ,IAAI,eAAe,IAAI,iBAAiB;AAAA,IACnF,KAAK;AACH,iBAAO,iBAAAC,qBAAwB,IAAI,QAAQ,IAAI,cAAc,IAAI,oBAAoB;AAAA,IACvF,KAAK;AACH,iBAAO,iBAAAC,qBAAwB,IAAI,QAAQ,IAAI,eAAe,IAAI,iBAAiB;AAAA,IACrF;AACE,YAAM,IAAI,MAAM,yBAA0B,IAAyB,IAAI,EAAE;AAAA,EAC7E;AACF;AAEA,SAAS,eAA2B;AAClC,MAAI,CAAC,OAAQ,OAAM,IAAI,MAAM,wBAAwB;AACrD,SAAO;AACT;","names":["init","wasmDecodeCatchupSnapshot","wasmSealLinkingTicket","wasmOpenLinkingTicket","wasmHpkeSeal","wasmHpkeOpen","wasmHpkeSealRaw","wasmHpkeOpenRaw","wasmHpkeGenerateKeypair","wasmSealLinkingTicketPq","wasmOpenLinkingTicketPq","wasmHpkeSealPq","wasmHpkeOpenPq","wasmHpkeSealRawPq","wasmHpkeOpenRawPq","wasmHpkeGenerateKeypairPq","wasmHpkePublicKeyFromSeed","wasmDeviceGroupIdFor","wasmHpkePublicKeyFromPrivate","wasmSignDeviceReauth","wasmSignDeviceLinkApproval","wasmSignDeviceLinkPossession","wasmGenerateMnemonicPhrase","wasmNormalizeMnemonicPhrase","wasmEncryptBackup","wasmDecryptBackup","wasmCheckBackupPhrase","wasmSealHistoryBundle","wasmOpenHistoryBundle","wasmSealHistoryBundlePq","wasmOpenHistoryBundlePq"]}
1
+ {"version":3,"sources":["../src/wasm-memory.ts","../src/worker.ts","../src/pending-root-store.ts","../src/epoch-events.ts","../src/catch-up-pass.ts","../src/request-lanes.ts"],"sourcesContent":["// Linear-memory reservation shared by every realm that instantiates the wasm.\n\n/**\n * Linear-memory headroom the worker reserves from JavaScript right after\n * instantiation, largest first; a target the engine refuses (`RangeError`)\n * falls through to the next. Sized so the Argon2id recovery backup\n * (64 MiB of blocks in ONE allocation) and a large history bundle fit\n * inside memory the module already owns.\n *\n * Why from JS and not inside the module: Safari/JSC (macOS 26 / iOS 26,\n * IPInt) crashes the WebContent process when the wasm `memory.grow`\n * INSTRUCTION runs in a Worker while the Web Inspector is attached — the GC\n * it triggers walks the stack and dies on the wasm frame. The same grow\n * requested through `WebAssembly.Memory.prototype.grow` has only JS frames\n * on the stack and is fine. The module's allocator (`ping-wasm/src/alloc.rs`)\n * claims these pages before it would ever execute the instruction itself.\n * The pages are virtual until touched, so an idle worker costs nothing extra.\n */\nexport const RESERVE_MIB_TARGETS = [192, 128, 64, 32] as const;\nconst WASM_PAGE_BYTES = 64 * 1024;\n\n/** Memories already reserved: `init` is idempotent per realm and returns the\n * same instance, so a second open must not grow it again. */\nconst reserved = new WeakSet<WebAssembly.Memory>();\n\nexport function reserveLinearMemory(memory: WebAssembly.Memory): void {\n if (reserved.has(memory)) return;\n reserved.add(memory);\n for (const mib of RESERVE_MIB_TARGETS) {\n try {\n memory.grow((mib * 1024 * 1024) / WASM_PAGE_BYTES);\n return;\n } catch {\n // Over the engine's limit for this memory; try a smaller reservation.\n }\n }\n}\n\n","// Web Worker entry. Owns the WASM `PingClient` instance. Receives Requests from the main thread\n// and posts Responses back. Storage / Transport calls back to the main thread are tracked by id.\n//\n// The WASM module is loaded lazily on the first `init` so that ephemeral identity-only spawns\n// (the static calls of `MessagingClient`) don't pay the cost.\n\n/// <reference lib=\"webworker\" />\n\nimport { reserveLinearMemory } from \"./wasm-memory\";\nimport init, {\n PingClient,\n beginDeviceLink as wasmBeginDeviceLink,\n sealLinkingTicketV3For as wasmSealLinkingTicketV3For,\n openLinkingTicketV3 as wasmOpenLinkingTicketV3,\n sealLinkAuthFor as wasmSealLinkAuthFor,\n linkCommitment as wasmLinkCommitment,\n normalizeLinkCode as wasmNormalizeLinkCode,\n linkQrCommitment as wasmLinkQrCommitment,\n verifyLinkHandshake as wasmVerifyLinkHandshake,\n hpkeSeal as wasmHpkeSeal,\n hpkeOpen as wasmHpkeOpen,\n hpkeSealRaw as wasmHpkeSealRaw,\n hpkeOpenRaw as wasmHpkeOpenRaw,\n hpkeGenerateKeypair as wasmHpkeGenerateKeypair,\n hpkeSealPq as wasmHpkeSealPq,\n hpkeOpenPq as wasmHpkeOpenPq,\n hpkeSealRawPq as wasmHpkeSealRawPq,\n hpkeOpenRawPq as wasmHpkeOpenRawPq,\n hpkeGenerateKeypairPq as wasmHpkeGenerateKeypairPq,\n deviceGroupIdFor as wasmDeviceGroupIdFor,\n hpkePublicKeyFromSeed as wasmHpkePublicKeyFromSeed,\n hpkePublicKeyFromPrivate as wasmHpkePublicKeyFromPrivate,\n signDeviceReauth as wasmSignDeviceReauth,\n signDeviceLinkApprovalFor as wasmSignDeviceLinkApprovalFor,\n signDeviceLinkPossession as wasmSignDeviceLinkPossession,\n decodeCatchupSnapshot as wasmDecodeCatchupSnapshot,\n generateMnemonicPhrase as wasmGenerateMnemonicPhrase,\n selfAdmissionCompiled as wasmSelfAdmissionCompiled,\n normalizeMnemonicPhrase as wasmNormalizeMnemonicPhrase,\n checkBackupPhrase as wasmCheckBackupPhrase,\n createAccount as wasmCreateAccount,\n pendingStatus as wasmPendingStatus,\n makeBackup as wasmMakeBackup,\n proveBackup as wasmProveBackup,\n openBackupForRestore as wasmOpenBackupForRestore,\n restoreTakeOver as wasmRestoreTakeOver,\n takeAccountBack as wasmTakeAccountBack,\n resumeRotation as wasmResumeRotation,\n resumeRotationAt as wasmResumeRotationAt,\n completeRotation as wasmCompleteRotation,\n setRotationPhase as wasmSetRotationPhase,\n finishRotation as wasmFinishRotation,\n abandonRotation as wasmAbandonRotation,\n rotationRecordState as wasmRotationRecordState,\n restoreJoin as wasmRestoreJoin,\n openStateBackup as wasmOpenStateBackup,\n refreshStateBackup as wasmRefreshStateBackup,\n endPending as wasmEndPending,\n beginAccountSetupInMemory as wasmBeginAccountSetupInMemory,\n type AccountSetupSession,\n} from \"../wasm/ping_wasm\";\nimport { PendingRootStore } from \"./pending-root-store\";\nimport { catchUpPass } from \"./catch-up-pass\";\nimport {\n advancedEpochs, changedHoldings, type ConversationEpoch, conversationKey, epochMap,\n} from \"./epoch-events\";\nimport type { Request, Response, StorageFeatures, TransportFeatures } from \"./protocol\";\nimport { RequestScheduler } from \"./request-lanes\";\nimport type {\n ApplyBatchResultWire,\n ConversationRemovalWire,\n ConversationUpdateWire,\n LogHeadWire,\n SequencedEnvelopeWire,\n SyncStepResultWire,\n} from \"./sequenced\";\nimport type { ConversationMeta, DeviceId, IncomingMessage, MessageEnvelope } from \"./types\";\n\ndeclare const self: DedicatedWorkerGlobalScope;\n\nlet client: PingClient | null = null;\nlet wasmReady: Promise<void> | null = null;\n\n// ---- Account set-up and the first backup (the account identity contract,\n// section 3.3; rule R34, \"which workers never make these calls\"; ruling ID38) ----\n//\n// The pending root is wrapped and unwrapped HERE, by the SDK's own store, in a\n// Worker that never runs a client: the main realm's `AccountSetup` owns one.\n// So the rule is held by construction in both directions:\n// * a Worker that runs a client (the tab's, and every background-session\n// worker, which is the same module with a client in it) refuses every\n// account kind before it touches the store;\n// * a Worker that made an account call never becomes a client.\n// The store is built here and nowhere else: no request carries one, and no\n// request or result carries a root seed or a wrapping key.\nlet pendingRootStore: PendingRootStore | null = null;\nlet setupSession: AccountSetupSession | null = null;\nlet ranAccountSetup = false;\n\nfunction accountWorker(): void {\n if (client) throw new Error(\"account refused: client-worker\");\n ranAccountSetup = true;\n}\n// ONE lock of the ORIGIN for every account call that writes (ruling V114).\n// The wasm holds one lock per Worker, which a second tab does not share; the\n// browser's Web Locks are shared by every tab and Worker of the origin. A\n// second tab's call waits here and then reads what the first one wrote (the\n// same device), instead of signing a second device under the first tab's\n// root. The ROOT itself is protected without this lock, by the pending\n// store's create-if-absent write. A realm with no Web Locks runs no account\n// call that writes: it is refused, typed.\nconst ACCOUNT_LOCK_NAME = \"ping-account-operations\";\ninterface WebLocks {\n request<T>(name: string, run: () => Promise<T>): Promise<T>;\n}\nfunction accountExclusive<T>(run: () => Promise<T>): Promise<T> {\n accountWorker();\n const locks = (globalThis as { navigator?: { locks?: WebLocks } }).navigator?.locks;\n if (!locks || typeof locks.request !== \"function\") {\n return Promise.reject(new Error(\"account refused: pending-store-unavailable\"));\n }\n return locks.request(ACCOUNT_LOCK_NAME, run);\n}\nfunction pendingStore(): PendingRootStore {\n accountWorker();\n pendingRootStore ??= new PendingRootStore();\n return pendingRootStore;\n}\nfunction openSession(): AccountSetupSession {\n accountWorker();\n if (!setupSession) throw new Error(\"account refused: setup-session-ended\");\n return setupSession;\n}\nfunction clientWorker(): void {\n if (ranAccountSetup) {\n throw new Error(\"this worker ran account set-up: a client starts in a worker of its own\");\n }\n}\n\n// ---- The build of a rotation (the account identity contract, 3.3 rule R34;\n// rulings V136 and V244) ----\n//\n// The ONE relaxation of the rule above: a rotation's build needs the root AND\n// a running client in one call, so it runs in the client's Worker, which\n// opens the root itself for the length of that call. This function is the\n// whole relaxation, for the two kinds `rotateGenerationWithPending` and\n// `rotateGenerationWithBackup` and for no other: `accountWorker()` is not\n// touched, so every other account kind is still refused here.\n// * A Worker with no client builds nothing (`no-client`), and is not made\n// an account Worker by having been asked.\n// * ONLY THE TAB'S OWN CLIENT builds (ruling V244). A background session's\n// Worker is this same module with a client in it, and so are a read-only\n// client's and a link's staging client's: the flag below is set by\n// `initFromDeviceRecord` alone, and only when its request says\n// `tabClient: true`. It is the HOST's word: the SDK cannot see which\n// Worker the person is looking at.\n// * The call holds the origin's account lock (ruling V114), as every\n// account call that writes does.\n// The pending store is the SDK's own, built inside the call and dropped with\n// it. No request carries a store, and no result carries anything of the root.\nlet tabClient = false;\nfunction rotationBuild<T>(run: (running: PingClient) => Promise<T>): Promise<T> {\n const running = client;\n if (!running) return Promise.reject(new Error(\"account refused: no-client\"));\n if (!tabClient) return Promise.reject(new Error(\"account refused: background-worker\"));\n const locks = (globalThis as { navigator?: { locks?: WebLocks } }).navigator?.locks;\n if (!locks || typeof locks.request !== \"function\") {\n return Promise.reject(new Error(\"account refused: pending-store-unavailable\"));\n }\n return locks.request(ACCOUNT_LOCK_NAME, () => run(running));\n}\n/** Zero this Worker's copy of a phrase that crossed as bytes. */\nfunction wipe(bytes: unknown): void {\n if (bytes instanceof Uint8Array) bytes.fill(0);\n}\n\nconst pendingStorage = new Map<number, (r: { ok: boolean; value: unknown }) => void>();\nconst pendingTransport = new Map<number, (r: { ok: boolean; value: unknown }) => void>();\nlet nextStorageId = 1;\nlet nextTransportId = 1;\n/** Calls made to the host transport so far. The worker runs one request at a\n * time, so the difference around a request is what that request sent and\n * fetched (see `sendLeftCopyBehind`). */\nlet transportCalls = 0;\n\nconst proxyStorage = {\n get: (namespace: string, key: string) => callMain<Uint8Array | null>(\"storage\", \"get\", [namespace, key]),\n put: (namespace: string, key: string, value: Uint8Array) =>\n callMain<void>(\"storage\", \"put\", [namespace, key, value]),\n del: (namespace: string, key: string) => callMain<void>(\"storage\", \"del\", [namespace, key]),\n listKeys: (namespace: string, prefix: string) =>\n callMain<string[]>(\"storage\", \"listKeys\", [namespace, prefix]),\n};\n// The two optional methods are declared on the proxy ONLY when the host\n// storage has them: the wasm bridge decides by their presence whether to hand\n// the per-row MLS store's delta to the host as one atomic batch (and read the\n// rows in one call) or to take its own journalled row-by-row fallback.\nconst applyBatchProxy = (namespace: string, puts: Array<[string, Uint8Array]>, deletes: string[]) =>\n callMain<void>(\"storage\", \"applyBatch\", [namespace, puts, deletes]);\nconst listEntriesProxy = (namespace: string, prefix: string) =>\n callMain<Array<[string, Uint8Array]>>(\"storage\", \"listEntries\", [namespace, prefix]);\nfunction makeProxyStorage(features: StorageFeatures | undefined) {\n return {\n ...proxyStorage,\n ...(features?.applyBatch ? { applyBatch: applyBatchProxy } : {}),\n ...(features?.listEntries ? { listEntries: listEntriesProxy } : {}),\n };\n}\nconst proxyTransport = {\n send: (envelope: MessageEnvelope) => callMain<void>(\"transport\", \"send\", [envelope]),\n // Always declared here: the main-thread dispatch emulates it with\n // sequential sends when the host transport has no `sendBatch`, encoding a\n // partial delivery with the `batch partial after <n>:` sentinel the wasm\n // bridge understands (see index.ts `BATCH_PARTIAL_PREFIX`).\n sendBatch: (envelopes: MessageEnvelope[]) => callMain<void>(\"transport\", \"sendBatch\", [envelopes]),\n fetchSince: (conv: Uint8Array, cursor: Uint8Array, limit: number) =>\n callMain<MessageEnvelope[]>(\"transport\", \"fetchSince\", [conv, cursor, limit]),\n discoverDevices: (userId: Uint8Array) => callMain<unknown[]>(\"transport\", \"discoverDevices\", [userId]),\n // Optional on the host (see `Transport.setNextWelcomeRecipients` in types.ts).\n // The main-thread dispatch (index.ts `handleWorker → case \"transport.call\"`)\n // resolves `undefined` to a `transport.reply { ok: true, value: undefined }`\n // when the host hasn't implemented the method, which we treat as a no-op.\n setNextWelcomeRecipients: (conv: Uint8Array, recipients: Uint8Array[]) =>\n callMain<void>(\"transport\", \"setNextWelcomeRecipients\", [conv, recipients]),\n};\n\n/** What the host transport declared at `init`; read by the catch-up pass. */\nlet transportFeatures: TransportFeatures = { fetchLogSince: false, fetchLogHeads: false };\n\nconst fetchLogSinceProxy = (position: unknown, limit: number) =>\n callMain<SequencedEnvelopeWire[] | null>(\"transport\", \"fetchLogSince\", [position, limit]);\nconst fetchLogHeadsProxy = () =>\n callMain<LogHeadWire[] | null | undefined>(\"transport\", \"fetchLogHeads\", []);\n\n/**\n * The transport proxy the wasm sees. Unlike `setNextWelcomeRecipients`, the\n * two sequenced-log methods are NOT always declared: the wasm bridge decides\n * by their presence whether to call them or fall back to the core default\n * (`fetchSince` at position 0; no heads), and `fetchLogSince` has no\n * main-thread emulation because only the core can encode the legacy cursor.\n */\nfunction makeProxyTransport(features: TransportFeatures) {\n return {\n ...proxyTransport,\n ...(features.fetchLogSince ? { fetchLogSince: fetchLogSinceProxy } : {}),\n ...(features.fetchLogHeads ? { fetchLogHeads: fetchLogHeadsProxy } : {}),\n // Self-admission: declared only when the host has them, like the two\n // above (absent, the wasm bridge answers the core's default: no route).\n ...(features.sendExternalCommit ? {\n sendExternalCommit: (envelope: MessageEnvelope) => callMain<void>(\"transport\", \"sendExternalCommit\", [envelope]),\n } : {}),\n ...(features.fetchSelfAdmissionStates ? {\n fetchSelfAdmissionStates: (conversations: Uint8Array[], unusable?: Uint8Array[]) =>\n callMain<unknown[]>(\"transport\", \"fetchSelfAdmissionStates\", [conversations, unusable ?? []]),\n } : {}),\n ...(features.fetchSealedGroupInfos ? {\n fetchSealedGroupInfos: (conversations: Uint8Array[]) =>\n callMain<unknown[]>(\"transport\", \"fetchSealedGroupInfos\", [conversations]),\n } : {}),\n ...(features.sendExternalCommits ? {\n sendExternalCommits: (envelopes: MessageEnvelope[]) =>\n callMain<unknown[] | null>(\"transport\", \"sendExternalCommits\", [envelopes]),\n } : {}),\n // The publishing half (ruling V320), declared like the four.\n ...(features.fetchSealingStatements ? {\n fetchSealingStatements: (accounts: Uint8Array[], conversation: Uint8Array) =>\n callMain<unknown[] | null>(\"transport\", \"fetchSealingStatements\", [accounts, conversation]),\n } : {}),\n ...(features.publishSealedGroupInfo ? {\n publishSealedGroupInfo: (publication: unknown) =>\n callMain<boolean | null>(\"transport\", \"publishSealedGroupInfo\", [publication]),\n } : {}),\n };\n}\n\nfunction callMain<T>(kind: \"storage\" | \"transport\", method: string, args: unknown[]): Promise<T> {\n return new Promise((resolve, reject) => {\n const id = kind === \"storage\" ? nextStorageId++ : nextTransportId++;\n const map = kind === \"storage\" ? pendingStorage : pendingTransport;\n if (kind === \"transport\") transportCalls += 1;\n map.set(id, ({ ok, value }) => ok ? resolve(value as T) : reject(new Error(String(value))));\n self.postMessage({ kind: `${kind}.call`, id, method, args } as Response);\n });\n}\n\nasync function ensureWasm() {\n if (wasmReady) return wasmReady;\n // The bundled wasm path is rewritten by the build script to be relative to `dist/`.\n wasmReady = init().then((out) => {\n reserveLinearMemory(out.memory);\n });\n return wasmReady;\n}\n\n// The WASM `PingClient` is SINGLE-THREADED (this one worker). Its async\n// methods hold internal locks across `.await` (e.g. a `conversations`\n// RwLock guard kept while `snapshot_to_storage` awaits IndexedDB). If we\n// let `onmessage` dispatch a SECOND top-level request while the first is\n// suspended at an await, the two WASM calls interleave on the single\n// thread, the second re-acquires a held lock, and `parking_lot`'s wasm\n// stub `panic!`s with \"Parking not supported on this platform\" — which\n// poisons the module (`RuntimeError: unreachable`) and breaks every\n// subsequent call. We therefore SERIALIZE top-level request dispatch:\n// one WASM call runs to completion before the next begins.\n//\n// ONE CALL AT A TIME IS NOT THE SAME AS FIRST COME, FIRST SERVED. A\n// whole-account `syncConversations` used to be one request: every\n// conversation paged inside a single turn, one network round trip each,\n// and a `send` posted while it ran started only after the last of them.\n// On a tab returning from an idle hour that was the whole visible cost of\n// the first message: the composer cleared, the bubble sat on a clock for\n// the length of the pass, and the second message went out at once. The\n// scheduler below keeps the one-call invariant but runs a whole-account\n// pass as a sequence of per-conversation steps (`syncConversation`) and\n// lets everything else queued run between steps. Ordinary requests stay\n// FIFO among themselves, so the inbound ordering that per-conversation\n// chaining on the main thread relies on is untouched; a host's own\n// `syncConversation` for the chat the user is looking at is an ordinary\n// request too, so it runs ahead of the background pass.\n//\n// CRUCIAL: `storage.reply` / `transport.reply` are NOT serialized — an\n// in-flight request awaits those replies (via `callMain`), so queuing\n// them behind the request would deadlock. They resolve pending callbacks\n// immediately, exactly as before.\nconst scheduler = new RequestScheduler();\n\n// Requests that can advance a conversation's MLS epoch WITHOUT an inbound\n// envelope to announce it.\n//\n// `event.conversation` was only ever emitted from `processEnvelope` and\n// `joinConversation`, so it announced exactly one of the three ways an epoch\n// moves: a Commit received from someone else. The other two were invisible to\n// every consumer:\n//\n// 1. A commit THIS device authored. `MessagingClient.dispatchIncoming` drops\n// envelopes whose `sender_device` is ours (the relay echoes our own\n// sends), so the author's own commit never reaches `processEnvelope`.\n// A host that re-derives exported secrets on epoch change — call media\n// keys are the load-bearing case — therefore kept using the PREVIOUS\n// epoch's secret after adding a member, and went silent against everyone\n// who had rotated. It is specifically the device that INVITES that breaks.\n// 2. A commit applied during catch-up. `syncConversations` fetches and\n// applies envelopes but posted nothing, so a client that reconnected after\n// missing a commit resumed on a stale secret.\n//\n// Rather than enumerate emissions per operation (and miss the next one added),\n// the epoch map is snapshotted around these requests and any conversation whose\n// epoch actually MOVED is announced. Conversations are only compared, never\n// created, so this can never invent an event: a freshly joined conversation is\n// already announced by `joinConversation`, and one that disappears (leave/drop)\n// is not an epoch change.\n//\n// `send` is deliberately absent from this set: it is the hot path. It must not\n// pay for two `listConversations` calls, and it reports no conversation event\n// of its own. A send is not only an application message, though: before it\n// encrypts, the core settles a Commit this device left in doubt there and\n// commits pending proposals, and after it the core refreshes this device's\n// leaf when that is due. Each of those moves the epoch, and the first can land\n// a rename. The core reports such a move with the next batch or page, and\n// that is where the host hears it, once. Here the main thread's copy of the\n// conversation is only kept level with the group, and a send that moved\n// nothing reads nothing (see `sendLeftCopyBehind`).\nconst EPOCH_ADVANCING_REQUESTS: ReadonlySet<string> = new Set([\n \"addMembers\",\n \"addMembersWithVerdicts\",\n \"reAdmitDevice\",\n \"removeMembers\",\n \"removeOwnOtherLeaves\",\n \"removeMembersByIdentity\",\n \"commitPendingProposals\",\n \"setConversationName\",\n \"setConversationRoles\",\n \"admitDeviceToChats\",\n \"admitDeviceToChatsConcurrent\",\n \"revokeDevice\",\n \"removeDeviceEverywhere\",\n \"removeOwnDevicesExcept\",\n \"addRestoredDevice\",\n \"syncConversations\",\n \"syncConversation\",\n \"completeDeviceLink\",\n \"recreateDeviceGroup\",\n \"importStateSnapshot\",\n]);\n\n// Requests that commit and whose epoch move is NOT announced to the host: it\n// never was, and a new host event is not what keeps a handle fresh. The\n// conversations are compared around them all the same, and the main thread's\n// copy of each one that moved is brought level with `cache.conversations`,\n// which calls no listener. `buildLinkingTicket` commits to the DeviceGroup.\nconst EPOCH_UPKEEP_REQUESTS: ReadonlySet<string> = new Set([\n \"buildLinkingTicketV3For\",\n]);\n\n// THE MAIN THREAD'S COPY OF A CONVERSATION'S METADATA\n//\n// The main thread keeps one `ConversationMeta` per conversation so that a\n// conversation handle can answer `name`, `epoch` and `meta()` without a round\n// trip. That copy used to be refilled by `listConversations()` only, so after\n// any change of a group it kept answering the metadata from before the change:\n// a host that carries a group's title and picture id in the name rebuilt the\n// name from the stale read and lost the picture on a rename.\n//\n// The rule now: every message that tells the main thread a conversation\n// changed CARRIES the conversation's metadata as the group holds it at that\n// moment, and the main thread stores it before it calls any host listener. A\n// request that changes a conversation without reporting an event (a creation,\n// a leave, a call whose Commit did not move the epoch, a `send` or a\n// `buildLinkingTicket` that moved one) says so with a\n// `cache.conversations` message before its `result`. Nothing here lists every\n// conversation to do it: the one conversation is read (`conversationMeta`), or\n// the record comes from a listing the request already paid for.\n\n/** One conversation's metadata as the group holds it now. `null`: the client\n * does not hold it (unknown, dropped, removed, or left) or it could not be\n * read; either way the main thread must not keep answering for it. */\nfunction readMeta(id: Uint8Array): ConversationMeta | null {\n if (!client) return null;\n try {\n return (client.conversationMeta(id) as ConversationMeta | null | undefined) ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Past this many conversations, one listing is cheaper than reading them one\n * at a time. The single read walks the client's conversations inside the\n * wasm and hands over one record; a listing hands over all of them and costs\n * about twelve single reads at any account size (measured at 100, 500 and\n * 2000 conversations). So the cost of bringing any number of conversations\n * up to date is bounded by one listing.\n */\nconst SINGLE_READS_MAX = 8;\n\n/** The metadata of each of `ids` as the groups hold it now, by\n * `conversationKey`; `null` for one the client does not hold. */\nfunction readMetas(ids: readonly Uint8Array[]): Map<string, ConversationMeta | null> {\n const out = new Map<string, ConversationMeta | null>();\n for (const id of ids) out.set(conversationKey(id), null);\n if (out.size <= SINGLE_READS_MAX) {\n for (const id of ids) out.set(conversationKey(id), readMeta(id));\n return out;\n }\n if (!client) return out;\n try {\n for (const meta of client.listConversations() as unknown as ConversationMeta[]) {\n const key = conversationKey(meta.id);\n if (out.has(key)) out.set(key, meta);\n }\n } catch {\n // Unreadable: every one of them stays `null`, and the main thread drops\n // its copies instead of keeping the old ones.\n }\n return out;\n}\n\n/** Tell the main thread a conversation changed, with its metadata as the\n * group holds it now (`null`: it is not held any more). */\nfunction postConversationEvent(\n id: Uint8Array,\n epoch: number,\n sender: DeviceId | undefined,\n meta: ConversationMeta | null,\n): void {\n (self.postMessage as (m: Response) => void)({\n kind: \"event.conversation\",\n id,\n epoch,\n ...(sender !== undefined ? { sender } : {}),\n ...(meta !== null ? { meta } : {}),\n });\n}\n\n/** Cache upkeep with no host event: what the main thread must hold now and\n * what it must forget. Posts nothing when there is nothing to say. */\nfunction postCacheUpkeep(held: ConversationMeta[], dropped: Uint8Array[]): void {\n if (held.length === 0 && dropped.length === 0) return;\n (self.postMessage as (m: Response) => void)({ kind: \"cache.conversations\", held, dropped });\n}\n\n/** Read each of `ids` and post the upkeep for them as one message. */\nfunction refreshCached(ids: readonly Uint8Array[]): void {\n if (ids.length === 0) return;\n const metas = readMetas(ids);\n const held: ConversationMeta[] = [];\n const dropped: Uint8Array[] = [];\n const done = new Set<string>();\n for (const id of ids) {\n const key = conversationKey(id);\n if (done.has(key)) continue;\n done.add(key);\n const meta = metas.get(key) ?? null;\n if (meta !== null) held.push(meta);\n else dropped.push(id);\n }\n postCacheUpkeep(held, dropped);\n}\n\n/**\n * What a request is watched over: the epoch of every conversation the client\n * held before it ran (one listing), and how to list them again after it.\n * `announce` says what a moved epoch becomes: a host event (the requests in\n * `EPOCH_ADVANCING_REQUESTS`) or upkeep of the main thread's copy only (the\n * requests in `EPOCH_UPKEEP_REQUESTS`).\n */\ninterface EpochWatch {\n before: Map<string, number>;\n after(): ConversationMeta[];\n announce: boolean;\n}\n\n/** The watch for `msg`, or `null` when it needs none or the conversations\n * could not be read: no epoch change is reported for that request then, and\n * nothing is concluded from an absence. */\nfunction watchFor(msg: Request): EpochWatch | null {\n const held = client;\n if (!held) return null;\n const announce = EPOCH_ADVANCING_REQUESTS.has(msg.kind);\n if (!announce && !EPOCH_UPKEEP_REQUESTS.has(msg.kind)) return null;\n const list = (): ConversationMeta[] => held.listConversations() as unknown as ConversationMeta[];\n try {\n return { before: epochMap(list()), after: list, announce };\n } catch {\n // A client mid-teardown (or a storage read failure) is not a reason to\n // fail the request the caller actually made.\n return null;\n }\n}\n\n/**\n * Tell the main thread about every watched conversation whose epoch moved,\n * each with the metadata just read: as a host event when the watch announces,\n * as cache upkeep when it does not. The conversations the request brought in\n * or took away are cache upkeep either way. Returns the keys of every\n * conversation the main thread was told about, so the caller does not read\n * one of them a second time.\n */\nfunction emitEpochAdvances(watch: EpochWatch): Set<string> {\n const told = new Set<string>();\n let metas: ConversationMeta[];\n try {\n metas = watch.after();\n } catch {\n return told;\n }\n const advanced = advancedEpochs(watch.before, metas);\n for (const meta of advanced) {\n told.add(conversationKey(meta.id));\n if (watch.announce) postConversationEvent(meta.id, meta.epoch, undefined, meta);\n }\n const { appeared, disappeared } = changedHoldings(watch.before, metas);\n for (const meta of appeared) told.add(conversationKey(meta.id));\n for (const id of disappeared) told.add(conversationKey(id));\n postCacheUpkeep(watch.announce ? appeared : [...advanced, ...appeared], disappeared);\n return told;\n}\n\n/**\n * Whether the main thread's copy of the conversation a `send` named may be\n * behind the group now. Answered from what the worker already holds, so a\n * send that moved nothing reads nothing:\n *\n * - The envelope the send produced carries the epoch it was encrypted at,\n * and the main thread sent the epoch of its own copy with the request.\n * Everything the core does BEFORE it encrypts shows in that comparison:\n * settling a Commit this device left in doubt, committing pending\n * proposals, applying another member's Commits from the log.\n * - The one thing the core does AFTER it encrypts is the refresh of this\n * device's leaf: a Commit, merged only once the transport accepted it. A\n * send that moved nothing makes exactly one transport call, the message\n * itself, so any other count means something else was sent or fetched.\n *\n * A send that failed produced no envelope to compare, so the conversation is\n * read. In every case the cost is at most ONE read of the one conversation,\n * made after the send; never a listing, and never a host event.\n */\nfunction sendLeftCopyBehind(\n msg: Extract<Request, { kind: \"send\" }>,\n outcome: { ok: true; value: unknown } | { ok: false },\n calls: number,\n): boolean {\n if (!outcome.ok || calls !== 1) return true;\n const sentAt = (outcome.value as { epoch?: unknown } | null | undefined)?.epoch;\n return typeof sentAt !== \"number\" || sentAt !== msg.heldEpoch;\n}\n\n/**\n * Announce the conversations a batch or page moved. The sequenced paths\n * report `updated` exactly (the core lists every conversation whose epoch\n * moved or that was joined), so there is nothing to diff: one event per\n * entry, each with the conversation's metadata read at that moment.\n * `senders` labels a join with the inviter's device, as `joinConversation`\n * does. `removed` are the conversations the batch took this device out of:\n * no host event (the result reports them), but the main thread's copy of\n * each is brought to what the client holds now.\n */\nfunction announceUpdated(\n updated: ConversationUpdateWire[],\n senders: Map<string, DeviceId> = new Map(),\n removed: ConversationRemovalWire[] = [],\n): void {\n if (updated.length === 0 && removed.length === 0) return;\n const metas = readMetas([\n ...updated.map((u) => u.conversation_id),\n ...removed.map((r) => r.conversation_id),\n ]);\n const told = new Set<string>();\n for (const u of updated) {\n const key = conversationKey(u.conversation_id);\n told.add(key);\n postConversationEvent(u.conversation_id, u.epoch, senders.get(key), metas.get(key) ?? null);\n }\n const held: ConversationMeta[] = [];\n const dropped: Uint8Array[] = [];\n for (const r of removed) {\n const key = conversationKey(r.conversation_id);\n if (told.has(key)) continue;\n told.add(key);\n const meta = metas.get(key) ?? null;\n if (meta !== null) held.push(meta);\n else dropped.push(r.conversation_id);\n }\n postCacheUpkeep(held, dropped);\n}\n\n/** The inviter's device for every conversation a batch joined, from the\n * Welcome that joined it. */\nfunction welcomeSenders(items: SequencedEnvelopeWire[], joined: Uint8Array[]): Map<string, DeviceId> {\n const out = new Map<string, DeviceId>();\n if (joined.length === 0) return out;\n const wanted = new Set(joined.map((id) => conversationKey(id)));\n for (const item of items) {\n if (item.envelope.kind !== \"Welcome\") continue;\n const key = conversationKey(item.envelope.conversation_id);\n if (wanted.has(key) && !out.has(key)) out.set(key, item.envelope.sender_device);\n }\n return out;\n}\n\n// Requests after which ONE conversation's metadata on the main thread must be\n// what the group holds, whether or not an event said so: this device's own\n// calls on a conversation. When the call moved the epoch, the event above\n// already carried the metadata and nothing more is read. When it did not (the\n// call failed, its Commit is in doubt, the conversation is now left or\n// dropped), the one conversation is read once, here.\nconst CONVERSATION_REQUESTS: ReadonlySet<string> = new Set([\n \"addMembers\",\n \"addMembersWithVerdicts\",\n \"reAdmitDevice\",\n \"removeMembers\",\n \"removeOwnOtherLeaves\",\n \"removeMembersByIdentity\",\n \"commitPendingProposals\",\n \"setConversationName\",\n \"setConversationRoles\",\n \"syncConversation\",\n \"leaveConversation\",\n \"dropConversationLocal\",\n]);\n\n// Requests that resolve to the id of a conversation they brought in.\nconst CONVERSATION_RESULT_REQUESTS: ReadonlySet<string> = new Set([\n \"createConversation\",\n \"createCallConversation\",\n \"importStateSnapshot\",\n]);\n\n/** The conversation a finished request must leave fresh on the main thread. */\nfunction conversationTouched(msg: Request, value: unknown): Uint8Array | null {\n if (CONVERSATION_REQUESTS.has(msg.kind)) {\n const conv = (msg as { conv?: unknown }).conv;\n return conv instanceof Uint8Array ? conv : null;\n }\n if (CONVERSATION_RESULT_REQUESTS.has(msg.kind)) {\n return value instanceof Uint8Array ? value : null;\n }\n return null;\n}\n\n/**\n * The conversations a request that applies inbound frames named. When such a\n * request succeeds, the events it posted carried the metadata. When it\n * THROWS it posted nothing, yet the group may have moved before the throw (a\n * Commit merged, then the checkpoint failed), so each conversation it named\n * is read once and the main thread's copy follows. No host event: a failed\n * apply never announced one.\n */\nfunction conversationsOfFailedApply(msg: Request): Uint8Array[] {\n switch (msg.kind) {\n case \"processEnvelope\":\n return [msg.envelope.conversation_id];\n case \"joinConversation\":\n case \"joinConversationAt\":\n case \"processWelcomeAt\":\n return [msg.welcome.conversation_id];\n case \"syncConversationStep\":\n return [msg.conv];\n case \"processSequencedBatch\":\n return msg.items.map((item) => item.envelope.conversation_id);\n default:\n return [];\n }\n}\n\n/** Everything the main thread must know about conversations before it hears\n * the request's outcome. `calls` is how many transport calls the request\n * made. Never throws. */\nfunction reportConversations(\n msg: Request,\n watch: EpochWatch | null,\n outcome: { ok: true; value: unknown } | { ok: false },\n calls: number,\n): void {\n try {\n const told = watch ? emitEpochAdvances(watch) : new Set<string>();\n const touched = conversationTouched(msg, outcome.ok ? outcome.value : undefined);\n const owed = outcome.ok ? [] : conversationsOfFailedApply(msg);\n if (touched !== null) owed.push(touched);\n if (msg.kind === \"send\" && sendLeftCopyBehind(msg, outcome, calls)) owed.push(msg.conv);\n refreshCached(owed.filter((id) => id instanceof Uint8Array && !told.has(conversationKey(id))));\n } catch {\n // Reporting is never a reason to fail the request the caller made.\n }\n}\n\nasync function runRequest(msg: Request): Promise<void> {\n // Snapshot BEFORE the request and diff after, so a self-authored commit or a\n // catch-up-applied one is announced like any other epoch change.\n const watch = watchFor(msg);\n const callsBefore = transportCalls;\n try {\n const value = await dispatch(msg);\n // Announce the epoch change BEFORE resolving the caller, so a host that\n // awaits `addMembers` and then reads a derived secret cannot observe the\n // new epoch before being told about it. The same order is what makes the\n // conversation handle fresh when the call resolves.\n reportConversations(msg, watch, { ok: true, value }, transportCalls - callsBefore);\n (self.postMessage as (m: Response) => void)({ kind: \"result\", id: msg.id, ok: true, value });\n } catch (e) {\n // A failed request can still have advanced the epoch (a commit that merged\n // locally before a later step threw), so report the change either way.\n reportConversations(msg, watch, { ok: false }, transportCalls - callsBefore);\n (self.postMessage as (m: Response) => void)({\n kind: \"result\", id: msg.id, ok: false, error: e instanceof Error ? e.message : String(e),\n });\n }\n}\n\nself.onmessage = (ev: MessageEvent<Request>) => {\n const msg = ev.data;\n\n // Storage / transport responses from the main thread — handle\n // immediately (they unblock the in-flight request). Never queued.\n if (msg.kind === \"storage.reply\") {\n const slot = pendingStorage.get(msg.id);\n if (slot) {\n pendingStorage.delete(msg.id);\n msg.ok ? slot({ ok: true, value: msg.value })\n : slot({ ok: false, value: msg.error });\n }\n return;\n }\n if (msg.kind === \"transport.reply\") {\n const slot = pendingTransport.get(msg.id);\n if (slot) {\n pendingTransport.delete(msg.id);\n msg.ok ? slot({ ok: true, value: msg.value })\n : slot({ ok: false, value: msg.error });\n }\n return;\n }\n\n // Top-level client request. A whole-account catch-up becomes a stepped\n // pass the scheduler runs one conversation per turn, behind everything\n // else queued; every other request runs FIFO, one WASM call at a time.\n // `runRequest` and the pass stepper never reject (errors are posted as\n // results), so the scheduler can't wedge.\n if (msg.kind === \"syncConversations\") {\n scheduler.enqueueStepped(catchUpPassStepper(msg));\n return;\n }\n // The SDK's own gap fill: one page per turn on the stepped lane, so a\n // send posted while a long fill runs goes between pages.\n if (msg.kind === \"syncConversationStep\" && msg.stepped === true) {\n scheduler.enqueueStepped(async () => {\n await runRequest(msg);\n return false;\n });\n return;\n }\n scheduler.enqueue(() => runRequest(msg));\n};\n\n/**\n * One whole-account catch-up as a stepped job: ONE PAGE of one conversation\n * per scheduler turn (`catch-up-pass.ts` has the policy). The scheduler runs\n * queued ordinary requests between pages. When the host transport reports\n * the server's log heads, only the conversations that are behind are\n * stepped. Each page's messages are posted as an `event.batch` (source\n * `page`) and its conversation updates come from the core's exact `updated`\n * list, so nothing here diffs epochs. The result is posted once, when the\n * pass is complete, with every decrypted application message in apply\n * order, the same contract `syncConversations()` callers have always had.\n */\nfunction catchUpPassStepper(\n msg: Extract<Request, { kind: \"syncConversations\" }>,\n): () => Promise<boolean> {\n const post = (m: Response): void => (self.postMessage as (m: Response) => void)(m);\n let pass: (() => Promise<boolean>) | null = null;\n return async (): Promise<boolean> => {\n if (pass === null) {\n try {\n await ensureWasm();\n ensureClient();\n } catch (e) {\n post({\n kind: \"result\", id: msg.id, ok: false,\n error: e instanceof Error ? e.message : String(e),\n });\n return false;\n }\n pass = catchUpPass({\n listConversationIds: () =>\n (ensureClient().listConversations() as unknown as ConversationEpoch[]).map((meta) => meta.id),\n fetchHeads: async () =>\n transportFeatures.fetchLogHeads ? (await fetchLogHeadsProxy()) ?? null : null,\n conversationsBehind: (heads) =>\n ensureClient().conversationsBehind(heads) as unknown as Uint8Array[],\n step: async (id) => {\n try {\n return await (ensureClient().syncConversationStep(id, msg.nowMs) as unknown as Promise<SyncStepResultWire>);\n } catch (e) {\n // A page that threw announced nothing; the group may still have\n // moved before the throw (see `conversationsOfFailedApply`).\n refreshCached([id]);\n throw e;\n }\n },\n onPage: (page) => {\n announceUpdated(page.updated, undefined, page.removed);\n if (page.messages.length > 0) {\n post({ kind: \"event.batch\", messages: page.messages, source: \"page\" });\n }\n },\n finish: (ok, value) => {\n if (ok) {\n post({ kind: \"result\", id: msg.id, ok: true, value });\n } else {\n post({\n kind: \"result\", id: msg.id, ok: false,\n error: value instanceof Error ? value.message : String(value),\n });\n }\n },\n });\n }\n return pass();\n };\n}\n\n/** The account calls that carry the recovery phrase (ruling V253). It\n * crosses to this Worker as UTF-8 bytes; the wasm copies them into its own\n * memory and wipes that copy; this Worker's copy is zeroed when the call\n * has answered, whatever it answered. (`rotateGenerationWithBackup` does\n * the same in its own case, with its second phrase.) */\nconst PHRASE_KINDS: ReadonlySet<string> = new Set([\n \"makeBackup\", \"proveBackup\", \"openBackupForRestore\", \"restoreTakeOver\", \"restoreJoin\",\n \"setupSessionMakeBackup\", \"setupSessionProveBackup\",\n]);\n\nasync function dispatch(msg: Request): Promise<unknown> {\n if (!PHRASE_KINDS.has(msg.kind)) return dispatchRequest(msg);\n // Anything but bytes never reaches the wasm: it is replaced by NO phrase,\n // which the call refuses as `invalid-phrase` after its own refusals (a\n // client's Worker still answers `client-worker` first).\n const carried = msg as { phrase?: unknown };\n if (!(carried.phrase instanceof Uint8Array)) carried.phrase = new Uint8Array();\n const phrase = carried.phrase;\n try {\n return await dispatchRequest(msg);\n } finally {\n wipe(phrase);\n }\n}\n\nasync function dispatchRequest(msg: Request): Promise<unknown> {\n await ensureWasm();\n switch (msg.kind) {\n case \"initFromDeviceRecord\": {\n clientWorker();\n transportFeatures = msg.transportFeatures ?? { fetchLogSince: false, fetchLogHeads: false };\n client = await PingClient.initFromDeviceRecord(\n msg.deviceLabel,\n makeProxyStorage(msg.storageFeatures) as unknown as never,\n makeProxyTransport(transportFeatures) as unknown as never,\n msg.nowMs,\n msg.deviceSigningSecretKey ?? null,\n msg.expectedOwners ?? null,\n );\n tabClient = msg.tabClient === true;\n client.onMessage((m: unknown) => {\n (self.postMessage as (m: Response) => void)({ kind: \"event.message\", msg: m as never });\n });\n return null;\n }\n case \"openReadOnlyFromDeviceRecord\": {\n clientWorker();\n client = await PingClient.openReadOnlyFromDeviceRecord(\n msg.deviceLabel,\n makeProxyStorage(msg.storageFeatures) as unknown as never,\n proxyTransport as unknown as never,\n msg.nowMs,\n );\n return null;\n }\n // The device link under the root design. `beginDeviceLink` starts a NEW\n // device's staging client: the wasm draws the device key, and the client\n // it answers becomes this worker's client until the link is complete.\n case \"beginDeviceLink\": {\n clientWorker();\n transportFeatures = msg.transportFeatures ?? { fetchLogSince: false, fetchLogHeads: false };\n const begun = await wasmBeginDeviceLink(\n msg.deviceLabel,\n makeProxyStorage(msg.storageFeatures) as unknown as never,\n makeProxyTransport(transportFeatures) as unknown as never,\n msg.nowMs,\n );\n try {\n client = begun.takeClient();\n client.onMessage((m: unknown) => {\n (self.postMessage as (m: Response) => void)({ kind: \"event.message\", msg: m as never });\n });\n return {\n payload: begun.payload,\n deviceId: begun.deviceId,\n deviceSigningSecretKey: begun.deviceSigningSecretKey,\n hpkeSecretKey: begun.hpkeSecretKey,\n };\n } finally {\n begun.free();\n }\n }\n case \"buildLinkingTicketV3For\":\n return await ensureClient().buildLinkingTicketV3For(\n msg.payload, msg.expectedCode, msg.expectedQr, msg.lastAppEvents, msg.nowMs,\n );\n case \"linkGenerationFor\":\n return ensureClient().linkGenerationFor(msg.payload, msg.expectedCode, msg.expectedQr);\n case \"recreateDeviceGroup\":\n await ensureClient().recreateDeviceGroup(msg.nowMs);\n return null;\n // The rotation in a client's Worker. The plan, the answer and the\n // adoption touch no root; the two builds open it for the length of the\n // call (see `rotationBuild` above).\n case \"rotateGenerationWithPending\":\n return await rotationBuild((running) =>\n running.rotateGenerationWithPending(\n // The SDK's own store, for this one call: never a host's object.\n new PendingRootStore() as unknown as never,\n msg.slot, msg.start, msg.devices, msg.kept, msg.reason, msg.accountId, msg.hostState, msg.nowMs,\n ));\n case \"rotateGenerationWithBackup\": {\n // The wasm copies the phrases into its own memory and wipes that copy;\n // this Worker's copy is zeroed when the call has answered, whatever it\n // answered (a refusal before the call included).\n try {\n if (!(msg.phrase instanceof Uint8Array)) throw new Error(\"account refused: invalid-phrase\");\n if (msg.newPhrase !== undefined && !(msg.newPhrase instanceof Uint8Array)) {\n throw new Error(\"account refused: invalid-phrase\");\n }\n return await rotationBuild((running) =>\n running.rotateGenerationWithBackup(\n msg.rootPart, msg.phrase, msg.newPhrase,\n msg.start, msg.devices, msg.kept, msg.reason, msg.accountId, msg.hostState, msg.nowMs,\n ));\n } finally {\n wipe(msg.phrase);\n wipe(msg.newPhrase);\n }\n }\n case \"planRotation\":\n return await ensureClient().planRotation(msg.start, msg.devices, msg.rootPartGeneration);\n case \"completeRotationOnClient\":\n return await ensureClient().completeRotation(msg.recordId, msg.answer);\n case \"adoptGeneration\":\n return await ensureClient().adoptGeneration(\n msg.generation, msg.credential, msg.gsWrap, msg.statement, msg.nowMs,\n );\n case \"completeDeviceLink\":\n // The client's own store: no store is an argument.\n return await ensureClient().completeDeviceLink(\n msg.ticket, msg.generation, msg.generationSecret, msg.nowMs,\n );\n case \"sealLinkingTicketV3For\":\n return wasmSealLinkingTicketV3For(msg.ticket, msg.payload, msg.expectedCode, msg.expectedQr);\n case \"openLinkingTicketV3\":\n return wasmOpenLinkingTicketV3(msg.sealed, msg.newDevicePriv);\n case \"heldCredential\": return ensureClient().heldCredential();\n case \"heldGeneration\": return ensureClient().heldGeneration();\n\n // Account set-up and the first backup: see the note at the top of this\n // file. The store is asked for FIRST, so a client's worker refuses\n // before anything else runs.\n case \"createAccount\": {\n return accountExclusive(async () => {\n const store = pendingStore();\n return wasmCreateAccount(\n makeProxyStorage(msg.storageFeatures) as unknown as never,\n store as unknown as never,\n msg.slot, msg.identityState, msg.persistentStorage, msg.nowMs,\n );\n });\n }\n case \"pendingStatus\": {\n const store = pendingStore();\n return wasmPendingStatus(\n makeProxyStorage(msg.storageFeatures) as unknown as never, store as unknown as never, msg.slot,\n );\n }\n case \"makeBackup\": {\n return accountExclusive(async () => {\n const store = pendingStore();\n return wasmMakeBackup(\n makeProxyStorage(msg.storageFeatures) as unknown as never, store as unknown as never,\n msg.slot, msg.phrase, msg.accountId, msg.hostState, msg.nowMs,\n );\n });\n }\n case \"proveBackup\": {\n return accountExclusive(async () => {\n accountWorker();\n return wasmProveBackup(\n makeProxyStorage(msg.storageFeatures) as unknown as never, msg.readBackRootPart, msg.phrase,\n );\n });\n }\n case \"endPending\": {\n return accountExclusive(async () => {\n const store = pendingStore();\n await wasmEndPending(\n makeProxyStorage(msg.storageFeatures) as unknown as never, store as unknown as never,\n msg.slot, msg.fingerprint,\n );\n return null;\n });\n }\n // The restore as a rotation: the same Worker that never runs a client.\n case \"openBackupForRestore\": {\n accountWorker();\n return wasmOpenBackupForRestore(msg.rootPart, msg.phrase, msg.statePart, msg.pinnedRootPublicKey);\n }\n case \"restoreTakeOver\": {\n return accountExclusive(async () => {\n accountWorker();\n return wasmRestoreTakeOver(\n makeProxyStorage(msg.storageFeatures) as unknown as never,\n msg.rootPart, msg.phrase, msg.start, msg.oldStatePart, msg.accountId, msg.hostState, msg.nowMs,\n );\n });\n }\n case \"takeAccountBack\": {\n return accountExclusive(async () => {\n const store = pendingStore();\n return wasmTakeAccountBack(\n makeProxyStorage(msg.storageFeatures) as unknown as never, store as unknown as never,\n msg.slot, msg.start, msg.oldStatePart, msg.accountId, msg.hostState, msg.nowMs,\n );\n });\n }\n case \"resumeRotation\": {\n accountWorker();\n // With the host's clock (ruling V461) a stalled take-over's kept\n // seed is blanked at 30 days; a caller that hands none gets the\n // call as it was.\n if (msg.nowMs === undefined) {\n return wasmResumeRotation(makeProxyStorage(msg.storageFeatures) as unknown as never);\n }\n return wasmResumeRotationAt(makeProxyStorage(msg.storageFeatures) as unknown as never, msg.nowMs);\n }\n case \"completeRotation\": {\n return accountExclusive(async () => {\n accountWorker();\n return wasmCompleteRotation(\n makeProxyStorage(msg.storageFeatures) as unknown as never, msg.recordId, msg.answer,\n );\n });\n }\n case \"setRotationPhase\": {\n return accountExclusive(async () => {\n accountWorker();\n await wasmSetRotationPhase(makeProxyStorage(msg.storageFeatures) as unknown as never, msg.recordId, msg.phase);\n return null;\n });\n }\n case \"finishRotation\": {\n return accountExclusive(async () => {\n accountWorker();\n await wasmFinishRotation(makeProxyStorage(msg.storageFeatures) as unknown as never, msg.recordId);\n return null;\n });\n }\n case \"abandonRotation\": {\n return accountExclusive(async () => {\n accountWorker();\n await wasmAbandonRotation(makeProxyStorage(msg.storageFeatures) as unknown as never, msg.recordId);\n return null;\n });\n }\n case \"rotationRecordState\": {\n // Ruling V232: one local read; no secret, no request.\n accountWorker();\n return wasmRotationRecordState(makeProxyStorage(msg.storageFeatures) as unknown as never);\n }\n case \"restoreJoin\": {\n return accountExclusive(async () => {\n accountWorker();\n return wasmRestoreJoin(\n makeProxyStorage(msg.storageFeatures) as unknown as never,\n msg.rootPart, msg.phrase, msg.statePart, msg.start, msg.nowMs,\n );\n });\n }\n case \"openStateBackup\": {\n accountWorker();\n return wasmOpenStateBackup(makeProxyStorage(msg.storageFeatures) as unknown as never, msg.statePart);\n }\n case \"refreshStateBackup\": {\n return accountExclusive(async () => {\n accountWorker();\n return wasmRefreshStateBackup(\n makeProxyStorage(msg.storageFeatures) as unknown as never, msg.accountId, msg.hostState, msg.nowMs,\n );\n });\n }\n case \"beginAccountSetupInMemory\": {\n accountWorker();\n if (setupSession) throw new Error(\"account refused: setup-session-open\");\n setupSession = wasmBeginAccountSetupInMemory(msg.identityState, msg.nowMs);\n return null;\n }\n case \"setupSessionMakeBackup\":\n return openSession().makeBackup(msg.phrase, msg.accountId, msg.hostState, msg.nowMs);\n case \"setupSessionProveBackup\":\n return openSession().proveBackup(msg.readBackRootPart, msg.phrase);\n case \"setupSessionFinish\": {\n return accountExclusive(async () => {\n const session = openSession();\n // A refusal (no proof yet) leaves the session open; an answer ends it.\n const made = await session.finish(makeProxyStorage(msg.storageFeatures) as unknown as never);\n session.free();\n setupSession = null;\n return made;\n });\n }\n case \"setupSessionKeepAsPending\": {\n return accountExclusive(async () => {\n const session = openSession();\n const store = pendingStore();\n const made = await session.keepAsPending(\n makeProxyStorage(msg.storageFeatures) as unknown as never, store as unknown as never,\n msg.slot, msg.persistentStorage,\n );\n session.free();\n setupSession = null;\n return made;\n });\n }\n case \"endAccountSetupSession\": {\n if (setupSession) {\n setupSession.free();\n setupSession = null;\n }\n return null;\n }\n\n case \"previewEnvelope\":\n return ensureClient().previewEnvelope(msg.envelope as unknown as never, msg.nowMs);\n case \"previewEnvelopeWithPrerequisites\":\n return ensureClient().previewEnvelopeWithPrerequisites(\n msg.prerequisites as unknown as never,\n msg.envelope as unknown as never,\n msg.nowMs,\n );\n\n case \"userId\": return ensureClient().userId();\n case \"deviceId\": return ensureClient().deviceId();\n case \"suspendStorage\": return ensureClient().suspendStorage();\n case \"resumeStorage\": return ensureClient().resumeStorage();\n case \"freshKeyPackage\": return ensureClient().freshKeyPackage();\n case \"freshLastResortKeyPackage\": return ensureClient().freshLastResortKeyPackage();\n case \"createConversation\":\n return await ensureClient().createConversation(msg.name ?? undefined, msg.nowMs);\n case \"createCallConversation\":\n return await ensureClient().createCallConversation(msg.name ?? undefined, msg.nowMs);\n case \"joinConversation\": {\n const id = await ensureClient().joinConversation(msg.welcome, msg.nowMs) as Uint8Array;\n // Notify the main thread that we just entered a new conversation. We forward the\n // Welcome's `sender_device` so the host can label \"joined chat with <inviter>\".\n postConversationEvent(id, 0, msg.welcome.sender_device, readMeta(id));\n return id;\n }\n case \"listConversations\":\n return ensureClient().listConversations();\n case \"conversationMeta\":\n // ONE conversation, read where the group lives: no listing crosses to\n // the main thread. `null` when the client does not hold it.\n return ensureClient().conversationMeta(msg.conv) ?? null;\n case \"strandedConversations\":\n return ensureClient().strandedConversations();\n case \"conversationsLeaving\":\n return ensureClient().conversationsLeaving();\n case \"conversationsLeaveStalled\":\n return ensureClient().conversationsLeaveStalled();\n case \"readmitPendingConversations\":\n return ensureClient().readmitPendingConversations(msg.nowMs);\n case \"undeliverableCount\":\n return ensureClient().undeliverableCount();\n case \"members\":\n return ensureClient().members(msg.conv);\n case \"conversationPolicy\":\n return ensureClient().conversationPolicy(msg.conv);\n case \"setExpectedOwners\":\n return ensureClient().setExpectedOwners(msg.entries);\n case \"setConversationRoles\":\n return await ensureClient().setConversationRoles(msg.conv, msg.owner, msg.admins, msg.nowMs);\n case \"send\":\n return await ensureClient().send(msg.conv, msg.plaintext, msg.nowMs);\n case \"addMembers\":\n // wasm-bindgen takes the entries as a plain array of {deviceId, keyPackage};\n // serde-wasm-bindgen on the Rust side deserialises into Vec<JsAddMemberEntry>.\n return await ensureClient().addMembers(msg.conv, msg.entries, msg.nowMs);\n case \"addMembersWithVerdicts\":\n // Per-entry verdicts; resolves to the serialised AddMembersReport.\n return await ensureClient().addMembersWithVerdicts(msg.conv, msg.entries, msg.nowMs);\n case \"reAdmitDevice\":\n // Re-admit one device that kept its key: the leaf with the KeyPackage's\n // own signature key goes and the fresh KeyPackage is added. Never an add:\n // with no such leaf it rejects \"not permitted: ...\", and so does a\n // committer the roles do not permit. Resolves to the device id of the\n // replaced leaf.\n return await ensureClient().reAdmitDevice(msg.conv, msg.entry, msg.nowMs);\n case \"mayReadmit\":\n // A pure query: would this device's Commit re-admitting or adding that\n // device pass the membership rules now. Nothing is built or sent.\n return ensureClient().mayReadmit(msg.conv, msg.identity, msg.deviceId);\n case \"keyPackageIdentity\":\n // A pure read: the identity the KeyPackage's credential claims, after the\n // KeyPackage was validated (signatures, lifetime). `undefined` for a\n // credential that is not the project's; throws for anything else.\n return ensureClient().keyPackageIdentity(msg.keyPackage);\n case \"setConversationName\":\n // GroupContextExtensions commit carrying the new conversation name — the\n // rename / avatar-id change propagates to every member via group state.\n return await ensureClient().setConversationName(msg.conv, msg.name ?? undefined, msg.nowMs);\n case \"admitDeviceToChats\":\n // Per-chat add for a newly-linked device. Returns Vec<JsAdmitChatOutcome>\n // — the host inspects per-entry status to decide whether to retry.\n return await ensureClient().admitDeviceToChats(msg.deviceId, msg.entries, msg.nowMs);\n case \"admitDeviceToChatsConcurrent\":\n // Same per-chat add with up to `concurrency` admissions in flight inside\n // this ONE wasm call (the worker still runs one call at a time; the\n // overlap is the core's, across conversations). Outcomes in input order.\n return await ensureClient().admitDeviceToChatsConcurrent(\n msg.deviceId,\n msg.entries,\n msg.nowMs,\n msg.concurrency,\n );\n case \"removeMembers\":\n // wasm-bindgen exposes Vec<u32> as Uint32Array; convert from the protocol's number[].\n return await ensureClient().removeMembers(msg.conv, new Uint32Array(msg.leaves), msg.nowMs);\n case \"removeOwnOtherLeaves\":\n // Every OTHER leaf of this account in one conversation; resolves to the count.\n return await ensureClient().removeOwnOtherLeaves(msg.conv, msg.nowMs);\n case \"removeMembersByIdentity\":\n // Every leaf whose credential verifies for one of `identities`; resolves to the count.\n return await ensureClient().removeMembersByIdentity(msg.conv, msg.identities, msg.nowMs);\n case \"leaveConversation\":\n return await ensureClient().leaveConversation(msg.conv, msg.nowMs);\n case \"dropConversationLocal\":\n return await ensureClient().dropConversationLocal(msg.conv);\n case \"conversationsWithPendingProposals\":\n return ensureClient().conversationsWithPendingProposals();\n case \"commitPendingProposals\":\n return await ensureClient().commitPendingProposals(msg.conv, msg.nowMs);\n case \"pendingProposalsCommitRank\":\n return ensureClient().pendingProposalsCommitRank(msg.conv) ?? null;\n case \"commitsInDoubt\":\n return ensureClient().commitsInDoubt();\n case \"revokeDevice\":\n // [CR-2] returns the array of Commit envelopes the SDK has already broadcast.\n return await ensureClient().revokeDevice(msg.deviceId, msg.nowMs);\n case \"removeDeviceEverywhere\":\n // Every group, DeviceGroup first, never stopping at a failure; resolves\n // to the report the host persists and retries from.\n return await ensureClient().removeDeviceEverywhere(msg.deviceId, msg.nowMs);\n case \"removeOwnDevicesExcept\":\n // The \"secure my account\" sweep: every other leaf of this account\n // except `keep` (by credential, or listed by the server); same report.\n return await ensureClient().removeOwnDevicesExcept(msg.keep, msg.listed, msg.nowMs);\n case \"addRestoredDevice\":\n // The tap of a kept device: the core believes the KeyPackage only for\n // a device of this account that restored with the root (ruling V123).\n await ensureClient().addRestoredDevice(msg.deviceId, msg.keyPackage, msg.nowMs);\n return null;\n case \"processEnvelope\": {\n const result = await ensureClient().processEnvelope(msg.envelope, msg.nowMs);\n postConversationEvent(\n msg.envelope.conversation_id, msg.envelope.epoch, undefined,\n readMeta(msg.envelope.conversation_id),\n );\n return result;\n }\n case \"pendingApplies\":\n // [D27] Journal listing — reading does not consume.\n return ensureClient().pendingApplies();\n case \"confirmApplied\":\n // [D27] Removes + checkpoints; unknown ids are ignored (idempotent).\n return await ensureClient().confirmApplied(msg.journalIds);\n case \"syncConversations\":\n // Reached only if a caller bypasses `onmessage`; the scheduler turns\n // this kind into a stepped pass before it can get here.\n return await ensureClient().syncConversations(msg.nowMs);\n case \"syncConversation\":\n return await ensureClient().syncConversation(msg.conv, msg.nowMs);\n // Sequenced log sync. The batch and page results carry their messages\n // (the wasm does not fan them out through `onMessage`); the main thread\n // delivers them from the result. Conversation updates are announced from\n // the core's exact `updated` list, before the result resolves.\n // Self-admission (ruling V273): every refusal is a value of the answer.\n case \"selfAdmit\":\n return ensureClient().selfAdmit(\n msg.conv, msg.fetched.blob, msg.fetched.wrap, msg.fetched.wrapCount, msg.fetched.currentEpoch, msg.nowMs,\n );\n case \"selfAdmitMany\":\n return ensureClient().selfAdmitMany(msg.first, msg.conversations, msg.nowMs);\n case \"clientRefreshStateBackup\":\n return ensureClient().refreshStateBackup(msg.accountId, msg.hostState, msg.nowMs);\n case \"processSequencedBatch\": {\n const raw = await ensureClient().processSequencedBatch(msg.items, msg.nowMs) as unknown as ApplyBatchResultWire;\n announceUpdated(raw.updated, welcomeSenders(msg.items, raw.joined), raw.removed);\n return raw;\n }\n case \"syncConversationStep\": {\n const raw = await ensureClient().syncConversationStep(msg.conv, msg.nowMs) as unknown as SyncStepResultWire;\n announceUpdated(raw.updated, undefined, raw.removed);\n return raw;\n }\n case \"logPositions\":\n return ensureClient().logPositions();\n case \"logPosition\":\n return ensureClient().logPosition(msg.conv);\n case \"adoptLogPosition\":\n return await ensureClient().adoptLogPosition(msg.conv, msg.epoch, msg.serverSeq);\n case \"logHoles\":\n return ensureClient().logHoles(msg.conv);\n case \"resolveLogHole\":\n return await ensureClient().resolveLogHole(msg.conv, msg.fromServerSeq, msg.toServerSeq);\n case \"conversationsBehind\":\n return ensureClient().conversationsBehind(msg.heads);\n case \"heldFrameCount\":\n return ensureClient().heldFrameCount();\n case \"joinConversationAt\": {\n const id = await ensureClient().joinConversationAt(msg.welcome, msg.position, msg.nowMs) as Uint8Array;\n postConversationEvent(id, 0, msg.welcome.sender_device, readMeta(id));\n return id;\n }\n case \"processWelcomeAt\": {\n const id = await ensureClient().processWelcomeAt(msg.welcome, msg.position, msg.nowMs) as Uint8Array | null;\n if (id !== null && id !== undefined) {\n postConversationEvent(id, 0, msg.welcome.sender_device, readMeta(id));\n return id;\n }\n return null;\n }\n case \"linkHandshakePayload\":\n return ensureClient().linkHandshakePayload(msg.hpkePublicKey, msg.keyPackage);\n case \"decodeCatchupSnapshot\":\n // Pure WASM — no client state required. The new device may call this in an\n // ephemeral worker before init() completes.\n return wasmDecodeCatchupSnapshot(msg.snapshotBytes);\n case \"exportConversationSecret\":\n // wasm-bindgen returns a Uint8Array sized to `length`. The bytes are a secret —\n // the main thread is responsible for clearing the typed array when done.\n return ensureClient().exportConversationSecret(\n msg.conv, msg.label, msg.context, msg.length,\n );\n case \"exportConversationSecretWithEpoch\":\n // `{ epoch, secret }` from ONE read inside the core: the epoch is the one\n // the secret was exported at. Passed through as it is, never rebuilt from\n // a second read. The secret is the main thread's to clear when done.\n return ensureClient().exportConversationSecretWithEpoch(\n msg.conv, msg.label, msg.context, msg.length,\n );\n // The link handshake commitment (2026-11-25): pure WASM, no client state.\n // Each call that acts on a handshake verifies it inside the call.\n case \"linkCommitment\":\n return wasmLinkCommitment(msg.payload);\n case \"normalizeLinkCode\":\n return wasmNormalizeLinkCode(msg.typed);\n case \"linkQrCommitment\":\n return wasmLinkQrCommitment(msg.qrText);\n case \"verifyLinkHandshake\":\n return wasmVerifyLinkHandshake(msg.payload, msg.expectedCode, msg.expectedQr);\n case \"sealLinkAuthFor\":\n return wasmSealLinkAuthFor(msg.plaintext, msg.payload, msg.expectedCode, msg.expectedQr);\n case \"hpkeSeal\":\n // Generic HPKE seal for app-layer envelopes (e.g. linking auth envelope).\n return wasmHpkeSeal(msg.plaintext, msg.recipientPub, msg.info);\n case \"hpkeOpen\":\n return wasmHpkeOpen(msg.sealed, msg.recipientPriv, msg.info);\n case \"hpkeSealRaw\":\n // The RFC 9180 canonical layout (`enc || ct`), which the app layers use.\n return wasmHpkeSealRaw(msg.plaintext, msg.recipientPub, msg.info);\n case \"hpkeOpenRaw\":\n return wasmHpkeOpenRaw(msg.sealed, msg.recipientPriv, msg.info);\n case \"hpkeGenerateKeypair\":\n return wasmHpkeGenerateKeypair();\n // Post-quantum (X-Wing) twins: all pure WASM, no client state required.\n case \"hpkeSealPq\":\n return wasmHpkeSealPq(msg.plaintext, msg.recipientPub, msg.info);\n case \"hpkeOpenPq\":\n return wasmHpkeOpenPq(msg.sealed, msg.recipientPriv, msg.info);\n case \"hpkeSealRawPq\":\n return wasmHpkeSealRawPq(msg.plaintext, msg.recipientPub, msg.info);\n case \"hpkeOpenRawPq\":\n return wasmHpkeOpenRawPq(msg.sealed, msg.recipientPriv, msg.info);\n case \"hpkeGenerateKeypairPq\":\n return wasmHpkeGenerateKeypairPq();\n case \"hpkePublicKeyFromSeed\":\n return wasmHpkePublicKeyFromSeed(msg.seed);\n case \"deviceGroupIdFor\":\n // Pure: the core's DeviceGroup id derivation for an MLS user id.\n return wasmDeviceGroupIdFor(msg.userId);\n case \"hpkePublicKeyFromPrivate\":\n return wasmHpkePublicKeyFromPrivate(msg.privateKey);\n case \"signDeviceReauth\":\n // Pure WASM: the SDK builds the signed bytes, so this signs nothing else\n // with the device key. Returns `deviceId (32) || signature (64)`.\n return wasmSignDeviceReauth(msg.deviceSigningSecretKey, msg.challengeId, msg.nonce, msg.accountId, msg.audience);\n case \"signDeviceLinkApprovalFor\":\n // Pure WASM, link verification v2: the handshake is verified inside the\n // call, then the SDK builds the signed bytes and derives both ids. Returns\n // `approverDeviceId (32) || newDeviceId (32) || signature (64)`.\n return wasmSignDeviceLinkApprovalFor(msg.deviceSigningSecretKey, msg.approvalSessionId, msg.accountId, msg.payload, msg.expectedCode, msg.expectedQr, msg.audience);\n case \"signDeviceLinkPossession\":\n // Pure WASM. Returns `deviceId (32) || signature (64)`.\n return wasmSignDeviceLinkPossession(msg.deviceSigningSecretKey, msg.approvalSessionId, msg.accountId, msg.audience);\n case \"exportConversationStateSnapshot\":\n // [CR-7] state snapshot bytes are a secret (past epoch keys); the main thread\n // is responsible for clearing the typed array when done.\n return ensureClient().exportConversationStateSnapshot(msg.conv, msg.nowMs);\n case \"importStateSnapshot\":\n // [CR-7] returns the imported conversation id as a Uint8Array.\n return await ensureClient().importStateSnapshot(msg.snapshotBytes, msg.nowMs);\n // Recovery — all pure WASM; no client state required.\n case \"generateMnemonicPhrase\":\n return wasmGenerateMnemonicPhrase();\n case \"selfAdmissionCompiled\":\n return wasmSelfAdmissionCompiled();\n case \"normalizeMnemonicPhrase\":\n return wasmNormalizeMnemonicPhrase(msg.phrase);\n case \"checkBackupPhrase\":\n // `{ outcome, reason? }`, the wasm's own codes, passed on untouched.\n return wasmCheckBackupPhrase(msg.blob, msg.mnemonicPhrase);\n // History, version 3 (rulings V88 to V92). The raw-key, seed-signed seals\n // and opens are gone: every call below runs in the client, which verifies\n // the recipient in its own tree (or the link handshake against what this\n // device was shown) before anything is signed or sealed.\n case \"historyDeliveryKeyNextCounter\":\n return await ensureClient().historyDeliveryKeyNextCounter(msg.counterFloor);\n case \"publishHistoryDeliveryKey\":\n return await ensureClient().publishHistoryDeliveryKey(msg.counterFloor);\n case \"adoptHistoryDeliveryKeyCounter\":\n return await ensureClient().adoptHistoryDeliveryKeyCounter(msg.stored);\n case \"sealHistoryBundleV3\":\n return await ensureClient().sealHistoryBundleV3(msg.bundle, msg.recipient, msg.ownAccount);\n case \"sealLinkHistoryBundle\":\n return ensureClient().sealLinkHistoryBundle(\n msg.bundle, msg.payload, msg.expectedCode, msg.expectedQr,\n );\n case \"openHistoryBundleV3\":\n return await ensureClient().openHistoryBundleV3(msg.sealed, msg.ownAccount);\n case \"openLinkHistoryBundle\":\n return await ensureClient().openLinkHistoryBundle(msg.sealed, msg.recipientPriv);\n case \"confirmHistoryImport\":\n return await ensureClient().confirmHistoryImport(msg.importId);\n case \"historyTrust\":\n return await ensureClient().historyTrust(msg.deviceId);\n case \"recordHistoryShipped\":\n await ensureClient().recordHistoryShipped(msg.deviceId);\n return null;\n case \"historyShipDecision\":\n return await ensureClient().historyShipDecision(msg.deviceId);\n default:\n throw new Error(`unknown request kind: ${(msg as { kind: string }).kind}`);\n }\n}\n\nfunction ensureClient(): PingClient {\n if (!client) throw new Error(\"client not initialised\");\n return client;\n}\n","// The pending root's store on web (the account identity contract, section\n// 3.3, rule R34 b; rulings ID38 to ID40 and ID45).\n//\n// On the ONE browser that set an account up and has not made its first\n// backup yet, the account root rests here until that backup is proven. This\n// module is the web row of the contract's table, and nothing else:\n//\n// * the root seed is wrapped with AES-256-GCM by the browser's own\n// WebCrypto, under a key generated NON-EXTRACTABLE with the usages\n// encrypt and decrypt only;\n// * a fresh random 96-bit nonce for every write (and a fresh key: an item\n// is written once per slot, so no key ever seals twice);\n// * a write is CREATE-IF-ABSENT AND ATOMIC (ruling V114): the item is\n// ADDED inside one readwrite transaction, which the browser refuses for\n// a slot that holds a row. Of two tabs that race for an empty slot one\n// is accepted; the other is told `PendingRootExists` and nothing it\n// made is kept. No write ever replaces a pending root;\n// * the associated data is the ASCII label `ping/pending-root-wrap/v1`\n// followed by the account's user id (SHA-256 of the root public key), so\n// an item moved under another account's public key does not open;\n// * the key, as a key object, and the ciphertext rest together in ONE\n// IndexedDB database per account slot, so two accounts in one origin\n// never share a store, and deleting the item deletes both;\n// * the browser's answer to the persistent-storage request, which the host\n// asked for before the write, is recorded beside the item (not secret).\n//\n// WHERE IT RUNS. Inside the SDK's own dedicated Worker of the open tab, and\n// only there: the wasm account calls are handed an instance by the Worker.\n// It refuses to run in a service worker. The root is never in the main\n// realm and never in app code's hands: the only caller of `write` and `read`\n// is the wasm module, which zero-fills the bytes that crossed.\n//\n// WHAT THIS DOES NOT GIVE (the contract says so to the owner): every realm\n// of the origin can open the database, and whoever runs script in the\n// origin can ask the browser to unwrap with the key object. The key cannot\n// be exported; it can be used.\n//\n// This is the browser's AES-256-GCM, a second implementation of a mode the\n// SDK otherwise runs only in Rust. No new primitive.\n\n/** The domain label of the wrap's associated data (ruling ID45). */\nexport const PENDING_ROOT_WRAP_LABEL = \"ping/pending-root-wrap/v1\";\n\nconst DB_PREFIX = \"ping-pending-root:\";\nconst STORE = \"item\";\nconst ITEM_KEY = \"pending\";\nconst SEED_LEN = 32;\nconst PUBLIC_KEY_LEN = 32;\nconst NONCE_LEN = 12;\nconst TAG_BITS = 128;\nconst WRAPPED_LEN = SEED_LEN + TAG_BITS / 8;\n\n/** What one slot's database holds: one row. */\ninterface StoredItem {\n v: 1;\n key: CryptoKey;\n iv: Uint8Array;\n ciphertext: Uint8Array;\n rootPublicKey: Uint8Array;\n persistentStorage: boolean | null;\n}\n\n/** The store cannot run in this realm (no WebCrypto, no IndexedDB, or a service worker). */\nexport class PendingStoreUnavailableError extends Error {\n constructor() {\n super(\"the pending store is not available in this realm\");\n this.name = \"PendingStoreUnavailable\";\n }\n}\n\n/** `write` found an item in the slot and wrote NOTHING (ruling V114). */\nexport class PendingRootExistsError extends Error {\n constructor() {\n super(\"the slot already holds a pending item\");\n this.name = \"PendingRootExists\";\n }\n}\n\n/** The database of one account slot. */\nexport function pendingRootDatabaseName(slot: string): string {\n return DB_PREFIX + slot;\n}\n\nfunction inServiceWorker(): boolean {\n const scope = (globalThis as { ServiceWorkerGlobalScope?: unknown }).ServiceWorkerGlobalScope;\n return typeof scope === \"function\" && globalThis instanceof (scope as new () => object);\n}\n\nfunction realm(): { idb: IDBFactory; subtle: SubtleCrypto } {\n const idb = (globalThis as { indexedDB?: IDBFactory }).indexedDB;\n const subtle = globalThis.crypto?.subtle;\n if (inServiceWorker() || !idb || !subtle) {\n throw new PendingStoreUnavailableError();\n }\n return { idb, subtle };\n}\n\nfunction request<T>(req: IDBRequest<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error ?? new Error(\"IndexedDB request failed\"));\n });\n}\n\nfunction open(idb: IDBFactory, slot: string): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const req = idb.open(pendingRootDatabaseName(slot), 1);\n req.onupgradeneeded = () => {\n if (!req.result.objectStoreNames.contains(STORE)) {\n req.result.createObjectStore(STORE);\n }\n };\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error ?? new Error(\"IndexedDB open failed\"));\n req.onblocked = () => reject(new Error(\"IndexedDB open blocked\"));\n });\n}\n\nfunction done(tx: IDBTransaction): Promise<void> {\n return new Promise((resolve, reject) => {\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error ?? new Error(\"IndexedDB transaction failed\"));\n tx.onabort = () => reject(tx.error ?? new Error(\"IndexedDB transaction aborted\"));\n });\n}\n\n/** WebCrypto's typings want a `BufferSource`; a `Uint8Array` is one. */\nfunction source(bytes: Uint8Array): BufferSource {\n return bytes as unknown as BufferSource;\n}\n\nfunction isBytes(value: unknown, length: number): value is Uint8Array {\n return value instanceof Uint8Array && value.length === length;\n}\n\n/** A row is an item only when every part of it is there and of its exact shape. */\nfunction asItem(row: unknown): StoredItem | null {\n if (typeof row !== \"object\" || row === null) return null;\n const item = row as Partial<StoredItem>;\n const key = item.key as CryptoKey | undefined;\n if (item.v !== 1 || !key || typeof key !== \"object\") return null;\n if (key.type !== \"secret\" || key.extractable !== false) return null;\n if ((key.algorithm as AesKeyAlgorithm).name !== \"AES-GCM\" || (key.algorithm as AesKeyAlgorithm).length !== 256) {\n return null;\n }\n if (!isBytes(item.iv, NONCE_LEN) || !isBytes(item.ciphertext, WRAPPED_LEN)) return null;\n if (!isBytes(item.rootPublicKey, PUBLIC_KEY_LEN)) return null;\n return item as StoredItem;\n}\n\nasync function associatedData(subtle: SubtleCrypto, rootPublicKey: Uint8Array): Promise<Uint8Array> {\n const label = new TextEncoder().encode(PENDING_ROOT_WRAP_LABEL);\n const userId = new Uint8Array(await subtle.digest(\"SHA-256\", source(rootPublicKey)));\n const out = new Uint8Array(label.length + userId.length);\n out.set(label, 0);\n out.set(userId, label.length);\n return out;\n}\n\nasync function load(idb: IDBFactory, slot: string): Promise<StoredItem | null> {\n // Opening a database creates it: ask first, so that a status question\n // never leaves an empty database behind for a slot that has no item.\n if (typeof idb.databases === \"function\") {\n const names = (await idb.databases()).map((info) => info.name);\n if (!names.includes(pendingRootDatabaseName(slot))) return null;\n }\n const db = await open(idb, slot);\n try {\n const tx = db.transaction(STORE, \"readonly\");\n const row = await request(tx.objectStore(STORE).get(ITEM_KEY));\n return asItem(row);\n } finally {\n db.close();\n }\n}\n\n/**\n * The pending store of the JS SDK. One item per account slot. The wasm\n * account calls take an instance (`JsPendingRootStore`); nothing else calls\n * `write` or `read`.\n */\nexport class PendingRootStore {\n /**\n * Wrap `seed` and keep it for `slot`, with the root public key and the\n * browser's answer to the persistent-storage request beside it. `seed` is\n * zero-filled before this resolves or rejects.\n *\n * Create-if-absent and atomic: a slot that holds a row (an item, or a row\n * that is not one) rejects with `PendingRootExistsError` and is unchanged.\n */\n async write(\n slot: string,\n seed: Uint8Array,\n rootPublicKey: Uint8Array,\n persistentStorage?: boolean,\n ): Promise<void> {\n const { idb, subtle } = realm();\n try {\n if (!isBytes(seed, SEED_LEN) || !isBytes(rootPublicKey, PUBLIC_KEY_LEN)) {\n throw new Error(\"pending root: wrong length\");\n }\n const key = await subtle.generateKey({ name: \"AES-GCM\", length: 256 }, false, [\"encrypt\", \"decrypt\"]);\n const iv = globalThis.crypto.getRandomValues(new Uint8Array(NONCE_LEN));\n const publicKey = new Uint8Array(rootPublicKey);\n const additionalData = await associatedData(subtle, publicKey);\n const ciphertext = new Uint8Array(\n await subtle.encrypt(\n { name: \"AES-GCM\", iv: source(iv), additionalData: source(additionalData), tagLength: TAG_BITS },\n key,\n source(seed),\n ),\n );\n const item: StoredItem = {\n v: 1,\n key,\n iv,\n ciphertext,\n rootPublicKey: publicKey,\n persistentStorage: persistentStorage ?? null,\n };\n const db = await open(idb, slot);\n try {\n const tx = db.transaction(STORE, \"readwrite\");\n // `add`, never `put`: the browser refuses a key that exists, inside\n // the transaction, whichever tab asks.\n const added = tx.objectStore(STORE).add(item, ITEM_KEY);\n try {\n await done(tx);\n } catch (failed) {\n if (added.error?.name === \"ConstraintError\") throw new PendingRootExistsError();\n throw failed;\n }\n } finally {\n db.close();\n }\n } finally {\n seed.fill(0);\n }\n }\n\n /** The root public key beside the item of `slot`, or `null`. No unwrap. */\n async publicKey(slot: string): Promise<Uint8Array | null> {\n const { idb } = realm();\n const item = await load(idb, slot);\n return item ? new Uint8Array(item.rootPublicKey) : null;\n }\n\n /**\n * The seed of `slot`, unwrapped, or `null` when the slot holds no item\n * or holds one that does not open with its own key object (a browser has\n * no lock that could make that a passing state: such an item is gone).\n * The caller zero-fills what it is given.\n */\n async read(slot: string): Promise<Uint8Array | null> {\n const { idb, subtle } = realm();\n const item = await load(idb, slot);\n if (!item) return null;\n const additionalData = await associatedData(subtle, item.rootPublicKey);\n try {\n const seed = await subtle.decrypt(\n { name: \"AES-GCM\", iv: source(item.iv), additionalData: source(additionalData), tagLength: TAG_BITS },\n item.key,\n source(item.ciphertext),\n );\n return new Uint8Array(seed);\n } catch {\n return null;\n }\n }\n\n /** Delete the item of `slot`: the ciphertext and the key object, and their database. */\n async del(slot: string): Promise<void> {\n const { idb } = realm();\n await new Promise<void>((resolve, reject) => {\n const req = idb.deleteDatabase(pendingRootDatabaseName(slot));\n req.onsuccess = () => resolve();\n req.onerror = () => reject(req.error ?? new Error(\"IndexedDB delete failed\"));\n req.onblocked = () => reject(new Error(\"IndexedDB delete blocked\"));\n });\n }\n\n /** The browser's answer to the persistent-storage request recorded beside the item, or `null`. */\n async persistentStorage(slot: string): Promise<boolean | null> {\n const { idb } = realm();\n const item = await load(idb, slot);\n return item ? item.persistentStorage : null;\n }\n}\n","// Which conversations' MLS epochs moved, and therefore which `event.conversation`\n// notifications the worker owes the main thread.\n//\n// This lives outside `worker.ts` purely so it is testable: importing the worker\n// module runs its top-level `self.onmessage` wiring, which needs a\n// `DedicatedWorkerGlobalScope`. The rule it encodes is small but load-bearing —\n// see `EPOCH_ADVANCING_REQUESTS` in the worker for why a self-authored or\n// catch-up-applied commit would otherwise be announced to nobody.\n\n/** The two fields of a `ConversationMeta` this comparison needs. */\nexport interface ConversationEpoch {\n id: Uint8Array;\n epoch: number;\n}\n\n/** Stable map key for a 16-byte conversation id. */\nexport function conversationKey(id: Uint8Array): string {\n let out = \"\";\n for (let i = 0; i < id.length; i += 1) out += (id[i] ?? 0).toString(16).padStart(2, \"0\");\n return out;\n}\n\n/** Epoch per conversation, keyed by `conversationKey`. */\nexport function epochMap(metas: readonly ConversationEpoch[]): Map<string, number> {\n const out = new Map<string, number>();\n for (const meta of metas) out.set(conversationKey(meta.id), meta.epoch);\n return out;\n}\n\n/**\n * Conversations whose epoch STRICTLY advanced between `before` and `after`.\n *\n * Only conversations present in both are considered:\n * - a conversation that is new since `before` was either just created by this\n * caller or just joined, and `joinConversation` already announces the\n * latter — announcing it here would double-fire;\n * - a conversation that has disappeared (left / dropped) has no epoch to\n * report;\n * - an epoch that did not move is not an event, however many times the\n * request that ran touched the group.\n *\n * The elements returned are the elements of `after` themselves, so a caller\n * that listed whole metadata records gets them back whole.\n */\nexport function advancedEpochs<T extends ConversationEpoch>(\n before: ReadonlyMap<string, number>,\n after: readonly T[],\n): T[] {\n const out: T[] = [];\n for (const meta of after) {\n const previous = before.get(conversationKey(meta.id));\n if (previous === undefined || meta.epoch <= previous) continue;\n out.push(meta);\n }\n return out;\n}\n\n/** The id a `conversationKey` was made from. */\nexport function conversationIdOf(key: string): Uint8Array {\n const out = new Uint8Array(key.length >> 1);\n for (let i = 0; i < out.length; i += 1) out[i] = Number.parseInt(key.slice(i * 2, i * 2 + 2), 16);\n return out;\n}\n\n/**\n * The conversations a request brought in or took away, which\n * {@link advancedEpochs} deliberately does not report.\n *\n * They are not host events (whoever joined or left already said so, or it is\n * not an epoch change at all), but the main thread's copy of a conversation's\n * metadata must still follow them: a conversation that `appeared` is held\n * now, one that `disappeared` is not, and a copy that kept answering for it\n * would be answering for a group this device no longer reads.\n */\nexport function changedHoldings<T extends ConversationEpoch>(\n before: ReadonlyMap<string, number>,\n after: readonly T[],\n): { appeared: T[]; disappeared: Uint8Array[] } {\n const appeared: T[] = [];\n const still = new Set<string>();\n for (const meta of after) {\n const key = conversationKey(meta.id);\n still.add(key);\n if (!before.has(key)) appeared.push(meta);\n }\n const disappeared: Uint8Array[] = [];\n for (const key of before.keys()) {\n if (!still.has(key)) disappeared.push(conversationIdOf(key));\n }\n return { appeared, disappeared };\n}\n","// The whole-account catch-up as a stepped job: one PAGE of one conversation\n// per scheduler turn.\n//\n// `syncConversations()` used to page each conversation to its end inside one\n// wasm call; a 2,000-message group backlog was eight pages behind which\n// every queued send waited. Each call of the returned step now applies ONE\n// page through `syncConversationStep` and yields, so the primary lane (a\n// send, a live batch, a host's own step) runs between pages as well as\n// between conversations. A conversation whose page was full stays at the\n// head of the queue and continues next turn.\n//\n// When the transport can report the server's log heads, only the\n// conversations `conversationsBehind` names are stepped: one request instead\n// of one page per conversation the account holds. A transport without\n// `fetchLogHeads` (or one that answers `null`: the relay has no heads route)\n// gets the whole-account walk, as before. A heads request that FAILS ends\n// the pass with that error instead: walking every conversation on a network\n// that just failed one request would fail N more times, and the host retries\n// the pass on its next trigger (reconnect, foreground, heartbeat), by which\n// time the socket's `resume_ack` has usually named what is behind anyway.\n//\n// The pass ends with one re-list so a conversation joined while it ran is\n// still covered, exactly as the core re-reads its map. Conversations already\n// evaluated (stepped, or present in the heads snapshot) are not re-stepped.\n//\n// Lives outside `worker.ts` so it is testable without a\n// `DedicatedWorkerGlobalScope`; the worker supplies the dependencies.\n\nimport { conversationKey } from \"./epoch-events\";\nimport type { LogHeadWire, SyncStepResultWire } from \"./sequenced\";\nimport type { IncomingMessage } from \"./types\";\n\nexport interface CatchUpPassDeps {\n /** Ids of every conversation the client holds right now. */\n listConversationIds(): Uint8Array[];\n /** The server's heads, or `null` when the transport cannot report them. */\n fetchHeads(): Promise<LogHeadWire[] | null>;\n /** The core's verdict on which of `heads` this device is behind on. */\n conversationsBehind(heads: LogHeadWire[]): Uint8Array[];\n /** Apply ONE page of one conversation. */\n step(id: Uint8Array): Promise<SyncStepResultWire>;\n /** Deliver a page: its conversation updates and its messages. */\n onPage(result: SyncStepResultWire): void;\n /** Post the pass result: every message in apply order, or the error. */\n finish(ok: boolean, value: IncomingMessage[] | unknown): void;\n}\n\n/**\n * Build the stepped job. Each call runs one step and resolves `true` while\n * the pass has more to do; it never rejects (errors are posted through\n * `finish`).\n */\nexport function catchUpPass(deps: CatchUpPassDeps): () => Promise<boolean> {\n const seen = new Set<string>();\n const delivered: IncomingMessage[] = [];\n let pending: Uint8Array[] | null = null;\n let relisted = false;\n\n const sortedUnseen = (ids: Uint8Array[]): Uint8Array[] =>\n ids\n .filter((id) => !seen.has(conversationKey(id)))\n .sort((a, b) => (conversationKey(a) < conversationKey(b) ? -1 : 1));\n\n const initial = async (): Promise<Uint8Array[]> => {\n // A rejection propagates to the caller, which posts it through `finish`.\n const heads = await deps.fetchHeads();\n if (heads === null) return sortedUnseen(deps.listConversationIds());\n // Every conversation the heads describe has been evaluated: the ones\n // that are current are not stepped now and not re-stepped by the re-list.\n for (const h of heads) seen.add(conversationKey(h.conversation_id));\n const behind = deps.conversationsBehind(heads);\n for (const id of behind) seen.delete(conversationKey(id));\n return sortedUnseen(behind);\n };\n\n return async (): Promise<boolean> => {\n try {\n if (pending === null) pending = await initial();\n if (pending.length === 0 && !relisted) {\n relisted = true;\n pending = sortedUnseen(deps.listConversationIds());\n }\n } catch (e) {\n deps.finish(false, e);\n return false;\n }\n const id = pending[0];\n if (id === undefined) {\n deps.finish(true, delivered);\n return false;\n }\n let more = false;\n try {\n const page = await deps.step(id);\n for (const m of page.messages) delivered.push(m);\n deps.onPage(page);\n more = page.has_more;\n } catch {\n // Dropped between the listing and this step (a wipe, a self-removal),\n // a transport failure, or a checkpoint failure: this conversation's\n // paging ends for this pass. The durable cursor is where the next\n // pass resumes, which is what the whole-account request did too.\n }\n if (!more) {\n seen.add(conversationKey(id));\n pending.shift();\n }\n return true;\n };\n}\n","// Request scheduling for the WASM worker: one call in flight at a time, in\n// two lanes.\n//\n// The worker may run only ONE WASM call at a time (see `worker.ts`), so every\n// request waits for the one before it. That is fine for the requests a user\n// is waiting on (a send, a live frame) — they are short. It was not fine for a\n// whole-account catch-up, which paged every conversation inside a single\n// request: a `send` posted while it ran started after all of them, and on a\n// tab returning from an idle hour that wait WAS the first message's latency.\n//\n// This scheduler keeps the one-call invariant and adds a second lane for\n// work that is allowed to be interrupted between its natural steps. An\n// ordinary request runs FIFO in the primary lane; a stepped job runs one\n// step per turn and only when the primary lane is empty, so anything queued\n// while a step ran goes next. Stepped jobs are FIFO among themselves and a\n// job's steps never interleave with another job's.\n//\n// Lives outside `worker.ts` so it is testable without a\n// `DedicatedWorkerGlobalScope` (the same reason `epoch-events.ts` exists).\n\n/** An ordinary request: runs to completion in one turn. Must not reject. */\nexport type LaneJob = () => Promise<void>;\n\n/**\n * A stepped job: each call runs ONE step and resolves `true` while more steps\n * remain. A rejected step ends the job (the scheduler treats it as `false`).\n */\nexport type SteppedJob = () => Promise<boolean>;\n\nexport class RequestScheduler {\n private readonly primary: LaneJob[] = [];\n private readonly stepped: SteppedJob[] = [];\n private pumping = false;\n\n /** Queue an ordinary request behind the ordinary requests before it. */\n enqueue(job: LaneJob): void {\n this.primary.push(job);\n void this.pump();\n }\n\n /** Queue a stepped job; its steps run whenever the primary lane is empty. */\n enqueueStepped(job: SteppedJob): void {\n this.stepped.push(job);\n void this.pump();\n }\n\n /** Requests waiting in the primary lane (diagnostics / tests). */\n get pendingPrimary(): number {\n return this.primary.length;\n }\n\n /** Stepped jobs not yet finished (diagnostics / tests). */\n get pendingStepped(): number {\n return this.stepped.length;\n }\n\n private async pump(): Promise<void> {\n if (this.pumping) return;\n this.pumping = true;\n try {\n for (;;) {\n const job = this.primary.shift();\n if (job !== undefined) {\n // A job posts its own error as a result; a rejection here would\n // only mean a bug in the job, and it must not stall the lane.\n await job().catch(() => undefined);\n continue;\n }\n const step = this.stepped[0];\n if (step === undefined) return;\n let more = false;\n try {\n more = await step();\n } catch {\n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AAsB,IAAI,MAAM,IAAI,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA,IAK3D,KAAK;AACH,aAAO,MAAM,aAAa,EAAE,8BAA8B,IAAI,YAAY;AAAA,IAC5E,KAAK;AACH,aAAO,MAAM,aAAa,EAAE,0BAA0B,IAAI,YAAY;AAAA,IACxE,KAAK;AACH,aAAO,MAAM,aAAa,EAAE,+BAA+B,IAAI,MAAM;AAAA,IACvE,KAAK;AACH,aAAO,MAAM,aAAa,EAAE,oBAAoB,IAAI,QAAQ,IAAI,WAAW,IAAI,UAAU;AAAA,IAC3F,KAAK;AACH,aAAO,aAAa,EAAE;AAAA,QACpB,IAAI;AAAA,QAAQ,IAAI;AAAA,QAAS,IAAI;AAAA,QAAc,IAAI;AAAA,MACjD;AAAA,IACF,KAAK;AACH,aAAO,MAAM,aAAa,EAAE,oBAAoB,IAAI,QAAQ,IAAI,UAAU;AAAA,IAC5E,KAAK;AACH,aAAO,MAAM,aAAa,EAAE,sBAAsB,IAAI,QAAQ,IAAI,aAAa;AAAA,IACjF,KAAK;AACH,aAAO,MAAM,aAAa,EAAE,qBAAqB,IAAI,QAAQ;AAAA,IAC/D,KAAK;AACH,aAAO,MAAM,aAAa,EAAE,aAAa,IAAI,QAAQ;AAAA,IACvD,KAAK;AACH,YAAM,aAAa,EAAE,qBAAqB,IAAI,QAAQ;AACtD,aAAO;AAAA,IACT,KAAK;AACH,aAAO,MAAM,aAAa,EAAE,oBAAoB,IAAI,QAAQ;AAAA,IAC9D;AACE,YAAM,IAAI,MAAM,yBAA0B,IAAyB,IAAI,EAAE;AAAA,EAC7E;AACF;AAEA,SAAS,eAA2B;AAClC,MAAI,CAAC,OAAQ,OAAM,IAAI,MAAM,wBAAwB;AACrD,SAAO;AACT;","names":["init","done","wasmBeginDeviceLink","wasmSealLinkingTicketV3For","wasmOpenLinkingTicketV3","wasmCreateAccount","wasmPendingStatus","wasmMakeBackup","wasmProveBackup","wasmEndPending","wasmOpenBackupForRestore","wasmRestoreTakeOver","wasmTakeAccountBack","wasmResumeRotation","wasmResumeRotationAt","wasmCompleteRotation","wasmSetRotationPhase","wasmFinishRotation","wasmAbandonRotation","wasmRotationRecordState","wasmRestoreJoin","wasmOpenStateBackup","wasmRefreshStateBackup","wasmBeginAccountSetupInMemory","wasmDecodeCatchupSnapshot","wasmLinkCommitment","wasmNormalizeLinkCode","wasmLinkQrCommitment","wasmVerifyLinkHandshake","wasmSealLinkAuthFor","wasmHpkeSeal","wasmHpkeOpen","wasmHpkeSealRaw","wasmHpkeOpenRaw","wasmHpkeGenerateKeypair","wasmHpkeSealPq","wasmHpkeOpenPq","wasmHpkeSealRawPq","wasmHpkeOpenRawPq","wasmHpkeGenerateKeypairPq","wasmHpkePublicKeyFromSeed","wasmDeviceGroupIdFor","wasmHpkePublicKeyFromPrivate","wasmSignDeviceReauth","wasmSignDeviceLinkApprovalFor","wasmSignDeviceLinkPossession","wasmGenerateMnemonicPhrase","wasmSelfAdmissionCompiled","wasmNormalizeMnemonicPhrase","wasmCheckBackupPhrase"]}