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

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/dist/worker.cjs CHANGED
@@ -41,6 +41,207 @@ function reserveLinearMemory(memory) {
41
41
  // src/worker.ts
42
42
  var import_ping_wasm = __toESM(require("../wasm/ping_wasm"), 1);
43
43
 
44
+ // src/pending-root-store.ts
45
+ var PENDING_ROOT_WRAP_LABEL = "ping/pending-root-wrap/v1";
46
+ var DB_PREFIX = "ping-pending-root:";
47
+ var STORE = "item";
48
+ var ITEM_KEY = "pending";
49
+ var SEED_LEN = 32;
50
+ var PUBLIC_KEY_LEN = 32;
51
+ var NONCE_LEN = 12;
52
+ var TAG_BITS = 128;
53
+ var WRAPPED_LEN = SEED_LEN + TAG_BITS / 8;
54
+ var PendingStoreUnavailableError = class extends Error {
55
+ constructor() {
56
+ super("the pending store is not available in this realm");
57
+ this.name = "PendingStoreUnavailable";
58
+ }
59
+ };
60
+ var PendingRootExistsError = class extends Error {
61
+ constructor() {
62
+ super("the slot already holds a pending item");
63
+ this.name = "PendingRootExists";
64
+ }
65
+ };
66
+ function pendingRootDatabaseName(slot) {
67
+ return DB_PREFIX + slot;
68
+ }
69
+ function inServiceWorker() {
70
+ const scope = globalThis.ServiceWorkerGlobalScope;
71
+ return typeof scope === "function" && globalThis instanceof scope;
72
+ }
73
+ function realm() {
74
+ const idb = globalThis.indexedDB;
75
+ const subtle = globalThis.crypto?.subtle;
76
+ if (inServiceWorker() || !idb || !subtle) {
77
+ throw new PendingStoreUnavailableError();
78
+ }
79
+ return { idb, subtle };
80
+ }
81
+ function request(req) {
82
+ return new Promise((resolve, reject) => {
83
+ req.onsuccess = () => resolve(req.result);
84
+ req.onerror = () => reject(req.error ?? new Error("IndexedDB request failed"));
85
+ });
86
+ }
87
+ function open(idb, slot) {
88
+ return new Promise((resolve, reject) => {
89
+ const req = idb.open(pendingRootDatabaseName(slot), 1);
90
+ req.onupgradeneeded = () => {
91
+ if (!req.result.objectStoreNames.contains(STORE)) {
92
+ req.result.createObjectStore(STORE);
93
+ }
94
+ };
95
+ req.onsuccess = () => resolve(req.result);
96
+ req.onerror = () => reject(req.error ?? new Error("IndexedDB open failed"));
97
+ req.onblocked = () => reject(new Error("IndexedDB open blocked"));
98
+ });
99
+ }
100
+ function done(tx) {
101
+ return new Promise((resolve, reject) => {
102
+ tx.oncomplete = () => resolve();
103
+ tx.onerror = () => reject(tx.error ?? new Error("IndexedDB transaction failed"));
104
+ tx.onabort = () => reject(tx.error ?? new Error("IndexedDB transaction aborted"));
105
+ });
106
+ }
107
+ function source(bytes) {
108
+ return bytes;
109
+ }
110
+ function isBytes(value, length) {
111
+ return value instanceof Uint8Array && value.length === length;
112
+ }
113
+ function asItem(row) {
114
+ if (typeof row !== "object" || row === null) return null;
115
+ const item = row;
116
+ const key = item.key;
117
+ if (item.v !== 1 || !key || typeof key !== "object") return null;
118
+ if (key.type !== "secret" || key.extractable !== false) return null;
119
+ if (key.algorithm.name !== "AES-GCM" || key.algorithm.length !== 256) {
120
+ return null;
121
+ }
122
+ if (!isBytes(item.iv, NONCE_LEN) || !isBytes(item.ciphertext, WRAPPED_LEN)) return null;
123
+ if (!isBytes(item.rootPublicKey, PUBLIC_KEY_LEN)) return null;
124
+ return item;
125
+ }
126
+ async function associatedData(subtle, rootPublicKey) {
127
+ const label = new TextEncoder().encode(PENDING_ROOT_WRAP_LABEL);
128
+ const userId = new Uint8Array(await subtle.digest("SHA-256", source(rootPublicKey)));
129
+ const out = new Uint8Array(label.length + userId.length);
130
+ out.set(label, 0);
131
+ out.set(userId, label.length);
132
+ return out;
133
+ }
134
+ async function load(idb, slot) {
135
+ if (typeof idb.databases === "function") {
136
+ const names = (await idb.databases()).map((info) => info.name);
137
+ if (!names.includes(pendingRootDatabaseName(slot))) return null;
138
+ }
139
+ const db = await open(idb, slot);
140
+ try {
141
+ const tx = db.transaction(STORE, "readonly");
142
+ const row = await request(tx.objectStore(STORE).get(ITEM_KEY));
143
+ return asItem(row);
144
+ } finally {
145
+ db.close();
146
+ }
147
+ }
148
+ var PendingRootStore = class {
149
+ /**
150
+ * Wrap `seed` and keep it for `slot`, with the root public key and the
151
+ * browser's answer to the persistent-storage request beside it. `seed` is
152
+ * zero-filled before this resolves or rejects.
153
+ *
154
+ * Create-if-absent and atomic: a slot that holds a row (an item, or a row
155
+ * that is not one) rejects with `PendingRootExistsError` and is unchanged.
156
+ */
157
+ async write(slot, seed, rootPublicKey, persistentStorage) {
158
+ const { idb, subtle } = realm();
159
+ try {
160
+ if (!isBytes(seed, SEED_LEN) || !isBytes(rootPublicKey, PUBLIC_KEY_LEN)) {
161
+ throw new Error("pending root: wrong length");
162
+ }
163
+ const key = await subtle.generateKey({ name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
164
+ const iv = globalThis.crypto.getRandomValues(new Uint8Array(NONCE_LEN));
165
+ const publicKey = new Uint8Array(rootPublicKey);
166
+ const additionalData = await associatedData(subtle, publicKey);
167
+ const ciphertext = new Uint8Array(
168
+ await subtle.encrypt(
169
+ { name: "AES-GCM", iv: source(iv), additionalData: source(additionalData), tagLength: TAG_BITS },
170
+ key,
171
+ source(seed)
172
+ )
173
+ );
174
+ const item = {
175
+ v: 1,
176
+ key,
177
+ iv,
178
+ ciphertext,
179
+ rootPublicKey: publicKey,
180
+ persistentStorage: persistentStorage ?? null
181
+ };
182
+ const db = await open(idb, slot);
183
+ try {
184
+ const tx = db.transaction(STORE, "readwrite");
185
+ const added = tx.objectStore(STORE).add(item, ITEM_KEY);
186
+ try {
187
+ await done(tx);
188
+ } catch (failed) {
189
+ if (added.error?.name === "ConstraintError") throw new PendingRootExistsError();
190
+ throw failed;
191
+ }
192
+ } finally {
193
+ db.close();
194
+ }
195
+ } finally {
196
+ seed.fill(0);
197
+ }
198
+ }
199
+ /** The root public key beside the item of `slot`, or `null`. No unwrap. */
200
+ async publicKey(slot) {
201
+ const { idb } = realm();
202
+ const item = await load(idb, slot);
203
+ return item ? new Uint8Array(item.rootPublicKey) : null;
204
+ }
205
+ /**
206
+ * The seed of `slot`, unwrapped, or `null` when the slot holds no item
207
+ * or holds one that does not open with its own key object (a browser has
208
+ * no lock that could make that a passing state: such an item is gone).
209
+ * The caller zero-fills what it is given.
210
+ */
211
+ async read(slot) {
212
+ const { idb, subtle } = realm();
213
+ const item = await load(idb, slot);
214
+ if (!item) return null;
215
+ const additionalData = await associatedData(subtle, item.rootPublicKey);
216
+ try {
217
+ const seed = await subtle.decrypt(
218
+ { name: "AES-GCM", iv: source(item.iv), additionalData: source(additionalData), tagLength: TAG_BITS },
219
+ item.key,
220
+ source(item.ciphertext)
221
+ );
222
+ return new Uint8Array(seed);
223
+ } catch {
224
+ return null;
225
+ }
226
+ }
227
+ /** Delete the item of `slot`: the ciphertext and the key object, and their database. */
228
+ async del(slot) {
229
+ const { idb } = realm();
230
+ await new Promise((resolve, reject) => {
231
+ const req = idb.deleteDatabase(pendingRootDatabaseName(slot));
232
+ req.onsuccess = () => resolve();
233
+ req.onerror = () => reject(req.error ?? new Error("IndexedDB delete failed"));
234
+ req.onblocked = () => reject(new Error("IndexedDB delete blocked"));
235
+ });
236
+ }
237
+ /** The browser's answer to the persistent-storage request recorded beside the item, or `null`. */
238
+ async persistentStorage(slot) {
239
+ const { idb } = realm();
240
+ const item = await load(idb, slot);
241
+ return item ? item.persistentStorage : null;
242
+ }
243
+ };
244
+
44
245
  // src/epoch-events.ts
45
246
  function conversationKey(id) {
46
247
  let out = "";
@@ -180,6 +381,51 @@ var RequestScheduler = class {
180
381
  // src/worker.ts
181
382
  var client = null;
182
383
  var wasmReady = null;
384
+ var pendingRootStore = null;
385
+ var setupSession = null;
386
+ var ranAccountSetup = false;
387
+ function accountWorker() {
388
+ if (client) throw new Error("account refused: client-worker");
389
+ ranAccountSetup = true;
390
+ }
391
+ var ACCOUNT_LOCK_NAME = "ping-account-operations";
392
+ function accountExclusive(run) {
393
+ accountWorker();
394
+ const locks = globalThis.navigator?.locks;
395
+ if (!locks || typeof locks.request !== "function") {
396
+ return Promise.reject(new Error("account refused: pending-store-unavailable"));
397
+ }
398
+ return locks.request(ACCOUNT_LOCK_NAME, run);
399
+ }
400
+ function pendingStore() {
401
+ accountWorker();
402
+ pendingRootStore ??= new PendingRootStore();
403
+ return pendingRootStore;
404
+ }
405
+ function openSession() {
406
+ accountWorker();
407
+ if (!setupSession) throw new Error("account refused: setup-session-ended");
408
+ return setupSession;
409
+ }
410
+ function clientWorker() {
411
+ if (ranAccountSetup) {
412
+ throw new Error("this worker ran account set-up: a client starts in a worker of its own");
413
+ }
414
+ }
415
+ var tabClient = false;
416
+ function rotationBuild(run) {
417
+ const running = client;
418
+ if (!running) return Promise.reject(new Error("account refused: no-client"));
419
+ if (!tabClient) return Promise.reject(new Error("account refused: background-worker"));
420
+ const locks = globalThis.navigator?.locks;
421
+ if (!locks || typeof locks.request !== "function") {
422
+ return Promise.reject(new Error("account refused: pending-store-unavailable"));
423
+ }
424
+ return locks.request(ACCOUNT_LOCK_NAME, () => run(running));
425
+ }
426
+ function wipe(bytes) {
427
+ if (bytes instanceof Uint8Array) bytes.fill(0);
428
+ }
183
429
  var pendingStorage = /* @__PURE__ */ new Map();
184
430
  var pendingTransport = /* @__PURE__ */ new Map();
185
431
  var nextStorageId = 1;
@@ -222,7 +468,28 @@ function makeProxyTransport(features) {
222
468
  return {
223
469
  ...proxyTransport,
224
470
  ...features.fetchLogSince ? { fetchLogSince: fetchLogSinceProxy } : {},
225
- ...features.fetchLogHeads ? { fetchLogHeads: fetchLogHeadsProxy } : {}
471
+ ...features.fetchLogHeads ? { fetchLogHeads: fetchLogHeadsProxy } : {},
472
+ // Self-admission: declared only when the host has them, like the two
473
+ // above (absent, the wasm bridge answers the core's default: no route).
474
+ ...features.sendExternalCommit ? {
475
+ sendExternalCommit: (envelope) => callMain("transport", "sendExternalCommit", [envelope])
476
+ } : {},
477
+ ...features.fetchSelfAdmissionStates ? {
478
+ fetchSelfAdmissionStates: (conversations, unusable) => callMain("transport", "fetchSelfAdmissionStates", [conversations, unusable ?? []])
479
+ } : {},
480
+ ...features.fetchSealedGroupInfos ? {
481
+ fetchSealedGroupInfos: (conversations) => callMain("transport", "fetchSealedGroupInfos", [conversations])
482
+ } : {},
483
+ ...features.sendExternalCommits ? {
484
+ sendExternalCommits: (envelopes) => callMain("transport", "sendExternalCommits", [envelopes])
485
+ } : {},
486
+ // The publishing half (ruling V320), declared like the four.
487
+ ...features.fetchSealingStatements ? {
488
+ fetchSealingStatements: (accounts, conversation) => callMain("transport", "fetchSealingStatements", [accounts, conversation])
489
+ } : {},
490
+ ...features.publishSealedGroupInfo ? {
491
+ publishSealedGroupInfo: (publication) => callMain("transport", "publishSealedGroupInfo", [publication])
492
+ } : {}
226
493
  };
227
494
  }
228
495
  function callMain(kind, method, args) {
@@ -257,13 +524,15 @@ var EPOCH_ADVANCING_REQUESTS = /* @__PURE__ */ new Set([
257
524
  "revokeDevice",
258
525
  "removeDeviceEverywhere",
259
526
  "removeOwnDevicesExcept",
527
+ "addRestoredDevice",
260
528
  "syncConversations",
261
529
  "syncConversation",
262
- "consumeLinkingTicket",
530
+ "completeDeviceLink",
531
+ "recreateDeviceGroup",
263
532
  "importStateSnapshot"
264
533
  ]);
265
534
  var EPOCH_UPKEEP_REQUESTS = /* @__PURE__ */ new Set([
266
- "buildLinkingTicket"
535
+ "buildLinkingTicketV3For"
267
536
  ]);
268
537
  function readMeta(id) {
269
538
  if (!client) return null;
@@ -309,11 +578,11 @@ function refreshCached(ids) {
309
578
  const metas = readMetas(ids);
310
579
  const held = [];
311
580
  const dropped = [];
312
- const done = /* @__PURE__ */ new Set();
581
+ const done2 = /* @__PURE__ */ new Set();
313
582
  for (const id of ids) {
314
583
  const key = conversationKey(id);
315
- if (done.has(key)) continue;
316
- done.add(key);
584
+ if (done2.has(key)) continue;
585
+ done2.add(key);
317
586
  const meta = metas.get(key) ?? null;
318
587
  if (meta !== null) held.push(meta);
319
588
  else dropped.push(id);
@@ -547,34 +816,49 @@ function catchUpPassStepper(msg) {
547
816
  return pass();
548
817
  };
549
818
  }
819
+ var PHRASE_KINDS = /* @__PURE__ */ new Set([
820
+ "makeBackup",
821
+ "proveBackup",
822
+ "openBackupForRestore",
823
+ "restoreTakeOver",
824
+ "restoreJoin",
825
+ "setupSessionMakeBackup",
826
+ "setupSessionProveBackup"
827
+ ]);
550
828
  async function dispatch(msg) {
829
+ if (!PHRASE_KINDS.has(msg.kind)) return dispatchRequest(msg);
830
+ const carried = msg;
831
+ if (!(carried.phrase instanceof Uint8Array)) carried.phrase = new Uint8Array();
832
+ const phrase = carried.phrase;
833
+ try {
834
+ return await dispatchRequest(msg);
835
+ } finally {
836
+ wipe(phrase);
837
+ }
838
+ }
839
+ async function dispatchRequest(msg) {
551
840
  await ensureWasm();
552
841
  switch (msg.kind) {
553
- case "init": {
842
+ case "initFromDeviceRecord": {
843
+ clientWorker();
554
844
  transportFeatures = msg.transportFeatures ?? { fetchLogSince: false, fetchLogHeads: false };
555
- client = await import_ping_wasm.PingClient.init(
556
- msg.identityExport,
845
+ client = await import_ping_wasm.PingClient.initFromDeviceRecord(
557
846
  msg.deviceLabel,
558
847
  makeProxyStorage(msg.storageFeatures),
559
848
  makeProxyTransport(transportFeatures),
560
849
  msg.nowMs,
561
- // Optional Ed25519 device signing secret — see protocol.ts
562
- // and ClientConfig.deviceSigningSecretKey. Forwarding `null`
563
- // explicitly when absent so the wasm-bindgen `Option<Vec<u8>>`
564
- // shape is matched correctly.
565
850
  msg.deviceSigningSecretKey ?? null,
566
- // The owner each conversation's FIRST roles write must name
567
- // (2026-11-04, round 2); `null` for none.
568
851
  msg.expectedOwners ?? null
569
852
  );
853
+ tabClient = msg.tabClient === true;
570
854
  client.onMessage((m) => {
571
855
  self.postMessage({ kind: "event.message", msg: m });
572
856
  });
573
857
  return null;
574
858
  }
575
- case "openReadOnly": {
576
- client = await import_ping_wasm.PingClient.openReadOnly(
577
- msg.identityExport,
859
+ case "openReadOnlyFromDeviceRecord": {
860
+ clientWorker();
861
+ client = await import_ping_wasm.PingClient.openReadOnlyFromDeviceRecord(
578
862
  msg.deviceLabel,
579
863
  makeProxyStorage(msg.storageFeatures),
580
864
  proxyTransport,
@@ -582,6 +866,318 @@ async function dispatch(msg) {
582
866
  );
583
867
  return null;
584
868
  }
869
+ // The device link under the root design. `beginDeviceLink` starts a NEW
870
+ // device's staging client: the wasm draws the device key, and the client
871
+ // it answers becomes this worker's client until the link is complete.
872
+ case "beginDeviceLink": {
873
+ clientWorker();
874
+ transportFeatures = msg.transportFeatures ?? { fetchLogSince: false, fetchLogHeads: false };
875
+ const begun = await (0, import_ping_wasm.beginDeviceLink)(
876
+ msg.deviceLabel,
877
+ makeProxyStorage(msg.storageFeatures),
878
+ makeProxyTransport(transportFeatures),
879
+ msg.nowMs
880
+ );
881
+ try {
882
+ client = begun.takeClient();
883
+ client.onMessage((m) => {
884
+ self.postMessage({ kind: "event.message", msg: m });
885
+ });
886
+ return {
887
+ payload: begun.payload,
888
+ deviceId: begun.deviceId,
889
+ deviceSigningSecretKey: begun.deviceSigningSecretKey,
890
+ hpkeSecretKey: begun.hpkeSecretKey
891
+ };
892
+ } finally {
893
+ begun.free();
894
+ }
895
+ }
896
+ case "buildLinkingTicketV3For":
897
+ return await ensureClient().buildLinkingTicketV3For(
898
+ msg.payload,
899
+ msg.expectedCode,
900
+ msg.expectedQr,
901
+ msg.lastAppEvents,
902
+ msg.nowMs
903
+ );
904
+ case "linkGenerationFor":
905
+ return ensureClient().linkGenerationFor(msg.payload, msg.expectedCode, msg.expectedQr);
906
+ case "recreateDeviceGroup":
907
+ await ensureClient().recreateDeviceGroup(msg.nowMs);
908
+ return null;
909
+ // The rotation in a client's Worker. The plan, the answer and the
910
+ // adoption touch no root; the two builds open it for the length of the
911
+ // call (see `rotationBuild` above).
912
+ case "rotateGenerationWithPending":
913
+ return await rotationBuild((running) => running.rotateGenerationWithPending(
914
+ // The SDK's own store, for this one call: never a host's object.
915
+ new PendingRootStore(),
916
+ msg.slot,
917
+ msg.start,
918
+ msg.devices,
919
+ msg.kept,
920
+ msg.reason,
921
+ msg.accountId,
922
+ msg.hostState,
923
+ msg.nowMs
924
+ ));
925
+ case "rotateGenerationWithBackup": {
926
+ try {
927
+ if (!(msg.phrase instanceof Uint8Array)) throw new Error("account refused: invalid-phrase");
928
+ if (msg.newPhrase !== void 0 && !(msg.newPhrase instanceof Uint8Array)) {
929
+ throw new Error("account refused: invalid-phrase");
930
+ }
931
+ return await rotationBuild((running) => running.rotateGenerationWithBackup(
932
+ msg.rootPart,
933
+ msg.phrase,
934
+ msg.newPhrase,
935
+ msg.start,
936
+ msg.devices,
937
+ msg.kept,
938
+ msg.reason,
939
+ msg.accountId,
940
+ msg.hostState,
941
+ msg.nowMs
942
+ ));
943
+ } finally {
944
+ wipe(msg.phrase);
945
+ wipe(msg.newPhrase);
946
+ }
947
+ }
948
+ case "planRotation":
949
+ return await ensureClient().planRotation(msg.start, msg.devices, msg.rootPartGeneration);
950
+ case "completeRotationOnClient":
951
+ return await ensureClient().completeRotation(msg.recordId, msg.answer);
952
+ case "adoptGeneration":
953
+ return await ensureClient().adoptGeneration(
954
+ msg.generation,
955
+ msg.credential,
956
+ msg.gsWrap,
957
+ msg.statement,
958
+ msg.nowMs
959
+ );
960
+ case "completeDeviceLink":
961
+ return await ensureClient().completeDeviceLink(
962
+ msg.ticket,
963
+ msg.generation,
964
+ msg.generationSecret,
965
+ msg.nowMs
966
+ );
967
+ case "sealLinkingTicketV3For":
968
+ return (0, import_ping_wasm.sealLinkingTicketV3For)(msg.ticket, msg.payload, msg.expectedCode, msg.expectedQr);
969
+ case "openLinkingTicketV3":
970
+ return (0, import_ping_wasm.openLinkingTicketV3)(msg.sealed, msg.newDevicePriv);
971
+ case "heldCredential":
972
+ return ensureClient().heldCredential();
973
+ case "heldGeneration":
974
+ return ensureClient().heldGeneration();
975
+ // Account set-up and the first backup: see the note at the top of this
976
+ // file. The store is asked for FIRST, so a client's worker refuses
977
+ // before anything else runs.
978
+ case "createAccount": {
979
+ return accountExclusive(async () => {
980
+ const store = pendingStore();
981
+ return (0, import_ping_wasm.createAccount)(
982
+ makeProxyStorage(msg.storageFeatures),
983
+ store,
984
+ msg.slot,
985
+ msg.identityState,
986
+ msg.persistentStorage,
987
+ msg.nowMs
988
+ );
989
+ });
990
+ }
991
+ case "pendingStatus": {
992
+ const store = pendingStore();
993
+ return (0, import_ping_wasm.pendingStatus)(
994
+ makeProxyStorage(msg.storageFeatures),
995
+ store,
996
+ msg.slot
997
+ );
998
+ }
999
+ case "makeBackup": {
1000
+ return accountExclusive(async () => {
1001
+ const store = pendingStore();
1002
+ return (0, import_ping_wasm.makeBackup)(
1003
+ makeProxyStorage(msg.storageFeatures),
1004
+ store,
1005
+ msg.slot,
1006
+ msg.phrase,
1007
+ msg.accountId,
1008
+ msg.hostState,
1009
+ msg.nowMs
1010
+ );
1011
+ });
1012
+ }
1013
+ case "proveBackup": {
1014
+ return accountExclusive(async () => {
1015
+ accountWorker();
1016
+ return (0, import_ping_wasm.proveBackup)(
1017
+ makeProxyStorage(msg.storageFeatures),
1018
+ msg.readBackRootPart,
1019
+ msg.phrase
1020
+ );
1021
+ });
1022
+ }
1023
+ case "endPending": {
1024
+ return accountExclusive(async () => {
1025
+ const store = pendingStore();
1026
+ await (0, import_ping_wasm.endPending)(
1027
+ makeProxyStorage(msg.storageFeatures),
1028
+ store,
1029
+ msg.slot,
1030
+ msg.fingerprint
1031
+ );
1032
+ return null;
1033
+ });
1034
+ }
1035
+ // The restore as a rotation: the same Worker that never runs a client.
1036
+ case "openBackupForRestore": {
1037
+ accountWorker();
1038
+ return (0, import_ping_wasm.openBackupForRestore)(msg.rootPart, msg.phrase, msg.statePart, msg.pinnedRootPublicKey);
1039
+ }
1040
+ case "restoreTakeOver": {
1041
+ return accountExclusive(async () => {
1042
+ accountWorker();
1043
+ return (0, import_ping_wasm.restoreTakeOver)(
1044
+ makeProxyStorage(msg.storageFeatures),
1045
+ msg.rootPart,
1046
+ msg.phrase,
1047
+ msg.start,
1048
+ msg.oldStatePart,
1049
+ msg.accountId,
1050
+ msg.hostState,
1051
+ msg.nowMs
1052
+ );
1053
+ });
1054
+ }
1055
+ case "takeAccountBack": {
1056
+ return accountExclusive(async () => {
1057
+ const store = pendingStore();
1058
+ return (0, import_ping_wasm.takeAccountBack)(
1059
+ makeProxyStorage(msg.storageFeatures),
1060
+ store,
1061
+ msg.slot,
1062
+ msg.start,
1063
+ msg.oldStatePart,
1064
+ msg.accountId,
1065
+ msg.hostState,
1066
+ msg.nowMs
1067
+ );
1068
+ });
1069
+ }
1070
+ case "resumeRotation": {
1071
+ accountWorker();
1072
+ if (msg.nowMs === void 0) {
1073
+ return (0, import_ping_wasm.resumeRotation)(makeProxyStorage(msg.storageFeatures));
1074
+ }
1075
+ return (0, import_ping_wasm.resumeRotationAt)(makeProxyStorage(msg.storageFeatures), msg.nowMs);
1076
+ }
1077
+ case "completeRotation": {
1078
+ return accountExclusive(async () => {
1079
+ accountWorker();
1080
+ return (0, import_ping_wasm.completeRotation)(
1081
+ makeProxyStorage(msg.storageFeatures),
1082
+ msg.recordId,
1083
+ msg.answer
1084
+ );
1085
+ });
1086
+ }
1087
+ case "setRotationPhase": {
1088
+ return accountExclusive(async () => {
1089
+ accountWorker();
1090
+ await (0, import_ping_wasm.setRotationPhase)(makeProxyStorage(msg.storageFeatures), msg.recordId, msg.phase);
1091
+ return null;
1092
+ });
1093
+ }
1094
+ case "finishRotation": {
1095
+ return accountExclusive(async () => {
1096
+ accountWorker();
1097
+ await (0, import_ping_wasm.finishRotation)(makeProxyStorage(msg.storageFeatures), msg.recordId);
1098
+ return null;
1099
+ });
1100
+ }
1101
+ case "abandonRotation": {
1102
+ return accountExclusive(async () => {
1103
+ accountWorker();
1104
+ await (0, import_ping_wasm.abandonRotation)(makeProxyStorage(msg.storageFeatures), msg.recordId);
1105
+ return null;
1106
+ });
1107
+ }
1108
+ case "rotationRecordState": {
1109
+ accountWorker();
1110
+ return (0, import_ping_wasm.rotationRecordState)(makeProxyStorage(msg.storageFeatures));
1111
+ }
1112
+ case "restoreJoin": {
1113
+ return accountExclusive(async () => {
1114
+ accountWorker();
1115
+ return (0, import_ping_wasm.restoreJoin)(
1116
+ makeProxyStorage(msg.storageFeatures),
1117
+ msg.rootPart,
1118
+ msg.phrase,
1119
+ msg.statePart,
1120
+ msg.start,
1121
+ msg.nowMs
1122
+ );
1123
+ });
1124
+ }
1125
+ case "openStateBackup": {
1126
+ accountWorker();
1127
+ return (0, import_ping_wasm.openStateBackup)(makeProxyStorage(msg.storageFeatures), msg.statePart);
1128
+ }
1129
+ case "refreshStateBackup": {
1130
+ return accountExclusive(async () => {
1131
+ accountWorker();
1132
+ return (0, import_ping_wasm.refreshStateBackup)(
1133
+ makeProxyStorage(msg.storageFeatures),
1134
+ msg.accountId,
1135
+ msg.hostState,
1136
+ msg.nowMs
1137
+ );
1138
+ });
1139
+ }
1140
+ case "beginAccountSetupInMemory": {
1141
+ accountWorker();
1142
+ if (setupSession) throw new Error("account refused: setup-session-open");
1143
+ setupSession = (0, import_ping_wasm.beginAccountSetupInMemory)(msg.identityState, msg.nowMs);
1144
+ return null;
1145
+ }
1146
+ case "setupSessionMakeBackup":
1147
+ return openSession().makeBackup(msg.phrase, msg.accountId, msg.hostState, msg.nowMs);
1148
+ case "setupSessionProveBackup":
1149
+ return openSession().proveBackup(msg.readBackRootPart, msg.phrase);
1150
+ case "setupSessionFinish": {
1151
+ return accountExclusive(async () => {
1152
+ const session = openSession();
1153
+ const made = await session.finish(makeProxyStorage(msg.storageFeatures));
1154
+ session.free();
1155
+ setupSession = null;
1156
+ return made;
1157
+ });
1158
+ }
1159
+ case "setupSessionKeepAsPending": {
1160
+ return accountExclusive(async () => {
1161
+ const session = openSession();
1162
+ const store = pendingStore();
1163
+ const made = await session.keepAsPending(
1164
+ makeProxyStorage(msg.storageFeatures),
1165
+ store,
1166
+ msg.slot,
1167
+ msg.persistentStorage
1168
+ );
1169
+ session.free();
1170
+ setupSession = null;
1171
+ return made;
1172
+ });
1173
+ }
1174
+ case "endAccountSetupSession": {
1175
+ if (setupSession) {
1176
+ setupSession.free();
1177
+ setupSession = null;
1178
+ }
1179
+ return null;
1180
+ }
585
1181
  case "previewEnvelope":
586
1182
  return ensureClient().previewEnvelope(msg.envelope, msg.nowMs);
587
1183
  case "previewEnvelopeWithPrerequisites":
@@ -590,16 +1186,8 @@ async function dispatch(msg) {
590
1186
  msg.envelope,
591
1187
  msg.nowMs
592
1188
  );
593
- case "generateIdentity":
594
- return import_ping_wasm.PingClient.generateIdentity();
595
1189
  case "userId":
596
1190
  return ensureClient().userId();
597
- case "exportIdentity":
598
- return ensureClient().exportIdentity();
599
- case "rotateIdentity":
600
- return await ensureClient().rotateIdentity(msg.newIdentityExport, msg.nowMs);
601
- case "rotateIdentityRetry":
602
- return await ensureClient().rotateIdentityRetry(msg.conv, msg.nowMs);
603
1191
  case "deviceId":
604
1192
  return ensureClient().deviceId();
605
1193
  case "suspendStorage":
@@ -688,6 +1276,9 @@ async function dispatch(msg) {
688
1276
  return await ensureClient().removeDeviceEverywhere(msg.deviceId, msg.nowMs);
689
1277
  case "removeOwnDevicesExcept":
690
1278
  return await ensureClient().removeOwnDevicesExcept(msg.keep, msg.listed, msg.nowMs);
1279
+ case "addRestoredDevice":
1280
+ await ensureClient().addRestoredDevice(msg.deviceId, msg.keyPackage, msg.nowMs);
1281
+ return null;
691
1282
  case "processEnvelope": {
692
1283
  const result = await ensureClient().processEnvelope(msg.envelope, msg.nowMs);
693
1284
  postConversationEvent(
@@ -710,6 +1301,20 @@ async function dispatch(msg) {
710
1301
  // (the wasm does not fan them out through `onMessage`); the main thread
711
1302
  // delivers them from the result. Conversation updates are announced from
712
1303
  // the core's exact `updated` list, before the result resolves.
1304
+ // Self-admission (ruling V273): every refusal is a value of the answer.
1305
+ case "selfAdmit":
1306
+ return ensureClient().selfAdmit(
1307
+ msg.conv,
1308
+ msg.fetched.blob,
1309
+ msg.fetched.wrap,
1310
+ msg.fetched.wrapCount,
1311
+ msg.fetched.currentEpoch,
1312
+ msg.nowMs
1313
+ );
1314
+ case "selfAdmitMany":
1315
+ return ensureClient().selfAdmitMany(msg.first, msg.conversations, msg.nowMs);
1316
+ case "clientRefreshStateBackup":
1317
+ return ensureClient().refreshStateBackup(msg.accountId, msg.hostState, msg.nowMs);
713
1318
  case "processSequencedBatch": {
714
1319
  const raw = await ensureClient().processSequencedBatch(msg.items, msg.nowMs);
715
1320
  announceUpdated(raw.updated, welcomeSenders(msg.items, raw.joined), raw.removed);
@@ -726,6 +1331,10 @@ async function dispatch(msg) {
726
1331
  return ensureClient().logPosition(msg.conv);
727
1332
  case "adoptLogPosition":
728
1333
  return await ensureClient().adoptLogPosition(msg.conv, msg.epoch, msg.serverSeq);
1334
+ case "logHoles":
1335
+ return ensureClient().logHoles(msg.conv);
1336
+ case "resolveLogHole":
1337
+ return await ensureClient().resolveLogHole(msg.conv, msg.fromServerSeq, msg.toServerSeq);
729
1338
  case "conversationsBehind":
730
1339
  return ensureClient().conversationsBehind(msg.heads);
731
1340
  case "heldFrameCount":
@@ -743,16 +1352,8 @@ async function dispatch(msg) {
743
1352
  }
744
1353
  return null;
745
1354
  }
746
- case "buildLinkingTicket":
747
- return await ensureClient().buildLinkingTicket(
748
- msg.newDeviceId,
749
- msg.newDeviceKp,
750
- msg.lastAppEvents,
751
- msg.nowMs
752
- );
753
- case "consumeLinkingTicket":
754
- await ensureClient().consumeLinkingTicket(msg.ticket, msg.nowMs);
755
- return null;
1355
+ case "linkHandshakePayload":
1356
+ return ensureClient().linkHandshakePayload(msg.hpkePublicKey, msg.keyPackage);
756
1357
  case "decodeCatchupSnapshot":
757
1358
  return (0, import_ping_wasm.decodeCatchupSnapshot)(msg.snapshotBytes);
758
1359
  case "exportConversationSecret":
@@ -769,10 +1370,18 @@ async function dispatch(msg) {
769
1370
  msg.context,
770
1371
  msg.length
771
1372
  );
772
- case "sealLinkingTicket":
773
- return (0, import_ping_wasm.sealLinkingTicket)(msg.ticket, msg.newDevicePub);
774
- case "openLinkingTicket":
775
- return (0, import_ping_wasm.openLinkingTicket)(msg.sealed, msg.newDevicePriv);
1373
+ // The link handshake commitment (2026-11-25): pure WASM, no client state.
1374
+ // Each call that acts on a handshake verifies it inside the call.
1375
+ case "linkCommitment":
1376
+ return (0, import_ping_wasm.linkCommitment)(msg.payload);
1377
+ case "normalizeLinkCode":
1378
+ return (0, import_ping_wasm.normalizeLinkCode)(msg.typed);
1379
+ case "linkQrCommitment":
1380
+ return (0, import_ping_wasm.linkQrCommitment)(msg.qrText);
1381
+ case "verifyLinkHandshake":
1382
+ return (0, import_ping_wasm.verifyLinkHandshake)(msg.payload, msg.expectedCode, msg.expectedQr);
1383
+ case "sealLinkAuthFor":
1384
+ return (0, import_ping_wasm.sealLinkAuthFor)(msg.plaintext, msg.payload, msg.expectedCode, msg.expectedQr);
776
1385
  case "hpkeSeal":
777
1386
  return (0, import_ping_wasm.hpkeSeal)(msg.plaintext, msg.recipientPub, msg.info);
778
1387
  case "hpkeOpen":
@@ -784,10 +1393,6 @@ async function dispatch(msg) {
784
1393
  case "hpkeGenerateKeypair":
785
1394
  return (0, import_ping_wasm.hpkeGenerateKeypair)();
786
1395
  // Post-quantum (X-Wing) twins: all pure WASM, no client state required.
787
- case "sealLinkingTicketPq":
788
- return (0, import_ping_wasm.sealLinkingTicketPq)(msg.ticket, msg.newDevicePub);
789
- case "openLinkingTicketPq":
790
- return (0, import_ping_wasm.openLinkingTicketPq)(msg.sealed, msg.newDevicePriv);
791
1396
  case "hpkeSealPq":
792
1397
  return (0, import_ping_wasm.hpkeSealPq)(msg.plaintext, msg.recipientPub, msg.info);
793
1398
  case "hpkeOpenPq":
@@ -806,8 +1411,8 @@ async function dispatch(msg) {
806
1411
  return (0, import_ping_wasm.hpkePublicKeyFromPrivate)(msg.privateKey);
807
1412
  case "signDeviceReauth":
808
1413
  return (0, import_ping_wasm.signDeviceReauth)(msg.deviceSigningSecretKey, msg.challengeId, msg.nonce, msg.accountId, msg.audience);
809
- case "signDeviceLinkApproval":
810
- return (0, import_ping_wasm.signDeviceLinkApproval)(msg.deviceSigningSecretKey, msg.approvalSessionId, msg.accountId, msg.newDevicePubkey, msg.audience);
1414
+ case "signDeviceLinkApprovalFor":
1415
+ return (0, import_ping_wasm.signDeviceLinkApprovalFor)(msg.deviceSigningSecretKey, msg.approvalSessionId, msg.accountId, msg.payload, msg.expectedCode, msg.expectedQr, msg.audience);
811
1416
  case "signDeviceLinkPossession":
812
1417
  return (0, import_ping_wasm.signDeviceLinkPossession)(msg.deviceSigningSecretKey, msg.approvalSessionId, msg.accountId, msg.audience);
813
1418
  case "exportConversationStateSnapshot":
@@ -817,32 +1422,44 @@ async function dispatch(msg) {
817
1422
  // Recovery — all pure WASM; no client state required.
818
1423
  case "generateMnemonicPhrase":
819
1424
  return (0, import_ping_wasm.generateMnemonicPhrase)();
1425
+ case "selfAdmissionCompiled":
1426
+ return (0, import_ping_wasm.selfAdmissionCompiled)();
820
1427
  case "normalizeMnemonicPhrase":
821
1428
  return (0, import_ping_wasm.normalizeMnemonicPhrase)(msg.phrase);
822
- case "encryptBackup":
823
- return (0, import_ping_wasm.encryptBackup)(
824
- msg.mnemonicPhrase,
825
- msg.accountId,
826
- msg.identityExport,
827
- msg.deviceGroupSnapshot,
828
- // Map idiomatic camelCase → the snake_case keys serde expects on the
829
- // WASM boundary (matches the decrypt view's account_id / group_state_bytes).
830
- msg.conversationSnapshots.map((c) => ({
831
- conversation_id: c.conversationId,
832
- group_state_bytes: c.groupStateBytes
833
- })),
834
- msg.createdAtMs
1429
+ case "checkBackupPhrase":
1430
+ return (0, import_ping_wasm.checkBackupPhrase)(msg.blob, msg.mnemonicPhrase);
1431
+ // History, version 3 (rulings V88 to V92). The raw-key, seed-signed seals
1432
+ // and opens are gone: every call below runs in the client, which verifies
1433
+ // the recipient in its own tree (or the link handshake against what this
1434
+ // device was shown) before anything is signed or sealed.
1435
+ case "historyDeliveryKeyNextCounter":
1436
+ return await ensureClient().historyDeliveryKeyNextCounter(msg.counterFloor);
1437
+ case "publishHistoryDeliveryKey":
1438
+ return await ensureClient().publishHistoryDeliveryKey(msg.counterFloor);
1439
+ case "adoptHistoryDeliveryKeyCounter":
1440
+ return await ensureClient().adoptHistoryDeliveryKeyCounter(msg.stored);
1441
+ case "sealHistoryBundleV3":
1442
+ return await ensureClient().sealHistoryBundleV3(msg.bundle, msg.recipient, msg.ownAccount);
1443
+ case "sealLinkHistoryBundle":
1444
+ return ensureClient().sealLinkHistoryBundle(
1445
+ msg.bundle,
1446
+ msg.payload,
1447
+ msg.expectedCode,
1448
+ msg.expectedQr
835
1449
  );
836
- case "decryptBackup":
837
- return (0, import_ping_wasm.decryptBackup)(msg.blob, msg.mnemonicPhrase);
838
- case "sealHistoryBundle":
839
- return (0, import_ping_wasm.sealHistoryBundle)(msg.bundle, msg.recipientPub, msg.senderIdentitySecret);
840
- case "openHistoryBundle":
841
- return (0, import_ping_wasm.openHistoryBundle)(msg.sealed, msg.recipientPriv, msg.senderIdentityPub);
842
- case "sealHistoryBundlePq":
843
- return (0, import_ping_wasm.sealHistoryBundlePq)(msg.bundle, msg.recipientPub, msg.senderIdentitySecret);
844
- case "openHistoryBundlePq":
845
- return (0, import_ping_wasm.openHistoryBundlePq)(msg.sealed, msg.recipientPriv, msg.senderIdentityPub);
1450
+ case "openHistoryBundleV3":
1451
+ return await ensureClient().openHistoryBundleV3(msg.sealed, msg.ownAccount);
1452
+ case "openLinkHistoryBundle":
1453
+ return await ensureClient().openLinkHistoryBundle(msg.sealed, msg.recipientPriv);
1454
+ case "confirmHistoryImport":
1455
+ return await ensureClient().confirmHistoryImport(msg.importId);
1456
+ case "historyTrust":
1457
+ return await ensureClient().historyTrust(msg.deviceId);
1458
+ case "recordHistoryShipped":
1459
+ await ensureClient().recordHistoryShipped(msg.deviceId);
1460
+ return null;
1461
+ case "historyShipDecision":
1462
+ return await ensureClient().historyShipDecision(msg.deviceId);
846
1463
  default:
847
1464
  throw new Error(`unknown request kind: ${msg.kind}`);
848
1465
  }