@witbitz/sdk 0.0.0-stage → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +200 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +223 -0
  6. package/accountIndexDoc.js +122 -0
  7. package/accountOwner.js +59 -0
  8. package/accountRecord.js +90 -0
  9. package/accountScope.js +114 -0
  10. package/accountSeal.js +42 -0
  11. package/accountStores.js +173 -0
  12. package/acctV2App.js +619 -0
  13. package/acctV2Check.js +29 -0
  14. package/acctV2Client.js +382 -0
  15. package/acctV2Keys.js +43 -0
  16. package/acctV2Legacy.js +14 -0
  17. package/acctV2Switch.js +80 -0
  18. package/acctV2UiCore.js +857 -0
  19. package/acctV2WebAuthn.js +61 -0
  20. package/acctV2Wire.js +59 -0
  21. package/address.js +42 -0
  22. package/attestedBox.js +30 -0
  23. package/attestedRooms.js +78 -0
  24. package/awsKey.js +98 -0
  25. package/backupRecord.js +106 -0
  26. package/backupVault.js +97 -0
  27. package/blocks.js +115 -0
  28. package/blocksPush.js +64 -0
  29. package/browseSeal.js +103 -0
  30. package/cbor.js +225 -0
  31. package/changePush.js +75 -0
  32. package/chatLock.js +149 -0
  33. package/chatLockSw.js +13 -0
  34. package/cloudDeviceBuilds.js +11 -0
  35. package/cloudDevicePins.js +33 -0
  36. package/cloudDeviceSeal.js +53 -0
  37. package/codeBrowse.js +224 -0
  38. package/codeCloud.js +652 -0
  39. package/codeCloudKeys.js +112 -0
  40. package/codeCommands.js +167 -0
  41. package/codeComputers.js +388 -0
  42. package/codeEgress.js +123 -0
  43. package/codeFilesRoutes.js +17 -0
  44. package/codeMkdir.js +8 -0
  45. package/codeModes.js +57 -0
  46. package/codeOrphanKeys.js +42 -0
  47. package/codeOutputs.js +141 -0
  48. package/codeRelay.js +505 -0
  49. package/codeSentinel.js +86 -0
  50. package/codeTransport.js +295 -0
  51. package/codeUndo.js +48 -0
  52. package/compress.js +24 -0
  53. package/config.js +11 -0
  54. package/connCatalog.js +164 -0
  55. package/connDisp.js +76 -0
  56. package/connOtherWays.js +74 -0
  57. package/connPending.js +16 -0
  58. package/connWrap.js +53 -0
  59. package/connectionEntry.js +89 -0
  60. package/connections.js +562 -0
  61. package/credits.js +30 -0
  62. package/csAttest.js +112 -0
  63. package/decrypt.html +384 -0
  64. package/deviceAttest.js +521 -0
  65. package/deviceCall.js +54 -0
  66. package/deviceKeyCore.js +41 -0
  67. package/deviceSeal.js +59 -0
  68. package/e2ee.js +323 -0
  69. package/eat.js +103 -0
  70. package/emailFork.js +275 -0
  71. package/emailSignIn.js +81 -0
  72. package/emptySpaces.js +111 -0
  73. package/encSource.js +55 -0
  74. package/enclaveAccept.js +214 -0
  75. package/enclaveClaim.js +241 -0
  76. package/enclaveRoute.js +102 -0
  77. package/enclaveSnapshotMerge.js +44 -0
  78. package/entrySig.js +165 -0
  79. package/env.js +73 -0
  80. package/eraseFile.js +58 -0
  81. package/followImage.js +86 -0
  82. package/healNames.js +45 -0
  83. package/idb.js +97 -0
  84. package/idbSeal.js +119 -0
  85. package/indexGone.js +12 -0
  86. package/invite.js +51 -0
  87. package/inviteEnroll.js +67 -0
  88. package/inviteSend.js +68 -0
  89. package/jobAgents.js +87 -0
  90. package/keptMerge.js +84 -0
  91. package/l1-worker-src.js +2 -0
  92. package/l1-worker.js +831 -0
  93. package/laneConfig.js +57 -0
  94. package/laneLinkCore.js +177 -0
  95. package/ledgerView.js +64 -0
  96. package/manifest.json +220 -0
  97. package/mcpRecommended.js +25 -0
  98. package/memberChange.js +123 -0
  99. package/mkseal.js +101 -0
  100. package/nativePush.js +153 -0
  101. package/nitroVerify.js +220 -0
  102. package/noble-p256.js +27 -0
  103. package/notice.js +116 -0
  104. package/notifKey.js +58 -0
  105. package/offlineBundle.js +62 -0
  106. package/ohttp.js +177 -0
  107. package/opencodeWire.js +282 -0
  108. package/oprf.js +70 -0
  109. package/ownAgentLink.js +96 -0
  110. package/ownerPolicy.js +117 -0
  111. package/package.json +254 -4
  112. package/pollVerdict.js +33 -0
  113. package/prefetchPoll.js +60 -0
  114. package/protectedLocal.js +410 -0
  115. package/pushCore.js +42 -0
  116. package/recovery.js +107 -0
  117. package/regions.js +42 -0
  118. package/removedMessage.js +11 -0
  119. package/renameRefusal.js +9 -0
  120. package/replyQuote.js +34 -0
  121. package/reqEnvelope.js +126 -0
  122. package/roomDefaultPrefs.js +76 -0
  123. package/roomDelete.js +109 -0
  124. package/roomName.js +177 -0
  125. package/roomPass.js +256 -0
  126. package/roomRoster.js +289 -0
  127. package/roomSettings.js +61 -0
  128. package/roomState.js +58 -0
  129. package/roomStreamClient.js +115 -0
  130. package/rosterCount.js +49 -0
  131. package/rosterHash.js +13 -0
  132. package/rowSchema.js +113 -0
  133. package/safeMedia.js +116 -0
  134. package/safeMediaPins.js +17 -0
  135. package/schedulesDoc.js +78 -0
  136. package/sdkA2A.js +404 -0
  137. package/sdkAccount.js +470 -0
  138. package/sdkAccountDoc.js +81 -0
  139. package/sdkAccountSections.js +223 -0
  140. package/sdkAgui.js +141 -0
  141. package/sdkAttest.js +34 -0
  142. package/sdkBackup.js +480 -0
  143. package/sdkBackupV2.js +630 -0
  144. package/sdkBrowserPrivate.js +28 -0
  145. package/sdkBuilds.js +208 -0
  146. package/sdkCloudDevice.js +215 -0
  147. package/sdkComputers.js +480 -0
  148. package/sdkDictation.js +142 -0
  149. package/sdkErase.js +283 -0
  150. package/sdkExports.js +69 -0
  151. package/sdkInvitations.js +34 -0
  152. package/sdkKeptAgent.js +188 -0
  153. package/sdkLaneLink.js +205 -0
  154. package/sdkPlan.js +94 -0
  155. package/sdkProtect.js +228 -0
  156. package/sdkRedact.js +36 -0
  157. package/sdkRekey.js +307 -0
  158. package/sdkReport.js +68 -0
  159. package/sdkSafeMedia.js +255 -0
  160. package/sdkSchedules.js +39 -0
  161. package/sdkSpeech.js +54 -0
  162. package/sdkTurn.js +117 -0
  163. package/sdkVault.js +124 -0
  164. package/sealShare.js +18 -0
  165. package/sealedNames.js +64 -0
  166. package/sealedReceipt.js +17 -0
  167. package/sentinelRelease.js +154 -0
  168. package/shamir.js +85 -0
  169. package/sharedViews.js +38 -0
  170. package/sheetChrome.js +450 -0
  171. package/siri.js +171 -0
  172. package/spaceClient.js +1418 -0
  173. package/spaceConfig.js +81 -0
  174. package/spaceEmailGate.js +813 -0
  175. package/spaceExport.js +125 -0
  176. package/spaceFork.js +216 -0
  177. package/spaceLock.js +358 -0
  178. package/spacePasskey.js +180 -0
  179. package/speechOut.js +100 -0
  180. package/splitKeyClient.js +90 -0
  181. package/store.js +587 -0
  182. package/streamHint.js +36 -0
  183. package/sttCloud.js +220 -0
  184. package/sttWorklet.js +38 -0
  185. package/sw-notif-core.js +538 -0
  186. package/tempList.js +48 -0
  187. package/tinfoilVerifier.js +78 -0
  188. package/toolBooks.js +31 -0
  189. package/toolRules.js +52 -0
  190. package/turnCerts.js +254 -0
  191. package/turnFeed.js +58 -0
  192. package/turnVerdict.js +36 -0
  193. package/usageReceipts.js +176 -0
  194. package/usageSummary.js +90 -0
  195. package/util.js +181 -0
  196. package/vault-core.js +1958 -0
  197. package/vault-kit.mjs +354 -0
  198. package/vault-screens.js +263 -0
  199. package/vaultAtRest.js +177 -0
  200. package/vaultCoreLock.js +111 -0
  201. package/vaultCorePush.js +140 -0
  202. package/vaultDeviceKey.js +95 -0
  203. package/vaultEnclaveHandoff.js +114 -0
  204. package/vaultKeep.js +281 -0
  205. package/vaultSealedStore.js +77 -0
  206. package/vaultWorkerHost.js +98 -0
  207. package/vcWorker.js +34 -0
  208. package/voiceAttest.js +50 -0
  209. package/voiceCert.js +51 -0
  210. package/witbitz-admin.d.ts +135 -0
  211. package/witbitz-admin.js +529 -0
  212. package/witbitz-admin.mjs +1459 -0
  213. package/witbitz-sdk.d.ts +1106 -0
  214. package/witbitz-sdk.js +3835 -0
  215. package/workerClient.js +16 -0
  216. package/workerLiveness.js +21 -0
  217. package/x509.js +218 -0
package/sdkBackup.js ADDED
@@ -0,0 +1,480 @@
1
+ // spaces/public/sdkBackup.js — `wb.backup`: the ACCOUNT BACKUP for a builder's app, on the SAME vault our own app uses
2
+ // (2026-10-02, a builder: "a short recovery code instead of the restore link"; the owner: "why not use our account
3
+ // structure?"). Nothing new is invented here — it is the existing vault, reached from the SDK:
4
+ //
5
+ // • backupVault.js: a random 32-byte MASTER SECRET seals the backup; each recovery method stores a WRAPPER of it.
6
+ // Here the method is a RECOVERY CODE (recovery.js: 16 random bytes, typed as 44YW-572I-…).
7
+ // • the store is `/v1/vault/*` (api.witbitz.chat) — content-blind: ids derived from the secrets, ciphertext only.
8
+ // • a SPLIT room (https://witbitz.chat/docs/sdk-keys.md#split-key) is recorded with its assembled key as well as its half-key link (§3.4).
9
+ // • the 2-of-2 recovery gate (design A): with an email, the gate record commits to it (an HMAC keyed by the code, so
10
+ // the server can neither read nor guess the address). When the server enforces the gate, a restore needs the code
11
+ // AND an emailed code (ENFORCE_GATE is on in every home since 2026-10-06); where it is off, the code alone restores. restore() handles both.
12
+ //
13
+ // SEPARATE PER APP, for free: each enable() mints its own master secret and code, so a builder's users get their own
14
+ // vault — it never mixes with the Witbitz app's, and one app's restore never touches another's. The writing origin is
15
+ // recorded beside the blob by the server (attribution, never permission).
16
+ //
17
+ // What the backup HOLDS: the rooms this client created or opened — each one's link (which carries its key), label, and
18
+ // for a lane, the Space it belongs to — enough for restore() to hand them back to openSpace / openLane.
19
+ // ⚑ The STATE (`wb.backup.state`) holds the master secret: persist it like the room links it protects, never send it.
20
+ import { newRecoveryCode, codeSecret, gateParams, emailCommit, seal, unseal } from './recovery.js'
21
+ import { recordFromRooms, roomsOfRecord, roomPin, tombOfRecord, keyInLink, vaultOwner, LEGACY_SDK_KIND, SDK_APP } from './accountRecord.js' // one account record for the app and the SDK; this module's original is LEGACY
22
+ import { applyPlan } from './backupRecord.js' // the Spaces app's restore rules, pure (docs/sdk-account-format-plan.md phase 1)
23
+ import { normUsageKey } from './usageReceipts.js'
24
+ import { indexRoomOf, mergeIndex } from './sdkAccount.js' // the account's derived index room — published in the record as the app's `indexRoom` pointer
25
+ import { newMasterSecret, backupLocation, wrapperLocation, enrollCredential, openWrapper } from './backupVault.js'
26
+
27
+ export const DEFAULT_VAULT_API = 'https://api.witbitz.chat/v1/vault'
28
+ const KIND = LEGACY_SDK_KIND
29
+ const MAX_ROOMS = 500
30
+
31
+ const b64 = (u8) => { let s = ''; for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]); return btoa(s) }
32
+ const ub64 = (s) => { const b = atob(s); const u = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i); return u }
33
+ const fail = (code, msg, extra = {}) => Object.assign(new Error('witbitz: ' + msg), { code, ...extra })
34
+ const is32 = (s) => { try { return typeof s === 'string' && ub64(s).length === 32 } catch { return false } }
35
+
36
+ // ── THE NEW ACCOUNT SERVICE (sdkBackupV2.js; the owner, 2026-11-16: "Yes. Do the sdk."): a builder's VAULT that names its tenant
37
+ // installs it (`backup._v2`) and NEW accounts start there; a state with `v2` is an account there. Its parts, as they may be kept:
38
+ // `svc` the service's record (acctV2App.js STATE_KEY: the account id, the service, the address), `bm` the BACKUP master (the
39
+ // service's objects are sealed under it; a new recovery code replaces it — `master` stays the account's identity), `pending` a
40
+ // new code's master kept before its activation, `dk` which of the vault's device keys is this account's, `checked` the last
41
+ // status answer, `pb` the PREVIOUS backup masters (≤ 3, ≤ 30 days: a signed-out device's push address was sealed under the
42
+ // master of its day — Codex sweep 2026-11-16 #1, as our vault's prevMasters). Anything else is dropped.
43
+ export function v2Of(x) {
44
+ if (!x || typeof x !== 'object' || Array.isArray(x)) return null
45
+ const o = {}
46
+ const sv = x.svc
47
+ if (sv && typeof sv === 'object' && typeof sv.acct === 'string' && sv.acct && sv.acct.length <= 200) {
48
+ o.svc = { acct: sv.acct, base: String(sv.base || '').slice(0, 300), at: Number(sv.at) || 0, trust: sv.trust == null ? null : String(sv.trust).slice(0, 40),
49
+ ...(sv.setup === 'pending' ? { setup: 'pending' } : {}), ...(typeof sv.address === 'string' && sv.address ? { address: sv.address.slice(0, 254) } : {}) }
50
+ }
51
+ if (is32(x.bm)) o.bm = x.bm
52
+ if (x.pending && is32(x.pending.master)) o.pending = { master: x.pending.master, rid: typeof x.pending.rid === 'string' ? x.pending.rid.slice(0, 200) : null, at: Number(x.pending.at) || 0 }
53
+ if (typeof x.dk === 'string' && /^[A-Za-z0-9]{8,32}$/.test(x.dk)) o.dk = x.dk
54
+ if (Number.isFinite(x.checked) && x.checked > 0) o.checked = x.checked
55
+ if (typeof x.erase === 'string' && x.erase.length <= 32768) o.erase = x.erase
56
+ if (x.moving === true) { o.moving = true; if (x.moveMode === 'signed') o.moveMode = 'signed' }
57
+ if (x.resetDraft === true) o.resetDraft = true
58
+ if (typeof x.reset === 'string' && x.reset.length <= 4096) o.reset = x.reset
59
+ if (typeof x.emailMove === 'string' && x.emailMove.length <= 4096) o.emailMove = x.emailMove
60
+ const pb = keptPrevMasters(x.pb)
61
+ if (pb.length) o.pb = pb
62
+ return o
63
+ }
64
+ /** The previous backup masters still worth trying: ≤ 3, newest first, ≤ 30 days old (acctV2VaultWiring.js keptMasters). */
65
+ export const keptPrevMasters = (list, now = Date.now()) => (Array.isArray(list) ? list : []).filter((x) => x && is32(x.m) && Number(x.at) > 0 && now - Number(x.at) < 30 * 86400000).slice(0, 3).map((x) => ({ m: x.m, at: Number(x.at) }))
66
+ /** An account made on the service whose first recovery code is not active (or not adopted) here yet: kept, never "enabled" — the
67
+ * next enable() finishes it (an address with an account and no code could not start again). */
68
+ export const halfMade = (s) => !!(s && s.v2 && (s.v2.resetDraft || !s.v2.bm || (s.v2.svc && s.v2.svc.setup === 'pending')))
69
+ const notOnService = () => fail('not_on_service', 'this call is for an account on the Witbitz account service, in a vault that names its tenant (wb.backup.service === \'account\')')
70
+
71
+ /** One room as the backup records it. `link` carries the room key (the fragment), so the whole list is sealed. */
72
+ const roomOf = (r) => (r && typeof r === 'object' && typeof r.room === 'string' && r.room && typeof r.link === 'string' && r.link
73
+ ? { room: r.room.slice(0, 120), ...roomPin(r), ...(typeof r.renamed === 'boolean' ? { renamed: r.renamed } : {}), ...(Number.isFinite(r.at) && r.at > 0 ? { at: r.at } : {}), ...(r.archived ? { archived: true } : {}), link: r.link.slice(0, 4000), kind: r.kind === 'lane' ? 'lane' : 'space', ...(r.label ? { label: String(r.label).slice(0, 120) } : {}), ...(r.kind === 'lane' && r.shared ? { shared: String(r.shared).slice(0, 120) } : {}), ...(typeof r.mk === 'string' && r.mk && r.mk.length <= 200 ? { mk: r.mk } : {}) }
74
+ : null)
75
+
76
+ function stateOf(x) {
77
+ const o = x && typeof x === 'object' ? x : null
78
+ if (!o || typeof o.master !== 'string') return null
79
+ try { if (ub64(o.master).length !== 32) return null } catch { return null }
80
+ // `tomb` + `device` belong to the LIVE index (sdkAccount.js): a forgotten room's tombstone, and this device's id in the account.
81
+ const tomb = (Array.isArray(o.tomb) ? o.tomb : []).filter((t) => t && typeof t.room === 'string' && Number.isFinite(t.at)).map((t) => ({ room: t.room.slice(0, 120), at: t.at })).slice(-500)
82
+ const device = o.device && typeof o.device.id === 'string' ? { id: o.device.id.slice(0, 40), name: String(o.device.name || '').slice(0, 80), ...(o.device.made ? { made: true } : {}) } : null
83
+ const links = (Array.isArray(o.links) ? o.links : []).filter((l) => l && typeof l.a === 'string' && typeof l.b === 'string' && Number.isFinite(l.at)).map((l) => ({ a: l.a.slice(0, 120), b: l.b.slice(0, 120), at: l.at, ...(Number.isFinite(l.cap) ? { cap: l.cap } : {}), ...(l.removed ? { removed: true } : {}) })).slice(-200)
84
+ // `outs`: sign-outs of OTHER devices this device made, kept until the index carries them (sdkAccount.js signOut; pass 6, K#7)
85
+ const outs = o.outs && typeof o.outs === 'object' ? Object.fromEntries(Object.entries(o.outs).filter(([id, at]) => typeof id === 'string' && id.length <= 40 && Number.isFinite(at)).slice(-50)) : {}
86
+ return { v: 1, ...(o.format === 'account' ? { format: 'account' } : {}), ...(Object.keys(outs).length ? { outs } : {}), master: o.master, ...(typeof o.savedVersion === 'string' && o.savedVersion.length <= 200 ? { savedVersion: o.savedVersion } : {}), rooms: (Array.isArray(o.rooms) ? o.rooms : []).map(roomOf).filter(Boolean).slice(0, MAX_ROOMS), ...(tomb.length ? { tomb } : {}), ...(links.length ? { links } : {}), ...(device ? { device } : {}), ...(o.email ? { email: String(o.email) } : {}), ...(inviteOf(o.invite) ? { invite: inviteOf(o.invite) } : {}), ...(normUsageKey(o.usage) ? { usage: normUsageKey(o.usage) } : {}), ...(usageOldOf(o.usageOld).length ? { usageOld: usageOldOf(o.usageOld) } : {}), ...(o.erased ? { erased: true } : {}), ...(v2Of(o.v2) ? { v2: v2Of(o.v2) } : {}) }
87
+ }
88
+ // the account's USAGE key (usageReceipts.js; the owner, 2026-10-23: a builder's app records the account's usage too) and the
89
+ // ones it replaced — kept in step between the devices by the live index (sdkAccount.js)
90
+ const usageOldOf = (a) => (Array.isArray(a) ? a.map(normUsageKey).filter(Boolean).slice(-5) : [])
91
+ // the account's invite key for this app (sdkRekey.js): kept as it was given, bounded
92
+ const inviteOf = (x) => (x && typeof x === 'object' && x.boxPub && x.boxPriv && typeof x.inbox === 'string' && JSON.stringify(x).length < 4000 ? JSON.parse(JSON.stringify(x)) : null)
93
+
94
+ export class AccountBackup {
95
+ /** @param {object} o { fetch, base?, state?, email?: () => string } — `email` answers the signed-in address, if any. */
96
+ constructor({ fetch: fetchImpl, base = DEFAULT_VAULT_API, state = null, email = () => '', tenant = '' } = {}) {
97
+ this._fetch = fetchImpl
98
+ this._base = String(base || DEFAULT_VAULT_API).replace(/\/+$/, '')
99
+ this._s = stateOf(state)
100
+ this._email = email
101
+ this._tenant = tenant
102
+ /** Called with the new state whenever it changes (a room added, a restore) — persist it there. */
103
+ this.onState = null
104
+ this._timer = null
105
+ this._v2 = null // the new account service (sdkBackupV2.js accountService), installed by a builder's vault
106
+ }
107
+
108
+ /** JSON-safe state to persist (it holds the master secret), or null while no backup is set up. */
109
+ get state() { return this._s && !this._isEnabling() ? JSON.parse(JSON.stringify(this._s)) : null }
110
+ get enabled() { return !!this._s && !this._isEnabling() && !halfMade(this._s) }
111
+ /** Where this account is kept: 'account' (the Witbitz account service — new accounts in a vault that names its tenant),
112
+ * 'legacy' (the backup store every account used before), or null (no backup on this client). */
113
+ get service() { return this._s && !this._isEnabling() ? (this._s.v2 && !(this._s.v2.moving && !this._s.v2.svc) ? 'account' : 'legacy') : null }
114
+ /** @private ENABLING (pass 6, K#4): enable() is between its first await and its answer. The state exists (a Space opened
115
+ * meanwhile is queued in it) but is handed to nobody — not the app (onState), not the live index — until the vault copy,
116
+ * the recovery code and the gate are all saved. A failed enable then leaves nothing behind that reads "enabled". */
117
+ _isEnabling() { return !!this._enabling && this._enabling === this._s }
118
+ /** The rooms the backup holds: [{ room, link, kind: 'space'|'lane', label?, shared?, archived? }]. */
119
+ get rooms() { return this._s ? this._s.rooms.map(({ at, ...r }) => r) : [] } // `at` is the live index's bookkeeping
120
+
121
+ /** Set up the backup → `{ code }`. Show the code ONCE: it is the only way back if this device is lost. With an email
122
+ * (default: the signed-in session's), the recovery gate is enrolled too, so a restore can also be made to need it. */
123
+ async enable({ email, address, getCode, showCode, initialRooms = [] } = {}) {
124
+ if (this._s?.v2?.resetDraft) throw fail('email_move_pending', 'finish or cancel this device’s email move first')
125
+ // one set-up at a time (review 2026-11-16: a second enable() during the first one's screens ran a second flow over the same state)
126
+ if (this._isEnabling()) throw fail('already_enabling', 'the backup is being set up already')
127
+ // an account the new service made whose first code did not go through: finished now, never a second one
128
+ if (this._s && !(this._v2 && halfMade(this._s))) throw fail('already_enabled', 'the backup is already set up on this client (its state is wb.backup.state)')
129
+ // IN A VAULT THAT NAMES ITS TENANT: the new account service (sdkBackupV2.js) — the vault's screens ask for the emailed code
130
+ // (`getCode`) and show the recovery code (`showCode`) before it is activated. null = the service refused this vault's tenant
131
+ // before anything was made: the old store, as before. `address`: one the person TYPED for the service (no sign-in) — never enrolled
132
+ // as the old store's email gate on the way back (a typo would lock the backup behind a code mailed elsewhere; review 2026-11-16)
133
+ const rooms = initialRooms.map(roomOf).filter(r => r && !r.room.startsWith('tmp-'))
134
+ if (this._v2) { const r = await this._v2.enable(this, { email: address || email, getCode, showCode, rooms }); if (r) return r }
135
+ const code = newRecoveryCode(), cs = codeSecret(code), master = newMasterSecret()
136
+ const s = { v: 1, format: 'account', master: b64(master), rooms } // a new backup is written in the account format (accountRecord.js)
137
+ this._s = s; this._enabling = s; this._enablingDirty = false
138
+ // another account's state put in place meanwhile (_adopt / _drop / restore) ends this enable: it must not finish on that one
139
+ const mine = () => { if (this._s !== s) throw fail('cancelled', 'the backup was replaced while it was being set up') }
140
+ try {
141
+ await this._write() // the backup itself first: a code that opens nothing is worse than no code
142
+ mine()
143
+ if (!(await enrollCredential(this._transport(), cs, master))) throw fail('enroll_failed', 'the recovery code could not be saved')
144
+ mine()
145
+ const addr = String(email || this._email() || '').trim().toLowerCase()
146
+ if (addr) {
147
+ const { gid, gk } = await gateParams(cs)
148
+ const gate = { methods: ['email'], members: [(await backupLocation(master)).id, (await wrapperLocation(cs)).id], commit_email: await emailCommit(gk, addr) }
149
+ const r = await this._post('/gate', { gid, gate })
150
+ if (!(r.json && (r.json.ok || r.json.reason === 'exists'))) throw fail('gate_failed', 'the recovery email could not be recorded', { status: r.status })
151
+ mine()
152
+ s.email = addr
153
+ }
154
+ } catch (e) {
155
+ const ours = this._s === s
156
+ if (this._enabling === s) this._enabling = null
157
+ if (ours) { this._s = null; this._changed() } // nothing was handed out, but say so: the app persists "no backup"
158
+ throw e
159
+ }
160
+ const queued = this._enablingDirty
161
+ this._enabling = null; this._enablingDirty = false
162
+ this._onEnabled?.(s.master); this._changed(); this._started()
163
+ if (queued) this._schedule() // a Space recorded while it was being set up: the vault copy and the index get it now
164
+ return { code }
165
+ }
166
+
167
+ /** Record a Space or Lane (done for you as rooms are created and opened). `label` names it in a restore. */
168
+ add(spaceOrLane, { label } = {}) {
169
+ if (!this._s || !spaceOrLane || !spaceOrLane.room || !spaceOrLane.shareLink) return this
170
+ if (String(spaceOrLane.room).startsWith('tmp-')) return this // a TEMPORARY room is never backed up (it is wiped) — whichever way it was opened (sync sweep 2026-10-27 #4)
171
+ const lane = !!spaceOrLane._sharedRoom
172
+ // A SPLIT room's link is half a key, so the backup also keeps the assembled key — a restore never depends on the
173
+ // app half (https://witbitz.chat/docs/sdk-keys.md#split-key). A plain room's link already is the key.
174
+ // a lane opened as a plain Space (wb.openSpace(laneLink)) knows nothing of its Space: the record it already has as a LANE
175
+ // stays one — a restore must not bring it back as a Space (sync sweep 2026-11-02 #5)
176
+ const had = this._s.rooms.find((x) => x.room === spaceOrLane.room)
177
+ const wasLane = !lane && had && had.kind === 'lane' && had.shared
178
+ const r = roomOf({ room: spaceOrLane.room, link: spaceOrLane.shareLink, kind: lane || wasLane ? 'lane' : 'space', label, shared: lane ? spaceOrLane._sharedRoom : wasLane ? had.shared : undefined, mk: spaceOrLane._split ? spaceOrLane._mk : undefined })
179
+ if (!r) return this
180
+ const i = this._s.rooms.findIndex((x) => x.room === r.room)
181
+ const prev = i >= 0 ? this._s.rooms[i] : null
182
+ if (prev && prev.link === r.link && prev.kind === r.kind && prev.mk === r.mk && (!label || prev.label === r.label)) return this
183
+ const next = { ...(prev ? { ...prev, ...r, ...(label ? {} : prev.label ? { label: prev.label } : {}), ...(prev.archived ? { archived: true } : {}) } : r), at: Date.now() } // `at`: the live index keeps the newer of each entry
184
+ if (i >= 0) this._s.rooms[i] = next; else { if (this._s.rooms.length >= MAX_ROOMS) return this; this._s.rooms.push(next) }
185
+ this._schedule()
186
+ return this
187
+ }
188
+
189
+ _detachLane(room, shared) {
190
+ const entry = this._s?.rooms.find((r) => r.room === room && r.kind === 'lane' && r.shared === shared)
191
+ if (!entry) return
192
+ delete entry.shared
193
+ entry.kind = 'space'
194
+ entry.at = Math.max(Date.now(), (entry.at || 0) + 1)
195
+ this._schedule()
196
+ }
197
+
198
+ /** The account's invite key for this app, kept with the rooms (wb.invite hands it over; a restore gives it back). */
199
+ get invite() { return this._s && this._s.invite ? { ...this._s.invite } : null }
200
+ setInvite(state) {
201
+ const v = inviteOf(state)
202
+ if (!this._s || !v || JSON.stringify(this._s.invite || null) === JSON.stringify(v)) return this
203
+ this._s.invite = v; this._schedule()
204
+ return this
205
+ }
206
+
207
+ /** The whole key the backup holds for a SPLIT room, or null — so a restored device opens it without the app half. */
208
+ // A room whose link IS its key answers null: a separate copy of it (an older SDK that restored a record carrying every room's
209
+ // key spreads one through the index) may be stale after a change in place — the link is the one kept current.
210
+ keyFor(room) { const r = this._s && this._s.rooms.find((x) => x.room === room); return (r && r.mk && !keyInLink(r.link) && r.mk) || null }
211
+
212
+ /** Stop backing up one room (e.g. the user left it). It leaves a tombstone, so the account's other devices drop it too
213
+ * (wb.account) — opening the room again later brings it back. */
214
+ remove(room) {
215
+ if (!this._s) return this
216
+ const n = this._s.rooms.length
217
+ this._s.rooms = this._s.rooms.filter((x) => x.room !== room)
218
+ if (this._s.rooms.length !== n) { this._s.tomb = [...(this._s.tomb || []).filter((t) => t.room !== room), { room, at: Date.now() }].slice(-500); this._schedule() }
219
+ return this
220
+ }
221
+
222
+ /** The backup's record format: 'account' (the one the Spaces app uses) or 'legacy' (this SDK's original). */
223
+ get format() { return this._s ? (this._s.format === 'account' ? 'account' : 'legacy') : null }
224
+ /** Rewrite a LEGACY backup in the account format (the one the Spaces app uses). Same vault, code and rooms; a client
225
+ * on an older SDK can no longer restore it. Nothing does this for you. */
226
+ async upgrade() {
227
+ if (!this._s) throw fail('not_enabled', 'no backup is set up — call wb.backup.enable() first')
228
+ if (this._s.format === 'account') return { format: 'account' }
229
+ const was = this._s.format
230
+ this._s.format = 'account'
231
+ try { await this._write() } catch (e) { this._s.format = was; throw e }
232
+ this._changed()
233
+ return { format: 'account' }
234
+ }
235
+
236
+ /** Write the backup now (it is also written shortly after every change). */
237
+ async save(verification) { clearTimeout(this._timer); this._timer = null; if (!this.enabled) throw fail('not_enabled', 'no backup is set up — call wb.backup.enable() first'); await this._write(verification); return { rooms: this._s.rooms.length } }
238
+ /** True when enable() recorded an email gate: deleting (or restoring) this backup then needs the emailed code as well. */
239
+ get gated() { return !!(this._s && this._s.email) }
240
+ /** Enroll the currently signed-in address for an existing legacy backup. */
241
+ async protectRecoveryEmail({ code } = {}) {
242
+ const state = this._s, email = String(this._email() || '').trim().toLowerCase()
243
+ if (!state?.master || state.v2?.svc) throw fail('legacy_required', 'open a legacy backup first')
244
+ if (!email) throw fail('sign_in_required', 'sign in with your recovery email first')
245
+ const cs = codeSecret(code || ''), wrapper = await wrapperLocation(cs)
246
+ const stored = await this._get('/backup', '?id=' + wrapper.id)
247
+ if (stored.status === 403 && stored.json?.reason === 'gated') throw fail('already_protected', 'the recovery code already has a recovery factor')
248
+ const master = stored.json?.ok && await openWrapper(cs, stored.json.blob)
249
+ if (!master || b64(master) !== state.master) throw fail('bad_code', 'use the recovery code for this backup')
250
+ const { gid, gk } = await gateParams(cs)
251
+ const gate = { methods: ['email'], members: [(await backupLocation(master)).id, wrapper.id], commit_email: await emailCommit(gk, email) }
252
+ const guard = () => { if (this._s !== state || String(this._email() || '').trim().toLowerCase() !== email) throw fail('account_changed', 'the account changed during enrollment') }
253
+ guard()
254
+ const r = await this._post('/gate', { gid, gate })
255
+ if (!r.json?.ok || r.json.reason === 'exists') throw fail(r.json?.reason === 'exists' ? 'already_protected' : 'gate_failed', 'the new recovery email could not be confirmed')
256
+ guard()
257
+ state.email = email
258
+ this._changed()
259
+ await this.save()
260
+ return { enrolled: true }
261
+ }
262
+ /** @private A RELEASE TOKEN for this backup's email gate — what the server asks before it deletes a gated backup, as a
263
+ * gated restore (vaultBackupApi backupDelete). The first call (with the recovery `code`) mails a code and throws
264
+ * `email_code_required` with a `ticket`; the second (with `ticket` + `emailCode`) returns the token. */
265
+ async _release({ code, email, ticket, emailCode } = {}) {
266
+ if (ticket && emailCode) return this._emailVerify(ticket, emailCode)
267
+ let cs
268
+ try { cs = codeSecret(code) } catch { throw fail('code_required', 'this backup is protected by its email: pass its recovery code ({ code }) — a code is then emailed to it') }
269
+ return this._emailStart(cs, String(email || (this._s && this._s.email) || this._email() || '').trim().toLowerCase())
270
+ }
271
+ /** @private the gate's emailed code → its release token */
272
+ async _emailVerify(ticket, emailCode) {
273
+ const v = await this._post('/email/verify', { ticket, code: String(emailCode).trim() })
274
+ const token = v.json && v.json.ok ? v.json.token : null
275
+ if (!token) throw fail('email_code_wrong', 'that email code did not verify', { status: v.status })
276
+ return token
277
+ }
278
+ /** @private mail the gate's code to `addr`; always throws (email_code_required with a ticket, or why it could not) */
279
+ async _emailStart(cs, addr) {
280
+ if (!addr) throw fail('email_required', 'this backup needs its email as well as the code — pass `email`')
281
+ const { gid, gk } = await gateParams(cs)
282
+ const s = await this._post('/email/start', { gid, commit: await emailCommit(gk, addr), email: addr, gk: Array.from(gk, (b) => b.toString(16).padStart(2, '0')).join('') })
283
+ // the server's own reason is the code when it gives one (update_required: an SDK too old for the gate's check) — a builder
284
+ // could not tell "update the SDK" from "wrong address" (sync sweep, 10-17 #10)
285
+ if (!(s.json && s.json.ok && s.json.ticket)) { const why = s.json && typeof s.json.reason === 'string' && /^[a-z_]{3,40}$/.test(s.json.reason) ? s.json.reason : 'email_refused'; throw fail(why, why === 'update_required' ? 'this backup\'s protection needs a newer SDK — load the latest release' : 'a code could not be sent to that address (it must be the one this backup was set up with)', { status: s.status }) }
286
+ throw fail('email_code_required', `we emailed a code to ${addr} — call again with { code, ticket, emailCode }`, { ticket: s.json.ticket })
287
+ }
288
+ /** @private DELETE MY ACCOUNT (wb.erasure.deleteAccount): delete the vault copy (POST /v1/vault/backup/delete — the one
289
+ * route; 404 = already gone), with the gate's release token when the backup has one (sync sweep 11-08 #1: it posted to a
290
+ * path that does not exist and read the 404 as done). Leaves the local state — the erase drops it last. → { ok, status?, reason? } */
291
+ async _deleteRemote(token = null) {
292
+ if (!this._s) return { ok: true }
293
+ if (this._s.v2) return { ok: false, status: 0, reason: 'this account is on the account service — wb.backup.deleteAccount() deletes it' }
294
+ const loc = await backupLocation(ub64(this._s.master))
295
+ const r = await this._post('/backup/delete', { id: loc.id, ...(token ? { token } : {}) })
296
+ if ((r.status === 200 && r.json?.deleted === true) || r.status === 404) return { ok: true }
297
+ return { ok: false, status: r.status, reason: (r.json && (r.json.error || (r.json.reason === 'incomplete' ? 'some old copies could not be deleted yet — run it again' : r.json.reason))) || ('backup ' + (r.status || 'unreachable')) }
298
+ }
299
+
300
+ /** Restore on a new device from the recovery code → `{ rooms }`, and this client now holds the backup.
301
+ * If the vault's gate requires the email, the first call mails a code and throws `code: 'email_code_required'` with
302
+ * a `ticket`; call again with `{ code, ticket, emailCode }`. `email` defaults to the signed-in address. */
303
+ async restore({ code, email, ticket, emailCode, getCode, askAddress } = {}) {
304
+ if (this._s?.v2?.resetDraft) throw fail('email_move_pending', 'finish or cancel this device’s email move first')
305
+ let cs
306
+ try { cs = codeSecret(code) } catch { throw fail('bad_code', 'that is not a recovery code') }
307
+ // THE NEW ACCOUNT SERVICE FIRST (a vault that names its tenant; `getCode` asks for its emailed code): a code that is no account
308
+ // there (or a service that could not say) goes on to the old store below. A ticket of the old store's gate goes straight there.
309
+ if (this._v2 && !(ticket && emailCode)) {
310
+ const d = await this._v2.restore(this, { code, email, getCode, askAddress })
311
+ if (d) { clearTimeout(this._timer); this._timer = null; this._s = stateOf(d); this._changed(); this._started(); return { rooms: this.rooms } }
312
+ }
313
+ const w = await wrapperLocation(cs)
314
+ let token = null
315
+ if (ticket && emailCode) token = await this._emailVerify(ticket, emailCode)
316
+ const read = async (id) => {
317
+ const r = token ? await this._post('/release', { token, id, builderRestore: true })
318
+ : await this._get('/backup', '?id=' + id + '&builderRestore=1')
319
+ if (r.json?.reason === 'other_app') throw fail('other_app', 'Open the app that created this backup to restore it.')
320
+ if (r.json?.reason === 'backup_app_unknown' || (r.json?.ok && r.json.appVerified !== true)) {
321
+ throw fail('backup_app_unknown', 'The backup service cannot verify which app created this recovery code.')
322
+ }
323
+ return r
324
+ }
325
+ let r = await read(w.id)
326
+ if (r.status === 403 && r.json && r.json.reason === 'gated') await this._emailStart(cs, String(email || this._email() || '').trim().toLowerCase()) // throws: email_code_required (with a ticket) or why not
327
+ if (r.status === 404) throw fail('not_found', 'no backup was found for that recovery code')
328
+ const master = r.json && r.json.ok ? await openWrapper(cs, r.json.blob) : null
329
+ if (!master) throw fail('unopenable', 'the backup for that code could not be opened', { status: r.status })
330
+ const loc = await backupLocation(master)
331
+ const b = await read(loc.id)
332
+ if (!(b.json && b.json.ok)) throw fail(b.status === 404 ? 'not_found' : 'unreadable', 'the backup could not be read', { status: b.status })
333
+ let doc
334
+ try { doc = await unseal(loc.key, b.json.blob) } catch { throw fail('unopenable', 'the backup could not be opened') }
335
+ // ⛔ This app's vault only — never a Witbitz account's (it would hold the key to every Space the person has).
336
+ if (vaultOwner(doc) !== 'sdk') throw fail('not_sdk_backup', 'that code opens a backup made by a different app')
337
+ // THROUGH THE SPACES APP'S RESTORE (backupRecord.js applyPlan) where its rule is the SDK's too: which rows come back — never
338
+ // one the record itself marks deleted in `tombstones` (the SDK writes there only rooms it no longer holds, so a record from
339
+ // any SDK loses nothing) — and the invite key (whole, or none). The SDK's own forget (`tomb`) is NOT applied: it is
340
+ // re-openable, a room opened again after one comes back. A fresh state: nothing on this client to keep. A LEGACY record
341
+ // is not in the account format: no plan, read as before.
342
+ const plan = applyPlan(doc, {}, { app: SDK_APP })
343
+ const invite = plan ? plan.inviteKey : doc.inviteKey
344
+ this._s = stateOf({ master: b64(master), savedVersion: b.json.ver, rooms: roomsOfRecord(plan ? { ...doc, recents: plan.add } : doc), tomb: tombOfRecord(doc), ...(doc.email ? { email: doc.email } : {}), ...(invite ? { invite } : {}), ...(doc.kind === KIND ? {} : { format: 'account' }) })
345
+ this._changed(); this._started()
346
+ return { rooms: this.rooms }
347
+ }
348
+
349
+ // ── THE ACCOUNT SERVICE'S OWN CALLS (an account with service === 'account'; a builder's vault runs them, its screens asking
350
+ // the person for the emailed code — `getCode` — and showing a new code — `showCode`).
351
+ /** Sign out every OTHER device of this account: each one forgets the account at its next status check. */
352
+ async signOutOthers({ getCode } = {}) { if (!this._v2) throw notOnService(); return this._v2.signOutOthers(this, { getCode }) }
353
+ /** A new recovery code (shown before it is activated): the old code stops working and every other device is signed out. */
354
+ async newRecoveryCode({ getCode, showCode } = {}) { if (!this._v2) throw notOnService(); return this._v2.newRecoveryCode(this, { getCode, showCode }) }
355
+ /** Delete this account on the account service (every device signed out, the address freed, the backup gone); this client then
356
+ * holds no account. The Spaces themselves are not deleted by this call. */
357
+ async deleteAccount({ getCode } = {}) { if (!this._v2) throw notOnService(); return this._v2.deleteAccount(this, { getCode }) }
358
+ async manageSecurityKeys() { throw fail('vault_required', 'manage account security keys in the account’s vault') }
359
+ async migrate({ code, getCode, silent = false } = {}) { if (!this._v2) throw notOnService(); return this._v2.migrate(this, { code, getCode, silent }) }
360
+ async beginEmailMove(opts = {}) { if (!this._v2) throw notOnService(); return this._v2.beginEmailMove(this, opts) }
361
+ async pendingEmailMove() { if (!this._v2) throw notOnService(); return this._v2.pendingEmailMove(this) }
362
+ async finishEmailMove(opts = {}) { if (!this._v2) throw notOnService(); return this._v2.finishEmailMove(this, opts) }
363
+ async cancelPendingEmailMove(opts = {}) { if (!this._v2) throw notOnService(); return this._v2.cancelPendingEmailMove(this, opts) }
364
+ async emailMove() { if (!this._v2) throw notOnService(); return this._v2.emailMove(this) }
365
+ async requestMoveTime() { if (!this._v2) throw notOnService(); return this._v2.requestMoveTime(this) }
366
+ async cancelEmailMove({ getCode } = {}) { if (!this._v2) throw notOnService(); return this._v2.cancelEmailMove(this, { getCode }) }
367
+
368
+ // ── internals ──────────────────────────────────────────────────────────────────────────────────────────────────
369
+ _schedule() { if (this._isEnabling()) { this._enablingDirty = true; return } this._persist(); if (typeof this._onLocal === 'function') { try { this._onLocal() } catch { /* the live index */ } } }
370
+ /** Write the vault copy soon and hand the app the new state — without telling the live index (it is the caller). */
371
+ _persist() { if (this._isEnabling()) { this._enablingDirty = true; return } if (this._s && this._s.erased) { this._changed(); return } clearTimeout(this._timer); this._timer = setTimeout(() => { this._timer = null; if (this._s) this._write().catch((e) => { this.lastError = e }) }, 400); this._changed() }
372
+ /** This device was signed out of the account (wb.account): forget it here, and tell the app to persist that. */
373
+ _drop() { clearTimeout(this._timer); this._timer = null; this._s = null; this._changed() }
374
+ /** @private take another persisted state in place (a vault switching accounts keeps one backup per account) */
375
+ _adopt(state) { clearTimeout(this._timer); this._timer = null; this._s = stateOf(state); this._changed() }
376
+ _started() { if (typeof this._onStart === 'function') { try { this._onStart() } catch { /* the live index */ } } }
377
+ _changed() { if (this._isEnabling()) return; if (typeof this.onState === 'function') { try { this.onState(this.state) } catch { /* the app's callback must not break the backup */ } } }
378
+ async _write(verification) {
379
+ if (this._migrating) return // the move pins the old head; its completion writes all rooms to the new service
380
+ if (this._s && this._s.v2 && this._s.v2.moving && !this._s.v2.svc) throw fail('migration_pending', 'retry migration to learn whether the service committed; no backup was overwritten')
381
+ // ★ THE STATE IT BEGAN WITH (pass 6, K#2): `master` and the location were this account's, but the rooms, email and invite key
382
+ // were read again after the awaits — an account switch meanwhile sealed the next account's rooms into this one's backup.
383
+ const s0 = this._s
384
+ if (!s0) return
385
+ if (s0.erased) throw fail('deleted', 'this backup was deleted with its account')
386
+ // an account on the NEW SERVICE is written there, and only there — never to the old store
387
+ if (s0.v2) { if (!this._v2) throw fail('service_unavailable', 'this account is on the Witbitz account service — only its vault can write it'); return this._v2.write(this, s0) }
388
+ const master = ub64(s0.master)
389
+ const loc = await backupLocation(master)
390
+ // ★ ONLY OVER THE VERSION WE READ (sync sweep 2026-11-09, 11-08 #32; the app's backup.js pushBackup since the 10-05 review):
391
+ // two devices of one backup each wrote their own list whole, so the room one added vanished at the other's next save. Each
392
+ // write reads the backup first, keeps the rooms another device added (never one this device forgot — its tombstone), and
393
+ // A gated read supplies only a version. Reuse our complete local copy
394
+ // only when the service identifies it as the last version we saved.
395
+ let releaseToken
396
+ for (let attempt = 0; attempt < 4; attempt++) {
397
+ let cur = await this._get('/backup', '?id=' + loc.id)
398
+ if (this._s !== s0) return // another account's state is in place now: its own write follows
399
+ if (cur.status === 404 && cur.json && cur.json.deleted === true) { s0.erased = true; this.lastError = null; this._changed(); return } // pass 7, F#2/F#10: deleted with its account
400
+ if (cur.status === 403 && cur.json?.reason === 'gated' && (!s0.savedVersion || s0.savedVersion !== cur.json.ver)) {
401
+ if (!verification) throw fail('backup_verification_required', 'Verify the recovery email to merge the latest backup before saving')
402
+ releaseToken ||= await this._release(verification)
403
+ if (this._s !== s0) return
404
+ cur = await this._post('/release', { token: releaseToken, id: loc.id })
405
+ if (this._s !== s0) return
406
+ if (cur.status !== 200) throw fail('backup_unreadable', 'The verified backup could not be read before saving')
407
+ }
408
+ const ver = cur.json && typeof cur.json.ver === 'string' && cur.json.ver ? cur.json.ver : undefined
409
+ let remote = { rooms: [], tomb: [] }
410
+ const absent = cur.status === 404 && cur.json?.reason === 'not_found'
411
+ const ownGatedVersion = cur.status === 403 && cur.json?.reason === 'gated' && ver && ver === s0.savedVersion
412
+ if (!absent && !ownGatedVersion) {
413
+ if (cur.status !== 200 || !cur.json?.ok || typeof cur.json.blob !== 'string' || !ver) throw fail('backup_unreadable', 'Could not read the current backup before saving')
414
+ const doc = await unseal(loc.key, cur.json.blob)
415
+ if (vaultOwner(doc) !== 'sdk') throw fail('backup_unreadable', 'The existing backup could not be opened as this account')
416
+ remote = { rooms: roomsOfRecord(doc).map(roomOf).filter(Boolean), tomb: tombOfRecord(doc) }
417
+ }
418
+ const { rooms, tomb } = mergeIndex({ rooms: s0.rooms, tomb: s0.tomb }, remote, MAX_ROOMS)
419
+ // The format this backup already has: the account record (accountRecord.js), or the LEGACY one it was made with —
420
+ // never changed under the builder's feet (upgrade() does it on request).
421
+ // The account record also names the account's index room (phase 2: the app's `indexRoom` pointer, derived from the master
422
+ // — the same room sdkAccount.js syncs; a legacy record stays as it was written).
423
+ const doc = s0.format === 'account'
424
+ ? recordFromRooms({ rooms, tomb, email: s0.email, inviteKey: s0.invite, indexRoom: await indexRoomOf(s0.master) })
425
+ : { kind: KIND, v: 1, at: Date.now(), rooms, ...(tomb.length ? { tomb } : {}), ...(s0.email ? { email: s0.email } : {}), ...(s0.invite ? { inviteKey: s0.invite } : {}) }
426
+ const blob = await seal(loc.key, doc)
427
+ if (this._s !== s0) return
428
+ const bindBuilder = this._enabling === s0
429
+ const r = await this._post('/backup', { id: loc.id, blob, ifVer: ver ?? null, returnVersion: true, ...(bindBuilder ? { bindBuilder: true } : {}) })
430
+ if (bindBuilder && r.json?.ok && r.json.appVerified !== true) throw fail('app_binding_unavailable', 'The backup service must support app-specific recovery before a new code can be created.')
431
+ if (r.status === 409) { await new Promise((res) => setTimeout(res, 100 + Math.floor(Math.random() * 300))); continue } // another device wrote since our read
432
+ // ⛔ DELETED WITH ITS ACCOUNT (state machines pass 7, F#2): an erase that stopped half way (or ran on another device) left
433
+ // this client writing it; the server refuses to bring it back (410). Final: the state says so (the app persists it) and
434
+ // no later change schedules a write — quietly, the backup is gone on purpose.
435
+ if (r.status === 410) { if (this._s === s0) { s0.erased = true; this.lastError = null; this._changed() } return }
436
+ if (!(r.json && r.json.ok)) throw fail('save_failed', 'the backup could not be saved', { status: r.status, reason: r.json && r.json.reason })
437
+ if (this._s !== s0) return
438
+ const adopted = mergeIndex({ rooms: s0.rooms, tomb: s0.tomb }, { rooms, tomb }, MAX_ROOMS)
439
+ s0.rooms = adopted.rooms
440
+ s0.tomb = adopted.tomb
441
+ s0.savedVersion = r.json.ver || undefined
442
+ this._changed()
443
+ this.lastError = null
444
+ return
445
+ }
446
+ throw fail('save_failed', 'the backup kept changing under this save (another device writing) — the next change tries again', { status: 409 })
447
+ }
448
+ /** @private Was this backup deleted with its account — by an erase on another device (state machines pass 7, F#10)? The server
449
+ * says so on a read (404 `deleted`); the state then says so too (the app persists it), and nothing writes it again. */
450
+ async _checkErased() {
451
+ const s0 = this._s
452
+ if (!s0) return false
453
+ if (s0.erased) return true
454
+ if (s0.v2) return false // the account service signs a deleted account's devices out: the vault's status check
455
+ const loc = await backupLocation(ub64(s0.master))
456
+ const r = await this._get('/backup', '?id=' + loc.id)
457
+ if (!(r.status === 404 && r.json && r.json.deleted === true) || this._s !== s0) return false
458
+ s0.erased = true; clearTimeout(this._timer); this._timer = null; this._changed()
459
+ return true
460
+ }
461
+ _transport() {
462
+ return {
463
+ put: async (id, blob) => { const r = await this._post('/backup', { id, blob, bindBuilder: true }); return !!(r.json?.ok && r.json.appVerified === true) },
464
+ get: async (id) => { const r = await this._get('/backup', '?id=' + id); return r.json && r.json.ok ? r.json.blob : null },
465
+ }
466
+ }
467
+ async _get(path, qs = '') { return this._req('GET', path + qs) }
468
+ async _post(path, body) { return this._req('POST', path, body) }
469
+ async _req(method, path, body) {
470
+ try {
471
+ if (this._tenant) {
472
+ if (body) body = { ...body, builderTenant: this._tenant }
473
+ else path += (path.includes('?') ? '&' : '?') + 'builderTenant=' + encodeURIComponent(this._tenant)
474
+ }
475
+ const res = await this._fetch(this._base + path, { method, headers: body ? { 'content-type': 'application/json' } : {}, ...(body ? { body: JSON.stringify(body) } : {}) })
476
+ let json = null; try { json = await res.json() } catch { json = null }
477
+ return { status: res.status, json }
478
+ } catch { return { status: 0, json: null } }
479
+ }
480
+ }