@ping-app/ping-openmls-sdk 0.0.0-stage → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +94 -2
- package/dist/index.cjs +2782 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1229 -0
- package/dist/index.d.ts +1229 -0
- package/dist/index.js +2715 -0
- package/dist/index.js.map +1 -0
- package/dist/notification-preview.cjs +137 -0
- package/dist/notification-preview.cjs.map +1 -0
- package/dist/notification-preview.d.cts +85 -0
- package/dist/notification-preview.d.ts +85 -0
- package/dist/notification-preview.js +98 -0
- package/dist/notification-preview.js.map +1 -0
- package/dist/storage/indexeddb.cjs +153 -0
- package/dist/storage/indexeddb.cjs.map +1 -0
- package/dist/storage/indexeddb.d.cts +21 -0
- package/dist/storage/indexeddb.d.ts +21 -0
- package/dist/storage/indexeddb.js +128 -0
- package/dist/storage/indexeddb.js.map +1 -0
- package/dist/transport/websocket.cjs +121 -0
- package/dist/transport/websocket.cjs.map +1 -0
- package/dist/transport/websocket.d.cts +23 -0
- package/dist/transport/websocket.d.ts +23 -0
- package/dist/transport/websocket.js +94 -0
- package/dist/transport/websocket.js.map +1 -0
- package/dist/types-B1GFwNXa.d.cts +535 -0
- package/dist/types-B1GFwNXa.d.ts +535 -0
- package/dist/worker.cjs +841 -0
- package/dist/worker.cjs.map +1 -0
- package/dist/worker.d.cts +2 -0
- package/dist/worker.d.ts +2 -0
- package/dist/worker.js +848 -0
- package/dist/worker.js.map +1 -0
- package/package.json +61 -4
- package/wasm/package.json +17 -0
- package/wasm/ping_wasm.d.ts +909 -0
- package/wasm/ping_wasm.js +3028 -0
- package/wasm/ping_wasm_bg.wasm +0 -0
- package/wasm/ping_wasm_bg.wasm.d.ts +112 -0
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/notification-preview.ts
|
|
31
|
+
var notification_preview_exports = {};
|
|
32
|
+
__export(notification_preview_exports, {
|
|
33
|
+
openNotificationPreview: () => openNotificationPreview,
|
|
34
|
+
readOnlyStorage: () => readOnlyStorage,
|
|
35
|
+
scopeStorage: () => scopeStorage
|
|
36
|
+
});
|
|
37
|
+
module.exports = __toCommonJS(notification_preview_exports);
|
|
38
|
+
|
|
39
|
+
// src/storage/scope.ts
|
|
40
|
+
function scopeStorage(storage, accountNamespace) {
|
|
41
|
+
const scope = (ns) => `${accountNamespace} ${ns}`;
|
|
42
|
+
const scoped = {
|
|
43
|
+
get: (ns, key) => storage.get(scope(ns), key),
|
|
44
|
+
put: (ns, key, value) => storage.put(scope(ns), key, value),
|
|
45
|
+
del: (ns, key) => storage.del(scope(ns), key),
|
|
46
|
+
listKeys: (ns, prefix) => storage.listKeys(scope(ns), prefix)
|
|
47
|
+
};
|
|
48
|
+
const hostApplyBatch = storage.applyBatch;
|
|
49
|
+
if (typeof hostApplyBatch === "function") {
|
|
50
|
+
scoped.applyBatch = (ns, puts, deletes) => hostApplyBatch.call(storage, scope(ns), puts, deletes);
|
|
51
|
+
}
|
|
52
|
+
const hostListEntries = storage.listEntries;
|
|
53
|
+
if (typeof hostListEntries === "function") {
|
|
54
|
+
scoped.listEntries = (ns, prefix) => hostListEntries.call(storage, scope(ns), prefix);
|
|
55
|
+
}
|
|
56
|
+
return scoped;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// src/wasm-memory.ts
|
|
60
|
+
var RESERVE_MIB_TARGETS = [192, 128, 64, 32];
|
|
61
|
+
var WASM_PAGE_BYTES = 64 * 1024;
|
|
62
|
+
var reserved = /* @__PURE__ */ new WeakSet();
|
|
63
|
+
function reserveLinearMemory(memory) {
|
|
64
|
+
if (reserved.has(memory)) return;
|
|
65
|
+
reserved.add(memory);
|
|
66
|
+
for (const mib of RESERVE_MIB_TARGETS) {
|
|
67
|
+
try {
|
|
68
|
+
memory.grow(mib * 1024 * 1024 / WASM_PAGE_BYTES);
|
|
69
|
+
return;
|
|
70
|
+
} catch {
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// src/notification-preview.ts
|
|
76
|
+
async function openNotificationPreview(opts) {
|
|
77
|
+
const now = opts.now ?? (() => Date.now());
|
|
78
|
+
const scoped = opts.accountNamespace !== void 0 && opts.accountNamespace.length > 0 ? scopeStorage(opts.storage, opts.accountNamespace) : opts.storage;
|
|
79
|
+
const storage = readOnlyStorage(scoped);
|
|
80
|
+
const wasm = await import("../wasm/ping_wasm");
|
|
81
|
+
const out = await wasm.default(
|
|
82
|
+
opts.wasmModuleOrPath === void 0 ? void 0 : { module_or_path: opts.wasmModuleOrPath }
|
|
83
|
+
);
|
|
84
|
+
reserveLinearMemory(out.memory);
|
|
85
|
+
const client = await wasm.PingClient.openReadOnly(
|
|
86
|
+
opts.identityExport,
|
|
87
|
+
// Label is unused on the read-only path (no LocalDevice is ever minted).
|
|
88
|
+
"notification-preview",
|
|
89
|
+
storage,
|
|
90
|
+
silentTransport(),
|
|
91
|
+
now()
|
|
92
|
+
);
|
|
93
|
+
let closed = false;
|
|
94
|
+
return {
|
|
95
|
+
async previewEnvelope(envelope) {
|
|
96
|
+
if (closed) throw new Error("notification-preview session is closed");
|
|
97
|
+
const result = client.previewEnvelope(envelope, now());
|
|
98
|
+
return result ?? null;
|
|
99
|
+
},
|
|
100
|
+
close() {
|
|
101
|
+
if (closed) return;
|
|
102
|
+
closed = true;
|
|
103
|
+
client.free();
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
function readOnlyStorage(storage) {
|
|
108
|
+
const refuse = (op) => Promise.reject(
|
|
109
|
+
new Error(`notification-preview storage is read-only (attempted ${op})`)
|
|
110
|
+
);
|
|
111
|
+
const readOnly = {
|
|
112
|
+
get: (ns, key) => storage.get(ns, key),
|
|
113
|
+
put: (_ns, _key, _value) => refuse("put"),
|
|
114
|
+
del: (_ns, _key) => refuse("del"),
|
|
115
|
+
listKeys: (ns, prefix) => storage.listKeys(ns, prefix)
|
|
116
|
+
};
|
|
117
|
+
const hostListEntries = storage.listEntries;
|
|
118
|
+
if (typeof hostListEntries === "function") {
|
|
119
|
+
readOnly.listEntries = (ns, prefix) => hostListEntries.call(storage, ns, prefix);
|
|
120
|
+
}
|
|
121
|
+
return readOnly;
|
|
122
|
+
}
|
|
123
|
+
function silentTransport() {
|
|
124
|
+
return {
|
|
125
|
+
send: () => Promise.reject(new Error("notification-preview cannot send")),
|
|
126
|
+
fetchSince: () => Promise.resolve([]),
|
|
127
|
+
discoverDevices: () => Promise.resolve([]),
|
|
128
|
+
setNextWelcomeRecipients: () => Promise.resolve()
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
132
|
+
0 && (module.exports = {
|
|
133
|
+
openNotificationPreview,
|
|
134
|
+
readOnlyStorage,
|
|
135
|
+
scopeStorage
|
|
136
|
+
});
|
|
137
|
+
//# sourceMappingURL=notification-preview.cjs.map
|
|
@@ -0,0 +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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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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4
|
+
* Wrap a host `Storage` so every namespace carries the per-account scope
|
|
5
|
+
* prefix: `"${accountNamespace} ${ns}"`, space separator. Keys and values pass
|
|
6
|
+
* through untouched.
|
|
7
|
+
*
|
|
8
|
+
* The optional batch methods are forwarded exactly when the host has them.
|
|
9
|
+
* That matters because the client tells the wasm which of them exist by
|
|
10
|
+
* probing the storage it will actually call (`storageFeaturesOf`). This
|
|
11
|
+
* wrapper once forwarded only the four basic methods, while the probe looked
|
|
12
|
+
* at the unwrapped host: every scoped account was told `listEntries` existed,
|
|
13
|
+
* the call reached the wrapper, resolved `undefined`, and the store open failed
|
|
14
|
+
* with "listEntries must resolve to an array". A dropped `applyBatch` would
|
|
15
|
+
* have been worse, acknowledging writes that never happened.
|
|
16
|
+
*/
|
|
17
|
+
declare function scopeStorage(storage: Storage, accountNamespace: string): Storage;
|
|
18
|
+
|
|
19
|
+
interface NotificationPreviewOptions {
|
|
20
|
+
/**
|
|
21
|
+
* The account identity export (CBOR-wrapped Ed25519 seed, SECRET) — the
|
|
22
|
+
* same bytes the tab passes to `MessagingClient.init`. The Service Worker
|
|
23
|
+
* host must read it from wherever the tab keeps it (e.g. the encrypted IDB
|
|
24
|
+
* slot); it never crosses the network.
|
|
25
|
+
*/
|
|
26
|
+
identityExport: Uint8Array;
|
|
27
|
+
/**
|
|
28
|
+
* The SAME `Storage` implementation (and underlying IndexedDB database)
|
|
29
|
+
* the tab's `MessagingClient` persists to. It is wrapped read-only here:
|
|
30
|
+
* `put`/`del` reject, so a host bug cannot make the Service Worker a
|
|
31
|
+
* second writer.
|
|
32
|
+
*/
|
|
33
|
+
storage: Storage;
|
|
34
|
+
/**
|
|
35
|
+
* The tab's `ClientConfig.accountNamespace` for this account slot, when it
|
|
36
|
+
* uses one. MUST match exactly — the preview scopes every namespace with
|
|
37
|
+
* the same `"${accountNamespace} "` prefix rule as `MessagingClient`, and a
|
|
38
|
+
* mismatch reads an empty store (open rejects with "no checkpoint").
|
|
39
|
+
*/
|
|
40
|
+
accountNamespace?: string;
|
|
41
|
+
/**
|
|
42
|
+
* Where to load `ping_wasm_bg.wasm` from, passed through to the
|
|
43
|
+
* wasm-bindgen `init`. Defaults to the URL baked next to the module —
|
|
44
|
+
* correct when the bundler ships the `wasm/` directory alongside. Classic
|
|
45
|
+
* (importScripts) Service Workers, or bundlers that relocate assets, pass
|
|
46
|
+
* an explicit URL here.
|
|
47
|
+
*/
|
|
48
|
+
wasmModuleOrPath?: string | URL | WebAssembly.Module;
|
|
49
|
+
/** Override the wall clock (test/sim only). */
|
|
50
|
+
now?: () => number;
|
|
51
|
+
}
|
|
52
|
+
interface NotificationPreviewSession {
|
|
53
|
+
/**
|
|
54
|
+
* Decrypt ONE push-delivered envelope for display. Resolves to the
|
|
55
|
+
* decrypted message (sender ids, conversation id, plaintext — everything a
|
|
56
|
+
* banner needs) or `null` when there is nothing to show. Rejects when the
|
|
57
|
+
* snapshot cannot decrypt it (commonly: the tab consumed it first) — treat
|
|
58
|
+
* a rejection exactly like `null` and fall back to the generic banner.
|
|
59
|
+
*
|
|
60
|
+
* The returned message never carries a `journal_id`: a preview decrypt is
|
|
61
|
+
* not journaled (nothing durable happened) and needs no `confirmApplied`.
|
|
62
|
+
*/
|
|
63
|
+
previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null>;
|
|
64
|
+
/** Release the WASM instance. The session is unusable afterwards. */
|
|
65
|
+
close(): void;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Open the SDK read-only for notification previews, from a Service Worker (or
|
|
69
|
+
* any realm without the SDK's Worker bridge). Rejects when the store holds no
|
|
70
|
+
* checkpoint or no device identity — a Service Worker for an account that
|
|
71
|
+
* never initialised locally has nothing to decrypt with, and "successfully
|
|
72
|
+
* decrypt nothing" would be the worst possible answer.
|
|
73
|
+
*/
|
|
74
|
+
declare function openNotificationPreview(opts: NotificationPreviewOptions): Promise<NotificationPreviewSession>;
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Wrap a host `Storage` so writes REJECT. The Rust side already opens the MLS
|
|
78
|
+
* snapshot through a read-only backend; this guards the host-KV half
|
|
79
|
+
* (`device`, `groups`, `cursors`, …), which the read-only MLS backend cannot
|
|
80
|
+
* see. Defense in depth against a host bug making the Service Worker a second
|
|
81
|
+
* writer. Exported for tests.
|
|
82
|
+
*/
|
|
83
|
+
declare function readOnlyStorage(storage: Storage): Storage;
|
|
84
|
+
|
|
85
|
+
export { type NotificationPreviewOptions, type NotificationPreviewSession, openNotificationPreview, readOnlyStorage, scopeStorage };
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { S as Storage, M as MessageEnvelope, i as IncomingMessage } from './types-B1GFwNXa.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Wrap a host `Storage` so every namespace carries the per-account scope
|
|
5
|
+
* prefix: `"${accountNamespace} ${ns}"`, space separator. Keys and values pass
|
|
6
|
+
* through untouched.
|
|
7
|
+
*
|
|
8
|
+
* The optional batch methods are forwarded exactly when the host has them.
|
|
9
|
+
* That matters because the client tells the wasm which of them exist by
|
|
10
|
+
* probing the storage it will actually call (`storageFeaturesOf`). This
|
|
11
|
+
* wrapper once forwarded only the four basic methods, while the probe looked
|
|
12
|
+
* at the unwrapped host: every scoped account was told `listEntries` existed,
|
|
13
|
+
* the call reached the wrapper, resolved `undefined`, and the store open failed
|
|
14
|
+
* with "listEntries must resolve to an array". A dropped `applyBatch` would
|
|
15
|
+
* have been worse, acknowledging writes that never happened.
|
|
16
|
+
*/
|
|
17
|
+
declare function scopeStorage(storage: Storage, accountNamespace: string): Storage;
|
|
18
|
+
|
|
19
|
+
interface NotificationPreviewOptions {
|
|
20
|
+
/**
|
|
21
|
+
* The account identity export (CBOR-wrapped Ed25519 seed, SECRET) — the
|
|
22
|
+
* same bytes the tab passes to `MessagingClient.init`. The Service Worker
|
|
23
|
+
* host must read it from wherever the tab keeps it (e.g. the encrypted IDB
|
|
24
|
+
* slot); it never crosses the network.
|
|
25
|
+
*/
|
|
26
|
+
identityExport: Uint8Array;
|
|
27
|
+
/**
|
|
28
|
+
* The SAME `Storage` implementation (and underlying IndexedDB database)
|
|
29
|
+
* the tab's `MessagingClient` persists to. It is wrapped read-only here:
|
|
30
|
+
* `put`/`del` reject, so a host bug cannot make the Service Worker a
|
|
31
|
+
* second writer.
|
|
32
|
+
*/
|
|
33
|
+
storage: Storage;
|
|
34
|
+
/**
|
|
35
|
+
* The tab's `ClientConfig.accountNamespace` for this account slot, when it
|
|
36
|
+
* uses one. MUST match exactly — the preview scopes every namespace with
|
|
37
|
+
* the same `"${accountNamespace} "` prefix rule as `MessagingClient`, and a
|
|
38
|
+
* mismatch reads an empty store (open rejects with "no checkpoint").
|
|
39
|
+
*/
|
|
40
|
+
accountNamespace?: string;
|
|
41
|
+
/**
|
|
42
|
+
* Where to load `ping_wasm_bg.wasm` from, passed through to the
|
|
43
|
+
* wasm-bindgen `init`. Defaults to the URL baked next to the module —
|
|
44
|
+
* correct when the bundler ships the `wasm/` directory alongside. Classic
|
|
45
|
+
* (importScripts) Service Workers, or bundlers that relocate assets, pass
|
|
46
|
+
* an explicit URL here.
|
|
47
|
+
*/
|
|
48
|
+
wasmModuleOrPath?: string | URL | WebAssembly.Module;
|
|
49
|
+
/** Override the wall clock (test/sim only). */
|
|
50
|
+
now?: () => number;
|
|
51
|
+
}
|
|
52
|
+
interface NotificationPreviewSession {
|
|
53
|
+
/**
|
|
54
|
+
* Decrypt ONE push-delivered envelope for display. Resolves to the
|
|
55
|
+
* decrypted message (sender ids, conversation id, plaintext — everything a
|
|
56
|
+
* banner needs) or `null` when there is nothing to show. Rejects when the
|
|
57
|
+
* snapshot cannot decrypt it (commonly: the tab consumed it first) — treat
|
|
58
|
+
* a rejection exactly like `null` and fall back to the generic banner.
|
|
59
|
+
*
|
|
60
|
+
* The returned message never carries a `journal_id`: a preview decrypt is
|
|
61
|
+
* not journaled (nothing durable happened) and needs no `confirmApplied`.
|
|
62
|
+
*/
|
|
63
|
+
previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null>;
|
|
64
|
+
/** Release the WASM instance. The session is unusable afterwards. */
|
|
65
|
+
close(): void;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Open the SDK read-only for notification previews, from a Service Worker (or
|
|
69
|
+
* any realm without the SDK's Worker bridge). Rejects when the store holds no
|
|
70
|
+
* checkpoint or no device identity — a Service Worker for an account that
|
|
71
|
+
* never initialised locally has nothing to decrypt with, and "successfully
|
|
72
|
+
* decrypt nothing" would be the worst possible answer.
|
|
73
|
+
*/
|
|
74
|
+
declare function openNotificationPreview(opts: NotificationPreviewOptions): Promise<NotificationPreviewSession>;
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Wrap a host `Storage` so writes REJECT. The Rust side already opens the MLS
|
|
78
|
+
* snapshot through a read-only backend; this guards the host-KV half
|
|
79
|
+
* (`device`, `groups`, `cursors`, …), which the read-only MLS backend cannot
|
|
80
|
+
* see. Defense in depth against a host bug making the Service Worker a second
|
|
81
|
+
* writer. Exported for tests.
|
|
82
|
+
*/
|
|
83
|
+
declare function readOnlyStorage(storage: Storage): Storage;
|
|
84
|
+
|
|
85
|
+
export { type NotificationPreviewOptions, type NotificationPreviewSession, openNotificationPreview, readOnlyStorage, scopeStorage };
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// src/storage/scope.ts
|
|
2
|
+
function scopeStorage(storage, accountNamespace) {
|
|
3
|
+
const scope = (ns) => `${accountNamespace} ${ns}`;
|
|
4
|
+
const scoped = {
|
|
5
|
+
get: (ns, key) => storage.get(scope(ns), key),
|
|
6
|
+
put: (ns, key, value) => storage.put(scope(ns), key, value),
|
|
7
|
+
del: (ns, key) => storage.del(scope(ns), key),
|
|
8
|
+
listKeys: (ns, prefix) => storage.listKeys(scope(ns), prefix)
|
|
9
|
+
};
|
|
10
|
+
const hostApplyBatch = storage.applyBatch;
|
|
11
|
+
if (typeof hostApplyBatch === "function") {
|
|
12
|
+
scoped.applyBatch = (ns, puts, deletes) => hostApplyBatch.call(storage, scope(ns), puts, deletes);
|
|
13
|
+
}
|
|
14
|
+
const hostListEntries = storage.listEntries;
|
|
15
|
+
if (typeof hostListEntries === "function") {
|
|
16
|
+
scoped.listEntries = (ns, prefix) => hostListEntries.call(storage, scope(ns), prefix);
|
|
17
|
+
}
|
|
18
|
+
return scoped;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// src/wasm-memory.ts
|
|
22
|
+
var RESERVE_MIB_TARGETS = [192, 128, 64, 32];
|
|
23
|
+
var WASM_PAGE_BYTES = 64 * 1024;
|
|
24
|
+
var reserved = /* @__PURE__ */ new WeakSet();
|
|
25
|
+
function reserveLinearMemory(memory) {
|
|
26
|
+
if (reserved.has(memory)) return;
|
|
27
|
+
reserved.add(memory);
|
|
28
|
+
for (const mib of RESERVE_MIB_TARGETS) {
|
|
29
|
+
try {
|
|
30
|
+
memory.grow(mib * 1024 * 1024 / WASM_PAGE_BYTES);
|
|
31
|
+
return;
|
|
32
|
+
} catch {
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// src/notification-preview.ts
|
|
38
|
+
async function openNotificationPreview(opts) {
|
|
39
|
+
const now = opts.now ?? (() => Date.now());
|
|
40
|
+
const scoped = opts.accountNamespace !== void 0 && opts.accountNamespace.length > 0 ? scopeStorage(opts.storage, opts.accountNamespace) : opts.storage;
|
|
41
|
+
const storage = readOnlyStorage(scoped);
|
|
42
|
+
const wasm = await import("../wasm/ping_wasm");
|
|
43
|
+
const out = await wasm.default(
|
|
44
|
+
opts.wasmModuleOrPath === void 0 ? void 0 : { module_or_path: opts.wasmModuleOrPath }
|
|
45
|
+
);
|
|
46
|
+
reserveLinearMemory(out.memory);
|
|
47
|
+
const client = await wasm.PingClient.openReadOnly(
|
|
48
|
+
opts.identityExport,
|
|
49
|
+
// Label is unused on the read-only path (no LocalDevice is ever minted).
|
|
50
|
+
"notification-preview",
|
|
51
|
+
storage,
|
|
52
|
+
silentTransport(),
|
|
53
|
+
now()
|
|
54
|
+
);
|
|
55
|
+
let closed = false;
|
|
56
|
+
return {
|
|
57
|
+
async previewEnvelope(envelope) {
|
|
58
|
+
if (closed) throw new Error("notification-preview session is closed");
|
|
59
|
+
const result = client.previewEnvelope(envelope, now());
|
|
60
|
+
return result ?? null;
|
|
61
|
+
},
|
|
62
|
+
close() {
|
|
63
|
+
if (closed) return;
|
|
64
|
+
closed = true;
|
|
65
|
+
client.free();
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
function readOnlyStorage(storage) {
|
|
70
|
+
const refuse = (op) => Promise.reject(
|
|
71
|
+
new Error(`notification-preview storage is read-only (attempted ${op})`)
|
|
72
|
+
);
|
|
73
|
+
const readOnly = {
|
|
74
|
+
get: (ns, key) => storage.get(ns, key),
|
|
75
|
+
put: (_ns, _key, _value) => refuse("put"),
|
|
76
|
+
del: (_ns, _key) => refuse("del"),
|
|
77
|
+
listKeys: (ns, prefix) => storage.listKeys(ns, prefix)
|
|
78
|
+
};
|
|
79
|
+
const hostListEntries = storage.listEntries;
|
|
80
|
+
if (typeof hostListEntries === "function") {
|
|
81
|
+
readOnly.listEntries = (ns, prefix) => hostListEntries.call(storage, ns, prefix);
|
|
82
|
+
}
|
|
83
|
+
return readOnly;
|
|
84
|
+
}
|
|
85
|
+
function silentTransport() {
|
|
86
|
+
return {
|
|
87
|
+
send: () => Promise.reject(new Error("notification-preview cannot send")),
|
|
88
|
+
fetchSince: () => Promise.resolve([]),
|
|
89
|
+
discoverDevices: () => Promise.resolve([]),
|
|
90
|
+
setNextWelcomeRecipients: () => Promise.resolve()
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
export {
|
|
94
|
+
openNotificationPreview,
|
|
95
|
+
readOnlyStorage,
|
|
96
|
+
scopeStorage
|
|
97
|
+
};
|
|
98
|
+
//# sourceMappingURL=notification-preview.js.map
|
|
@@ -0,0 +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":";AAwBO,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,QAA4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AG;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":[]}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/storage/indexeddb.ts
|
|
21
|
+
var indexeddb_exports = {};
|
|
22
|
+
__export(indexeddb_exports, {
|
|
23
|
+
IndexedDbStorage: () => IndexedDbStorage
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(indexeddb_exports);
|
|
26
|
+
var DB_NAME = "ping-sdk";
|
|
27
|
+
var DB_VERSION = 1;
|
|
28
|
+
var STORE = "kv";
|
|
29
|
+
function open() {
|
|
30
|
+
return new Promise((resolve, reject) => {
|
|
31
|
+
const req = indexedDB.open(DB_NAME, DB_VERSION);
|
|
32
|
+
req.onupgradeneeded = () => {
|
|
33
|
+
const db = req.result;
|
|
34
|
+
if (!db.objectStoreNames.contains(STORE)) {
|
|
35
|
+
const os = db.createObjectStore(STORE, { keyPath: ["ns", "key"] });
|
|
36
|
+
os.createIndex("ns", "ns", { unique: false });
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
req.onsuccess = () => resolve(req.result);
|
|
40
|
+
req.onerror = () => reject(req.error);
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
var IndexedDbStorage = class {
|
|
44
|
+
dbPromise;
|
|
45
|
+
constructor() {
|
|
46
|
+
this.dbPromise = open();
|
|
47
|
+
}
|
|
48
|
+
async get(namespace, key) {
|
|
49
|
+
const db = await this.dbPromise;
|
|
50
|
+
return new Promise((resolve, reject) => {
|
|
51
|
+
const tx = db.transaction(STORE, "readonly");
|
|
52
|
+
const r = tx.objectStore(STORE).get([namespace, key]);
|
|
53
|
+
r.onsuccess = () => resolve(r.result?.value ?? null);
|
|
54
|
+
r.onerror = () => reject(r.error);
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
async put(namespace, key, value) {
|
|
58
|
+
const db = await this.dbPromise;
|
|
59
|
+
return new Promise((resolve, reject) => {
|
|
60
|
+
const tx = db.transaction(STORE, "readwrite");
|
|
61
|
+
tx.objectStore(STORE).put({ ns: namespace, key, value });
|
|
62
|
+
tx.oncomplete = () => resolve();
|
|
63
|
+
tx.onerror = () => reject(tx.error);
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
async del(namespace, key) {
|
|
67
|
+
const db = await this.dbPromise;
|
|
68
|
+
return new Promise((resolve, reject) => {
|
|
69
|
+
const tx = db.transaction(STORE, "readwrite");
|
|
70
|
+
tx.objectStore(STORE).delete([namespace, key]);
|
|
71
|
+
tx.oncomplete = () => resolve();
|
|
72
|
+
tx.onerror = () => reject(tx.error);
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* One `readwrite` transaction for the whole batch. Every request is issued
|
|
77
|
+
* synchronously inside it (an await on anything else would let the
|
|
78
|
+
* transaction auto-commit), so a failure or a crash mid-way aborts all of
|
|
79
|
+
* it: the per-row MLS store relies on that to keep a checkpoint atomic.
|
|
80
|
+
*/
|
|
81
|
+
async applyBatch(namespace, puts, deletes) {
|
|
82
|
+
if (puts.length === 0 && deletes.length === 0) return;
|
|
83
|
+
const db = await this.dbPromise;
|
|
84
|
+
return new Promise((resolve, reject) => {
|
|
85
|
+
const tx = db.transaction(STORE, "readwrite");
|
|
86
|
+
let settled = false;
|
|
87
|
+
const fail = (e) => {
|
|
88
|
+
if (settled) return;
|
|
89
|
+
settled = true;
|
|
90
|
+
reject(e instanceof Error ? e : new Error(String(e)));
|
|
91
|
+
};
|
|
92
|
+
tx.oncomplete = () => {
|
|
93
|
+
if (!settled) {
|
|
94
|
+
settled = true;
|
|
95
|
+
resolve();
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
tx.onerror = () => fail(tx.error);
|
|
99
|
+
tx.onabort = () => fail(tx.error ?? new Error("applyBatch aborted"));
|
|
100
|
+
try {
|
|
101
|
+
const os = tx.objectStore(STORE);
|
|
102
|
+
for (const [key, value] of puts) os.put({ ns: namespace, key, value });
|
|
103
|
+
for (const key of deletes) os.delete([namespace, key]);
|
|
104
|
+
} catch (e) {
|
|
105
|
+
try {
|
|
106
|
+
tx.abort();
|
|
107
|
+
} catch {
|
|
108
|
+
}
|
|
109
|
+
fail(e);
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
/** Every `[key, value]` under `namespace` with the prefix, in one read. */
|
|
114
|
+
async listEntries(namespace, prefix) {
|
|
115
|
+
const db = await this.dbPromise;
|
|
116
|
+
return new Promise((resolve, reject) => {
|
|
117
|
+
const tx = db.transaction(STORE, "readonly");
|
|
118
|
+
const idx = tx.objectStore(STORE).index("ns");
|
|
119
|
+
const req = idx.openCursor(IDBKeyRange.only(namespace));
|
|
120
|
+
const out = [];
|
|
121
|
+
req.onsuccess = () => {
|
|
122
|
+
const cur = req.result;
|
|
123
|
+
if (!cur) return resolve(out);
|
|
124
|
+
const row = cur.value;
|
|
125
|
+
if (!prefix || row.key.startsWith(prefix)) out.push([row.key, row.value]);
|
|
126
|
+
cur.continue();
|
|
127
|
+
};
|
|
128
|
+
req.onerror = () => reject(req.error);
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
async listKeys(namespace, prefix) {
|
|
132
|
+
const db = await this.dbPromise;
|
|
133
|
+
return new Promise((resolve, reject) => {
|
|
134
|
+
const tx = db.transaction(STORE, "readonly");
|
|
135
|
+
const idx = tx.objectStore(STORE).index("ns");
|
|
136
|
+
const req = idx.openCursor(IDBKeyRange.only(namespace));
|
|
137
|
+
const out = [];
|
|
138
|
+
req.onsuccess = () => {
|
|
139
|
+
const cur = req.result;
|
|
140
|
+
if (!cur) return resolve(out);
|
|
141
|
+
const row = cur.value;
|
|
142
|
+
if (!prefix || row.key.startsWith(prefix)) out.push(row.key);
|
|
143
|
+
cur.continue();
|
|
144
|
+
};
|
|
145
|
+
req.onerror = () => reject(req.error);
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
150
|
+
0 && (module.exports = {
|
|
151
|
+
IndexedDbStorage
|
|
152
|
+
});
|
|
153
|
+
//# sourceMappingURL=indexeddb.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/storage/indexeddb.ts"],"sourcesContent":["// Default IndexedDB-backed Storage implementation. Hosts can supply their own.\n\nimport type { Storage } from \"../types\";\n\nconst DB_NAME = \"ping-sdk\";\nconst DB_VERSION = 1;\nconst STORE = \"kv\";\n\ninterface Row { ns: string; key: string; value: Uint8Array }\n\nfunction open(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const req = indexedDB.open(DB_NAME, DB_VERSION);\n req.onupgradeneeded = () => {\n const db = req.result;\n if (!db.objectStoreNames.contains(STORE)) {\n const os = db.createObjectStore(STORE, { keyPath: [\"ns\", \"key\"] });\n os.createIndex(\"ns\", \"ns\", { unique: false });\n }\n };\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n });\n}\n\nexport class IndexedDbStorage implements Storage {\n private dbPromise: Promise<IDBDatabase>;\n\n constructor() { this.dbPromise = open(); }\n\n async get(namespace: string, key: string): Promise<Uint8Array | null> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readonly\");\n const r = tx.objectStore(STORE).get([namespace, key]);\n r.onsuccess = () => resolve(((r.result as Row | undefined)?.value) ?? null);\n r.onerror = () => reject(r.error);\n });\n }\n\n async put(namespace: string, key: string, value: Uint8Array): Promise<void> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).put({ ns: namespace, key, value } as Row);\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n }\n\n async del(namespace: string, key: string): Promise<void> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).delete([namespace, key]);\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n }\n\n /**\n * One `readwrite` transaction for the whole batch. Every request is issued\n * synchronously inside it (an await on anything else would let the\n * transaction auto-commit), so a failure or a crash mid-way aborts all of\n * it: the per-row MLS store relies on that to keep a checkpoint atomic.\n */\n async applyBatch(\n namespace: string,\n puts: Array<[key: string, value: Uint8Array]>,\n deletes: string[],\n ): Promise<void> {\n if (puts.length === 0 && deletes.length === 0) return;\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\");\n let settled = false;\n const fail = (e: unknown) => {\n if (settled) return;\n settled = true;\n reject(e instanceof Error ? e : new Error(String(e)));\n };\n tx.oncomplete = () => {\n if (!settled) {\n settled = true;\n resolve();\n }\n };\n tx.onerror = () => fail(tx.error);\n tx.onabort = () => fail(tx.error ?? new Error(\"applyBatch aborted\"));\n try {\n const os = tx.objectStore(STORE);\n for (const [key, value] of puts) os.put({ ns: namespace, key, value } as Row);\n for (const key of deletes) os.delete([namespace, key]);\n } catch (e) {\n // A request that throws synchronously (an unserialisable key) does\n // not abort the transaction on its own; the requests already issued\n // would commit. Abort explicitly so the batch stays all-or-nothing.\n try {\n tx.abort();\n } catch {\n // Already aborted or finished.\n }\n fail(e);\n }\n });\n }\n\n /** Every `[key, value]` under `namespace` with the prefix, in one read. */\n async listEntries(\n namespace: string,\n prefix: string,\n ): Promise<Array<[key: string, value: Uint8Array]>> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readonly\");\n const idx = tx.objectStore(STORE).index(\"ns\");\n const req = idx.openCursor(IDBKeyRange.only(namespace));\n const out: Array<[string, Uint8Array]> = [];\n req.onsuccess = () => {\n const cur = req.result;\n if (!cur) return resolve(out);\n const row = cur.value as Row;\n if (!prefix || row.key.startsWith(prefix)) out.push([row.key, row.value]);\n cur.continue();\n };\n req.onerror = () => reject(req.error);\n });\n }\n\n async listKeys(namespace: string, prefix: string): Promise<string[]> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readonly\");\n const idx = tx.objectStore(STORE).index(\"ns\");\n const req = idx.openCursor(IDBKeyRange.only(namespace));\n const out: string[] = [];\n req.onsuccess = () => {\n const cur = req.result;\n if (!cur) return resolve(out);\n const row = cur.value as Row;\n if (!prefix || row.key.startsWith(prefix)) out.push(row.key);\n cur.continue();\n };\n req.onerror = () => reject(req.error);\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,IAAM,UAAU;AAChB,IAAM,aAAa;AACnB,IAAM,QAAQ;AAId,SAAS,OAA6B;AACpC,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,UAAM,MAAM,UAAU,KAAK,SAAS,UAAU;AAC9C,QAAI,kBAAkB,MAAM;AAC1B,YAAM,KAAK,IAAI;AACf,UAAI,CAAC,GAAG,iBAAiB,SAAS,KAAK,GAAG;AACxC,cAAM,KAAK,GAAG,kBAAkB,OAAO,EAAE,SAAS,CAAC,MAAM,KAAK,EAAE,CAAC;AACjE,WAAG,YAAY,MAAM,MAAM,EAAE,QAAQ,MAAM,CAAC;AAAA,MAC9C;AAAA,IACF;AACA,QAAI,YAAY,MAAM,QAAQ,IAAI,MAAM;AACxC,QAAI,UAAU,MAAM,OAAO,IAAI,KAAK;AAAA,EACtC,CAAC;AACH;AAEO,IAAM,mBAAN,MAA0C;AAAA,EACvC;AAAA,EAER,cAAc;AAAE,SAAK,YAAY,KAAK;AAAA,EAAG;AAAA,EAEzC,MAAM,IAAI,WAAmB,KAAyC;AACpE,UAAM,KAAK,MAAM,KAAK;AACtB,WAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,YAAM,KAAK,GAAG,YAAY,OAAO,UAAU;AAC3C,YAAM,IAAI,GAAG,YAAY,KAAK,EAAE,IAAI,CAAC,WAAW,GAAG,CAAC;AACpD,QAAE,YAAY,MAAM,QAAU,EAAE,QAA4B,SAAU,IAAI;AAC1E,QAAE,UAAU,MAAM,OAAO,EAAE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