@ping-app/ping-openmls-sdk 0.10.3 → 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/index.js CHANGED
@@ -202,7 +202,8 @@ function logHeadToWire(h) {
202
202
  return {
203
203
  conversation_id: h.conversationId,
204
204
  head_server_seq: h.headServerSeq,
205
- head_epoch: h.headEpoch
205
+ head_epoch: h.headEpoch,
206
+ ...h.sealedGroupInfoWanted === true ? { sealed_group_info_wanted: true } : {}
206
207
  };
207
208
  }
208
209
  function logGapFromWire(g) {
@@ -248,13 +249,45 @@ function bufferOverflowFromWire(o) {
248
249
  dropped: o.dropped
249
250
  };
250
251
  }
252
+ function selfAdmissionFromWire(a) {
253
+ return {
254
+ conversationId: a.conversation_id,
255
+ identity: a.identity,
256
+ deviceId: a.device_id,
257
+ replacedOwnLeaf: a.replaced_own_leaf,
258
+ ownAccount: a.own_account,
259
+ epoch: a.epoch
260
+ };
261
+ }
262
+ function logHoleFromWire(h) {
263
+ return {
264
+ conversationId: h.conversation_id,
265
+ fromServerSeq: h.from_server_seq,
266
+ toServerSeq: h.to_server_seq,
267
+ reason: variant(h.reason),
268
+ contentHashes: h.content_hashes.map((c) => Uint8Array.from(c)),
269
+ kept: h.kept
270
+ };
271
+ }
272
+ function logAckFromWire(a) {
273
+ return { conversationId: a.conversation_id, serverSeq: a.server_seq };
274
+ }
275
+ function journalFullAtFromWire(j) {
276
+ return { conversationId: j.conversation_id, serverSeq: j.server_seq, rows: j.rows };
277
+ }
251
278
  function outcomesFromWire(r) {
252
279
  return {
253
280
  removed: (r.removed ?? []).map(conversationRemovalFromWire),
254
281
  welcomeFailures: (r.welcome_failures ?? []).map(welcomeFailureFromWire),
255
282
  stranded: (r.stranded ?? []).map(strandedConversationFromWire),
256
283
  proposalsPending: r.proposals_pending ?? [],
257
- overflow: (r.overflow ?? []).map(bufferOverflowFromWire)
284
+ overflow: (r.overflow ?? []).map(bufferOverflowFromWire),
285
+ selfAdmissions: (r.self_admissions ?? []).map(selfAdmissionFromWire),
286
+ // Absent from an older wasm: nothing recorded, nothing safe to acknowledge.
287
+ holes: (r.holes ?? []).map(logHoleFromWire),
288
+ acks: (r.acks ?? []).map(logAckFromWire),
289
+ // Absent from an older wasm, which never stopped for the journal.
290
+ journalFull: (r.journal_full ?? []).map(journalFullAtFromWire)
258
291
  };
259
292
  }
260
293
  function applyBatchResultFromWire(r) {
@@ -267,7 +300,10 @@ function applyBatchResultFromWire(r) {
267
300
  gaps: r.gaps.map(logGapFromWire),
268
301
  joined: r.joined,
269
302
  updated: r.updated.map(conversationUpdateFromWire),
270
- ...outcomesFromWire(r)
303
+ ...outcomesFromWire(r),
304
+ // Present only when the SDK says it: said once, with the batch at which
305
+ // the anchor record was seen to change.
306
+ ...r.state_backup_owed === true ? { stateBackupOwed: true } : {}
271
307
  };
272
308
  }
273
309
  function syncStepResultFromWire(r) {
@@ -303,6 +339,7 @@ function commitInDoubtFromWire(c) {
303
339
  var DB_NAME = "ping-sdk";
304
340
  var DB_VERSION = 1;
305
341
  var STORE = "kv";
342
+ var DURABLE = { durability: "strict" };
306
343
  function open() {
307
344
  return new Promise((resolve, reject) => {
308
345
  const req = indexedDB.open(DB_NAME, DB_VERSION);
@@ -334,7 +371,7 @@ var IndexedDbStorage = class {
334
371
  async put(namespace, key, value) {
335
372
  const db = await this.dbPromise;
336
373
  return new Promise((resolve, reject) => {
337
- const tx = db.transaction(STORE, "readwrite");
374
+ const tx = db.transaction(STORE, "readwrite", DURABLE);
338
375
  tx.objectStore(STORE).put({ ns: namespace, key, value });
339
376
  tx.oncomplete = () => resolve();
340
377
  tx.onerror = () => reject(tx.error);
@@ -343,7 +380,7 @@ var IndexedDbStorage = class {
343
380
  async del(namespace, key) {
344
381
  const db = await this.dbPromise;
345
382
  return new Promise((resolve, reject) => {
346
- const tx = db.transaction(STORE, "readwrite");
383
+ const tx = db.transaction(STORE, "readwrite", DURABLE);
347
384
  tx.objectStore(STORE).delete([namespace, key]);
348
385
  tx.oncomplete = () => resolve();
349
386
  tx.onerror = () => reject(tx.error);
@@ -359,7 +396,7 @@ var IndexedDbStorage = class {
359
396
  if (puts.length === 0 && deletes.length === 0) return;
360
397
  const db = await this.dbPromise;
361
398
  return new Promise((resolve, reject) => {
362
- const tx = db.transaction(STORE, "readwrite");
399
+ const tx = db.transaction(STORE, "readwrite", DURABLE);
363
400
  let settled = false;
364
401
  const fail = (e) => {
365
402
  if (settled) return;
@@ -592,6 +629,433 @@ function btoaUrl(b) {
592
629
  return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
593
630
  }
594
631
 
632
+ // src/account-setup.ts
633
+ function phraseBytes(phrase) {
634
+ return new TextEncoder().encode(phrase);
635
+ }
636
+ function rotationAnswerFields(answer) {
637
+ return {
638
+ status: answer.status,
639
+ error: answer.error ?? null,
640
+ generation: answer.generation ?? null,
641
+ statement: answer.statement ?? null
642
+ };
643
+ }
644
+ function accountRefusalCode(error) {
645
+ const text = error instanceof Error ? error.message : String(error);
646
+ const at = text.indexOf("account refused: ");
647
+ return at < 0 ? null : text.slice(at + "account refused: ".length).trim();
648
+ }
649
+ var AccountSetupClosedError = class extends Error {
650
+ constructor() {
651
+ super("AccountSetup is closed");
652
+ this.name = "AccountSetupClosedError";
653
+ }
654
+ };
655
+ var AccountSetup = class _AccountSetup {
656
+ worker;
657
+ storage;
658
+ now;
659
+ pending = /* @__PURE__ */ new Map();
660
+ nextId = 1;
661
+ closed = false;
662
+ constructor(cfg, worker) {
663
+ this.worker = worker;
664
+ this.storage = cfg.accountNamespace !== void 0 && cfg.accountNamespace.length > 0 ? scopeStorage(cfg.storage, cfg.accountNamespace) : cfg.storage;
665
+ this.now = cfg.now ?? (() => Date.now());
666
+ this.worker.onmessage = (ev) => void this.handleWorker(ev.data);
667
+ this.worker.onerror = () => this.fail(new AccountSetupClosedError());
668
+ }
669
+ /** Start the SDK's set-up Worker over the device's own store. */
670
+ static open(cfg) {
671
+ const worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
672
+ return new _AccountSetup(cfg, worker);
673
+ }
674
+ /**
675
+ * Set a NEW account up on this browser after "Not now" (rule R34 b): the
676
+ * pending root first, then the device record. `identityState` is the
677
+ * sign-in body's `identity_state` field as the server sent it; only
678
+ * `"none_pinned"` lets the call run (ruling V102). `persistentStorage` is the
679
+ * browser's answer to `navigator.storage.persist()`, which the host asked
680
+ * for before this call (ruling ID39).
681
+ */
682
+ createAccount(args) {
683
+ return this.call({
684
+ kind: "createAccount",
685
+ id: this.nextId++,
686
+ slot: args.slot,
687
+ identityState: args.identityState,
688
+ persistentStorage: args.persistentStorage,
689
+ nowMs: this.now(),
690
+ storageFeatures: storageFeaturesOf(this.storage)
691
+ });
692
+ }
693
+ /** Whether the slot holds the pending root this device expects (rule R32).
694
+ * No prompt, no read of the seed. */
695
+ pendingStatus(slot) {
696
+ return this.call({
697
+ kind: "pendingStatus",
698
+ id: this.nextId++,
699
+ slot,
700
+ storageFeatures: storageFeaturesOf(this.storage)
701
+ });
702
+ }
703
+ /** The first backup of a PENDING account. `accountId` is the account's
704
+ * 16-byte id at the auth layer. */
705
+ makeBackup(args) {
706
+ return this.call({
707
+ kind: "makeBackup",
708
+ id: this.nextId++,
709
+ slot: args.slot,
710
+ phrase: phraseBytes(args.phrase),
711
+ accountId: args.accountId,
712
+ hostState: args.hostState,
713
+ nowMs: this.now(),
714
+ storageFeatures: storageFeaturesOf(this.storage)
715
+ });
716
+ }
717
+ /** Rule R10 (b): the root part READ BACK from where it was stored opens to
718
+ * this account. Answers the fingerprint `endPending` asks for. */
719
+ async proveBackup(args) {
720
+ const proof = await this.call({
721
+ kind: "proveBackup",
722
+ id: this.nextId++,
723
+ readBackRootPart: args.readBackRootPart,
724
+ phrase: phraseBytes(args.phrase),
725
+ storageFeatures: storageFeaturesOf(this.storage)
726
+ });
727
+ return proof.fingerprint;
728
+ }
729
+ /** End PENDING: delete the pending item, only against the proof on record. */
730
+ async endPending(args) {
731
+ await this.call({
732
+ kind: "endPending",
733
+ id: this.nextId++,
734
+ slot: args.slot,
735
+ fingerprint: args.fingerprint,
736
+ storageFeatures: storageFeaturesOf(this.storage)
737
+ });
738
+ }
739
+ // ---- The restore as a rotation (the account identity contract, sections
740
+ // 3.9, 3.13, 13.1). None of these needs a client or a session: the backup
741
+ // is opened and the whole `rotation` object is built before the device
742
+ // exists at the server. No call takes or returns a root. ----
743
+ /** Step 3 of a restore: the root part opens with the phrase to the PINNED
744
+ * root; `hostState` is there when the root part's secret opens the state
745
+ * part. Writes nothing. */
746
+ openBackupForRestore(args) {
747
+ return this.call({
748
+ kind: "openBackupForRestore",
749
+ id: this.nextId++,
750
+ rootPart: args.rootPart,
751
+ phrase: phraseBytes(args.phrase),
752
+ statePart: args.statePart,
753
+ pinnedRootPublicKey: args.pinnedRootPublicKey
754
+ });
755
+ }
756
+ /**
757
+ * M1, take the account over: the next generation (the pinned one plus one,
758
+ * or a refusal), a NEW device key, the new generation secret, the device's
759
+ * credential, the statement, its wrap, the new backup parts, and the
760
+ * rotation record. `oldStatePart` gives its anchors only; `hostState` is
761
+ * the NEW host state with the NEW sign-in key companion. Called again with
762
+ * the same rotation id it answers the same request and the same device key.
763
+ */
764
+ restoreTakeOver(args) {
765
+ return this.call({
766
+ kind: "restoreTakeOver",
767
+ id: this.nextId++,
768
+ rootPart: args.rootPart,
769
+ phrase: phraseBytes(args.phrase),
770
+ start: args.start,
771
+ oldStatePart: args.oldStatePart,
772
+ accountId: args.accountId,
773
+ hostState: args.hostState,
774
+ nowMs: this.now(),
775
+ storageFeatures: storageFeaturesOf(this.storage)
776
+ });
777
+ }
778
+ /** "Take your account back": the take-over with the pending root of the
779
+ * slot. The pending item is read, never written and never deleted.
780
+ * `oldStatePart` is the account's state part as the escrow served it
781
+ * (it gives its anchors only); `undefined` only when none was served.
782
+ * ON AN EMPTY STORE EVERY JOIN IS UNCHECKED: never empty the SDK's
783
+ * store on the service's word while the slot holds a pending item
784
+ * (ruling V538). */
785
+ takeAccountBack(args) {
786
+ return this.call({
787
+ kind: "takeAccountBack",
788
+ id: this.nextId++,
789
+ slot: args.slot,
790
+ start: args.start,
791
+ oldStatePart: args.oldStatePart,
792
+ accountId: args.accountId,
793
+ hostState: args.hostState,
794
+ nowMs: this.now(),
795
+ storageFeatures: storageFeaturesOf(this.storage)
796
+ });
797
+ }
798
+ /** At every start: the rotation this device built and has not finished, or
799
+ * `null`. While its phase is `"built"` the host sends the identical
800
+ * request again. */
801
+ resumeRotation() {
802
+ return this.call({
803
+ kind: "resumeRotation",
804
+ id: this.nextId++,
805
+ storageFeatures: storageFeaturesOf(this.storage)
806
+ });
807
+ }
808
+ /** `resumeRotation` WITH THE HOST'S CLOCK (ruling V461; `nowMs`, by default
809
+ * this client's own): the call an app makes at every start. A take-over
810
+ * the server never answered loses the sealing seed it kept once 30 days
811
+ * have passed since its record was made; the record itself stays. */
812
+ resumeRotationAt(nowMs = this.now()) {
813
+ return this.call({
814
+ kind: "resumeRotation",
815
+ id: this.nextId++,
816
+ nowMs,
817
+ storageFeatures: storageFeaturesOf(this.storage)
818
+ });
819
+ }
820
+ /** The server's answer to the request of record `recordId`, AS RECEIVED
821
+ * and judged inside the SDK (ruling V161): the device adopts, or discards
822
+ * the record only against a DIFFERENT pinned statement the root signed
823
+ * (`"lost"`); a final refusal of the server (`"refused"`, `400
824
+ * rotation_invalid` included) keeps the record until `abandonRotation`; any
825
+ * other answer is `"undecided"` and changes nothing. */
826
+ completeRotation(recordId, answer) {
827
+ return this.call({
828
+ kind: "completeRotation",
829
+ id: this.nextId++,
830
+ recordId,
831
+ answer: rotationAnswerFields(answer),
832
+ storageFeatures: storageFeaturesOf(this.storage)
833
+ });
834
+ }
835
+ /** Move an adopted rotation forward. */
836
+ async setRotationPhase(recordId, phase) {
837
+ await this.call({
838
+ kind: "setRotationPhase",
839
+ id: this.nextId++,
840
+ recordId,
841
+ phase,
842
+ storageFeatures: storageFeaturesOf(this.storage)
843
+ });
844
+ }
845
+ /** Step 6: delete the record of an adopted rotation. */
846
+ async finishRotation(recordId) {
847
+ await this.call({
848
+ kind: "finishRotation",
849
+ id: this.nextId++,
850
+ recordId,
851
+ storageFeatures: storageFeaturesOf(this.storage)
852
+ });
853
+ }
854
+ /** Ruling V212: ABANDON a rotation that was never adopted. Its record is
855
+ * deleted, so that another rotation can start. THE PERSON'S CHOICE (after
856
+ * `"refused"`, or to supply the phrase after `"root_part_required"`): the
857
+ * SDK never calls it. ONLY a record the server answered with one of
858
+ * those two is deleted (ruling V227): a record the server never answered
859
+ * is refused (`rotation-refused`) and its request is sent again, because
860
+ * the server may have applied it and the record then holds the only copy
861
+ * of the new device's key. An adopted rotation is refused
862
+ * (`rotation-refused`); it ends by `finishRotation`. */
863
+ async abandonRotation(recordId) {
864
+ await this.call({
865
+ kind: "abandonRotation",
866
+ id: this.nextId++,
867
+ recordId,
868
+ storageFeatures: storageFeaturesOf(this.storage)
869
+ });
870
+ }
871
+ /** Ruling V232: whether this store holds a rotation record and whether the
872
+ * server refused it for good, so a screen can offer "start over" after a
873
+ * restart without sending the request once more. One local read: no secret,
874
+ * no id, no request. The refusal it reports is the server's unauthenticated
875
+ * word; this read decides nothing. */
876
+ rotationRecordState() {
877
+ return this.call({
878
+ kind: "rotationRecordState",
879
+ id: this.nextId++,
880
+ storageFeatures: storageFeaturesOf(this.storage)
881
+ });
882
+ }
883
+ /** M2, join beside the devices that stay: no rotation; a depth 0 credential
884
+ * at the pinned generation. `restore-join-not-current`: offer M1 or a link. */
885
+ restoreJoin(args) {
886
+ return this.call({
887
+ kind: "restoreJoin",
888
+ id: this.nextId++,
889
+ rootPart: args.rootPart,
890
+ phrase: phraseBytes(args.phrase),
891
+ statePart: args.statePart,
892
+ start: args.start,
893
+ nowMs: this.now(),
894
+ storageFeatures: storageFeaturesOf(this.storage)
895
+ });
896
+ }
897
+ /** Open the account's state part with the generation secret this device
898
+ * holds, and keep its anchors. No phrase, no root.
899
+ * It is also the ONE look a linked device owes before it writes a state
900
+ * part: until this ran once, `refreshStateBackup` and a rotation that keeps
901
+ * the device's key reject with the code `state-part-look-owed`. Pass an
902
+ * EMPTY part when the service serves none; whatever this answers, the look
903
+ * is made. */
904
+ openStateBackup(statePart) {
905
+ return this.call({
906
+ kind: "openStateBackup",
907
+ id: this.nextId++,
908
+ statePart,
909
+ storageFeatures: storageFeaturesOf(this.storage)
910
+ });
911
+ }
912
+ /** Write the account's state part anew under the generation secret this
913
+ * device holds. */
914
+ refreshStateBackup(args) {
915
+ return this.call({
916
+ kind: "refreshStateBackup",
917
+ id: this.nextId++,
918
+ accountId: args.accountId,
919
+ hostState: args.hostState,
920
+ nowMs: this.now(),
921
+ storageFeatures: storageFeaturesOf(this.storage)
922
+ });
923
+ }
924
+ /**
925
+ * Begin a set-up session whose root is in memory only (rule R34 a): for the
926
+ * person who makes the backup during set-up. One session per object; it
927
+ * lives in the Worker until `sessionFinish`, `sessionKeepAsPending` or
928
+ * `close`.
929
+ */
930
+ async beginInMemory(identityState) {
931
+ await this.call({
932
+ kind: "beginAccountSetupInMemory",
933
+ id: this.nextId++,
934
+ identityState,
935
+ nowMs: this.now()
936
+ });
937
+ }
938
+ /** The session's backup. */
939
+ sessionMakeBackup(args) {
940
+ return this.call({
941
+ kind: "setupSessionMakeBackup",
942
+ id: this.nextId++,
943
+ phrase: phraseBytes(args.phrase),
944
+ accountId: args.accountId,
945
+ hostState: args.hostState,
946
+ nowMs: this.now()
947
+ });
948
+ }
949
+ /** Rule R10 (b) for the session. Answers the fingerprint. */
950
+ async sessionProveBackup(args) {
951
+ const proof = await this.call({
952
+ kind: "setupSessionProveBackup",
953
+ id: this.nextId++,
954
+ readBackRootPart: args.readBackRootPart,
955
+ phrase: phraseBytes(args.phrase)
956
+ });
957
+ return proof.fingerprint;
958
+ }
959
+ /** End the session after the proof: the device record is written, the root
960
+ * is wiped. Only then does the host upload KeyPackages. */
961
+ sessionFinish() {
962
+ return this.call({
963
+ kind: "setupSessionFinish",
964
+ id: this.nextId++,
965
+ storageFeatures: storageFeaturesOf(this.storage)
966
+ });
967
+ }
968
+ /** "Not now" after the session began (ruling ID42): THIS session's root
969
+ * becomes the pending item, then the device record is written. */
970
+ sessionKeepAsPending(args) {
971
+ return this.call({
972
+ kind: "setupSessionKeepAsPending",
973
+ id: this.nextId++,
974
+ slot: args.slot,
975
+ persistentStorage: args.persistentStorage,
976
+ storageFeatures: storageFeaturesOf(this.storage)
977
+ });
978
+ }
979
+ /** Stop the Worker. A session still open there is wiped with it. */
980
+ close() {
981
+ if (this.closed) return;
982
+ this.closed = true;
983
+ try {
984
+ this.worker.postMessage({ kind: "endAccountSetupSession", id: this.nextId++ });
985
+ } catch {
986
+ }
987
+ this.worker.onmessage = null;
988
+ this.worker.onerror = null;
989
+ this.worker.terminate();
990
+ this.fail(new AccountSetupClosedError());
991
+ }
992
+ fail(error) {
993
+ const waiting = [...this.pending.values()];
994
+ this.pending.clear();
995
+ for (const slot of waiting) slot.reject(error);
996
+ }
997
+ /** Post a request. A recovery phrase in it crossed as bytes (ruling
998
+ * V253): this side's copy is zeroed when the call has answered, whatever
999
+ * it answered; the Worker zeroes its own. */
1000
+ call(req) {
1001
+ const phrase = req.phrase;
1002
+ const answered = this.post(req);
1003
+ return phrase instanceof Uint8Array ? answered.finally(() => {
1004
+ phrase.fill(0);
1005
+ }) : answered;
1006
+ }
1007
+ post(req) {
1008
+ if (this.closed) return Promise.reject(new AccountSetupClosedError());
1009
+ return new Promise((resolve, reject) => {
1010
+ this.pending.set(req.id, { resolve, reject });
1011
+ try {
1012
+ this.worker.postMessage(req);
1013
+ } catch (e) {
1014
+ this.pending.delete(req.id);
1015
+ reject(e);
1016
+ }
1017
+ });
1018
+ }
1019
+ async handleWorker(msg) {
1020
+ switch (msg.kind) {
1021
+ case "result": {
1022
+ const slot = this.pending.get(msg.id);
1023
+ if (!slot) return;
1024
+ this.pending.delete(msg.id);
1025
+ if (msg.ok) slot.resolve(msg.value);
1026
+ else slot.reject(new Error(msg.error));
1027
+ return;
1028
+ }
1029
+ case "storage.call": {
1030
+ try {
1031
+ const method = this.storage[msg.method];
1032
+ if (typeof method !== "function") {
1033
+ throw new Error(`storage.${String(msg.method)} is not implemented by the host storage`);
1034
+ }
1035
+ const value = await method.apply(this.storage, msg.args);
1036
+ if (!this.closed) this.worker.postMessage({ kind: "storage.reply", id: msg.id, ok: true, value });
1037
+ } catch (e) {
1038
+ if (!this.closed) {
1039
+ this.worker.postMessage({ kind: "storage.reply", id: msg.id, ok: false, error: String(e) });
1040
+ }
1041
+ }
1042
+ return;
1043
+ }
1044
+ case "transport.call": {
1045
+ this.worker.postMessage({
1046
+ kind: "transport.reply",
1047
+ id: msg.id,
1048
+ ok: false,
1049
+ error: "account set-up has no transport"
1050
+ });
1051
+ return;
1052
+ }
1053
+ default:
1054
+ return;
1055
+ }
1056
+ }
1057
+ };
1058
+
595
1059
  // src/wasm-memory.ts
596
1060
  var RESERVE_MIB_TARGETS = [192, 128, 64, 32];
597
1061
  var WASM_PAGE_BYTES = 64 * 1024;
@@ -619,9 +1083,7 @@ async function openNotificationPreview(opts) {
619
1083
  opts.wasmModuleOrPath === void 0 ? void 0 : { module_or_path: opts.wasmModuleOrPath }
620
1084
  );
621
1085
  reserveLinearMemory(out.memory);
622
- const client = await wasm.PingClient.openReadOnly(
623
- opts.identityExport,
624
- // Label is unused on the read-only path (no LocalDevice is ever minted).
1086
+ const client = await wasm.PingClient.openReadOnlyFromDeviceRecord(
625
1087
  "notification-preview",
626
1088
  storage,
627
1089
  silentTransport(),
@@ -746,56 +1208,6 @@ var MessagingClient = class _MessagingClient {
746
1208
  this.worker.onmessage = (ev) => this.handleWorker(ev.data);
747
1209
  this.worker.onerror = () => this.failPending(new MessagingClientClosedError("worker-error"));
748
1210
  }
749
- /** Generate a fresh identity. The returned bytes are a secret — store them encrypted. */
750
- static async generateIdentity() {
751
- return _MessagingClient.ephemeralWorkerCall({
752
- kind: "generateIdentity",
753
- id: 1
754
- });
755
- }
756
- /**
757
- * HPKE-seal a `LinkingTicket` for delivery to a new device ([CR-3]).
758
- *
759
- * Returns CBOR-encoded bytes safe to relay through an untrusted inbox. The new device's
760
- * X25519 public key (`newDevicePub`) is exchanged out-of-band — typically as part of a
761
- * QR-encoded handshake on the linking screen. Pure function; runs in an ephemeral
762
- * worker so no live `MessagingClient` is required on the sender side.
763
- *
764
- * Suite: `DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, AES-128-GCM` (matches MLS).
765
- */
766
- static async sealLinkingTicket(ticket, newDevicePub) {
767
- if (newDevicePub.length !== 32) {
768
- throw new Error("sealLinkingTicket: newDevicePub must be 32 bytes");
769
- }
770
- return _MessagingClient.ephemeralWorkerCall({
771
- kind: "sealLinkingTicket",
772
- id: 1,
773
- ticket,
774
- newDevicePub
775
- });
776
- }
777
- /**
778
- * HPKE-open a sealed `LinkingTicket` on the new device ([CR-3]).
779
- *
780
- * The receiving device hasn't booted a `MessagingClient` yet — it only has its X25519
781
- * ephemeral keypair. This static method runs the open in an ephemeral worker, returning
782
- * the cleartext ticket which the host then feeds to `init()` + `consumeLinkingTicket()`.
783
- *
784
- * On failure the error message is deliberately generic (no discriminator between "wrong
785
- * key" vs "tampered ciphertext") so a probing attacker can't tell the new device's key
786
- * was the issue.
787
- */
788
- static async openLinkingTicket(sealed, newDevicePriv) {
789
- if (newDevicePriv.length !== 32) {
790
- throw new Error("openLinkingTicket: newDevicePriv must be 32 bytes");
791
- }
792
- return _MessagingClient.ephemeralWorkerCall({
793
- kind: "openLinkingTicket",
794
- id: 1,
795
- sealed,
796
- newDevicePriv
797
- });
798
- }
799
1211
  /**
800
1212
  * Generic HPKE-Base seal of arbitrary bytes to `recipientPub` (32-byte X25519)
801
1213
  * under a caller-supplied `info`. One shared HPKE implementation so app layers
@@ -895,39 +1307,6 @@ var MessagingClient = class _MessagingClient {
895
1307
  // forms stay for app inboxes created with a 32-byte key before the roll. A
896
1308
  // classical private key and an X-Wing seed are both 32 bytes but are NOT
897
1309
  // interchangeable: the host knows which family a stored key belongs to.
898
- /**
899
- * HPKE-seal a `LinkingTicket` under the new device's X-Wing public key
900
- * ([CR-3], post-quantum). CBOR `{v: 2, enc, ct}` under `ping/link/v2`; the
901
- * classical {@link openLinkingTicket} refuses it and {@link openLinkingTicketPq}
902
- * refuses a `v: 1` blob, so there is no downgrade in either direction.
903
- */
904
- static async sealLinkingTicketPq(ticket, newDevicePub) {
905
- if (newDevicePub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {
906
- throw new Error(`sealLinkingTicketPq: newDevicePub must be ${HPKE_PQ_PUBLIC_KEY_BYTES} bytes`);
907
- }
908
- return _MessagingClient.ephemeralWorkerCall({
909
- kind: "sealLinkingTicketPq",
910
- id: 1,
911
- ticket,
912
- newDevicePub
913
- });
914
- }
915
- /**
916
- * HPKE-open a sealed `v: 2` ticket with the new device's 32-byte X-Wing seed
917
- * ([CR-3], post-quantum). The error is deliberately generic, like
918
- * {@link openLinkingTicket}.
919
- */
920
- static async openLinkingTicketPq(sealed, newDevicePriv) {
921
- if (newDevicePriv.length !== 32) {
922
- throw new Error("openLinkingTicketPq: newDevicePriv must be 32 bytes");
923
- }
924
- return _MessagingClient.ephemeralWorkerCall({
925
- kind: "openLinkingTicketPq",
926
- id: 1,
927
- sealed,
928
- newDevicePriv
929
- });
930
- }
931
1310
  /** Post-quantum {@link hpkeSeal}: CBOR-wrapped (`v: 2`), `recipientPub` is 1216 bytes. */
932
1311
  static async hpkeSealPq(plaintext, recipientPub, info) {
933
1312
  if (recipientPub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {
@@ -1091,52 +1470,112 @@ var MessagingClient = class _MessagingClient {
1091
1470
  }
1092
1471
  return { deviceId: both.slice(0, 32), signature: both.slice(32) };
1093
1472
  }
1473
+ // ---- The link handshake commitment (2026-11-25) ----
1474
+ //
1475
+ // REMOVED 2026-11-28 (ruling V576): `openLinkingTicket`, `openLinkingTicketPq`,
1476
+ // `sealLinkingTicketFor`, `buildLinkingTicketFor`, `consumeLinkingTicket` and the type
1477
+ // `LinkingTicket`. A ticket of version 1 or 2 carries a binding an ACCOUNT KEY signs;
1478
+ // the only ticket is version 3 (`buildLinkingTicketV3For`, `completeDeviceLink`).
1479
+ // REMOVED 2026-11-25 (ruling ID15): `sealLinkingTicket`, `sealLinkingTicketPq`,
1480
+ // `signDeviceLinkApproval` (a raw key) and `buildLinkingTicket(deviceId,
1481
+ // keyPackage)`. Every call below takes the handshake payload the relay returned
1482
+ // together with what THIS device was shown (`expected`) and verifies inside the
1483
+ // call, so nothing can be approved for, built for or sealed to a handshake that
1484
+ // was not verified. `hpkeSeal*` refuse the infos `ping/link/*` and
1485
+ // `ping/link-auth/*`. Host notes: docs-site/api.md, "Device link commitment".
1486
+ /**
1487
+ * The commitment of a handshake payload: what a NEW device shows for the exact
1488
+ * bytes it publishes ({@link MessagingClient.linkHandshakePayload}). `qrText` is
1489
+ * `{"v":3,"h":"<base64url(commitment)>"}`; `code` is the 20 characters the relay
1490
+ * indexes; `codeDisplay` is the same in five groups of four.
1491
+ */
1492
+ static async linkCommitment(payload) {
1493
+ const parts = await _MessagingClient.ephemeralWorkerCall({
1494
+ kind: "linkCommitment",
1495
+ id: 1,
1496
+ payload
1497
+ });
1498
+ return { commitment: parts[0], qrText: parts[1], code: parts[2], codeDisplay: parts[3] };
1499
+ }
1094
1500
  /**
1095
- * Link verification v2, on the APPROVING device: approve ONE new device on ONE
1096
- * server link session (`POST /v1/auth/link/sessions` returned `approvalSessionId`)
1097
- * with this device's signing key. The new device sends the result with its own
1098
- * {@link signDeviceLinkPossession} proof to `POST /v1/auth/link/verify`.
1099
- *
1100
- * The SDK builds the signed bytes itself (`"ping/device-link-approve/v1" ||
1101
- * approvalSessionId || accountId || approverDeviceId || newDeviceId ||
1102
- * newDevicePubkey || audience`, see docs/DEVICE_LINK_V2_VECTORS.md) and derives
1103
- * both device ids from the keys, so this cannot sign anything else with the device
1104
- * key. `deviceSigningSecretKey` is the 32-byte seed the host holds for THIS device
1105
- * (the one registered as its device signing key); `accountId` (16 bytes) is the
1106
- * account stored with this device's session; `newDevicePubkey` (32 bytes) is the
1107
- * new device's key from its handshake; `audience` is the canonical origin of the API
1108
- * THIS host is configured to reach (`new URL(apiBase).origin`), as for
1109
- * {@link signDeviceReauth}.
1110
- *
1111
- * Rejects wrong widths, a non-canonical audience, a new key that is not a canonical
1112
- * Ed25519 point outside the small-order subgroup, and this device's own key. Runs in
1113
- * an ephemeral worker.
1501
+ * THE normaliser of a typed link code. Hand it what the person typed; send the
1502
+ * relay, and pass to the calls below, only the 20 characters it returns. No host
1503
+ * normalises a code itself. Rejects anything that is not a code.
1504
+ */
1505
+ static async normalizeLinkCode(typed) {
1506
+ return _MessagingClient.ephemeralWorkerCall({ kind: "normalizeLinkCode", id: 1, typed });
1507
+ }
1508
+ /** The 32 bytes of a QR text `{"v":3,"h":"..."}`. Rejects any other shape. */
1509
+ static async linkQrCommitment(qrText) {
1510
+ return _MessagingClient.ephemeralWorkerCall({ kind: "linkQrCommitment", id: 1, qrText });
1511
+ }
1512
+ /**
1513
+ * Verify the handshake payload a relay returned against what this device was
1514
+ * shown. Call it BEFORE anything else is done with the handshake. Rejects with
1515
+ * {@link LinkCommitmentMismatchError} when the payload is not the committed one:
1516
+ * send nothing, open no approval session, ask the person to try again.
1517
+ */
1518
+ static async verifyLinkHandshake(payload, expected) {
1519
+ const all = await _MessagingClient.ephemeralWorkerCall({
1520
+ kind: "verifyLinkHandshake",
1521
+ id: 1,
1522
+ payload,
1523
+ ...linkExpectedFields(expected)
1524
+ });
1525
+ if (all.length !== 97) {
1526
+ throw new Error("verifyLinkHandshake: expected 97 bytes");
1527
+ }
1528
+ return {
1529
+ deviceId: all.slice(0, 32),
1530
+ deviceSigningPubkey: all.slice(32, 64),
1531
+ commitment: all.slice(64, 96),
1532
+ verifiedByQr: all[96] === 1
1533
+ };
1534
+ }
1535
+ /**
1536
+ * HPKE-seal the device-linking auth envelope (`ping/link-auth/v2`) to the
1537
+ * X-Wing key of the handshake `payload`, verified inside the call.
1538
+ */
1539
+ static async sealLinkAuthFor(plaintext, payload, expected) {
1540
+ return _MessagingClient.ephemeralWorkerCall({
1541
+ kind: "sealLinkAuthFor",
1542
+ id: 1,
1543
+ plaintext,
1544
+ payload,
1545
+ ...linkExpectedFields(expected)
1546
+ });
1547
+ }
1548
+ /**
1549
+ * Link verification v2, on the EXISTING device: approve the new device of the
1550
+ * handshake `payload`, verified inside the call, on one server link session with
1551
+ * this device's signing key. The signed bytes are those of
1552
+ * docs/DEVICE_LINK_V2_VECTORS.md; the key that is approved is the handshake's
1553
+ * device signing key and cannot be passed separately. `audience` as for
1554
+ * {@link signDeviceReauth}. Runs in an ephemeral worker.
1114
1555
  */
1115
- static async signDeviceLinkApproval(params) {
1116
- const { deviceSigningSecretKey, approvalSessionId, accountId, newDevicePubkey, audience } = params;
1556
+ static async signDeviceLinkApprovalFor(params) {
1557
+ const { deviceSigningSecretKey, approvalSessionId, accountId, payload, expected, audience } = params;
1117
1558
  if (deviceSigningSecretKey.length !== 32) {
1118
- throw new Error("signDeviceLinkApproval: deviceSigningSecretKey must be 32 bytes");
1559
+ throw new Error("signDeviceLinkApprovalFor: deviceSigningSecretKey must be 32 bytes");
1119
1560
  }
1120
1561
  if (approvalSessionId.length !== 16) {
1121
- throw new Error("signDeviceLinkApproval: approvalSessionId must be 16 bytes");
1562
+ throw new Error("signDeviceLinkApprovalFor: approvalSessionId must be 16 bytes");
1122
1563
  }
1123
1564
  if (accountId.length !== 16) {
1124
- throw new Error("signDeviceLinkApproval: accountId must be 16 bytes");
1125
- }
1126
- if (newDevicePubkey.length !== 32) {
1127
- throw new Error("signDeviceLinkApproval: newDevicePubkey must be 32 bytes");
1565
+ throw new Error("signDeviceLinkApprovalFor: accountId must be 16 bytes");
1128
1566
  }
1129
1567
  const all = await _MessagingClient.ephemeralWorkerCall({
1130
- kind: "signDeviceLinkApproval",
1568
+ kind: "signDeviceLinkApprovalFor",
1131
1569
  id: 1,
1132
1570
  deviceSigningSecretKey,
1133
1571
  approvalSessionId,
1134
1572
  accountId,
1135
- newDevicePubkey,
1573
+ payload,
1574
+ ...linkExpectedFields(expected),
1136
1575
  audience
1137
1576
  });
1138
1577
  if (all.length !== 128) {
1139
- throw new Error("signDeviceLinkApproval: expected 128 bytes");
1578
+ throw new Error("signDeviceLinkApprovalFor: expected 128 bytes");
1140
1579
  }
1141
1580
  return {
1142
1581
  approverDeviceId: all.slice(0, 32),
@@ -1187,7 +1626,7 @@ var MessagingClient = class _MessagingClient {
1187
1626
  // result, on a worker `error` (the script failed to load or import, or threw at top
1188
1627
  // level), on a `messageerror` (a reply that could not be deserialised), and when the
1189
1628
  // worker cannot be created or the request cannot be posted. Only `onmessage` used to be
1190
- // wired, so a worker that failed to load left `generateIdentity()` pending forever and
1629
+ // wired, so a worker that failed to load left a static call pending forever and
1191
1630
  // the worker alive.
1192
1631
  static ephemeralWorkerCall(req) {
1193
1632
  let w;
@@ -1222,30 +1661,99 @@ var MessagingClient = class _MessagingClient {
1222
1661
  }
1223
1662
  });
1224
1663
  }
1225
- static async init(cfg) {
1664
+ /**
1665
+ * Start the client FROM THE DEVICE RECORD: the ONE start of a client (after
1666
+ * `AccountSetup`, a link or a restore wrote the record into `cfg.storage`).
1667
+ * The client holds no account key: every leaf and KeyPackage it builds
1668
+ * carries the one credential the device holds (`heldCredential()`). No call
1669
+ * starts a client from an account identity and none hands one out (the
1670
+ * start from an identity export, `generateIdentity` and `exportIdentity`
1671
+ * left every binding on 2026-11-28). Rejects when the
1672
+ * store holds no device record, or when `cfg.deviceSigningSecretKey` is not
1673
+ * the record's own device key.
1674
+ */
1675
+ static async initFromDeviceRecord(cfg) {
1676
+ return (await _MessagingClient.start(cfg, "record")).client;
1677
+ }
1678
+ /**
1679
+ * Begin a link on a NEW device, in one call: the SDK draws the device key
1680
+ * (no field of `cfg` is a key), records "link begun" in `cfg.storage`,
1681
+ * starts the staging client and builds the handshake payload. A repeat
1682
+ * after a reload answers the SAME key and the SAME handshake. Rejects with
1683
+ * `account refused: account-already-set-up` over a store that already holds
1684
+ * a device.
1685
+ */
1686
+ static async beginDeviceLink(cfg) {
1687
+ const { client, answer } = await _MessagingClient.start(cfg, "link");
1688
+ const begun = answer;
1689
+ return { client, ...begun };
1690
+ }
1691
+ /**
1692
+ * HPKE-seal a version 3 ticket to the X-Wing key of the handshake `payload`,
1693
+ * verified inside the call (`ping/link/v2`). Rejects a ticket that was built
1694
+ * for another device than the handshake's.
1695
+ */
1696
+ static async sealLinkingTicketV3For(ticket, payload, expected) {
1697
+ return _MessagingClient.ephemeralWorkerCall({
1698
+ kind: "sealLinkingTicketV3For",
1699
+ id: 1,
1700
+ ticket,
1701
+ payload,
1702
+ ...linkExpectedFields(expected)
1703
+ });
1704
+ }
1705
+ /**
1706
+ * HPKE-open a sealed version 3 ticket with the new device's X-Wing seed.
1707
+ * NOT yet verified: `completeDeviceLink` runs every check.
1708
+ */
1709
+ static async openLinkingTicketV3(sealed, newDevicePriv) {
1710
+ return _MessagingClient.ephemeralWorkerCall({
1711
+ kind: "openLinkingTicketV3",
1712
+ id: 1,
1713
+ sealed,
1714
+ newDevicePriv
1715
+ });
1716
+ }
1717
+ static async start(cfg, mode) {
1226
1718
  const worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
1227
1719
  const client = new _MessagingClient(cfg, worker);
1228
1720
  const transportFeatures = {
1229
1721
  fetchLogSince: typeof cfg.transport.fetchLogSince === "function",
1230
- fetchLogHeads: typeof cfg.transport.fetchLogHeads === "function"
1722
+ fetchLogHeads: typeof cfg.transport.fetchLogHeads === "function",
1723
+ sendExternalCommit: typeof cfg.transport.sendExternalCommit === "function",
1724
+ fetchSelfAdmissionStates: typeof cfg.transport.fetchSelfAdmissionStates === "function",
1725
+ fetchSealedGroupInfos: typeof cfg.transport.fetchSealedGroupInfos === "function",
1726
+ sendExternalCommits: typeof cfg.transport.sendExternalCommits === "function",
1727
+ fetchSealingStatements: typeof cfg.transport.fetchSealingStatements === "function",
1728
+ publishSealedGroupInfo: typeof cfg.transport.publishSealedGroupInfo === "function"
1231
1729
  };
1232
1730
  const storageFeatures = storageFeaturesOf(client.storage);
1233
- await client.call({
1234
- kind: "init",
1731
+ const first = {
1235
1732
  id: client.nextId++,
1236
- identityExport: cfg.identityExport,
1237
1733
  deviceLabel: cfg.deviceLabel,
1238
1734
  nowMs: client.now(),
1239
1735
  ...cfg.deviceSigningSecretKey ? { deviceSigningSecretKey: cfg.deviceSigningSecretKey } : {},
1240
1736
  ...cfg.expectedOwners ? { expectedOwners: cfg.expectedOwners } : {},
1737
+ // Handed on as given: the Worker counts only the value `true`.
1738
+ ...cfg.tabClient !== void 0 ? { tabClient: cfg.tabClient } : {},
1241
1739
  transportFeatures,
1242
1740
  storageFeatures
1243
- });
1741
+ };
1742
+ const answer = await client.call(
1743
+ mode === "link" ? {
1744
+ kind: "beginDeviceLink",
1745
+ id: first.id,
1746
+ deviceLabel: first.deviceLabel,
1747
+ nowMs: first.nowMs,
1748
+ transportFeatures,
1749
+ storageFeatures
1750
+ } : { kind: "initFromDeviceRecord", ...first }
1751
+ );
1244
1752
  client.ownDeviceId = await client.deviceId();
1245
1753
  client.subscription = cfg.transport.subscribe(
1246
1754
  (frame) => client.dispatchIncoming(frame)
1247
1755
  );
1248
- return client;
1756
+ return { client, answer };
1249
1757
  }
1250
1758
  /**
1251
1759
  * Internal: route an inbound envelope to the right handler, IN ARRIVAL ORDER
@@ -1369,55 +1877,26 @@ var MessagingClient = class _MessagingClient {
1369
1877
  });
1370
1878
  const result = syncStepResultFromWire(raw);
1371
1879
  this.fanout.deliverBatch(result.messages, { source: "page" });
1372
- return result;
1373
- }
1374
- // ------------------------ Public API ------------------------
1375
- async userId() {
1376
- return await this.call({ kind: "userId", id: this.nextId++ });
1377
- }
1378
- /**
1379
- * Export the account identity seed (CBOR-wrapped Ed25519, **SECRET**).
1380
- * Transfer to a newly-linked device over the sealed linking channel so all of
1381
- * an account's devices share one `userId` — the basis for cross-device
1382
- * self-attribution (`IncomingMessage.sender_user_id === userId()`). Never log
1383
- * or persist in cleartext.
1384
- */
1385
- async exportIdentity() {
1386
- return await this.call({ kind: "exportIdentity", id: this.nextId++ });
1387
- }
1388
- /**
1389
- * RETIRED (2026-11-03): always rejects (`Invalid`) and changes nothing.
1390
- *
1391
- * It moved every conversation's own leaf to a new account identity with a
1392
- * credential-changing Commit, the way out of `409 mls_identity_conflict`.
1393
- * Every Ping client now refuses a Commit that changes a member's leaf
1394
- * credential (a hostile linked device could otherwise move its leaf to a
1395
- * peer's identity and escape the account's removal), so a rotation would
1396
- * strand every conversation it touched. The way out of an identity conflict
1397
- * is to link this device again, or sign out and in. Kept so no caller
1398
- * breaks. See `docs/MULTIDEVICE.md` "Identity rotation".
1399
- *
1400
- * @deprecated Retired: always rejects. Link this device again instead.
1401
- */
1402
- async rotateIdentity(newIdentityExport, nowMs = this.now()) {
1403
- return await this.call({
1404
- kind: "rotateIdentity",
1405
- id: this.nextId++,
1406
- newIdentityExport,
1407
- nowMs
1408
- });
1409
- }
1410
- /**
1411
- * RETIRED with [[rotateIdentity]]: always rejects (`Invalid`).
1412
- *
1413
- * @deprecated Retired: always rejects.
1414
- */
1415
- async rotateIdentityRetry(conv, nowMs = this.now()) {
1416
- await this.call({ kind: "rotateIdentityRetry", id: this.nextId++, conv, nowMs });
1880
+ return result;
1881
+ }
1882
+ // ------------------------ Public API ------------------------
1883
+ async userId() {
1884
+ return await this.call({ kind: "userId", id: this.nextId++ });
1417
1885
  }
1418
1886
  async deviceId() {
1419
1887
  return await this.call({ kind: "deviceId", id: this.nextId++ });
1420
1888
  }
1889
+ /** The credential this device HOLDS for itself (version 2), which every
1890
+ * leaf and KeyPackage it builds carries. A public value. Never absent
1891
+ * (2026-11-28): every client starts from a device record. Rejects with
1892
+ * `NoDeviceRecord` on a read-only client, which holds no credential. */
1893
+ async heldCredential() {
1894
+ return await this.call({ kind: "heldCredential", id: this.nextId++ });
1895
+ }
1896
+ /** The generation of the held credential. Rejects as `heldCredential` does. */
1897
+ async heldGeneration() {
1898
+ return await this.call({ kind: "heldGeneration", id: this.nextId++ });
1899
+ }
1421
1900
  /**
1422
1901
  * Release every file lock the MLS store holds so the host process can be
1423
1902
  * suspended. Resolves `true` when the locks are genuinely gone.
@@ -1809,6 +2288,91 @@ var MessagingClient = class _MessagingClient {
1809
2288
  // See docs/SYNC_PROTOCOL.md "Sequenced log sync". The subscribe path feeds
1810
2289
  // these itself for a transport that hands over sequenced frames; they are
1811
2290
  // public for hosts that drive their own socket.
2291
+ /**
2292
+ * SELF-ADMISSION: enter `conversationId` by this device's own act, from
2293
+ * what the delivery service returned for it (the sealed GroupInfo and
2294
+ * this account's wrap). Every refusal is a VALUE (`kind: "refused"`);
2295
+ * while the SDK is built without self-admission the answer is `refusal:
2296
+ * "notCompiled"` and nothing was touched. The client reads the anchor
2297
+ * record its device holds by itself, before the join. Rejects only for an
2298
+ * id of the wrong length.
2299
+ *
2300
+ * THE MESSAGES OF A JOIN. `joined` carries `replayed`: messages of this
2301
+ * conversation that waited for the join. Show them, save them and
2302
+ * confirm them (`confirmApplied`) exactly as the messages of a batch
2303
+ * (also for every `joined` entry of `selfAdmitMany`). This client
2304
+ * DELIVERS them to its observers by itself (source `live`), as it
2305
+ * delivers the messages of `processSequencedBatch`; Swift and Kotlin
2306
+ * return them, as they return a batch's messages.
2307
+ */
2308
+ async selfAdmit(conversationId, fetched) {
2309
+ const result = await this.call({
2310
+ kind: "selfAdmit",
2311
+ id: this.nextId++,
2312
+ conv: conversationId,
2313
+ fetched: {
2314
+ blob: fetched.blob,
2315
+ wrap: fetched.wrap,
2316
+ wrapCount: fetched.wrapCount,
2317
+ ...fetched.currentEpoch === void 0 ? {} : { currentEpoch: fetched.currentEpoch }
2318
+ },
2319
+ nowMs: this.now()
2320
+ });
2321
+ if (result.kind === "joined") {
2322
+ holeOfJoin(result);
2323
+ this.fanout.deliverBatch(result.replayed, { source: "live" });
2324
+ }
2325
+ return result;
2326
+ }
2327
+ /**
2328
+ * Enter MANY conversations with few requests (the transport's
2329
+ * `fetchSelfAdmissionStates`, `fetchSealedGroupInfos` and
2330
+ * `sendExternalCommits`): `first` (the conversation on screen) goes to
2331
+ * the head, then the order given, each once. One entry per conversation,
2332
+ * each judged and answered alone. A conversation this device holds and is
2333
+ * not stranded in answers `alreadyHeld` with no request. Nothing is
2334
+ * polled: call again when the account event of a publication arrives.
2335
+ */
2336
+ async selfAdmitMany(conversations, opts = {}) {
2337
+ const entries = await this.call({
2338
+ kind: "selfAdmitMany",
2339
+ id: this.nextId++,
2340
+ ...opts.first === void 0 ? {} : { first: opts.first },
2341
+ conversations,
2342
+ nowMs: this.now()
2343
+ });
2344
+ for (const entry of entries) {
2345
+ if (entry.result.kind === "joined") {
2346
+ holeOfJoin(entry.result);
2347
+ this.fanout.deliverBatch(entry.result.replayed, { source: "live" });
2348
+ }
2349
+ }
2350
+ return entries;
2351
+ }
2352
+ /**
2353
+ * THE ONE CALL A HOST REMEMBERS FOR THE ANCHOR RECORD: write the account's
2354
+ * state part from the RUNNING client. The record of who may sign a
2355
+ * GroupInfo a restoring device enters by is rebuilt from this client's
2356
+ * own conversations first (at every call; the SDK also rebuilds it
2357
+ * by itself during `processSequencedBatch` and at every rotation), and
2358
+ * the part carries it. The host stores the part where it stores every
2359
+ * state part. (`AccountSetup.refreshStateBackup` takes a store and
2360
+ * carries the record as it was last built.)
2361
+ *
2362
+ * A LINKED device owes ONE look first: until `AccountSetup.openStateBackup`
2363
+ * ran once on it, this rejects with the code `state-part-look-owed` (so does
2364
+ * a rotation that keeps the device's key). Pass an EMPTY part there when the
2365
+ * service serves none; whatever it answers, the look is made.
2366
+ */
2367
+ async refreshStateBackup(args) {
2368
+ return await this.call({
2369
+ kind: "clientRefreshStateBackup",
2370
+ id: this.nextId++,
2371
+ accountId: args.accountId,
2372
+ hostState: args.hostState,
2373
+ nowMs: this.now()
2374
+ });
2375
+ }
1812
2376
  /**
1813
2377
  * Apply a batch of live frames, each with its server log position, and
1814
2378
  * checkpoint once per touched conversation. Per conversation: the next
@@ -1896,6 +2460,30 @@ var MessagingClient = class _MessagingClient {
1896
2460
  serverSeq
1897
2461
  });
1898
2462
  }
2463
+ /**
2464
+ * The holes of one conversation's log on this device, lowest position
2465
+ * first: every position at or below the stored position that was not
2466
+ * applied, with the reason and the content hashes the envelopes named.
2467
+ * `kept: true` entries are rows the SDK still holds and retries by itself.
2468
+ */
2469
+ async logHoles(id) {
2470
+ const raw = await this.call({ kind: "logHoles", id: this.nextId++, conv: id });
2471
+ return raw.map(logHoleFromWire);
2472
+ }
2473
+ /**
2474
+ * The host filled `fromServerSeq..toServerSeq` (inclusive) of a
2475
+ * conversation from elsewhere (the account's other device): take the range
2476
+ * out of the recorded holes. Resolves `true` when a recorded hole changed.
2477
+ */
2478
+ async resolveLogHole(id, fromServerSeq, toServerSeq) {
2479
+ return await this.call({
2480
+ kind: "resolveLogHole",
2481
+ id: this.nextId++,
2482
+ conv: id,
2483
+ fromServerSeq,
2484
+ toServerSeq
2485
+ });
2486
+ }
1899
2487
  /**
1900
2488
  * Conversations the server's heads show this device is behind on: not
1901
2489
  * anchored yet, a head above the applied position, or frames held in the
@@ -1976,28 +2564,17 @@ var MessagingClient = class _MessagingClient {
1976
2564
  await this.call({ kind: "confirmApplied", id: this.nextId++, journalIds });
1977
2565
  }
1978
2566
  /**
1979
- * Build a `LinkingTicket` for a new device.
1980
- *
1981
- * [CR-13] `lastAppEvents` is host-supplied per-conversation "what you missed" data
1982
- * (decrypted AppEvent bytes the new device will render before sync catches up).
1983
- * Pass `[]` to suppress catchup data — the new device will see an empty conversation
1984
- * list until normal sync runs.
1985
- *
1986
- * Caller is responsible for HPKE-sealing the returned ticket via
1987
- * `MessagingClient.sealLinkingTicket` before transmitting (CR-3).
1988
- *
1989
- * Rejects (`Invalid`), before anything is sent, a KeyPackage that claims the
1990
- * identity of another account this client knows: a new device links under an
1991
- * identity of its own, or the account's.
2567
+ * The version 3 handshake payload this NEW device publishes: its own signing key,
2568
+ * the id derived from it, `hpkePublicKey` (X-Wing, 1216 bytes) and a KeyPackage it
2569
+ * just made. Show {@link MessagingClient.linkCommitment} of exactly these bytes and
2570
+ * publish exactly these bytes; nobody re-serialises them.
1992
2571
  */
1993
- async buildLinkingTicket(newDeviceId, newDeviceKp, lastAppEvents = []) {
2572
+ async linkHandshakePayload(hpkePublicKey, keyPackage) {
1994
2573
  return await this.call({
1995
- kind: "buildLinkingTicket",
2574
+ kind: "linkHandshakePayload",
1996
2575
  id: this.nextId++,
1997
- newDeviceId,
1998
- newDeviceKp,
1999
- lastAppEvents,
2000
- nowMs: this.now()
2576
+ hpkePublicKey,
2577
+ keyPackage
2001
2578
  });
2002
2579
  }
2003
2580
  /**
@@ -2018,18 +2595,201 @@ var MessagingClient = class _MessagingClient {
2018
2595
  snapshotBytes
2019
2596
  });
2020
2597
  }
2021
- async consumeLinkingTicket(ticket) {
2022
- await this.call({
2023
- kind: "consumeLinkingTicket",
2598
+ /**
2599
+ * The linking ticket, version 3, for the handshake `payload`, verified
2600
+ * inside the call: for a client started from a device record. The new
2601
+ * device's credential is signed by THIS device's key. Rejects when this
2602
+ * device's own chain is at its limit (show the "link from another device"
2603
+ * copy) or it holds no device record. Seal it with
2604
+ * {@link MessagingClient.sealLinkingTicketV3For} and the SAME payload and
2605
+ * `expected`.
2606
+ */
2607
+ async buildLinkingTicketV3For(payload, expected, lastAppEvents = []) {
2608
+ return await this.call({
2609
+ kind: "buildLinkingTicketV3For",
2610
+ id: this.nextId++,
2611
+ payload,
2612
+ ...linkExpectedFields(expected),
2613
+ lastAppEvents,
2614
+ nowMs: this.now()
2615
+ });
2616
+ }
2617
+ /**
2618
+ * The generation and its secret for the link-auth envelope, version 6:
2619
+ * answered only for a handshake whose version 3 ticket this client built
2620
+ * since it started.
2621
+ */
2622
+ async linkGenerationFor(payload, expected) {
2623
+ return await this.call({
2624
+ kind: "linkGenerationFor",
2625
+ id: this.nextId++,
2626
+ payload,
2627
+ ...linkExpectedFields(expected)
2628
+ });
2629
+ }
2630
+ /**
2631
+ * Complete the link on the NEW device, on the staging client of
2632
+ * {@link MessagingClient.beginDeviceLink}: every check of the ticket and of
2633
+ * the envelope's two values, then the DeviceGroup, then the device record.
2634
+ * Rejects with `account refused: link-refused` when anything does not fit:
2635
+ * nothing was kept. Afterwards close this client and start
2636
+ * {@link MessagingClient.initFromDeviceRecord} on the same store.
2637
+ */
2638
+ async completeDeviceLink(ticket, generation, generationSecret) {
2639
+ return await this.call({
2640
+ kind: "completeDeviceLink",
2024
2641
  id: this.nextId++,
2025
2642
  ticket,
2643
+ generation,
2644
+ generationSecret,
2645
+ nowMs: this.now(),
2646
+ storageFeatures: storageFeaturesOf(this.storage)
2647
+ });
2648
+ }
2649
+ /**
2650
+ * Create the DeviceGroup anew after a take-over (the account identity
2651
+ * contract, 3.13, "The DeviceGroup reset"): drops what this device holds
2652
+ * under the DeviceGroup's id, then creates the group alone. Call it ONLY
2653
+ * after the server answered the DeviceGroup reset with `200` or with the
2654
+ * reason `already_reset`. There is no call that joins a DeviceGroup from
2655
+ * outside.
2656
+ */
2657
+ async recreateDeviceGroup() {
2658
+ await this.call({ kind: "recreateDeviceGroup", id: this.nextId++, nowMs: this.now() });
2659
+ }
2660
+ /**
2661
+ * Step 0 of a rotation (removing a device, Secure my account): the next
2662
+ * generation is the pinned one plus one, proven by the root's own
2663
+ * statement, or the call rejects (`account refused:
2664
+ * pinned-generation-unproven`, `generation-ahead`). A listed device is
2665
+ * offered only when its signed delivery key verifies under a leaf of THIS
2666
+ * device's own DeviceGroup. Signs nothing.
2667
+ */
2668
+ async planRotation(start, devices, rootPartGeneration = 0) {
2669
+ return await this.call({
2670
+ kind: "planRotation",
2671
+ id: this.nextId++,
2672
+ start,
2673
+ devices,
2674
+ rootPartGeneration
2675
+ });
2676
+ }
2677
+ /**
2678
+ * Step 1 of a rotation, THE BUILD, with the pending item of `slot` as the
2679
+ * root's source (an account with no backup yet). It runs in this client's
2680
+ * Worker, which opens the root itself for the length of the call (rulings
2681
+ * V136 and V244): nothing of the root reaches this realm or any other
2682
+ * Worker, in the answer or in a refusal. Only the tab's own client builds
2683
+ * (`ClientConfig.tabClient`); any other answers `account refused:
2684
+ * background-worker`. `kept` is every device that stays, this one
2685
+ * included. The answer is the request for the server (public values and
2686
+ * ciphertext) with the record's id, or `keptSetRefused` naming the one
2687
+ * device that cannot be kept: a value, final for that kept set. The
2688
+ * request carries no root part. No request is made by this call.
2689
+ */
2690
+ async rotateGenerationWithPending(args) {
2691
+ return await this.call({
2692
+ kind: "rotateGenerationWithPending",
2693
+ id: this.nextId++,
2694
+ slot: args.slot,
2695
+ start: args.start,
2696
+ devices: args.devices,
2697
+ kept: args.kept,
2698
+ reason: args.reason,
2699
+ accountId: args.accountId,
2700
+ hostState: args.hostState,
2701
+ nowMs: this.now()
2702
+ });
2703
+ }
2704
+ /**
2705
+ * Step 1 of a rotation, THE BUILD, with the backup as the root's source:
2706
+ * the root part as the server holds it and the CURRENT recovery phrase,
2707
+ * and `newPhrase` when the person asked for a new one. As
2708
+ * {@link rotateGenerationWithPending}: the root part is opened inside this
2709
+ * client's Worker for the length of the call. The phrases cross to the
2710
+ * Worker as bytes; the Worker zeroes its copy when the call has answered
2711
+ * and this call zeroes the copy it made. The strings themselves are the
2712
+ * host's: drop them. A phrase that does not open the root part answers
2713
+ * `account refused: backup-authentication` and nothing of the cause.
2714
+ */
2715
+ async rotateGenerationWithBackup(args) {
2716
+ const encoder = new TextEncoder();
2717
+ const phrase = encoder.encode(args.phrase);
2718
+ const newPhrase = args.newPhrase === void 0 ? void 0 : encoder.encode(args.newPhrase);
2719
+ try {
2720
+ return await this.call({
2721
+ kind: "rotateGenerationWithBackup",
2722
+ id: this.nextId++,
2723
+ rootPart: args.rootPart,
2724
+ phrase,
2725
+ ...newPhrase ? { newPhrase } : {},
2726
+ start: args.start,
2727
+ devices: args.devices,
2728
+ kept: args.kept,
2729
+ reason: args.reason,
2730
+ accountId: args.accountId,
2731
+ hostState: args.hostState,
2732
+ nowMs: this.now()
2733
+ });
2734
+ } finally {
2735
+ phrase.fill(0);
2736
+ newPhrase?.fill(0);
2737
+ }
2738
+ }
2739
+ /**
2740
+ * Step 3 of a rotation this device built, on the running client: the
2741
+ * server's answer AS RECEIVED, judged inside the SDK (ruling V161; no
2742
+ * value says "applied"). When the device adopts, this client runs on the
2743
+ * new record from that moment. `"undecided"`: nothing changed, the record
2744
+ * stays.
2745
+ */
2746
+ async completeRotation(recordId, answer) {
2747
+ return await this.call({
2748
+ kind: "completeRotationOnClient",
2749
+ id: this.nextId++,
2750
+ recordId,
2751
+ answer: rotationAnswerFields(answer)
2752
+ });
2753
+ }
2754
+ /**
2755
+ * Step 7 of a rotation, on every other kept device: this device's mailbox
2756
+ * row (`GET /v1/devices/self/credential`). The credential must be this
2757
+ * device's and the root's own; the wrap must open with this device's
2758
+ * delivery key and match the root's statement. On any refusal the device
2759
+ * stays on its generation. From the adoption on, this device's next Commit
2760
+ * in each conversation carries its new credential.
2761
+ */
2762
+ async adoptGeneration(row) {
2763
+ return await this.call({
2764
+ kind: "adoptGeneration",
2765
+ id: this.nextId++,
2766
+ generation: row.generation,
2767
+ credential: row.credential,
2768
+ gsWrap: row.gsWrap,
2769
+ statement: row.statement,
2026
2770
  nowMs: this.now()
2027
2771
  });
2028
2772
  }
2029
2773
  // ------------------------ Recovery (account backup) ------------------------
2030
2774
  // All static + stateless: they run on an ephemeral worker, so the recovery screen can
2031
- // call them before any client is initialised. Same Argon2id/AES-256-GCM IdentityBackup
2032
- // wire format as the iOS/Android FFI bindings — backups are portable across platforms.
2775
+ // call them before any client is initialised. `encryptBackup` and `decryptBackup`
2776
+ // (the version 1 blob) took and returned the account identity and left every
2777
+ // binding on 2026-11-28: a backup is made, proven and opened by `AccountSetup`
2778
+ // and the restore calls, which hand no root to a host.
2779
+ /**
2780
+ * The one switch of self-admission as the wasm module of this package was
2781
+ * COMPILED (a constant of the SDK's source: the same value in every artifact
2782
+ * built from one commit). Read-only. `false`: the module refuses every
2783
+ * external Commit, lists no capability marker and sends nothing of the
2784
+ * feature. A host that ships more than one artifact asserts at start that
2785
+ * they agree.
2786
+ */
2787
+ static async selfAdmissionCompiled() {
2788
+ return _MessagingClient.ephemeralWorkerCall({
2789
+ kind: "selfAdmissionCompiled",
2790
+ id: 1
2791
+ });
2792
+ }
2033
2793
  /** Generate a fresh 12-word BIP39 mnemonic, returned as its canonical phrase string. */
2034
2794
  static async generateMnemonicPhrase() {
2035
2795
  return _MessagingClient.ephemeralWorkerCall({
@@ -2038,7 +2798,7 @@ var MessagingClient = class _MessagingClient {
2038
2798
  });
2039
2799
  }
2040
2800
  /** Validate + canonicalise a user-entered phrase (BIP39 wordlist + checksum). Rejects
2041
- * malformed input. Use on the recovery screen before calling `decryptBackup`. */
2801
+ * malformed input. */
2042
2802
  static async normalizeMnemonicPhrase(phrase) {
2043
2803
  return _MessagingClient.ephemeralWorkerCall({
2044
2804
  kind: "normalizeMnemonicPhrase",
@@ -2046,30 +2806,6 @@ var MessagingClient = class _MessagingClient {
2046
2806
  phrase
2047
2807
  });
2048
2808
  }
2049
- /** Encrypt an IdentityBackup for `POST /v1/recovery/blobs`. `deviceGroupSnapshot` may be
2050
- * empty (Conservative path) or the DeviceGroup's `exportConversationStateSnapshot`. */
2051
- static async encryptBackup(args) {
2052
- return _MessagingClient.ephemeralWorkerCall({
2053
- kind: "encryptBackup",
2054
- id: 1,
2055
- mnemonicPhrase: args.mnemonicPhrase,
2056
- accountId: args.accountId,
2057
- identityExport: args.identityExport,
2058
- deviceGroupSnapshot: args.deviceGroupSnapshot,
2059
- conversationSnapshots: args.conversationSnapshots ?? [],
2060
- createdAtMs: args.createdAtMs
2061
- });
2062
- }
2063
- /** Decrypt a recovery blob from `GET /v1/recovery/blobs`. Throws on wrong mnemonic or a
2064
- * tampered blob. The returned `identity_export` is the secret seed for `init`. */
2065
- static async decryptBackup(blob, mnemonicPhrase) {
2066
- return _MessagingClient.ephemeralWorkerCall({
2067
- kind: "decryptBackup",
2068
- id: 1,
2069
- blob,
2070
- mnemonicPhrase
2071
- });
2072
- }
2073
2809
  /**
2074
2810
  * Whether `mnemonicPhrase` opens `blob` (a recovery backup as the server returned
2075
2811
  * it), with THREE answers to switch on:
@@ -2084,7 +2820,6 @@ var MessagingClient = class _MessagingClient {
2084
2820
  * version or a format this build cannot read, a payload it cannot decode, a
2085
2821
  * failure inside the SDK. Delete nothing, claim nothing, ask again later.
2086
2822
  *
2087
- * `decryptBackup` rejects with one message for the last two alike; it is unchanged.
2088
2823
  * This call NEVER rejects: a wasm trap, an out-of-memory failure and a one-shot
2089
2824
  * worker that could not be created or did not answer are `couldNotCheck` with
2090
2825
  * `reason: "internal"`. It resolves nothing of the backup: the decrypted identity
@@ -2105,62 +2840,134 @@ var MessagingClient = class _MessagingClient {
2105
2840
  }
2106
2841
  }
2107
2842
  // ------------------------ Peer-assisted history transfer ------------------------
2108
- // Authenticated (sign-then-encrypt) device-to-device history used by linking and
2109
- // post-recovery peer re-add. Confidential to the recipient's ephemeral X25519 key AND
2110
- // signed by the account identity key, so the receiver proves the sender. Plaintext-only
2111
- // share — preserves forward secrecy (no MLS keys leave the device).
2112
- /** Seal+sign a `HistoryBundle` for a recipient device. `recipientPub` (X25519, 32B) is the
2113
- * recipient's ephemeral pubkey from the linking QR; `senderIdentitySecret` (Ed25519 seed,
2114
- * 32B) is this account's identity key. Returns the blob to POST to /v1/history-transfers. */
2115
- static async sealHistoryBundle(bundle, recipientPub, senderIdentitySecret) {
2116
- return _MessagingClient.ephemeralWorkerCall({
2117
- kind: "sealHistoryBundle",
2118
- id: 1,
2119
- bundle,
2120
- recipientPub,
2121
- senderIdentitySecret
2843
+ // History, version 3 (2026-11-25, rulings V88 to V92). A bundle is signed by
2844
+ // this DEVICE's key and sealed only to a key the SDK verified itself: the
2845
+ // signed delivery key of a device that is a verified leaf of this device's own
2846
+ // tree, or the key of a link handshake verified against what the person was
2847
+ // shown. No call takes a recipient key, so a server that answers a key request
2848
+ // with a key of its own gets nothing. The raw-key, seed-signed forms
2849
+ // (sealHistoryBundle, openHistoryBundle and their Pq twins) are REMOVED.
2850
+ /** The counter the next {@link publishHistoryDeliveryKey} with this floor will
2851
+ * sign. A host that keeps the device key outside the SDK's store writes this
2852
+ * number beside that key BEFORE the publish, and passes what it kept as
2853
+ * `counterFloor` from then on (0 when it keeps none). Never a server's number. */
2854
+ async historyDeliveryKeyNextCounter(counterFloor = 0) {
2855
+ return await this.call({
2856
+ kind: "historyDeliveryKeyNextCounter",
2857
+ id: this.nextId++,
2858
+ counterFloor
2122
2859
  });
2123
2860
  }
2124
- /** Open+verify a sealed history bundle. `recipientPriv` (X25519, 32B) is this device's
2125
- * ephemeral private key; `senderIdentityPub` (Ed25519, 32B) is the account identity pubkey
2126
- * from the linking handshake. Throws if the signature doesn't verify. */
2127
- static async openHistoryBundle(sealed, recipientPriv, senderIdentityPub) {
2128
- return _MessagingClient.ephemeralWorkerCall({
2129
- kind: "openHistoryBundle",
2130
- id: 1,
2131
- sealed,
2132
- recipientPriv,
2133
- senderIdentityPub
2861
+ /** This device's signed history delivery key: post it at every start. The key
2862
+ * pair is made once, inside the SDK; the device signs only the key it holds. */
2863
+ async publishHistoryDeliveryKey(counterFloor = 0) {
2864
+ return await this.call({
2865
+ kind: "publishHistoryDeliveryKey",
2866
+ id: this.nextId++,
2867
+ counterFloor
2868
+ });
2869
+ }
2870
+ /** The server refused the publication (`409 delivery_key_counter_behind`) and
2871
+ * answered with the statement IT holds. Taken only when that statement
2872
+ * verifies strictly under THIS device's own key and is not older than this
2873
+ * device's own; resolves with the statement to publish once more. Anything
2874
+ * else rejects ({@link NotPermittedError}) and nothing is signed. */
2875
+ async adoptHistoryDeliveryKeyCounter(stored) {
2876
+ return await this.call({
2877
+ kind: "adoptHistoryDeliveryKeyCounter",
2878
+ id: this.nextId++,
2879
+ stored
2134
2880
  });
2135
2881
  }
2136
2882
  /**
2137
- * Post-quantum {@link sealHistoryBundle}: `recipientPub` is the recipient's
2138
- * X-Wing public key ({@link HPKE_PQ_PUBLIC_KEY_BYTES} bytes). Wrapper `v: 2`;
2139
- * the classical open refuses it and vice versa.
2883
+ * Verify `recipient` (the statement a server returned for the device the bundle
2884
+ * names) in this device's own tree, then sign the bundle with the device key and
2885
+ * seal it to that key. `ownAccount` is what the host believes (true: a device of
2886
+ * this account, looked up in the DeviceGroup; false: another account's device,
2887
+ * looked up in the tree of the bundle's conversation). It decides nothing: the
2888
+ * SDK takes the path the recipient's verified identity gives and rejects
2889
+ * ({@link NotPermittedError}) when the host said the other one.
2140
2890
  */
2141
- static async sealHistoryBundlePq(bundle, recipientPub, senderIdentitySecret) {
2142
- if (recipientPub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {
2143
- throw new Error(`sealHistoryBundlePq: recipientPub must be ${HPKE_PQ_PUBLIC_KEY_BYTES} bytes`);
2144
- }
2145
- return _MessagingClient.ephemeralWorkerCall({
2146
- kind: "sealHistoryBundlePq",
2147
- id: 1,
2891
+ async sealHistoryBundleV3(bundle, recipient, ownAccount) {
2892
+ return await this.call({
2893
+ kind: "sealHistoryBundleV3",
2894
+ id: this.nextId++,
2148
2895
  bundle,
2149
- recipientPub,
2150
- senderIdentitySecret
2896
+ recipient,
2897
+ ownAccount
2151
2898
  });
2152
2899
  }
2153
- /** Post-quantum {@link openHistoryBundle}: `recipientPriv` is the 32-byte X-Wing seed. */
2154
- static async openHistoryBundlePq(sealed, recipientPriv, senderIdentityPub) {
2155
- if (recipientPriv.length !== 32) {
2156
- throw new Error("openHistoryBundlePq: recipientPriv must be 32 bytes");
2157
- }
2158
- return _MessagingClient.ephemeralWorkerCall({
2159
- kind: "openHistoryBundlePq",
2160
- id: 1,
2900
+ /** The link's own transfer. The handshake `payload` is verified inside the call
2901
+ * against what this device was shown, and the bundle is sealed to the verified
2902
+ * handshake's key: no key can be passed. Rejects with
2903
+ * {@link LinkCommitmentMismatchError} when the payload is not the committed one. */
2904
+ async sealLinkHistoryBundle(bundle, payload, expected) {
2905
+ return await this.call({
2906
+ kind: "sealLinkHistoryBundle",
2907
+ id: this.nextId++,
2908
+ bundle,
2909
+ payload,
2910
+ ...linkExpectedFields(expected)
2911
+ });
2912
+ }
2913
+ /** Open a transfer sealed to this device's published delivery key. `ownAccount`
2914
+ * as in {@link sealHistoryBundleV3}, and as there only a reason to refuse. A
2915
+ * bundle whose import the host CONFIRMED ({@link confirmHistoryImport}) is never
2916
+ * returned again: the transfer then rejects with {@link HistoryRefusedError}
2917
+ * `replayed`, and the host drops it. Until the confirmation the same transfer
2918
+ * opens again (the host's import is idempotent by event id). */
2919
+ async openHistoryBundleV3(sealed, ownAccount) {
2920
+ return await this.call({
2921
+ kind: "openHistoryBundleV3",
2922
+ id: this.nextId++,
2161
2923
  sealed,
2162
- recipientPriv,
2163
- senderIdentityPub
2924
+ ownAccount
2925
+ });
2926
+ }
2927
+ /** The NEW device opens its link's own transfer, sealed to the X-Wing key of the
2928
+ * handshake it published; `recipientPriv` is that key's 32-byte seed. */
2929
+ async openLinkHistoryBundle(sealed, recipientPriv) {
2930
+ return await this.call({
2931
+ kind: "openLinkHistoryBundle",
2932
+ id: this.nextId++,
2933
+ sealed,
2934
+ recipientPriv
2935
+ });
2936
+ }
2937
+ /** Ruling V177: call AFTER the host's own store holds the events of a bundle an
2938
+ * open returned, with that result's `import_id`. From then on the same bundle
2939
+ * (sealed afresh or not, from any sender) is refused as a replay. `true` when
2940
+ * this call recorded it, `false` when it was recorded before. The id may be
2941
+ * kept and confirmed after a restart. A local write; no request. */
2942
+ async confirmHistoryImport(importId) {
2943
+ return await this.call({
2944
+ kind: "confirmHistoryImport",
2945
+ id: this.nextId++,
2946
+ importId
2947
+ });
2948
+ }
2949
+ /** Whether this device's trust record names `deviceId` for history. */
2950
+ async historyTrust(deviceId) {
2951
+ return await this.call({
2952
+ kind: "historyTrust",
2953
+ id: this.nextId++,
2954
+ deviceId
2955
+ });
2956
+ }
2957
+ /** Record that this device shipped history to `deviceId`, once the server
2958
+ * accepted the transfer and never before. */
2959
+ async recordHistoryShipped(deviceId) {
2960
+ await this.call({ kind: "recordHistoryShipped", id: this.nextId++, deviceId });
2961
+ }
2962
+ /** For a device of this account: ship history by itself, only after the person
2963
+ * confirms on this device, or not at all. Ask it for every entry of the
2964
+ * admission ledger and before the "send your chats" prompt; a link's own
2965
+ * transfer does not ask. */
2966
+ async historyShipDecision(deviceId) {
2967
+ return await this.call({
2968
+ kind: "historyShipDecision",
2969
+ id: this.nextId++,
2970
+ deviceId
2164
2971
  });
2165
2972
  }
2166
2973
  /**
@@ -2297,6 +3104,32 @@ var MessagingClient = class _MessagingClient {
2297
3104
  nowMs
2298
3105
  });
2299
3106
  }
3107
+ /**
3108
+ * THE ONE TAP AFTER A RESTORE BESIDE DEVICES THAT STAY (ruling V123). Call it on
3109
+ * a KEPT device when the person confirmed, on that device, the device `deviceId`
3110
+ * that restored with the recovery phrase and waits for its DeviceGroup.
3111
+ * `keyPackage` is a KeyPackage of that device, as the host fetched it. Nothing
3112
+ * the server says is believed: the KeyPackage must be the named device's, and its
3113
+ * credential must verify for THIS device's own account root, be signed by the
3114
+ * root itself (a linked device enters by its ticket) and stand at the generation
3115
+ * this device holds; anything else rejects (`NotPermitted`; `StaleGeneration`
3116
+ * when this device is behind its account). Then the DeviceGroup's ordinary Add,
3117
+ * sent with its Welcome and merged only when the delivery service accepted. As
3118
+ * every Commit there it rejects with `DeviceGroupBehind` while this device is
3119
+ * behind or may not commit yet after a rotation (catch up, or run the sweep, and
3120
+ * call again), and with `WelcomeUndelivered` when the Add is in and the Welcome is
3121
+ * not (call again). The waiting device calls nothing: the Welcome reaches it by
3122
+ * the transport. MLS only.
3123
+ */
3124
+ async addRestoredDevice(deviceId, keyPackage, nowMs = this.now()) {
3125
+ await this.call({
3126
+ kind: "addRestoredDevice",
3127
+ id: this.nextId++,
3128
+ deviceId,
3129
+ keyPackage,
3130
+ nowMs
3131
+ });
3132
+ }
2300
3133
  /**
2301
3134
  * Export a portable MLS state snapshot for one conversation ([CR-7]).
2302
3135
  *
@@ -2597,6 +3430,29 @@ var MessagingClient = class _MessagingClient {
2597
3430
  const heads = await this.transport.fetchLogHeads();
2598
3431
  return heads === null || heads === void 0 ? null : heads.map(logHeadToWire);
2599
3432
  }
3433
+ if (method === "send" || method === "sendBatch") {
3434
+ try {
3435
+ return await t[method]?.(...args);
3436
+ } catch (e) {
3437
+ if (e?.staleGeneration === true) {
3438
+ throw new Error(TRANSPORT_STALE_GENERATION);
3439
+ }
3440
+ throw e;
3441
+ }
3442
+ }
3443
+ if (method === "sendExternalCommit" || method === "sendExternalCommits" || method === "publishSealedGroupInfo") {
3444
+ try {
3445
+ return await t[method]?.(...args) ?? null;
3446
+ } catch (e) {
3447
+ if (e?.epochOccupied === true) {
3448
+ throw new Error(EXTERNAL_COMMIT_EPOCH_OCCUPIED);
3449
+ }
3450
+ if (e?.staleGeneration === true) {
3451
+ throw new Error(TRANSPORT_STALE_GENERATION);
3452
+ }
3453
+ throw e;
3454
+ }
3455
+ }
2600
3456
  return await t[method]?.(...args);
2601
3457
  }
2602
3458
  async handleWorker(msg) {
@@ -2730,11 +3586,162 @@ function isSenderMismatchError(e) {
2730
3586
  const text = typeof e === "string" ? e : e !== null && typeof e === "object" && typeof e.message === "string" ? e.message : null;
2731
3587
  return text !== null && text.startsWith(SENDER_MISMATCH_PREFIX);
2732
3588
  }
3589
+ var STORE_MOVED_PREFIX = "store moved: ";
3590
+ var StoreMovedError = class extends Error {
3591
+ constructor(message) {
3592
+ super(message);
3593
+ this.name = "StoreMovedError";
3594
+ }
3595
+ };
3596
+ function isStoreMovedError(e) {
3597
+ const text = typeof e === "string" ? e : e !== null && typeof e === "object" && typeof e.message === "string" ? e.message : null;
3598
+ return text !== null && text.startsWith(STORE_MOVED_PREFIX);
3599
+ }
3600
+ var READ_ONLY_PREFIX = "read-only client: ";
3601
+ var ReadOnlyError = class extends Error {
3602
+ constructor(message) {
3603
+ super(message);
3604
+ this.name = "ReadOnlyError";
3605
+ }
3606
+ };
3607
+ function isReadOnlyError(e) {
3608
+ const text = typeof e === "string" ? e : e !== null && typeof e === "object" && typeof e.message === "string" ? e.message : null;
3609
+ return text !== null && text.startsWith(READ_ONLY_PREFIX);
3610
+ }
3611
+ function linkExpectedFields(expected) {
3612
+ return "code" in expected ? { expectedCode: expected.code } : { expectedQr: expected.qrCommitment };
3613
+ }
3614
+ var LINK_COMMITMENT_MISMATCH_PREFIX = "link commitment mismatch: ";
3615
+ var LinkCommitmentMismatchError = class extends Error {
3616
+ constructor(message) {
3617
+ super(message);
3618
+ this.name = "LinkCommitmentMismatchError";
3619
+ }
3620
+ };
3621
+ function isLinkCommitmentMismatchError(e) {
3622
+ if (e instanceof LinkCommitmentMismatchError) return true;
3623
+ const text = e instanceof Error ? e.message : typeof e === "string" ? e : null;
3624
+ return text !== null && text.startsWith(LINK_COMMITMENT_MISMATCH_PREFIX);
3625
+ }
3626
+ var WELCOME_MISLABELED_PREFIX = "welcome mislabeled: ";
3627
+ var WelcomeMislabeledError = class extends Error {
3628
+ constructor(message) {
3629
+ super(message);
3630
+ this.name = "WelcomeMislabeledError";
3631
+ }
3632
+ };
3633
+ function isWelcomeMislabeledError(e) {
3634
+ const text = typeof e === "string" ? e : e !== null && typeof e === "object" && typeof e.message === "string" ? e.message : null;
3635
+ return text !== null && text.startsWith(WELCOME_MISLABELED_PREFIX);
3636
+ }
3637
+ var STALE_GENERATION_PREFIX = "stale generation: ";
3638
+ var StaleGenerationError = class extends Error {
3639
+ constructor(message) {
3640
+ super(message);
3641
+ this.name = "StaleGenerationError";
3642
+ }
3643
+ };
3644
+ function isStaleGenerationError(e) {
3645
+ const text = typeof e === "string" ? e : e !== null && typeof e === "object" && typeof e.message === "string" ? e.message : null;
3646
+ return text !== null && text.startsWith(STALE_GENERATION_PREFIX);
3647
+ }
3648
+ var DEVICE_GROUP_BEHIND_PREFIX = "device group behind: ";
3649
+ var DeviceGroupBehindError = class extends Error {
3650
+ constructor(message) {
3651
+ super(message);
3652
+ this.name = "DeviceGroupBehindError";
3653
+ }
3654
+ };
3655
+ function isDeviceGroupBehindError(e) {
3656
+ const text = typeof e === "string" ? e : e !== null && typeof e === "object" && typeof e.message === "string" ? e.message : null;
3657
+ return text !== null && text.startsWith(DEVICE_GROUP_BEHIND_PREFIX);
3658
+ }
3659
+ var LINK_CHAIN_TOO_DEEP_PREFIX = "link chain too deep: ";
3660
+ var LinkChainTooDeepError = class extends Error {
3661
+ constructor(message) {
3662
+ super(message);
3663
+ this.name = "LinkChainTooDeepError";
3664
+ }
3665
+ };
3666
+ var LINK_ADD_REFUSED_PREFIX = "link add refused: ";
3667
+ var LinkAddRefusedError = class extends Error {
3668
+ constructor(message) {
3669
+ super(message);
3670
+ this.name = "LinkAddRefusedError";
3671
+ }
3672
+ };
3673
+ var WELCOME_WAITS_PREFIX = "welcome waits: ";
3674
+ var WelcomeWaitsError = class extends Error {
3675
+ constructor(message) {
3676
+ super(message);
3677
+ this.name = "WelcomeWaitsError";
3678
+ }
3679
+ };
3680
+ function startsWithPrefix(e, prefix) {
3681
+ const text = typeof e === "string" ? e : e !== null && typeof e === "object" && typeof e.message === "string" ? e.message : null;
3682
+ return text !== null && text.startsWith(prefix);
3683
+ }
3684
+ function isLinkChainTooDeepError(e) {
3685
+ return startsWithPrefix(e, LINK_CHAIN_TOO_DEEP_PREFIX);
3686
+ }
3687
+ function isLinkAddRefusedError(e) {
3688
+ return startsWithPrefix(e, LINK_ADD_REFUSED_PREFIX);
3689
+ }
3690
+ function isWelcomeWaitsError(e) {
3691
+ return startsWithPrefix(e, WELCOME_WAITS_PREFIX);
3692
+ }
3693
+ var HISTORY_REFUSED_PREFIX = "history refused: ";
3694
+ var HistoryRefusedError = class extends Error {
3695
+ reason;
3696
+ constructor(message) {
3697
+ super(message);
3698
+ this.name = "HistoryRefusedError";
3699
+ const reason = message.slice(HISTORY_REFUSED_PREFIX.length);
3700
+ this.reason = HISTORY_REFUSAL_REASONS.includes(reason) ? reason : "unknown";
3701
+ }
3702
+ };
3703
+ var HISTORY_REFUSAL_REASONS = [
3704
+ "recipient",
3705
+ "sender",
3706
+ "signature",
3707
+ "recipient-key",
3708
+ "too-large",
3709
+ "replayed"
3710
+ ];
3711
+ function isHistoryRefusedError(e) {
3712
+ if (e instanceof HistoryRefusedError) return true;
3713
+ const text = typeof e === "string" ? e : e !== null && typeof e === "object" && typeof e.message === "string" ? e.message : null;
3714
+ return text !== null && text.startsWith(HISTORY_REFUSED_PREFIX);
3715
+ }
3716
+ var JOURNAL_FULL_PREFIX = "journal full: ";
3717
+ var JournalFullError = class extends Error {
3718
+ constructor(message) {
3719
+ super(message);
3720
+ this.name = "JournalFullError";
3721
+ }
3722
+ };
3723
+ function isJournalFullError(e) {
3724
+ const text = typeof e === "string" ? e : e !== null && typeof e === "object" && typeof e.message === "string" ? e.message : null;
3725
+ return text !== null && text.startsWith(JOURNAL_FULL_PREFIX);
3726
+ }
2733
3727
  function errorFromWorker(text) {
2734
3728
  if (text.startsWith(NOT_PERMITTED_PREFIX)) return new NotPermittedError(text);
2735
3729
  if (text.startsWith(SENDER_MISMATCH_PREFIX)) return new SenderMismatchError(text);
3730
+ if (text.startsWith(STORE_MOVED_PREFIX)) return new StoreMovedError(text);
3731
+ if (text.startsWith(READ_ONLY_PREFIX)) return new ReadOnlyError(text);
3732
+ if (text.startsWith(WELCOME_MISLABELED_PREFIX)) return new WelcomeMislabeledError(text);
3733
+ if (text.startsWith(LINK_COMMITMENT_MISMATCH_PREFIX)) return new LinkCommitmentMismatchError(text);
3734
+ if (text.startsWith(STALE_GENERATION_PREFIX)) return new StaleGenerationError(text);
3735
+ if (text.startsWith(DEVICE_GROUP_BEHIND_PREFIX)) return new DeviceGroupBehindError(text);
3736
+ if (text.startsWith(JOURNAL_FULL_PREFIX)) return new JournalFullError(text);
3737
+ if (text.startsWith(LINK_CHAIN_TOO_DEEP_PREFIX)) return new LinkChainTooDeepError(text);
3738
+ if (text.startsWith(LINK_ADD_REFUSED_PREFIX)) return new LinkAddRefusedError(text);
3739
+ if (text.startsWith(WELCOME_WAITS_PREFIX)) return new WelcomeWaitsError(text);
3740
+ if (text.startsWith(HISTORY_REFUSED_PREFIX)) return new HistoryRefusedError(text);
2736
3741
  return new Error(text);
2737
3742
  }
3743
+ var EXTERNAL_COMMIT_EPOCH_OCCUPIED = "external commit: epoch occupied";
3744
+ var TRANSPORT_STALE_GENERATION = "transport: stale generation";
2738
3745
  async function emulateSendBatch(transport, envelopes) {
2739
3746
  let delivered = 0;
2740
3747
  for (const envelope of envelopes) {
@@ -2777,16 +3784,35 @@ function sameBytesU8(a, b) {
2777
3784
  for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
2778
3785
  return true;
2779
3786
  }
3787
+ function holeOfJoin(result) {
3788
+ if (result.beforeReturn !== void 0 && result.beforeReturn !== null) {
3789
+ result.beforeReturn = logHoleFromWire(result.beforeReturn);
3790
+ }
3791
+ }
2780
3792
  export {
3793
+ AccountSetup,
3794
+ AccountSetupClosedError,
2781
3795
  BATCH_PARTIAL_PREFIX,
2782
3796
  CONTENT_TYPE_CBOR,
2783
3797
  CONTENT_TYPE_CBOR_LEGACY_V1,
2784
3798
  CONTENT_TYPE_JSON,
2785
3799
  CONTENT_TYPE_JSON_LEGACY_V1,
3800
+ DEVICE_GROUP_BEHIND_PREFIX,
3801
+ DeviceGroupBehindError,
2786
3802
  EphemeralWorkerError,
3803
+ HISTORY_REFUSED_PREFIX,
2787
3804
  HPKE_PQ_ENC_BYTES,
2788
3805
  HPKE_PQ_PUBLIC_KEY_BYTES,
3806
+ HistoryRefusedError,
2789
3807
  IndexedDbStorage,
3808
+ JOURNAL_FULL_PREFIX,
3809
+ JournalFullError,
3810
+ LINK_ADD_REFUSED_PREFIX,
3811
+ LINK_CHAIN_TOO_DEEP_PREFIX,
3812
+ LINK_COMMITMENT_MISMATCH_PREFIX,
3813
+ LinkAddRefusedError,
3814
+ LinkChainTooDeepError,
3815
+ LinkCommitmentMismatchError,
2790
3816
  MAX_PREVIEW_PREREQUISITES,
2791
3817
  MessagingClient,
2792
3818
  MessagingClientClosedError,
@@ -2795,16 +3821,38 @@ export {
2795
3821
  PING_WIRE_CONTRACT_HEADER,
2796
3822
  PING_WIRE_CONTRACT_HEADER_VALUE,
2797
3823
  PING_WIRE_CONTRACT_VERSION,
3824
+ READ_ONLY_PREFIX,
3825
+ ReadOnlyError,
2798
3826
  SENDER_MISMATCH_PREFIX,
3827
+ STALE_GENERATION_PREFIX,
3828
+ STORE_MOVED_PREFIX,
2799
3829
  SenderMismatchError,
3830
+ StaleGenerationError,
3831
+ StoreMovedError,
2800
3832
  ValidationError,
3833
+ WELCOME_MISLABELED_PREFIX,
3834
+ WELCOME_WAITS_PREFIX,
2801
3835
  WIRE_VERSION_MIN_ACCEPTED,
2802
3836
  WebSocketTransport,
3837
+ WelcomeMislabeledError,
3838
+ WelcomeWaitsError,
3839
+ accountRefusalCode,
2803
3840
  backupPhraseCheckFromWire,
2804
3841
  describeTransportError,
2805
3842
  emulateSendBatch,
3843
+ isDeviceGroupBehindError,
3844
+ isHistoryRefusedError,
3845
+ isJournalFullError,
3846
+ isLinkAddRefusedError,
3847
+ isLinkChainTooDeepError,
3848
+ isLinkCommitmentMismatchError,
2806
3849
  isNotPermittedError,
3850
+ isReadOnlyError,
2807
3851
  isSenderMismatchError,
3852
+ isStaleGenerationError,
3853
+ isStoreMovedError,
3854
+ isWelcomeMislabeledError,
3855
+ isWelcomeWaitsError,
2808
3856
  negotiates,
2809
3857
  notPermittedRule,
2810
3858
  openNotificationPreview,