@ping-app/ping-openmls-sdk 0.10.0 → 0.10.2

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.
@@ -30,6 +30,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/notification-preview.ts
31
31
  var notification_preview_exports = {};
32
32
  __export(notification_preview_exports, {
33
+ MAX_PREVIEW_PREREQUISITES: () => MAX_PREVIEW_PREREQUISITES,
34
+ assertPrerequisiteCount: () => assertPrerequisiteCount,
33
35
  openNotificationPreview: () => openNotificationPreview,
34
36
  readOnlyStorage: () => readOnlyStorage,
35
37
  scopeStorage: () => scopeStorage
@@ -73,6 +75,7 @@ function reserveLinearMemory(memory) {
73
75
  }
74
76
 
75
77
  // src/notification-preview.ts
78
+ var MAX_PREVIEW_PREREQUISITES = 64;
76
79
  async function openNotificationPreview(opts) {
77
80
  const now = opts.now ?? (() => Date.now());
78
81
  const scoped = opts.accountNamespace !== void 0 && opts.accountNamespace.length > 0 ? scopeStorage(opts.storage, opts.accountNamespace) : opts.storage;
@@ -97,6 +100,16 @@ async function openNotificationPreview(opts) {
97
100
  const result = client.previewEnvelope(envelope, now());
98
101
  return result ?? null;
99
102
  },
103
+ async previewEnvelopeWithPrerequisites(prerequisites, envelope) {
104
+ if (closed) throw new Error("notification-preview session is closed");
105
+ assertPrerequisiteCount(prerequisites);
106
+ const result = client.previewEnvelopeWithPrerequisites(
107
+ prerequisites,
108
+ envelope,
109
+ now()
110
+ );
111
+ return result ?? null;
112
+ },
100
113
  close() {
101
114
  if (closed) return;
102
115
  closed = true;
@@ -104,6 +117,16 @@ async function openNotificationPreview(opts) {
104
117
  }
105
118
  };
106
119
  }
120
+ function assertPrerequisiteCount(prerequisites) {
121
+ if (!Array.isArray(prerequisites)) {
122
+ throw new Error("notification-preview prerequisites must be an array");
123
+ }
124
+ if (prerequisites.length > MAX_PREVIEW_PREREQUISITES) {
125
+ throw new Error(
126
+ `notification-preview takes at most ${MAX_PREVIEW_PREREQUISITES} prerequisite envelopes`
127
+ );
128
+ }
129
+ }
107
130
  function readOnlyStorage(storage) {
108
131
  const refuse = (op) => Promise.reject(
109
132
  new Error(`notification-preview storage is read-only (attempted ${op})`)
@@ -130,6 +153,8 @@ function silentTransport() {
130
153
  }
131
154
  // Annotate the CommonJS export names for ESM import in node:
132
155
  0 && (module.exports = {
156
+ MAX_PREVIEW_PREREQUISITES,
157
+ assertPrerequisiteCount,
133
158
  openNotificationPreview,
134
159
  readOnlyStorage,
135
160
  scopeStorage
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/notification-preview.ts","../src/storage/scope.ts","../src/wasm-memory.ts"],"sourcesContent":["// [CR-5] Read-only notification preview for the web Service Worker.\n//\n// The web mirror of the iOS Notification Service Extension: a second JS realm\n// (the push-handling Service Worker, woken while the tab may be closed OR open\n// and writing) that must turn one push-delivered envelope into a sender and a\n// body preview, and change NOTHING.\n//\n// This module deliberately does NOT go through the SDK's usual Worker bridge:\n// a Service Worker cannot spawn a dedicated `Worker` on every browser, and a\n// preview needs one decrypt, not a message pipeline. The WASM module is loaded\n// INLINE in the calling realm (no DOM APIs are touched), wrapping the core's\n// `MessagingClient::open_read_only` + `preview_envelope` — the same read-only\n// seam the iOS NSE uses, with the same semantics:\n//\n// * the SDK storage is opened READ-ONLY: the MLS snapshot is copied into\n// memory at open and never written back, so the tab remains the single\n// writer and cannot be disturbed (two writers on the whole-state blob\n// REPLACE each other — see `StorageBackend::AsyncBlobReadOnly`);\n// * the ratchet advance from the preview decrypt is thrown away; the tab\n// decrypts the same message again later, independently. Nothing is\n// consumed that the tab needs, and nothing this session does is\n// observable by the tab;\n// * handshake traffic (Commit/Welcome/Proposal), unknown conversations, and\n// replays the hydrated cursor rejects all resolve to `null` — show the\n// generic banner, it is a normal answer;\n// * a message the tab ALREADY consumed and checkpointed cannot be decrypted\n// from the newer snapshot (its generation is burned): `previewEnvelope`\n// rejects. Treat ANY rejection as \"no preview\" (generic banner), never as\n// fatal.\n//\n// Concurrent-open safety: IndexedDB reads never block the tab's writes and the\n// session takes a point-in-time copy of the `__mls snapshot` blob at open, so\n// opening while a tab is live is safe by construction. The copy can be STALE\n// relative to the tab, which only widens the `null`/reject cases above. Open a\n// fresh session per push event (or per small batch) rather than caching one —\n// a fresh open sees the newest checkpoint.\n//\n// See docs/NOTIFICATION_PREVIEW_WEB.md for the full Service Worker guide\n// (wasm init in module vs classic workers, account-slot storage, ping-prime\n// wiring).\n\nimport { scopeStorage } from \"./storage/scope\";\nimport type { IncomingMessage, MessageEnvelope, Storage } from \"./types\";\nimport { reserveLinearMemory } from \"./wasm-memory\";\n\nexport interface NotificationPreviewOptions {\n /**\n * The account identity export (CBOR-wrapped Ed25519 seed, SECRET) — the\n * same bytes the tab passes to `MessagingClient.init`. The Service Worker\n * host must read it from wherever the tab keeps it (e.g. the encrypted IDB\n * slot); it never crosses the network.\n */\n identityExport: Uint8Array;\n /**\n * The SAME `Storage` implementation (and underlying IndexedDB database)\n * the tab's `MessagingClient` persists to. It is wrapped read-only here:\n * `put`/`del` reject, so a host bug cannot make the Service Worker a\n * second writer.\n */\n storage: Storage;\n /**\n * The tab's `ClientConfig.accountNamespace` for this account slot, when it\n * uses one. MUST match exactly — the preview scopes every namespace with\n * the same `\"${accountNamespace} \"` prefix rule as `MessagingClient`, and a\n * mismatch reads an empty store (open rejects with \"no checkpoint\").\n */\n accountNamespace?: string;\n /**\n * Where to load `ping_wasm_bg.wasm` from, passed through to the\n * wasm-bindgen `init`. Defaults to the URL baked next to the module —\n * correct when the bundler ships the `wasm/` directory alongside. Classic\n * (importScripts) Service Workers, or bundlers that relocate assets, pass\n * an explicit URL here.\n */\n wasmModuleOrPath?: string | URL | WebAssembly.Module;\n /** Override the wall clock (test/sim only). */\n now?: () => number;\n}\n\nexport interface NotificationPreviewSession {\n /**\n * Decrypt ONE push-delivered envelope for display. Resolves to the\n * decrypted message (sender ids, conversation id, plaintext — everything a\n * banner needs) or `null` when there is nothing to show. Rejects when the\n * snapshot cannot decrypt it (commonly: the tab consumed it first) — treat\n * a rejection exactly like `null` and fall back to the generic banner.\n *\n * The returned message never carries a `journal_id`: a preview decrypt is\n * not journaled (nothing durable happened) and needs no `confirmApplied`.\n */\n previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null>;\n /** Release the WASM instance. The session is unusable afterwards. */\n close(): void;\n}\n\n/**\n * Open the SDK read-only for notification previews, from a Service Worker (or\n * any realm without the SDK's Worker bridge). Rejects when the store holds no\n * checkpoint or no device identity — a Service Worker for an account that\n * never initialised locally has nothing to decrypt with, and \"successfully\n * decrypt nothing\" would be the worst possible answer.\n */\nexport async function openNotificationPreview(\n opts: NotificationPreviewOptions,\n): Promise<NotificationPreviewSession> {\n const now = opts.now ?? (() => Date.now());\n const scoped =\n opts.accountNamespace !== undefined && opts.accountNamespace.length > 0\n ? scopeStorage(opts.storage, opts.accountNamespace)\n : opts.storage;\n const storage = readOnlyStorage(scoped);\n\n // Inline WASM load — the module ships no DOM dependency, so this works in\n // window, worker, and service-worker realms alike. `init` is idempotent per\n // realm (subsequent opens reuse the instantiated module).\n const wasm = await import(\"../wasm/ping_wasm\");\n const out = await wasm.default(\n opts.wasmModuleOrPath === undefined\n ? undefined\n : ({ module_or_path: opts.wasmModuleOrPath } as never),\n );\n // Same Safari mitigation as the worker (`wasm-memory.ts`): grow from JS\n // once so the module never executes `memory.grow` itself. Idempotent.\n reserveLinearMemory(out.memory);\n\n const client = await wasm.PingClient.openReadOnly(\n opts.identityExport,\n // Label is unused on the read-only path (no LocalDevice is ever minted).\n \"notification-preview\",\n storage as never,\n silentTransport() as never,\n now(),\n );\n\n let closed = false;\n return {\n async previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null> {\n if (closed) throw new Error(\"notification-preview session is closed\");\n const result = client.previewEnvelope(envelope as never, now());\n return (result ?? null) as IncomingMessage | null;\n },\n close() {\n if (closed) return;\n closed = true;\n client.free();\n },\n };\n}\n\n/**\n * The per-account scope rule, shared with `MessagingClient` so the preview and\n * the tab's writer always read the same slot. Re-exported for tests.\n */\nexport { scopeStorage };\n\n/**\n * Wrap a host `Storage` so writes REJECT. The Rust side already opens the MLS\n * snapshot through a read-only backend; this guards the host-KV half\n * (`device`, `groups`, `cursors`, …), which the read-only MLS backend cannot\n * see. Defense in depth against a host bug making the Service Worker a second\n * writer. Exported for tests.\n */\nexport function readOnlyStorage(storage: Storage): Storage {\n const refuse = (op: string): Promise<never> =>\n Promise.reject(\n new Error(`notification-preview storage is read-only (attempted ${op})`),\n );\n const readOnly: Storage = {\n get: (ns, key) => storage.get(ns, key),\n put: (_ns, _key, _value) => refuse(\"put\"),\n del: (_ns, _key) => refuse(\"del\"),\n listKeys: (ns, prefix) => storage.listKeys(ns, prefix),\n };\n // `listEntries` is a read, so the read-only open keeps its one-call path.\n // `applyBatch` is a write and is deliberately absent: the wasm only uses\n // the methods it finds, and the read-only backend never batches.\n const hostListEntries = storage.listEntries;\n if (typeof hostListEntries === \"function\") {\n readOnly.listEntries = (ns, prefix) => hostListEntries.call(storage, ns, prefix);\n }\n return readOnly;\n}\n\n/**\n * A transport that can never be used: the preview client never sends, never\n * fetches, never discovers. `send` rejects loudly so a wiring mistake is\n * caught instead of silently networking from a push handler.\n */\nfunction silentTransport(): {\n send(envelope: unknown): Promise<never>;\n fetchSince(conv: unknown, cursor: unknown, limit: number): Promise<unknown[]>;\n discoverDevices(userId: unknown): Promise<unknown[]>;\n setNextWelcomeRecipients(conv: unknown, recipients: unknown): Promise<void>;\n} {\n return {\n send: () => Promise.reject(new Error(\"notification-preview cannot send\")),\n fetchSince: () => Promise.resolve([]),\n discoverDevices: () => Promise.resolve([]),\n setNextWelcomeRecipients: () => Promise.resolve(),\n };\n}\n","// Per-account storage scoping, and the optional-method probe that has to agree\n// with it.\n//\n// `MessagingClient` and `openNotificationPreview` both scope through\n// `scopeStorage`, so the tab's writer and the Service Worker's reader can never\n// disagree about which slot a namespace lives in.\n\nimport type { StorageFeatures } from \"../protocol\";\nimport type { Storage } from \"../types\";\n\n/**\n * Wrap a host `Storage` so every namespace carries the per-account scope\n * prefix: `\"${accountNamespace} ${ns}\"`, space separator. Keys and values pass\n * through untouched.\n *\n * The optional batch methods are forwarded exactly when the host has them.\n * That matters because the client tells the wasm which of them exist by\n * probing the storage it will actually call (`storageFeaturesOf`). This\n * wrapper once forwarded only the four basic methods, while the probe looked\n * at the unwrapped host: every scoped account was told `listEntries` existed,\n * the call reached the wrapper, resolved `undefined`, and the store open failed\n * with \"listEntries must resolve to an array\". A dropped `applyBatch` would\n * have been worse, acknowledging writes that never happened.\n */\nexport function scopeStorage(storage: Storage, accountNamespace: string): Storage {\n const scope = (ns: string): string => `${accountNamespace} ${ns}`;\n const scoped: Storage = {\n get: (ns, key) => storage.get(scope(ns), key),\n put: (ns, key, value) => storage.put(scope(ns), key, value),\n del: (ns, key) => storage.del(scope(ns), key),\n listKeys: (ns, prefix) => storage.listKeys(scope(ns), prefix),\n };\n const hostApplyBatch = storage.applyBatch;\n if (typeof hostApplyBatch === \"function\") {\n scoped.applyBatch = (ns, puts, deletes) =>\n hostApplyBatch.call(storage, scope(ns), puts, deletes);\n }\n const hostListEntries = storage.listEntries;\n if (typeof hostListEntries === \"function\") {\n scoped.listEntries = (ns, prefix) => hostListEntries.call(storage, scope(ns), prefix);\n }\n return scoped;\n}\n\n/**\n * Which optional methods `storage` really has. Probe the storage the client\n * dispatches to (after any wrapping), never the one the host passed in: the\n * worker hands the wasm a proxy for exactly these, and a method the dispatch\n * target lacks must never be advertised.\n */\nexport function storageFeaturesOf(storage: Storage): StorageFeatures {\n return {\n applyBatch: typeof storage.applyBatch === \"function\",\n listEntries: typeof storage.listEntries === \"function\",\n };\n}\n","// 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"],"mappings":"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","names":[]}
1
+ {"version":3,"sources":["../src/notification-preview.ts","../src/storage/scope.ts","../src/wasm-memory.ts"],"sourcesContent":["// [CR-5] Read-only notification preview for the web Service Worker.\n//\n// The web mirror of the iOS Notification Service Extension: a second JS realm\n// (the push-handling Service Worker, woken while the tab may be closed OR open\n// and writing) that must turn one push-delivered envelope into a sender and a\n// body preview, and change NOTHING.\n//\n// This module deliberately does NOT go through the SDK's usual Worker bridge:\n// a Service Worker cannot spawn a dedicated `Worker` on every browser, and a\n// preview needs one decrypt, not a message pipeline. The WASM module is loaded\n// INLINE in the calling realm (no DOM APIs are touched), wrapping the core's\n// `MessagingClient::open_read_only` + `preview_envelope` — the same read-only\n// seam the iOS NSE uses, with the same semantics:\n//\n// * the SDK storage is opened READ-ONLY: the MLS snapshot is copied into\n// memory at open and never written back, so the tab remains the single\n// writer and cannot be disturbed (two writers on the whole-state blob\n// REPLACE each other — see `StorageBackend::AsyncBlobReadOnly`);\n// * the ratchet advance from the preview decrypt is thrown away; the tab\n// decrypts the same message again later, independently. Nothing is\n// consumed that the tab needs, and nothing this session does is\n// observable by the tab;\n// * handshake traffic (Commit/Welcome/Proposal), unknown conversations, and\n// replays the hydrated cursor rejects all resolve to `null` — show the\n// generic banner, it is a normal answer;\n// * a message the tab ALREADY consumed and checkpointed cannot be decrypted\n// from the newer snapshot (its generation is burned): `previewEnvelope`\n// rejects. Treat ANY rejection as \"no preview\" (generic banner), never as\n// fatal.\n//\n// Concurrent-open safety: IndexedDB reads never block the tab's writes and the\n// session takes a point-in-time copy of the `__mls snapshot` blob at open, so\n// opening while a tab is live is safe by construction. The copy can be STALE\n// relative to the tab, which only widens the `null`/reject cases above. Open a\n// fresh session per push event (or per small batch) rather than caching one —\n// a fresh open sees the newest checkpoint.\n//\n// See docs/NOTIFICATION_PREVIEW_WEB.md for the full Service Worker guide\n// (wasm init in module vs classic workers, account-slot storage, ping-prime\n// wiring).\n\nimport { scopeStorage } from \"./storage/scope\";\nimport type { IncomingMessage, MessageEnvelope, Storage } from \"./types\";\nimport { reserveLinearMemory } from \"./wasm-memory\";\n\nexport interface NotificationPreviewOptions {\n /**\n * The account identity export (CBOR-wrapped Ed25519 seed, SECRET) — the\n * same bytes the tab passes to `MessagingClient.init`. The Service Worker\n * host must read it from wherever the tab keeps it (e.g. the encrypted IDB\n * slot); it never crosses the network.\n */\n identityExport: Uint8Array;\n /**\n * The SAME `Storage` implementation (and underlying IndexedDB database)\n * the tab's `MessagingClient` persists to. It is wrapped read-only here:\n * `put`/`del` reject, so a host bug cannot make the Service Worker a\n * second writer.\n */\n storage: Storage;\n /**\n * The tab's `ClientConfig.accountNamespace` for this account slot, when it\n * uses one. MUST match exactly — the preview scopes every namespace with\n * the same `\"${accountNamespace} \"` prefix rule as `MessagingClient`, and a\n * mismatch reads an empty store (open rejects with \"no checkpoint\").\n */\n accountNamespace?: string;\n /**\n * Where to load `ping_wasm_bg.wasm` from, passed through to the\n * wasm-bindgen `init`. Defaults to the URL baked next to the module —\n * correct when the bundler ships the `wasm/` directory alongside. Classic\n * (importScripts) Service Workers, or bundlers that relocate assets, pass\n * an explicit URL here.\n */\n wasmModuleOrPath?: string | URL | WebAssembly.Module;\n /** Override the wall clock (test/sim only). */\n now?: () => number;\n}\n\n/**\n * The most prerequisite envelopes `previewEnvelopeWithPrerequisites` accepts.\n * The envelopes come from the server before anything authenticates them, so\n * the work they can cause is bounded. Mirrors the core's\n * `PREVIEW_PREREQUISITES_MAX`.\n */\nexport const MAX_PREVIEW_PREREQUISITES = 64;\n\nexport interface NotificationPreviewSession {\n /**\n * Decrypt ONE push-delivered envelope for display. Resolves to the\n * decrypted message (sender ids, conversation id, plaintext — everything a\n * banner needs) or `null` when there is nothing to show. Rejects when the\n * snapshot cannot decrypt it (commonly: the tab consumed it first) — treat\n * a rejection exactly like `null` and fall back to the generic banner.\n *\n * The returned message never carries a `journal_id`: a preview decrypt is\n * not journaled (nothing durable happened) and needs no `confirmApplied`.\n */\n previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null>;\n /**\n * Decrypt ONE push-delivered envelope that this device cannot read yet,\n * because the handshake traffic in front of it has not been processed: the\n * first message of a conversation whose Welcome is still pending, or a\n * message sent after a Commit the tab has not applied.\n *\n * `prerequisites` are the envelopes that precede `envelope`, oldest first:\n * the pending Welcome (if any) and the Commits and Proposals after it.\n * They are applied to this session's private in-memory copy and then\n * `envelope` is decrypted. Nothing is persisted, the one-time KeyPackage\n * the Welcome was sealed to stays in the store, and the tab later joins and\n * decrypts for itself as if this call never happened.\n *\n * Envelopes for other conversations are ignored, a Welcome is not applied\n * to a conversation the snapshot already holds and can read, and a\n * prerequisite that does not apply is skipped. At most\n * {@link MAX_PREVIEW_PREREQUISITES} prerequisites; more rejects.\n *\n * Same result contract as `previewEnvelope`: `null` when there is nothing\n * to show, a rejection when the message cannot be decrypted. Treat both as\n * \"no preview\" and fall back to the generic banner.\n *\n * The applied prerequisites stay in the session's memory, so open a fresh\n * session per push event (the module comment already says to).\n */\n previewEnvelopeWithPrerequisites(\n prerequisites: MessageEnvelope[],\n envelope: MessageEnvelope,\n ): Promise<IncomingMessage | null>;\n /** Release the WASM instance. The session is unusable afterwards. */\n close(): void;\n}\n\n/**\n * Open the SDK read-only for notification previews, from a Service Worker (or\n * any realm without the SDK's Worker bridge). Rejects when the store holds no\n * checkpoint or no device identity — a Service Worker for an account that\n * never initialised locally has nothing to decrypt with, and \"successfully\n * decrypt nothing\" would be the worst possible answer.\n */\nexport async function openNotificationPreview(\n opts: NotificationPreviewOptions,\n): Promise<NotificationPreviewSession> {\n const now = opts.now ?? (() => Date.now());\n const scoped =\n opts.accountNamespace !== undefined && opts.accountNamespace.length > 0\n ? scopeStorage(opts.storage, opts.accountNamespace)\n : opts.storage;\n const storage = readOnlyStorage(scoped);\n\n // Inline WASM load — the module ships no DOM dependency, so this works in\n // window, worker, and service-worker realms alike. `init` is idempotent per\n // realm (subsequent opens reuse the instantiated module).\n const wasm = await import(\"../wasm/ping_wasm\");\n const out = await wasm.default(\n opts.wasmModuleOrPath === undefined\n ? undefined\n : ({ module_or_path: opts.wasmModuleOrPath } as never),\n );\n // Same Safari mitigation as the worker (`wasm-memory.ts`): grow from JS\n // once so the module never executes `memory.grow` itself. Idempotent.\n reserveLinearMemory(out.memory);\n\n const client = await wasm.PingClient.openReadOnly(\n opts.identityExport,\n // Label is unused on the read-only path (no LocalDevice is ever minted).\n \"notification-preview\",\n storage as never,\n silentTransport() as never,\n now(),\n );\n\n let closed = false;\n return {\n async previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null> {\n if (closed) throw new Error(\"notification-preview session is closed\");\n const result = client.previewEnvelope(envelope as never, now());\n return (result ?? null) as IncomingMessage | null;\n },\n async previewEnvelopeWithPrerequisites(\n prerequisites: MessageEnvelope[],\n envelope: MessageEnvelope,\n ): Promise<IncomingMessage | null> {\n if (closed) throw new Error(\"notification-preview session is closed\");\n assertPrerequisiteCount(prerequisites);\n const result = client.previewEnvelopeWithPrerequisites(\n prerequisites as never,\n envelope as never,\n now(),\n );\n return (result ?? null) as IncomingMessage | null;\n },\n close() {\n if (closed) return;\n closed = true;\n client.free();\n },\n };\n}\n\n/**\n * Refuse an oversized prerequisite list before it crosses into WASM. The core\n * enforces the same bound; checking here keeps the copy out of linear memory.\n * Exported for tests.\n */\nexport function assertPrerequisiteCount(prerequisites: readonly unknown[]): void {\n if (!Array.isArray(prerequisites)) {\n throw new Error(\"notification-preview prerequisites must be an array\");\n }\n if (prerequisites.length > MAX_PREVIEW_PREREQUISITES) {\n throw new Error(\n `notification-preview takes at most ${MAX_PREVIEW_PREREQUISITES} prerequisite envelopes`,\n );\n }\n}\n\n/**\n * The per-account scope rule, shared with `MessagingClient` so the preview and\n * the tab's writer always read the same slot. Re-exported for tests.\n */\nexport { scopeStorage };\n\n/**\n * Wrap a host `Storage` so writes REJECT. The Rust side already opens the MLS\n * snapshot through a read-only backend; this guards the host-KV half\n * (`device`, `groups`, `cursors`, …), which the read-only MLS backend cannot\n * see. Defense in depth against a host bug making the Service Worker a second\n * writer. Exported for tests.\n */\nexport function readOnlyStorage(storage: Storage): Storage {\n const refuse = (op: string): Promise<never> =>\n Promise.reject(\n new Error(`notification-preview storage is read-only (attempted ${op})`),\n );\n const readOnly: Storage = {\n get: (ns, key) => storage.get(ns, key),\n put: (_ns, _key, _value) => refuse(\"put\"),\n del: (_ns, _key) => refuse(\"del\"),\n listKeys: (ns, prefix) => storage.listKeys(ns, prefix),\n };\n // `listEntries` is a read, so the read-only open keeps its one-call path.\n // `applyBatch` is a write and is deliberately absent: the wasm only uses\n // the methods it finds, and the read-only backend never batches.\n const hostListEntries = storage.listEntries;\n if (typeof hostListEntries === \"function\") {\n readOnly.listEntries = (ns, prefix) => hostListEntries.call(storage, ns, prefix);\n }\n return readOnly;\n}\n\n/**\n * A transport that can never be used: the preview client never sends, never\n * fetches, never discovers. `send` rejects loudly so a wiring mistake is\n * caught instead of silently networking from a push handler.\n */\nfunction silentTransport(): {\n send(envelope: unknown): Promise<never>;\n fetchSince(conv: unknown, cursor: unknown, limit: number): Promise<unknown[]>;\n discoverDevices(userId: unknown): Promise<unknown[]>;\n setNextWelcomeRecipients(conv: unknown, recipients: unknown): Promise<void>;\n} {\n return {\n send: () => Promise.reject(new Error(\"notification-preview cannot send\")),\n fetchSince: () => Promise.resolve([]),\n discoverDevices: () => Promise.resolve([]),\n setNextWelcomeRecipients: () => Promise.resolve(),\n };\n}\n","// Per-account storage scoping, and the optional-method probe that has to agree\n// with it.\n//\n// `MessagingClient` and `openNotificationPreview` both scope through\n// `scopeStorage`, so the tab's writer and the Service Worker's reader can never\n// disagree about which slot a namespace lives in.\n\nimport type { StorageFeatures } from \"../protocol\";\nimport type { Storage } from \"../types\";\n\n/**\n * Wrap a host `Storage` so every namespace carries the per-account scope\n * prefix: `\"${accountNamespace} ${ns}\"`, space separator. Keys and values pass\n * through untouched.\n *\n * The optional batch methods are forwarded exactly when the host has them.\n * That matters because the client tells the wasm which of them exist by\n * probing the storage it will actually call (`storageFeaturesOf`). This\n * wrapper once forwarded only the four basic methods, while the probe looked\n * at the unwrapped host: every scoped account was told `listEntries` existed,\n * the call reached the wrapper, resolved `undefined`, and the store open failed\n * with \"listEntries must resolve to an array\". A dropped `applyBatch` would\n * have been worse, acknowledging writes that never happened.\n */\nexport function scopeStorage(storage: Storage, accountNamespace: string): Storage {\n const scope = (ns: string): string => `${accountNamespace} ${ns}`;\n const scoped: Storage = {\n get: (ns, key) => storage.get(scope(ns), key),\n put: (ns, key, value) => storage.put(scope(ns), key, value),\n del: (ns, key) => storage.del(scope(ns), key),\n listKeys: (ns, prefix) => storage.listKeys(scope(ns), prefix),\n };\n const hostApplyBatch = storage.applyBatch;\n if (typeof hostApplyBatch === \"function\") {\n scoped.applyBatch = (ns, puts, deletes) =>\n hostApplyBatch.call(storage, scope(ns), puts, deletes);\n }\n const hostListEntries = storage.listEntries;\n if (typeof hostListEntries === \"function\") {\n scoped.listEntries = (ns, prefix) => hostListEntries.call(storage, scope(ns), prefix);\n }\n return scoped;\n}\n\n/**\n * Which optional methods `storage` really has. Probe the storage the client\n * dispatches to (after any wrapping), never the one the host passed in: the\n * worker hands the wasm a proxy for exactly these, and a method the dispatch\n * target lacks must never be advertised.\n */\nexport function storageFeaturesOf(storage: Storage): StorageFeatures {\n return {\n applyBatch: typeof storage.applyBatch === \"function\",\n listEntries: typeof storage.listEntries === \"function\",\n };\n}\n","// 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACwBO,SAAS,aAAa,SAAkB,kBAAmC;AAChF,QAAM,QAAQ,CAAC,OAAuB,GAAG,gBAAgB,IAAI,EAAE;AAC/D,QAAM,SAAkB;AAAA,IACtB,KAAK,CAAC,IAAI,QAAQ,QAAQ,IAAI,MAAM,EAAE,GAAG,GAAG;AAAA,IAC5C,KAAK,CAAC,IAAI,KAAK,UAAU,QAAQ,IAAI,MAAM,EAAE,GAAG,KAAK,KAAK;AAAA,IAC1D,KAAK,CAAC,IAAI,QAAQ,QAAQ,IAAI,MAAM,EAAE,GAAG,GAAG;AAAA,IAC5C,UAAU,CAAC,IAAI,WAAW,QAAQ,SAAS,MAAM,EAAE,GAAG,MAAM;AAAA,EAC9D;AACA,QAAM,iBAAiB,QAAQ;AAC/B,MAAI,OAAO,mBAAmB,YAAY;AACxC,WAAO,aAAa,CAAC,IAAI,MAAM,YAC7B,eAAe,KAAK,SAAS,MAAM,EAAE,GAAG,MAAM,OAAO;AAAA,EACzD;AACA,QAAM,kBAAkB,QAAQ;AAChC,MAAI,OAAO,oBAAoB,YAAY;AACzC,WAAO,cAAc,CAAC,IAAI,WAAW,gBAAgB,KAAK,SAAS,MAAM,EAAE,GAAG,MAAM;AAAA,EACtF;AACA,SAAO;AACT;;;ACxBO,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;;;AFiDO,IAAM,4BAA4B;AAsDzC,eAAsB,wBACpB,MACqC;AACrC,QAAM,MAAM,KAAK,QAAQ,MAAM,KAAK,IAAI;AACxC,QAAM,SACJ,KAAK,qBAAqB,UAAa,KAAK,iBAAiB,SAAS,IAClE,aAAa,KAAK,SAAS,KAAK,gBAAgB,IAChD,KAAK;AACX,QAAM,UAAU,gBAAgB,MAAM;AAKtC,QAAM,OAAO,MAAM,OAAO,mBAAmB;AAC7C,QAAM,MAAM,MAAM,KAAK;AAAA,IACrB,KAAK,qBAAqB,SACtB,SACC,EAAE,gBAAgB,KAAK,iBAAiB;AAAA,EAC/C;AAGA,sBAAoB,IAAI,MAAM;AAE9B,QAAM,SAAS,MAAM,KAAK,WAAW;AAAA,IACnC,KAAK;AAAA;AAAA,IAEL;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,IAChB,IAAI;AAAA,EACN;AAEA,MAAI,SAAS;AACb,SAAO;AAAA,IACL,MAAM,gBAAgB,UAA4D;AAChF,UAAI,OAAQ,OAAM,IAAI,MAAM,wCAAwC;AACpE,YAAM,SAAS,OAAO,gBAAgB,UAAmB,IAAI,CAAC;AAC9D,aAAQ,UAAU;AAAA,IACpB;AAAA,IACA,MAAM,iCACJ,eACA,UACiC;AACjC,UAAI,OAAQ,OAAM,IAAI,MAAM,wCAAwC;AACpE,8BAAwB,aAAa;AACrC,YAAM,SAAS,OAAO;AAAA,QACpB;AAAA,QACA;AAAA,QACA,IAAI;AAAA,MACN;AACA,aAAQ,UAAU;AAAA,IACpB;AAAA,IACA,QAAQ;AACN,UAAI,OAAQ;AACZ,eAAS;AACT,aAAO,KAAK;AAAA,IACd;AAAA,EACF;AACF;AAOO,SAAS,wBAAwB,eAAyC;AAC/E,MAAI,CAAC,MAAM,QAAQ,aAAa,GAAG;AACjC,UAAM,IAAI,MAAM,qDAAqD;AAAA,EACvE;AACA,MAAI,cAAc,SAAS,2BAA2B;AACpD,UAAM,IAAI;AAAA,MACR,sCAAsC,yBAAyB;AAAA,IACjE;AAAA,EACF;AACF;AAeO,SAAS,gBAAgB,SAA2B;AACzD,QAAM,SAAS,CAAC,OACd,QAAQ;AAAA,IACN,IAAI,MAAM,wDAAwD,EAAE,GAAG;AAAA,EACzE;AACF,QAAM,WAAoB;AAAA,IACxB,KAAK,CAAC,IAAI,QAAQ,QAAQ,IAAI,IAAI,GAAG;AAAA,IACrC,KAAK,CAAC,KAAK,MAAM,WAAW,OAAO,KAAK;AAAA,IACxC,KAAK,CAAC,KAAK,SAAS,OAAO,KAAK;AAAA,IAChC,UAAU,CAAC,IAAI,WAAW,QAAQ,SAAS,IAAI,MAAM;AAAA,EACvD;AAIA,QAAM,kBAAkB,QAAQ;AAChC,MAAI,OAAO,oBAAoB,YAAY;AACzC,aAAS,cAAc,CAAC,IAAI,WAAW,gBAAgB,KAAK,SAAS,IAAI,MAAM;AAAA,EACjF;AACA,SAAO;AACT;AAOA,SAAS,kBAKP;AACA,SAAO;AAAA,IACL,MAAM,MAAM,QAAQ,OAAO,IAAI,MAAM,kCAAkC,CAAC;AAAA,IACxE,YAAY,MAAM,QAAQ,QAAQ,CAAC,CAAC;AAAA,IACpC,iBAAiB,MAAM,QAAQ,QAAQ,CAAC,CAAC;AAAA,IACzC,0BAA0B,MAAM,QAAQ,QAAQ;AAAA,EAClD;AACF;","names":[]}
@@ -1,4 +1,4 @@
1
- import { S as Storage, M as MessageEnvelope, i as IncomingMessage } from './types-B1GFwNXa.cjs';
1
+ import { S as Storage, M as MessageEnvelope, i as IncomingMessage } from './types-gAmJFSC-.cjs';
2
2
 
3
3
  /**
4
4
  * Wrap a host `Storage` so every namespace carries the per-account scope
@@ -49,6 +49,13 @@ interface NotificationPreviewOptions {
49
49
  /** Override the wall clock (test/sim only). */
50
50
  now?: () => number;
51
51
  }
52
+ /**
53
+ * The most prerequisite envelopes `previewEnvelopeWithPrerequisites` accepts.
54
+ * The envelopes come from the server before anything authenticates them, so
55
+ * the work they can cause is bounded. Mirrors the core's
56
+ * `PREVIEW_PREREQUISITES_MAX`.
57
+ */
58
+ declare const MAX_PREVIEW_PREREQUISITES = 64;
52
59
  interface NotificationPreviewSession {
53
60
  /**
54
61
  * Decrypt ONE push-delivered envelope for display. Resolves to the
@@ -61,6 +68,32 @@ interface NotificationPreviewSession {
61
68
  * not journaled (nothing durable happened) and needs no `confirmApplied`.
62
69
  */
63
70
  previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null>;
71
+ /**
72
+ * Decrypt ONE push-delivered envelope that this device cannot read yet,
73
+ * because the handshake traffic in front of it has not been processed: the
74
+ * first message of a conversation whose Welcome is still pending, or a
75
+ * message sent after a Commit the tab has not applied.
76
+ *
77
+ * `prerequisites` are the envelopes that precede `envelope`, oldest first:
78
+ * the pending Welcome (if any) and the Commits and Proposals after it.
79
+ * They are applied to this session's private in-memory copy and then
80
+ * `envelope` is decrypted. Nothing is persisted, the one-time KeyPackage
81
+ * the Welcome was sealed to stays in the store, and the tab later joins and
82
+ * decrypts for itself as if this call never happened.
83
+ *
84
+ * Envelopes for other conversations are ignored, a Welcome is not applied
85
+ * to a conversation the snapshot already holds and can read, and a
86
+ * prerequisite that does not apply is skipped. At most
87
+ * {@link MAX_PREVIEW_PREREQUISITES} prerequisites; more rejects.
88
+ *
89
+ * Same result contract as `previewEnvelope`: `null` when there is nothing
90
+ * to show, a rejection when the message cannot be decrypted. Treat both as
91
+ * "no preview" and fall back to the generic banner.
92
+ *
93
+ * The applied prerequisites stay in the session's memory, so open a fresh
94
+ * session per push event (the module comment already says to).
95
+ */
96
+ previewEnvelopeWithPrerequisites(prerequisites: MessageEnvelope[], envelope: MessageEnvelope): Promise<IncomingMessage | null>;
64
97
  /** Release the WASM instance. The session is unusable afterwards. */
65
98
  close(): void;
66
99
  }
@@ -72,6 +105,12 @@ interface NotificationPreviewSession {
72
105
  * decrypt nothing" would be the worst possible answer.
73
106
  */
74
107
  declare function openNotificationPreview(opts: NotificationPreviewOptions): Promise<NotificationPreviewSession>;
108
+ /**
109
+ * Refuse an oversized prerequisite list before it crosses into WASM. The core
110
+ * enforces the same bound; checking here keeps the copy out of linear memory.
111
+ * Exported for tests.
112
+ */
113
+ declare function assertPrerequisiteCount(prerequisites: readonly unknown[]): void;
75
114
 
76
115
  /**
77
116
  * Wrap a host `Storage` so writes REJECT. The Rust side already opens the MLS
@@ -82,4 +121,4 @@ declare function openNotificationPreview(opts: NotificationPreviewOptions): Prom
82
121
  */
83
122
  declare function readOnlyStorage(storage: Storage): Storage;
84
123
 
85
- export { type NotificationPreviewOptions, type NotificationPreviewSession, openNotificationPreview, readOnlyStorage, scopeStorage };
124
+ export { MAX_PREVIEW_PREREQUISITES, type NotificationPreviewOptions, type NotificationPreviewSession, assertPrerequisiteCount, openNotificationPreview, readOnlyStorage, scopeStorage };
@@ -1,4 +1,4 @@
1
- import { S as Storage, M as MessageEnvelope, i as IncomingMessage } from './types-B1GFwNXa.js';
1
+ import { S as Storage, M as MessageEnvelope, i as IncomingMessage } from './types-gAmJFSC-.js';
2
2
 
3
3
  /**
4
4
  * Wrap a host `Storage` so every namespace carries the per-account scope
@@ -49,6 +49,13 @@ interface NotificationPreviewOptions {
49
49
  /** Override the wall clock (test/sim only). */
50
50
  now?: () => number;
51
51
  }
52
+ /**
53
+ * The most prerequisite envelopes `previewEnvelopeWithPrerequisites` accepts.
54
+ * The envelopes come from the server before anything authenticates them, so
55
+ * the work they can cause is bounded. Mirrors the core's
56
+ * `PREVIEW_PREREQUISITES_MAX`.
57
+ */
58
+ declare const MAX_PREVIEW_PREREQUISITES = 64;
52
59
  interface NotificationPreviewSession {
53
60
  /**
54
61
  * Decrypt ONE push-delivered envelope for display. Resolves to the
@@ -61,6 +68,32 @@ interface NotificationPreviewSession {
61
68
  * not journaled (nothing durable happened) and needs no `confirmApplied`.
62
69
  */
63
70
  previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null>;
71
+ /**
72
+ * Decrypt ONE push-delivered envelope that this device cannot read yet,
73
+ * because the handshake traffic in front of it has not been processed: the
74
+ * first message of a conversation whose Welcome is still pending, or a
75
+ * message sent after a Commit the tab has not applied.
76
+ *
77
+ * `prerequisites` are the envelopes that precede `envelope`, oldest first:
78
+ * the pending Welcome (if any) and the Commits and Proposals after it.
79
+ * They are applied to this session's private in-memory copy and then
80
+ * `envelope` is decrypted. Nothing is persisted, the one-time KeyPackage
81
+ * the Welcome was sealed to stays in the store, and the tab later joins and
82
+ * decrypts for itself as if this call never happened.
83
+ *
84
+ * Envelopes for other conversations are ignored, a Welcome is not applied
85
+ * to a conversation the snapshot already holds and can read, and a
86
+ * prerequisite that does not apply is skipped. At most
87
+ * {@link MAX_PREVIEW_PREREQUISITES} prerequisites; more rejects.
88
+ *
89
+ * Same result contract as `previewEnvelope`: `null` when there is nothing
90
+ * to show, a rejection when the message cannot be decrypted. Treat both as
91
+ * "no preview" and fall back to the generic banner.
92
+ *
93
+ * The applied prerequisites stay in the session's memory, so open a fresh
94
+ * session per push event (the module comment already says to).
95
+ */
96
+ previewEnvelopeWithPrerequisites(prerequisites: MessageEnvelope[], envelope: MessageEnvelope): Promise<IncomingMessage | null>;
64
97
  /** Release the WASM instance. The session is unusable afterwards. */
65
98
  close(): void;
66
99
  }
@@ -72,6 +105,12 @@ interface NotificationPreviewSession {
72
105
  * decrypt nothing" would be the worst possible answer.
73
106
  */
74
107
  declare function openNotificationPreview(opts: NotificationPreviewOptions): Promise<NotificationPreviewSession>;
108
+ /**
109
+ * Refuse an oversized prerequisite list before it crosses into WASM. The core
110
+ * enforces the same bound; checking here keeps the copy out of linear memory.
111
+ * Exported for tests.
112
+ */
113
+ declare function assertPrerequisiteCount(prerequisites: readonly unknown[]): void;
75
114
 
76
115
  /**
77
116
  * Wrap a host `Storage` so writes REJECT. The Rust side already opens the MLS
@@ -82,4 +121,4 @@ declare function openNotificationPreview(opts: NotificationPreviewOptions): Prom
82
121
  */
83
122
  declare function readOnlyStorage(storage: Storage): Storage;
84
123
 
85
- export { type NotificationPreviewOptions, type NotificationPreviewSession, openNotificationPreview, readOnlyStorage, scopeStorage };
124
+ export { MAX_PREVIEW_PREREQUISITES, type NotificationPreviewOptions, type NotificationPreviewSession, assertPrerequisiteCount, openNotificationPreview, readOnlyStorage, scopeStorage };
@@ -35,6 +35,7 @@ function reserveLinearMemory(memory) {
35
35
  }
36
36
 
37
37
  // src/notification-preview.ts
38
+ var MAX_PREVIEW_PREREQUISITES = 64;
38
39
  async function openNotificationPreview(opts) {
39
40
  const now = opts.now ?? (() => Date.now());
40
41
  const scoped = opts.accountNamespace !== void 0 && opts.accountNamespace.length > 0 ? scopeStorage(opts.storage, opts.accountNamespace) : opts.storage;
@@ -59,6 +60,16 @@ async function openNotificationPreview(opts) {
59
60
  const result = client.previewEnvelope(envelope, now());
60
61
  return result ?? null;
61
62
  },
63
+ async previewEnvelopeWithPrerequisites(prerequisites, envelope) {
64
+ if (closed) throw new Error("notification-preview session is closed");
65
+ assertPrerequisiteCount(prerequisites);
66
+ const result = client.previewEnvelopeWithPrerequisites(
67
+ prerequisites,
68
+ envelope,
69
+ now()
70
+ );
71
+ return result ?? null;
72
+ },
62
73
  close() {
63
74
  if (closed) return;
64
75
  closed = true;
@@ -66,6 +77,16 @@ async function openNotificationPreview(opts) {
66
77
  }
67
78
  };
68
79
  }
80
+ function assertPrerequisiteCount(prerequisites) {
81
+ if (!Array.isArray(prerequisites)) {
82
+ throw new Error("notification-preview prerequisites must be an array");
83
+ }
84
+ if (prerequisites.length > MAX_PREVIEW_PREREQUISITES) {
85
+ throw new Error(
86
+ `notification-preview takes at most ${MAX_PREVIEW_PREREQUISITES} prerequisite envelopes`
87
+ );
88
+ }
89
+ }
69
90
  function readOnlyStorage(storage) {
70
91
  const refuse = (op) => Promise.reject(
71
92
  new Error(`notification-preview storage is read-only (attempted ${op})`)
@@ -91,6 +112,8 @@ function silentTransport() {
91
112
  };
92
113
  }
93
114
  export {
115
+ MAX_PREVIEW_PREREQUISITES,
116
+ assertPrerequisiteCount,
94
117
  openNotificationPreview,
95
118
  readOnlyStorage,
96
119
  scopeStorage
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/storage/scope.ts","../src/wasm-memory.ts","../src/notification-preview.ts"],"sourcesContent":["// Per-account storage scoping, and the optional-method probe that has to agree\n// with it.\n//\n// `MessagingClient` and `openNotificationPreview` both scope through\n// `scopeStorage`, so the tab's writer and the Service Worker's reader can never\n// disagree about which slot a namespace lives in.\n\nimport type { StorageFeatures } from \"../protocol\";\nimport type { Storage } from \"../types\";\n\n/**\n * Wrap a host `Storage` so every namespace carries the per-account scope\n * prefix: `\"${accountNamespace} ${ns}\"`, space separator. Keys and values pass\n * through untouched.\n *\n * The optional batch methods are forwarded exactly when the host has them.\n * That matters because the client tells the wasm which of them exist by\n * probing the storage it will actually call (`storageFeaturesOf`). This\n * wrapper once forwarded only the four basic methods, while the probe looked\n * at the unwrapped host: every scoped account was told `listEntries` existed,\n * the call reached the wrapper, resolved `undefined`, and the store open failed\n * with \"listEntries must resolve to an array\". A dropped `applyBatch` would\n * have been worse, acknowledging writes that never happened.\n */\nexport function scopeStorage(storage: Storage, accountNamespace: string): Storage {\n const scope = (ns: string): string => `${accountNamespace} ${ns}`;\n const scoped: Storage = {\n get: (ns, key) => storage.get(scope(ns), key),\n put: (ns, key, value) => storage.put(scope(ns), key, value),\n del: (ns, key) => storage.del(scope(ns), key),\n listKeys: (ns, prefix) => storage.listKeys(scope(ns), prefix),\n };\n const hostApplyBatch = storage.applyBatch;\n if (typeof hostApplyBatch === \"function\") {\n scoped.applyBatch = (ns, puts, deletes) =>\n hostApplyBatch.call(storage, scope(ns), puts, deletes);\n }\n const hostListEntries = storage.listEntries;\n if (typeof hostListEntries === \"function\") {\n scoped.listEntries = (ns, prefix) => hostListEntries.call(storage, scope(ns), prefix);\n }\n return scoped;\n}\n\n/**\n * Which optional methods `storage` really has. Probe the storage the client\n * dispatches to (after any wrapping), never the one the host passed in: the\n * worker hands the wasm a proxy for exactly these, and a method the dispatch\n * target lacks must never be advertised.\n */\nexport function storageFeaturesOf(storage: Storage): StorageFeatures {\n return {\n applyBatch: typeof storage.applyBatch === \"function\",\n listEntries: typeof storage.listEntries === \"function\",\n };\n}\n","// 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","// [CR-5] Read-only notification preview for the web Service Worker.\n//\n// The web mirror of the iOS Notification Service Extension: a second JS realm\n// (the push-handling Service Worker, woken while the tab may be closed OR open\n// and writing) that must turn one push-delivered envelope into a sender and a\n// body preview, and change NOTHING.\n//\n// This module deliberately does NOT go through the SDK's usual Worker bridge:\n// a Service Worker cannot spawn a dedicated `Worker` on every browser, and a\n// preview needs one decrypt, not a message pipeline. The WASM module is loaded\n// INLINE in the calling realm (no DOM APIs are touched), wrapping the core's\n// `MessagingClient::open_read_only` + `preview_envelope` — the same read-only\n// seam the iOS NSE uses, with the same semantics:\n//\n// * the SDK storage is opened READ-ONLY: the MLS snapshot is copied into\n// memory at open and never written back, so the tab remains the single\n// writer and cannot be disturbed (two writers on the whole-state blob\n// REPLACE each other — see `StorageBackend::AsyncBlobReadOnly`);\n// * the ratchet advance from the preview decrypt is thrown away; the tab\n// decrypts the same message again later, independently. Nothing is\n// consumed that the tab needs, and nothing this session does is\n// observable by the tab;\n// * handshake traffic (Commit/Welcome/Proposal), unknown conversations, and\n// replays the hydrated cursor rejects all resolve to `null` — show the\n// generic banner, it is a normal answer;\n// * a message the tab ALREADY consumed and checkpointed cannot be decrypted\n// from the newer snapshot (its generation is burned): `previewEnvelope`\n// rejects. Treat ANY rejection as \"no preview\" (generic banner), never as\n// fatal.\n//\n// Concurrent-open safety: IndexedDB reads never block the tab's writes and the\n// session takes a point-in-time copy of the `__mls snapshot` blob at open, so\n// opening while a tab is live is safe by construction. The copy can be STALE\n// relative to the tab, which only widens the `null`/reject cases above. Open a\n// fresh session per push event (or per small batch) rather than caching one —\n// a fresh open sees the newest checkpoint.\n//\n// See docs/NOTIFICATION_PREVIEW_WEB.md for the full Service Worker guide\n// (wasm init in module vs classic workers, account-slot storage, ping-prime\n// wiring).\n\nimport { scopeStorage } from \"./storage/scope\";\nimport type { IncomingMessage, MessageEnvelope, Storage } from \"./types\";\nimport { reserveLinearMemory } from \"./wasm-memory\";\n\nexport interface NotificationPreviewOptions {\n /**\n * The account identity export (CBOR-wrapped Ed25519 seed, SECRET) — the\n * same bytes the tab passes to `MessagingClient.init`. The Service Worker\n * host must read it from wherever the tab keeps it (e.g. the encrypted IDB\n * slot); it never crosses the network.\n */\n identityExport: Uint8Array;\n /**\n * The SAME `Storage` implementation (and underlying IndexedDB database)\n * the tab's `MessagingClient` persists to. It is wrapped read-only here:\n * `put`/`del` reject, so a host bug cannot make the Service Worker a\n * second writer.\n */\n storage: Storage;\n /**\n * The tab's `ClientConfig.accountNamespace` for this account slot, when it\n * uses one. MUST match exactly — the preview scopes every namespace with\n * the same `\"${accountNamespace} \"` prefix rule as `MessagingClient`, and a\n * mismatch reads an empty store (open rejects with \"no checkpoint\").\n */\n accountNamespace?: string;\n /**\n * Where to load `ping_wasm_bg.wasm` from, passed through to the\n * wasm-bindgen `init`. Defaults to the URL baked next to the module —\n * correct when the bundler ships the `wasm/` directory alongside. Classic\n * (importScripts) Service Workers, or bundlers that relocate assets, pass\n * an explicit URL here.\n */\n wasmModuleOrPath?: string | URL | WebAssembly.Module;\n /** Override the wall clock (test/sim only). */\n now?: () => number;\n}\n\nexport interface NotificationPreviewSession {\n /**\n * Decrypt ONE push-delivered envelope for display. Resolves to the\n * decrypted message (sender ids, conversation id, plaintext — everything a\n * banner needs) or `null` when there is nothing to show. Rejects when the\n * snapshot cannot decrypt it (commonly: the tab consumed it first) — treat\n * a rejection exactly like `null` and fall back to the generic banner.\n *\n * The returned message never carries a `journal_id`: a preview decrypt is\n * not journaled (nothing durable happened) and needs no `confirmApplied`.\n */\n previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null>;\n /** Release the WASM instance. The session is unusable afterwards. */\n close(): void;\n}\n\n/**\n * Open the SDK read-only for notification previews, from a Service Worker (or\n * any realm without the SDK's Worker bridge). Rejects when the store holds no\n * checkpoint or no device identity — a Service Worker for an account that\n * never initialised locally has nothing to decrypt with, and \"successfully\n * decrypt nothing\" would be the worst possible answer.\n */\nexport async function openNotificationPreview(\n opts: NotificationPreviewOptions,\n): Promise<NotificationPreviewSession> {\n const now = opts.now ?? (() => Date.now());\n const scoped =\n opts.accountNamespace !== undefined && opts.accountNamespace.length > 0\n ? scopeStorage(opts.storage, opts.accountNamespace)\n : opts.storage;\n const storage = readOnlyStorage(scoped);\n\n // Inline WASM load — the module ships no DOM dependency, so this works in\n // window, worker, and service-worker realms alike. `init` is idempotent per\n // realm (subsequent opens reuse the instantiated module).\n const wasm = await import(\"../wasm/ping_wasm\");\n const out = await wasm.default(\n opts.wasmModuleOrPath === undefined\n ? undefined\n : ({ module_or_path: opts.wasmModuleOrPath } as never),\n );\n // Same Safari mitigation as the worker (`wasm-memory.ts`): grow from JS\n // once so the module never executes `memory.grow` itself. Idempotent.\n reserveLinearMemory(out.memory);\n\n const client = await wasm.PingClient.openReadOnly(\n opts.identityExport,\n // Label is unused on the read-only path (no LocalDevice is ever minted).\n \"notification-preview\",\n storage as never,\n silentTransport() as never,\n now(),\n );\n\n let closed = false;\n return {\n async previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null> {\n if (closed) throw new Error(\"notification-preview session is closed\");\n const result = client.previewEnvelope(envelope as never, now());\n return (result ?? null) as IncomingMessage | null;\n },\n close() {\n if (closed) return;\n closed = true;\n client.free();\n },\n };\n}\n\n/**\n * The per-account scope rule, shared with `MessagingClient` so the preview and\n * the tab's writer always read the same slot. Re-exported for tests.\n */\nexport { scopeStorage };\n\n/**\n * Wrap a host `Storage` so writes REJECT. The Rust side already opens the MLS\n * snapshot through a read-only backend; this guards the host-KV half\n * (`device`, `groups`, `cursors`, …), which the read-only MLS backend cannot\n * see. Defense in depth against a host bug making the Service Worker a second\n * writer. Exported for tests.\n */\nexport function readOnlyStorage(storage: Storage): Storage {\n const refuse = (op: string): Promise<never> =>\n Promise.reject(\n new Error(`notification-preview storage is read-only (attempted ${op})`),\n );\n const readOnly: Storage = {\n get: (ns, key) => storage.get(ns, key),\n put: (_ns, _key, _value) => refuse(\"put\"),\n del: (_ns, _key) => refuse(\"del\"),\n listKeys: (ns, prefix) => storage.listKeys(ns, prefix),\n };\n // `listEntries` is a read, so the read-only open keeps its one-call path.\n // `applyBatch` is a write and is deliberately absent: the wasm only uses\n // the methods it finds, and the read-only backend never batches.\n const hostListEntries = storage.listEntries;\n if (typeof hostListEntries === \"function\") {\n readOnly.listEntries = (ns, prefix) => hostListEntries.call(storage, ns, prefix);\n }\n return readOnly;\n}\n\n/**\n * A transport that can never be used: the preview client never sends, never\n * fetches, never discovers. `send` rejects loudly so a wiring mistake is\n * caught instead of silently networking from a push handler.\n */\nfunction silentTransport(): {\n send(envelope: unknown): Promise<never>;\n fetchSince(conv: unknown, cursor: unknown, limit: number): Promise<unknown[]>;\n discoverDevices(userId: unknown): Promise<unknown[]>;\n setNextWelcomeRecipients(conv: unknown, recipients: unknown): Promise<void>;\n} {\n return {\n send: () => Promise.reject(new Error(\"notification-preview cannot send\")),\n fetchSince: () => Promise.resolve([]),\n discoverDevices: () => Promise.resolve([]),\n setNextWelcomeRecipients: () => Promise.resolve(),\n };\n}\n"],"mappings":"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","names":[]}
1
+ {"version":3,"sources":["../src/storage/scope.ts","../src/wasm-memory.ts","../src/notification-preview.ts"],"sourcesContent":["// Per-account storage scoping, and the optional-method probe that has to agree\n// with it.\n//\n// `MessagingClient` and `openNotificationPreview` both scope through\n// `scopeStorage`, so the tab's writer and the Service Worker's reader can never\n// disagree about which slot a namespace lives in.\n\nimport type { StorageFeatures } from \"../protocol\";\nimport type { Storage } from \"../types\";\n\n/**\n * Wrap a host `Storage` so every namespace carries the per-account scope\n * prefix: `\"${accountNamespace} ${ns}\"`, space separator. Keys and values pass\n * through untouched.\n *\n * The optional batch methods are forwarded exactly when the host has them.\n * That matters because the client tells the wasm which of them exist by\n * probing the storage it will actually call (`storageFeaturesOf`). This\n * wrapper once forwarded only the four basic methods, while the probe looked\n * at the unwrapped host: every scoped account was told `listEntries` existed,\n * the call reached the wrapper, resolved `undefined`, and the store open failed\n * with \"listEntries must resolve to an array\". A dropped `applyBatch` would\n * have been worse, acknowledging writes that never happened.\n */\nexport function scopeStorage(storage: Storage, accountNamespace: string): Storage {\n const scope = (ns: string): string => `${accountNamespace} ${ns}`;\n const scoped: Storage = {\n get: (ns, key) => storage.get(scope(ns), key),\n put: (ns, key, value) => storage.put(scope(ns), key, value),\n del: (ns, key) => storage.del(scope(ns), key),\n listKeys: (ns, prefix) => storage.listKeys(scope(ns), prefix),\n };\n const hostApplyBatch = storage.applyBatch;\n if (typeof hostApplyBatch === \"function\") {\n scoped.applyBatch = (ns, puts, deletes) =>\n hostApplyBatch.call(storage, scope(ns), puts, deletes);\n }\n const hostListEntries = storage.listEntries;\n if (typeof hostListEntries === \"function\") {\n scoped.listEntries = (ns, prefix) => hostListEntries.call(storage, scope(ns), prefix);\n }\n return scoped;\n}\n\n/**\n * Which optional methods `storage` really has. Probe the storage the client\n * dispatches to (after any wrapping), never the one the host passed in: the\n * worker hands the wasm a proxy for exactly these, and a method the dispatch\n * target lacks must never be advertised.\n */\nexport function storageFeaturesOf(storage: Storage): StorageFeatures {\n return {\n applyBatch: typeof storage.applyBatch === \"function\",\n listEntries: typeof storage.listEntries === \"function\",\n };\n}\n","// 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","// [CR-5] Read-only notification preview for the web Service Worker.\n//\n// The web mirror of the iOS Notification Service Extension: a second JS realm\n// (the push-handling Service Worker, woken while the tab may be closed OR open\n// and writing) that must turn one push-delivered envelope into a sender and a\n// body preview, and change NOTHING.\n//\n// This module deliberately does NOT go through the SDK's usual Worker bridge:\n// a Service Worker cannot spawn a dedicated `Worker` on every browser, and a\n// preview needs one decrypt, not a message pipeline. The WASM module is loaded\n// INLINE in the calling realm (no DOM APIs are touched), wrapping the core's\n// `MessagingClient::open_read_only` + `preview_envelope` — the same read-only\n// seam the iOS NSE uses, with the same semantics:\n//\n// * the SDK storage is opened READ-ONLY: the MLS snapshot is copied into\n// memory at open and never written back, so the tab remains the single\n// writer and cannot be disturbed (two writers on the whole-state blob\n// REPLACE each other — see `StorageBackend::AsyncBlobReadOnly`);\n// * the ratchet advance from the preview decrypt is thrown away; the tab\n// decrypts the same message again later, independently. Nothing is\n// consumed that the tab needs, and nothing this session does is\n// observable by the tab;\n// * handshake traffic (Commit/Welcome/Proposal), unknown conversations, and\n// replays the hydrated cursor rejects all resolve to `null` — show the\n// generic banner, it is a normal answer;\n// * a message the tab ALREADY consumed and checkpointed cannot be decrypted\n// from the newer snapshot (its generation is burned): `previewEnvelope`\n// rejects. Treat ANY rejection as \"no preview\" (generic banner), never as\n// fatal.\n//\n// Concurrent-open safety: IndexedDB reads never block the tab's writes and the\n// session takes a point-in-time copy of the `__mls snapshot` blob at open, so\n// opening while a tab is live is safe by construction. The copy can be STALE\n// relative to the tab, which only widens the `null`/reject cases above. Open a\n// fresh session per push event (or per small batch) rather than caching one —\n// a fresh open sees the newest checkpoint.\n//\n// See docs/NOTIFICATION_PREVIEW_WEB.md for the full Service Worker guide\n// (wasm init in module vs classic workers, account-slot storage, ping-prime\n// wiring).\n\nimport { scopeStorage } from \"./storage/scope\";\nimport type { IncomingMessage, MessageEnvelope, Storage } from \"./types\";\nimport { reserveLinearMemory } from \"./wasm-memory\";\n\nexport interface NotificationPreviewOptions {\n /**\n * The account identity export (CBOR-wrapped Ed25519 seed, SECRET) — the\n * same bytes the tab passes to `MessagingClient.init`. The Service Worker\n * host must read it from wherever the tab keeps it (e.g. the encrypted IDB\n * slot); it never crosses the network.\n */\n identityExport: Uint8Array;\n /**\n * The SAME `Storage` implementation (and underlying IndexedDB database)\n * the tab's `MessagingClient` persists to. It is wrapped read-only here:\n * `put`/`del` reject, so a host bug cannot make the Service Worker a\n * second writer.\n */\n storage: Storage;\n /**\n * The tab's `ClientConfig.accountNamespace` for this account slot, when it\n * uses one. MUST match exactly — the preview scopes every namespace with\n * the same `\"${accountNamespace} \"` prefix rule as `MessagingClient`, and a\n * mismatch reads an empty store (open rejects with \"no checkpoint\").\n */\n accountNamespace?: string;\n /**\n * Where to load `ping_wasm_bg.wasm` from, passed through to the\n * wasm-bindgen `init`. Defaults to the URL baked next to the module —\n * correct when the bundler ships the `wasm/` directory alongside. Classic\n * (importScripts) Service Workers, or bundlers that relocate assets, pass\n * an explicit URL here.\n */\n wasmModuleOrPath?: string | URL | WebAssembly.Module;\n /** Override the wall clock (test/sim only). */\n now?: () => number;\n}\n\n/**\n * The most prerequisite envelopes `previewEnvelopeWithPrerequisites` accepts.\n * The envelopes come from the server before anything authenticates them, so\n * the work they can cause is bounded. Mirrors the core's\n * `PREVIEW_PREREQUISITES_MAX`.\n */\nexport const MAX_PREVIEW_PREREQUISITES = 64;\n\nexport interface NotificationPreviewSession {\n /**\n * Decrypt ONE push-delivered envelope for display. Resolves to the\n * decrypted message (sender ids, conversation id, plaintext — everything a\n * banner needs) or `null` when there is nothing to show. Rejects when the\n * snapshot cannot decrypt it (commonly: the tab consumed it first) — treat\n * a rejection exactly like `null` and fall back to the generic banner.\n *\n * The returned message never carries a `journal_id`: a preview decrypt is\n * not journaled (nothing durable happened) and needs no `confirmApplied`.\n */\n previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null>;\n /**\n * Decrypt ONE push-delivered envelope that this device cannot read yet,\n * because the handshake traffic in front of it has not been processed: the\n * first message of a conversation whose Welcome is still pending, or a\n * message sent after a Commit the tab has not applied.\n *\n * `prerequisites` are the envelopes that precede `envelope`, oldest first:\n * the pending Welcome (if any) and the Commits and Proposals after it.\n * They are applied to this session's private in-memory copy and then\n * `envelope` is decrypted. Nothing is persisted, the one-time KeyPackage\n * the Welcome was sealed to stays in the store, and the tab later joins and\n * decrypts for itself as if this call never happened.\n *\n * Envelopes for other conversations are ignored, a Welcome is not applied\n * to a conversation the snapshot already holds and can read, and a\n * prerequisite that does not apply is skipped. At most\n * {@link MAX_PREVIEW_PREREQUISITES} prerequisites; more rejects.\n *\n * Same result contract as `previewEnvelope`: `null` when there is nothing\n * to show, a rejection when the message cannot be decrypted. Treat both as\n * \"no preview\" and fall back to the generic banner.\n *\n * The applied prerequisites stay in the session's memory, so open a fresh\n * session per push event (the module comment already says to).\n */\n previewEnvelopeWithPrerequisites(\n prerequisites: MessageEnvelope[],\n envelope: MessageEnvelope,\n ): Promise<IncomingMessage | null>;\n /** Release the WASM instance. The session is unusable afterwards. */\n close(): void;\n}\n\n/**\n * Open the SDK read-only for notification previews, from a Service Worker (or\n * any realm without the SDK's Worker bridge). Rejects when the store holds no\n * checkpoint or no device identity — a Service Worker for an account that\n * never initialised locally has nothing to decrypt with, and \"successfully\n * decrypt nothing\" would be the worst possible answer.\n */\nexport async function openNotificationPreview(\n opts: NotificationPreviewOptions,\n): Promise<NotificationPreviewSession> {\n const now = opts.now ?? (() => Date.now());\n const scoped =\n opts.accountNamespace !== undefined && opts.accountNamespace.length > 0\n ? scopeStorage(opts.storage, opts.accountNamespace)\n : opts.storage;\n const storage = readOnlyStorage(scoped);\n\n // Inline WASM load — the module ships no DOM dependency, so this works in\n // window, worker, and service-worker realms alike. `init` is idempotent per\n // realm (subsequent opens reuse the instantiated module).\n const wasm = await import(\"../wasm/ping_wasm\");\n const out = await wasm.default(\n opts.wasmModuleOrPath === undefined\n ? undefined\n : ({ module_or_path: opts.wasmModuleOrPath } as never),\n );\n // Same Safari mitigation as the worker (`wasm-memory.ts`): grow from JS\n // once so the module never executes `memory.grow` itself. Idempotent.\n reserveLinearMemory(out.memory);\n\n const client = await wasm.PingClient.openReadOnly(\n opts.identityExport,\n // Label is unused on the read-only path (no LocalDevice is ever minted).\n \"notification-preview\",\n storage as never,\n silentTransport() as never,\n now(),\n );\n\n let closed = false;\n return {\n async previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null> {\n if (closed) throw new Error(\"notification-preview session is closed\");\n const result = client.previewEnvelope(envelope as never, now());\n return (result ?? null) as IncomingMessage | null;\n },\n async previewEnvelopeWithPrerequisites(\n prerequisites: MessageEnvelope[],\n envelope: MessageEnvelope,\n ): Promise<IncomingMessage | null> {\n if (closed) throw new Error(\"notification-preview session is closed\");\n assertPrerequisiteCount(prerequisites);\n const result = client.previewEnvelopeWithPrerequisites(\n prerequisites as never,\n envelope as never,\n now(),\n );\n return (result ?? null) as IncomingMessage | null;\n },\n close() {\n if (closed) return;\n closed = true;\n client.free();\n },\n };\n}\n\n/**\n * Refuse an oversized prerequisite list before it crosses into WASM. The core\n * enforces the same bound; checking here keeps the copy out of linear memory.\n * Exported for tests.\n */\nexport function assertPrerequisiteCount(prerequisites: readonly unknown[]): void {\n if (!Array.isArray(prerequisites)) {\n throw new Error(\"notification-preview prerequisites must be an array\");\n }\n if (prerequisites.length > MAX_PREVIEW_PREREQUISITES) {\n throw new Error(\n `notification-preview takes at most ${MAX_PREVIEW_PREREQUISITES} prerequisite envelopes`,\n );\n }\n}\n\n/**\n * The per-account scope rule, shared with `MessagingClient` so the preview and\n * the tab's writer always read the same slot. Re-exported for tests.\n */\nexport { scopeStorage };\n\n/**\n * Wrap a host `Storage` so writes REJECT. The Rust side already opens the MLS\n * snapshot through a read-only backend; this guards the host-KV half\n * (`device`, `groups`, `cursors`, …), which the read-only MLS backend cannot\n * see. Defense in depth against a host bug making the Service Worker a second\n * writer. Exported for tests.\n */\nexport function readOnlyStorage(storage: Storage): Storage {\n const refuse = (op: string): Promise<never> =>\n Promise.reject(\n new Error(`notification-preview storage is read-only (attempted ${op})`),\n );\n const readOnly: Storage = {\n get: (ns, key) => storage.get(ns, key),\n put: (_ns, _key, _value) => refuse(\"put\"),\n del: (_ns, _key) => refuse(\"del\"),\n listKeys: (ns, prefix) => storage.listKeys(ns, prefix),\n };\n // `listEntries` is a read, so the read-only open keeps its one-call path.\n // `applyBatch` is a write and is deliberately absent: the wasm only uses\n // the methods it finds, and the read-only backend never batches.\n const hostListEntries = storage.listEntries;\n if (typeof hostListEntries === \"function\") {\n readOnly.listEntries = (ns, prefix) => hostListEntries.call(storage, ns, prefix);\n }\n return readOnly;\n}\n\n/**\n * A transport that can never be used: the preview client never sends, never\n * fetches, never discovers. `send` rejects loudly so a wiring mistake is\n * caught instead of silently networking from a push handler.\n */\nfunction silentTransport(): {\n send(envelope: unknown): Promise<never>;\n fetchSince(conv: unknown, cursor: unknown, limit: number): Promise<unknown[]>;\n discoverDevices(userId: unknown): Promise<unknown[]>;\n setNextWelcomeRecipients(conv: unknown, recipients: unknown): Promise<void>;\n} {\n return {\n send: () => Promise.reject(new Error(\"notification-preview cannot send\")),\n fetchSince: () => Promise.resolve([]),\n discoverDevices: () => Promise.resolve([]),\n setNextWelcomeRecipients: () => Promise.resolve(),\n };\n}\n"],"mappings":"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","names":[]}
@@ -1,4 +1,4 @@
1
- import { S as Storage } from '../types-B1GFwNXa.cjs';
1
+ import { S as Storage } from '../types-gAmJFSC-.cjs';
2
2
 
3
3
  declare class IndexedDbStorage implements Storage {
4
4
  private dbPromise;
@@ -1,4 +1,4 @@
1
- import { S as Storage } from '../types-B1GFwNXa.js';
1
+ import { S as Storage } from '../types-gAmJFSC-.js';
2
2
 
3
3
  declare class IndexedDbStorage implements Storage {
4
4
  private dbPromise;
@@ -1,4 +1,4 @@
1
- import { T as Transport, M as MessageEnvelope, C as ConversationId, U as UserId, D as DiscoveredDevice } from '../types-B1GFwNXa.cjs';
1
+ import { T as Transport, M as MessageEnvelope, C as ConversationId, U as UserId, D as DiscoveredDevice } from '../types-gAmJFSC-.cjs';
2
2
 
3
3
  interface WsTransportConfig {
4
4
  baseUrl: string;
@@ -1,4 +1,4 @@
1
- import { T as Transport, M as MessageEnvelope, C as ConversationId, U as UserId, D as DiscoveredDevice } from '../types-B1GFwNXa.js';
1
+ import { T as Transport, M as MessageEnvelope, C as ConversationId, U as UserId, D as DiscoveredDevice } from '../types-gAmJFSC-.js';
2
2
 
3
3
  interface WsTransportConfig {
4
4
  baseUrl: string;
@@ -285,6 +285,16 @@ interface SequencedEnvelope {
285
285
  envelope: MessageEnvelope;
286
286
  serverSeq: number;
287
287
  }
288
+ /** A secret from a conversation's MLS exporter and the MLS epoch it was
289
+ * exported at, from `exportConversationSecretWithEpoch`. The two are one
290
+ * read of one group state: `secret` is the exporter's output at exactly
291
+ * `epoch`. `secret` is secret key material: never log it, persist it only
292
+ * encrypted, and `secret.fill(0)` after use. `epoch` may be logged. */
293
+ interface ExportedSecret {
294
+ /** MLS epoch the secret was exported at. */
295
+ epoch: number;
296
+ secret: Uint8Array;
297
+ }
288
298
  /** This device's applied position in one conversation's server log.
289
299
  * `anchored` false means `serverSeq` is not a real position yet (a
290
300
  * conversation joined through a linking ticket, or a cursor written before
@@ -532,4 +542,4 @@ interface Transport {
532
542
  setNextWelcomeRecipients?(conversationId: ConversationId, recipientDeviceIds: DeviceId[]): Promise<void>;
533
543
  }
534
544
 
535
- export type { WelcomeFailureReason as $, AddMembersReport as A, BufferOverflow as B, ConversationId as C, DiscoveredDevice as D, ExpectedOwner as E, DeviceInfo as F, DeviceRemovalFailure as G, HistoryBundle as H, IdentityRotation as I, HistoryAppEvent as J, KeyPackageEntry as K, LinkingTicket as L, MessageEnvelope as M, Hlc as N, IdentityRotationFailure as O, PendingApply as P, LogGap as Q, RecoveryBackup as R, Storage as S, Transport as T, UserId as U, MessageKind as V, OverflowReason as W, SenderRole as X, StrandReason as Y, StrandedConversation as Z, WelcomeFailure as _, DeviceId as a, ConversationMeta as b, DeviceReauthProof as c, DeviceLinkApproval as d, DeviceLinkPossession as e, CommitInDoubt as f, MemberInfo as g, ConversationPolicy as h, IncomingMessage as i, SequencedEnvelope as j, ApplyBatchResult as k, SyncStepResult as l, LogPosition as m, LogHead as n, CatchupAppEvent as o, CatchupSnapshotView as p, AdmitChatEntry as q, AdmitChatOutcome as r, DeviceRemovalReport as s, MessageBatchMeta as t, AddMemberStatus as u, AddMemberVerdict as v, Bytes as w, CatchupSnapshotEntry as x, ConversationRemoval as y, ConversationUpdate as z };
545
+ export type { WelcomeFailure as $, AddMembersReport as A, BufferOverflow as B, ConversationId as C, DiscoveredDevice as D, ExpectedOwner as E, ConversationUpdate as F, DeviceInfo as G, HistoryBundle as H, IdentityRotation as I, DeviceRemovalFailure as J, KeyPackageEntry as K, LinkingTicket as L, MessageEnvelope as M, HistoryAppEvent as N, Hlc as O, PendingApply as P, IdentityRotationFailure as Q, RecoveryBackup as R, Storage as S, Transport as T, UserId as U, LogGap as V, MessageKind as W, OverflowReason as X, SenderRole as Y, StrandReason as Z, StrandedConversation as _, DeviceId as a, WelcomeFailureReason as a0, ConversationMeta as b, DeviceReauthProof as c, DeviceLinkApproval as d, DeviceLinkPossession as e, CommitInDoubt as f, MemberInfo as g, ConversationPolicy as h, IncomingMessage as i, SequencedEnvelope as j, ApplyBatchResult as k, SyncStepResult as l, LogPosition as m, LogHead as n, CatchupAppEvent as o, CatchupSnapshotView as p, AdmitChatEntry as q, AdmitChatOutcome as r, DeviceRemovalReport as s, ExportedSecret as t, MessageBatchMeta as u, AddMemberStatus as v, AddMemberVerdict as w, Bytes as x, CatchupSnapshotEntry as y, ConversationRemoval as z };
@@ -285,6 +285,16 @@ interface SequencedEnvelope {
285
285
  envelope: MessageEnvelope;
286
286
  serverSeq: number;
287
287
  }
288
+ /** A secret from a conversation's MLS exporter and the MLS epoch it was
289
+ * exported at, from `exportConversationSecretWithEpoch`. The two are one
290
+ * read of one group state: `secret` is the exporter's output at exactly
291
+ * `epoch`. `secret` is secret key material: never log it, persist it only
292
+ * encrypted, and `secret.fill(0)` after use. `epoch` may be logged. */
293
+ interface ExportedSecret {
294
+ /** MLS epoch the secret was exported at. */
295
+ epoch: number;
296
+ secret: Uint8Array;
297
+ }
288
298
  /** This device's applied position in one conversation's server log.
289
299
  * `anchored` false means `serverSeq` is not a real position yet (a
290
300
  * conversation joined through a linking ticket, or a cursor written before
@@ -532,4 +542,4 @@ interface Transport {
532
542
  setNextWelcomeRecipients?(conversationId: ConversationId, recipientDeviceIds: DeviceId[]): Promise<void>;
533
543
  }
534
544
 
535
- export type { WelcomeFailureReason as $, AddMembersReport as A, BufferOverflow as B, ConversationId as C, DiscoveredDevice as D, ExpectedOwner as E, DeviceInfo as F, DeviceRemovalFailure as G, HistoryBundle as H, IdentityRotation as I, HistoryAppEvent as J, KeyPackageEntry as K, LinkingTicket as L, MessageEnvelope as M, Hlc as N, IdentityRotationFailure as O, PendingApply as P, LogGap as Q, RecoveryBackup as R, Storage as S, Transport as T, UserId as U, MessageKind as V, OverflowReason as W, SenderRole as X, StrandReason as Y, StrandedConversation as Z, WelcomeFailure as _, DeviceId as a, ConversationMeta as b, DeviceReauthProof as c, DeviceLinkApproval as d, DeviceLinkPossession as e, CommitInDoubt as f, MemberInfo as g, ConversationPolicy as h, IncomingMessage as i, SequencedEnvelope as j, ApplyBatchResult as k, SyncStepResult as l, LogPosition as m, LogHead as n, CatchupAppEvent as o, CatchupSnapshotView as p, AdmitChatEntry as q, AdmitChatOutcome as r, DeviceRemovalReport as s, MessageBatchMeta as t, AddMemberStatus as u, AddMemberVerdict as v, Bytes as w, CatchupSnapshotEntry as x, ConversationRemoval as y, ConversationUpdate as z };
545
+ export type { WelcomeFailure as $, AddMembersReport as A, BufferOverflow as B, ConversationId as C, DiscoveredDevice as D, ExpectedOwner as E, ConversationUpdate as F, DeviceInfo as G, HistoryBundle as H, IdentityRotation as I, DeviceRemovalFailure as J, KeyPackageEntry as K, LinkingTicket as L, MessageEnvelope as M, HistoryAppEvent as N, Hlc as O, PendingApply as P, IdentityRotationFailure as Q, RecoveryBackup as R, Storage as S, Transport as T, UserId as U, LogGap as V, MessageKind as W, OverflowReason as X, SenderRole as Y, StrandReason as Z, StrandedConversation as _, DeviceId as a, WelcomeFailureReason as a0, ConversationMeta as b, DeviceReauthProof as c, DeviceLinkApproval as d, DeviceLinkPossession as e, CommitInDoubt as f, MemberInfo as g, ConversationPolicy as h, IncomingMessage as i, SequencedEnvelope as j, ApplyBatchResult as k, SyncStepResult as l, LogPosition as m, LogHead as n, CatchupAppEvent as o, CatchupSnapshotView as p, AdmitChatEntry as q, AdmitChatOutcome as r, DeviceRemovalReport as s, ExportedSecret as t, MessageBatchMeta as u, AddMemberStatus as v, AddMemberVerdict as w, Bytes as x, CatchupSnapshotEntry as y, ConversationRemoval as z };
package/dist/worker.cjs CHANGED
@@ -584,6 +584,12 @@ async function dispatch(msg) {
584
584
  }
585
585
  case "previewEnvelope":
586
586
  return ensureClient().previewEnvelope(msg.envelope, msg.nowMs);
587
+ case "previewEnvelopeWithPrerequisites":
588
+ return ensureClient().previewEnvelopeWithPrerequisites(
589
+ msg.prerequisites,
590
+ msg.envelope,
591
+ msg.nowMs
592
+ );
587
593
  case "generateIdentity":
588
594
  return import_ping_wasm.PingClient.generateIdentity();
589
595
  case "userId":
@@ -756,6 +762,13 @@ async function dispatch(msg) {
756
762
  msg.context,
757
763
  msg.length
758
764
  );
765
+ case "exportConversationSecretWithEpoch":
766
+ return ensureClient().exportConversationSecretWithEpoch(
767
+ msg.conv,
768
+ msg.label,
769
+ msg.context,
770
+ msg.length
771
+ );
759
772
  case "sealLinkingTicket":
760
773
  return (0, import_ping_wasm.sealLinkingTicket)(msg.ticket, msg.newDevicePub);
761
774
  case "openLinkingTicket":