@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/vault-core.js ADDED
@@ -0,0 +1,1958 @@
1
+ import { spacesUsingConnection } from './connOtherWays.js'
2
+ // vault-core.js — the key-holding core of a BUILDER-HOSTED VAULT (docs/sdk-vault-mode.md).
3
+ //
4
+ // A builder serves two origins: this vault (e.g. https://vault.acme.com) and their own app page (https://app.acme.com),
5
+ // which the vault frames. The room keys live ONLY here — in the l1 worker this module starts, the same worker the Spaces
6
+ // app keeps its keys in. The framed page uses the SDK (`Witbitz.inVault`), which sends each room operation up the
7
+ // `wbvault` channel; this module checks it, runs it in the worker and sends the answer back. A key never goes down.
8
+ //
9
+ // What is the builder's: the SCREENS (sign-in, share, "didn't load" — `screens`, see vault-screens.js for the defaults)
10
+ // and the page. What is ours: everything that touches a key, here and in l1-worker.js. Upgrading = replacing these files.
11
+ //
12
+ // import { startVault } from './vault-core.js'
13
+ // import { defaultScreens } from './vault-screens.js'
14
+ // startVault({ page: 'https://app.acme.com/chat', tenant: 't_…', screens: defaultScreens({ brand: 'Acme' }) })
15
+ //
16
+ // The page may ask for ONLY: the room operations in PAGE_OPS on a room this vault holds, create, rooms, share, signIn,
17
+ // signOut, whoami, forget, stream, and the account calls in ACCOUNT_CALLS / ROOM_ACCOUNT_CALLS. Everything else the worker can do (remember a key, export, the index, protection) is the
18
+ // vault's own and is not reachable from the page.
19
+ import { memberHash } from './rosterHash.js'
20
+ import { Witbitz, Space, Lane } from './witbitz-sdk.js'
21
+ import { LaneA2A, assertAgentTarget } from './sdkA2A.js'
22
+ import { openGrant, relink, changeMembers, rotateKey, changeable, planMembers } from './sdkRekey.js' // a Space's members changed in place (https://witbitz.chat/docs/sdk-people.md#members)
23
+ import { setPendingKeyStore } from './connections.js' // the SDK's pending-key store (N#7): this vault's
24
+ import { adoptPendingKeys } from './connPending.js'
25
+ import { idb } from './idb.js'
26
+ import { unprotectIdb } from './idbSeal.js'
27
+ import { assertNotKept, isKeptSpace, disconnectRoomLanes } from './sdkCloudDevice.js'
28
+ import { blockTokens, BLOCKS_SW_KEY } from './blocksPush.js'
29
+ import { mirrorLockedRooms, CHAT_LOCKED_SW_KEY } from './chatLockSw.js'
30
+ import { liveLocks } from './chatLock.js'
31
+ import { openItem, cardUrlOf, mcpUrlOf } from './a2aCore.js'
32
+ import { judgeMove, checkNewRoomGov } from './emailFork.js'
33
+ import { ROSTER_DOC, selfRow, ensureSelf, unseenIn, entriesMissing, announcedIn } from './roomRoster.js'
34
+ import { findEmptySpaces, removeEmptySpaces, ownAdmissionEntries } from './emptySpaces.js'
35
+ import { readAllPages } from './ledgerView.js'
36
+ import { commit as keyCommit } from './e2ee.js'
37
+ import { createEnclaveHandoff, enclaveReady, reattestOnce, saysConfidential } from './vaultEnclaveHandoff.js' // what the worker is told of the confidential tier — the same rules as our hosted vault's (C2)
38
+ import { dropFor, receiptFor } from './usageReceipts.js'
39
+ import { makeVerifiedWorker } from './vcWorker.js' // the key worker from its PINNED source, never a file fetched by URL
40
+ import { createWorkerHost } from './vaultWorkerHost.js' // the key worker's host: load, heartbeat, restart, replay (shared with our hosted vault)
41
+ import { keepPass, viewOfKeep, tabStores } from './vaultKeep.js' // connections, Siri and outside agents on every device of the account (sync sweep 2026-11-11 P7)
42
+ import { laneInherits, gatedStub } from './laneConfig.js' // the heartbeat that finds a worker iOS reclaimed (l1.js and the app's vault use it too)
43
+ import { sealedStorage } from './vaultSealedStore.js' // the vault's other secrets sealed on disk too (2026-11-24)
44
+ import { createAtRest, deviceWrapKey, holdsSealed } from './vaultAtRest.js' // the room list's keys and the backup state, sealed on disk (2026-11-13)
45
+ import { deviceStorageKey } from './vaultDeviceKey.js' // the key worker's store sealed at rest too (11-21 sweep P8): our hosted vault's device key
46
+ import { pushAcctSecretOf } from './spaceClient.js' // the account's push tag secret (handDownPushAcct)
47
+ import { indexRoomOf } from './sdkAccount.js'
48
+ import { accountService, restoreBridge, restoreSignInProof, idbKeyStore } from './sdkBackupV2.js' // NEW accounts on the Witbitz account service (account v2; the owner, 2026-11-16: "Yes. Do the sdk.")
49
+ import { roomRegion } from './regions.js' // a lane's region is its Space's
50
+ import { makeRoomPassHolder, roomPassSwitchOn, isRoomPassAsk, isSigninRenewAsk } from './roomPass.js' // the room pass of an account on the account service (docs/device-gate-design.md)
51
+
52
+ export const VAULT_PROTOCOL = 1
53
+ // The room operations a page may run, on a room this vault holds. Left out on purpose: purge/carry (destructive or
54
+ // cross-room), subscribe/unsubscribe (push belongs to the vault), and the intake ops (the account's). Sealed exports and supported chat imports are allowed.
55
+ // (no 'safeCopy': a safe copy is made only where the sign-in and the key are — space.safeMedia.make is refused in a vault, and
56
+ // nothing in vault mode posts one; sync sweep backlog P7)
57
+ export const PAGE_OPS = new Set(['poll', 'pollSealed', 'turn', 'state', 'data', 'title', 'decide', 'pending', 'mirror', 'toolResult', 'getConfig', 'setConfig', 'blob', 'react', 'mark', 'sealed', 'exportSealed', 'stop', 'toolRules', 'importChat', 'importWhatsApp'])
58
+ const KEYS = { rooms: 'wbvault:rooms', session: 'wbvault:session', siri: 'wbvault:siri', a2a: 'wbvault:a2a', invite: 'wbvault:invite', connections: 'wbvault:connections', backup: 'wbvault:backup', keep: 'wbvault:keep', connPending: 'wbvault:connPending' }
59
+ // THE ACCOUNT, through the vault's session (docs/sdk-vault-mode.md § The account). The page asks; the vault runs it on its
60
+ // own SDK client, which holds the sign-in. What stays here: the session, the Siri inbox's private keys, each connection's
61
+ // callKey (a grant is made by id). `confirm`: the person says yes in the vault's own pixels first — it acts in their name.
62
+ export const ACCOUNT_CALLS = {
63
+ cloudDevice: { status: {}, enroll: { confirm: true }, register: { confirm: true }, setBuilds: { confirm: true }, forget: { confirm: true } },
64
+ connections: { catalog: {}, spacesUsing: {}, attach: {}, list: {}, detach: { confirm: true }, startConnect: {}, finishConnect: {}, startMcp: {}, attachMcp: {}, finishMcp: {}, mcpTools: {} }, // MCP servers (2026-10-23): the callKey stays here, as attach's
65
+ usernames: { claim: { confirm: true }, release: { confirm: true }, mine: {}, resolve: {} },
66
+ siri: { status: {}, rotateKey: { confirm: true }, revoke: { confirm: true }, shortcut: {}, showKey: {} },
67
+ a2a: { status: {}, revoke: { confirm: true } },
68
+ // the account BACKUP and the account INDEX across devices: the vault's own, over the Spaces it holds. The recovery code
69
+ // is shown and typed ONLY in the vault's screens (screens.recoveryCode / screens.restore) — a page that saw it would hold
70
+ // the way back to every key.
71
+ // signOutOthers / newRecoveryCode / deleteAccount: an account on the Witbitz account service (sdkBackupV2.js) — the vault's
72
+ // screens ask for the emailed code (screens.emailCode) and show a new code (screens.recoveryCode)
73
+ backup: { enable: {}, restore: {}, protectRecoveryEmail: {}, exportArchive: { confirm: true }, migrate: { confirm: true }, manageSecurityKeys: {}, save: {}, upgrade: {}, remove: { confirm: true }, signOutOthers: { confirm: true }, newRecoveryCode: { confirm: true }, deleteAccount: { confirm: true }, beginEmailMove: { confirm: true }, pendingEmailMove: {}, finishEmailMove: { confirm: true }, cancelPendingEmailMove: { confirm: true }, emailMove: {}, requestMoveTime: { confirm: true }, cancelEmailMove: { confirm: true } },
74
+ // (SERVICE_CALLS, below: the three that need an account on the service — checked before their confirm)
75
+ account: { repairNames: {}, previewEmptySpaces: {}, removeEmptySpaces: {}, listDevices: {}, signOutDevice: {}, sync: {}, start: {}, stop: {}, archive: {}, pin: {}, rename: {}, forget: { confirm: true }, signOut: { confirm: true }, noteLink: {}, dropLink: {}, section: {}, usage: {} }, // section: wb.account.contacts / .name / .roomDefaults (sdkAccountSections.js — the person's own data, no key; plan phase 5) // usage: what the account used, from its receipts (2026-10-23) // noteLink/dropLink: lane.link() across devices (sync sweep, 10-17 #6)
76
+ erasure: { file: {}, status: {} },
77
+ }
78
+ /** The backup calls that need an account on the Witbitz account service (sync sweep 11-16 #15). */
79
+ const SERVICE_CALLS = new Set(['manageSecurityKeys', 'signOutOthers', 'newRecoveryCode', 'emailMove', 'requestMoveTime', 'cancelEmailMove'])
80
+ export const ROOM_ACCOUNT_CALLS = {
81
+ roster: { list: {}, admission: {} },
82
+ portable: { export: { confirm: true } },
83
+ keptAgent: { link: { confirm: true }, unlink: { confirm: true } },
84
+ alwaysOn: { status: {}, enable: { confirm: true }, disable: { confirm: true }, run: {}, assertNotKept: {} },
85
+ invitations: { resend: { confirm: true } },
86
+ schedules: { list: {}, add: {}, remove: {}, pause: {} },
87
+ connections: { grants: {}, grant: { confirm: true }, revoke: {} },
88
+ siri: { enable: {}, disable: {}, collect: {} },
89
+ // a private lane's door for outside agents: `pull` opens the waiting messages here (the inbox key stays), the page posts
90
+ // each into the lane, then `ack`s it — as outside a vault
91
+ a2a: { view: {}, enable: {}, addPeer: { confirm: true }, setReply: {}, removePeer: {}, disable: {}, pull: {}, ack: {}, reply: {}, sharedDrafts: {}, reviewDraft: {} },
92
+ }
93
+ const ASK_MS = 60_000 // the page's answer to a question the vault asks it (a Siri drop handed to its deliver)
94
+ // What a page may put in a NEW Space's config — the fields the SDK's createSpace writes (roomConfig + the email gate).
95
+ // Anything else (a key model, a confidential tier, a direct chat) is refused HERE: the SDK's own refusals run in the
96
+ // page, and a hostile page skips them (security review, 2026-10-15).
97
+ export const CREATE_FIELDS = new Set(['agentName', 'persona', 'tools', 'immediateTools', 'clientTools', 'agentReplies', 'model', 'admission', 'allow', 'advertise', 'admins', 'owners', 'platformTools', 'framing', 'dataWrites', 'dataSchema', 'region', 'direct', 'safeMedia', 'lanes', 'lane']) // lane: a private lane says so (laneConfig.js) — it only takes things away (no schedules, no always on)
98
+ const CREATE_LIMIT = { n: 20, ms: 10 * 60_000 } // new Spaces per window, per vault page
99
+ const SPEECH_LIMIT = { n: 30, ms: 10 * 60_000 } // speech keys (dictation, reading aloud) per window, per vault page
100
+ const REFRESH_BEFORE_MS = 10 * 60_000 // renew the sign-in this long before it expires
101
+ const WIPE_PUSH_MS = 10_000 // a sign-out takes this device off its Spaces' notification lists for at most this long — then it goes on
102
+
103
+ const read = (st, k, d) => { try { const v = st.getItem(k); return v ? JSON.parse(v) : d } catch { return d } }
104
+ const write = (st, k, v) => { try { if (v == null) st.removeItem(k); else st.setItem(k, JSON.stringify(v)) } catch { /* a full or blocked store: the vault still works this session */ } }
105
+
106
+ /** What an invite link carries: `…/space?room=<id>#mk=<key>` → { room, mk }; a SPLIT room's `#us=<half>&spc=<commit>`
107
+ * → { room, userShare, commit, split: true } (the other half is the builder's app-half function's); else null. */
108
+ export function linkParts(href) {
109
+ try {
110
+ const u = new URL(href)
111
+ const room = u.searchParams.get('room') || ''
112
+ const frag = new URLSearchParams(u.hash.replace(/^#/, ''))
113
+ const mk = frag.get('mk') || '', us = frag.get('us') || ''
114
+ if (room && mk) return { room, mk }
115
+ if (room && us) return { room, userShare: us, commit: frag.get('spc') || '', split: true }
116
+ return null
117
+ } catch { return null }
118
+ }
119
+ /** A room's config as the page may see it: each connection without its callKey (the key that lets the room spend it),
120
+ * a funding grant without its secrets. Everything else — the assistant, the gate, the store — the page shows. */
121
+ /** A refusal the vault's own SDK made, as the PAGE must read it: in a vault the call that signs in is wb.vault.signIn — wb.signIn
122
+ * is refused there (sync sweep 11-14 P7: space.connections / siri through the vault said "wb.signIn"). Same error, same code. */
123
+ export function vaultSignInWords(e) {
124
+ if (e && e.code === 'sign_in_required' && typeof e.message === 'string' && /\bwb\.signIn\b/.test(e.message)) {
125
+ try { e.message = e.message.replace(/\bwb\.signIn\b/g, 'wb.vault.signIn') } catch { /* a frozen message: as it was */ }
126
+ }
127
+ return e
128
+ }
129
+
130
+ export function configForPage(cfg) {
131
+ if (!cfg || typeof cfg !== 'object') return cfg
132
+ const out = { ...cfg }
133
+ if (Array.isArray(out.connections)) out.connections = out.connections.map((c) => { if (!c || typeof c !== 'object') return c; const { callKey: _k, ...rest } = c; return rest })
134
+ if (out.funding && typeof out.funding === 'object') { const { grant: _g, grantToken: _t, key: _x, token: _y, ...rest } = out.funding; out.funding = rest }
135
+ return out
136
+ }
137
+ const holdLink = (worker, p) => { if (!p) return; if (p.mk) worker.postMessage({ t: 'remember', room: p.room, mk: p.mk }); else if (p.split) worker.postMessage({ t: 'rememberSplit', room: p.room, userShare: p.userShare, commit: p.commit }) }
138
+
139
+ /**
140
+ * Start the vault: frame the builder's page, start the key worker, answer the page.
141
+ * @param {object} o
142
+ * @param {string} o.page the builder's page (full https URL); only its ORIGIN may talk to this vault
143
+ * @param {string} [o.tenant] the builder's tenant id (public) — the Spaces this vault creates are its tenant's
144
+ * @param {string} [o.endpoint] the Space API (default: Witbitz's)
145
+ * @param {string} [o.loginBase] where the email sign-in endpoints live (default: Witbitz's)
146
+ * @param {string} [o.app] a short app tag sent with each request
147
+ * @param {object} o.screens the builder's screens: { signIn, share, failed?, ready? } (vault-screens.js)
148
+ * @param {HTMLElement} [o.mount] where the page's frame goes (default: document.body)
149
+ * @param {Storage} [o.storage] where the room list and the session are kept (default: localStorage of THIS origin)
150
+ * @param {Function} [o.makeWorker] () => Worker — tests inject; default: ./l1-worker.js as a module worker
151
+ * @param {boolean} [o.lock] offer the person the lock and storage protection (vaultCoreLock.js; the page: wb.vault.showLock())
152
+ * @param {boolean} [o.push] offer the person notifications (vaultCorePush.js; the page: wb.vault.showNotifications())
153
+ * @param {string} [o.pushWorker] the service worker's path (default /push-sw.js, the kit's)
154
+ * @param {string|false} [o.accountService] where NEW accounts are kept: the Witbitz account service (default
155
+ * https://api.witbitz.chat/v1, with a `tenant` — the vault's origin must be one of the tenant's proven origins); `false` keeps
156
+ * new accounts on the old backup store, as before this release. Without a tenant: the old store.
157
+ */
158
+ export async function startVault(o = {}) {
159
+ const pageUrl = new URL(String(o.page || ''))
160
+ const pageOrigin = pageUrl.origin
161
+ if (!/^https?:$/.test(pageUrl.protocol)) throw new Error('vault: `page` must be an http(s) URL')
162
+ if (pageOrigin === location.origin) throw new Error('vault: the page must be on ANOTHER origin — that is the wall that keeps the keys out of it')
163
+ if (globalThis.localStorage?.getItem('witbitz-builder-reset-pending')) {
164
+ const { finishBuilderReset } = await import('./vaultCoreLock.js')
165
+ if (!(await finishBuilderReset())) {
166
+ const retry = document.createElement('button')
167
+ retry.textContent = 'Close other vault tabs, then retry clearing this device'
168
+ retry.onclick = () => location.reload()
169
+ document.body.replaceChildren(retry)
170
+ return
171
+ }
172
+ }
173
+ const screens = o.screens || {}
174
+ // A screen the builder's screens.js does not have falls back to OURS (sync sweep 10-15 #7): a kit upgraded from an older
175
+ // release keeps the builder's screens.js (it is theirs) — and the backup and Siri-key screens came later. Brand: theirs if given.
176
+ let _ours = null
177
+ const screenFor = async (name) => {
178
+ if (typeof screens[name] === 'function') return screens[name].bind(screens)
179
+ try { _ours = _ours || (await import('./vault-screens.js')).defaultScreens({ brand: String(o.brand || (typeof document !== 'undefined' && document.title) || location.hostname || 'this app').slice(0, 60) }) } catch { _ours = {} } // an older kit's vault.js passes no brand: the vault page's own title, then its host (sync sweep, 10-16)
180
+ return typeof _ours[name] === 'function' ? _ours[name].bind(_ours) : null
181
+ }
182
+ // ── THE LOCK, opt-in twice (vaultCoreLock.js; 2026-11-13): the builder starts the vault with `lock: true`, the person turns it
183
+ // on in the vault's sheet (wb.vault.showLock()). Without `lock: true` none of it is even loaded. With it, a locked launch waits
184
+ // HERE — before the vault reads its storage, starts its worker or frames the page — for the passkey.
185
+ let frameEl = null, frameHidden = false
186
+ const vlock = o.lock === true ? await (async () => {
187
+ const lockUi = await screenFor('lockUi')
188
+ return (await import('./vaultCoreLock.js')).createVaultLock({
189
+ brand: String(o.brand || (typeof document !== 'undefined' && document.title) || location.hostname || 'this app').slice(0, 60),
190
+ mountUi: () => { if (lockUi) lockUi() },
191
+ hide: () => { frameHidden = true; if (frameEl) frameEl.style.display = 'none' },
192
+ show: () => { frameHidden = false; if (frameEl) frameEl.style.display = 'block' },
193
+ onState: (lock) => { if (frameEl) { emit({ ev: 'lock', lock }); queuePushPrivacy() } },
194
+ confirm: (q) => (typeof screens.confirm === 'function' ? screens.confirm(q) : Promise.resolve(window.confirm(q.title))),
195
+ onUnprotected: () => workerAtRest(), // protection off: the worker's store goes back under the device key, never clear
196
+ beforeProtect: async () => { if (workerDeviceKey) { await unprotectIdb(idb, workerDeviceKey); await wcall({ t: 'unprotect', key: workerDeviceKey }) } }, // remove the old device-key copies before resealing with the passkey
197
+ })
198
+ })() : null
199
+ if (vlock) await vlock.boot()
200
+ // EVERY SECRET ON DISK SEALED (vaultSealedStore.js; the owner, 2026-11-24, as our hosted vault): the session, the invite key, Siri,
201
+ // outside agents, connections (and those being granted) and the merged view are kept in memory and sealed to disk under the at-rest key
202
+ const learnedBlocksKey = 'wbvault:learnedBlockIdentities'
203
+ const SEALED_KEYS = [learnedBlocksKey, KEYS.session, KEYS.siri, KEYS.a2a, KEYS.invite, KEYS.connections, KEYS.keep, KEYS.connPending]
204
+ const wipeMarker = 'wbvault:signout-pending'
205
+ let wipeRun = null, peerSignedOut = false
206
+ const st = sealedStorage(o.storage || localStorage, SEALED_KEYS)
207
+ // THE ROOM PASS (docs/device-gate-design.md; roomPass.js): an account on the Witbitz account service proves, on every verified-Space
208
+ // request, that this device is still one of its active devices — a ten-minute pass from the service (this vault's device key, its
209
+ // tenant's scope) and the session key's signature. Made HERE (the page never holds a key); the worker asks for it under the reserved
210
+ // name '#room-pass', and this vault's own client carries it too. On only with the apps' switch (ROOM_PASS_APP, or `space:roompass=1`
211
+ // in this vault's storage) and an account on the service; set below, once the account service is.
212
+ let roomPass = null
213
+ const roomPassClient = { fieldsFor: (b, o) => (roomPass ? roomPass.client.fieldsFor(b, o) : Promise.resolve({})), /* o: { ts } — the request's time (roomPass.js sign; sync sweep 11-16 #8) */ renew: (b) => (roomPass ? roomPass.client.renew(b) : Promise.resolve()) }
214
+ // A SIGN-IN THAT NAMES NO APP (docs/device-gate-design.md § 12.1, `pass: app_unnamed` — a session token from before `asc`): the
215
+ // session is renewed once, quietly (its /refresh names this vault's tenant), and the request sent again. One renewal at a time.
216
+ let renewing = null
217
+ const renewSession = () => {
218
+ if (!renewing) renewing = (async () => {
219
+ try {
220
+ if (!signedIn()) return null
221
+ const renewed = await sdk.refreshSession()
222
+ if (sdk._session !== renewed) return null
223
+ keepSession(); emit({ ev: 'session', keyId: sessionKeyId() }); scheduleRefresh()
224
+ return { idToken: sdk.session.idToken, spk: sdk.session.sign.pub }
225
+ } catch (err) {
226
+ if (!signedIn() || ['revoked', 'signed_out', 'no_session'].includes(err?.code) || [401, 403].includes(err?.status)) return null
227
+ return { retryable: true }
228
+ }
229
+ })().finally(() => { renewing = null })
230
+ return renewing
231
+ }
232
+ const sdk = new Witbitz({ ...(o.appShare ? { appShare: new URL('/api/appshare', location.origin).href } : {}), ...(o.endpoint ? { endpoint: o.endpoint } : {}), ...(o.loginBase ? { loginBase: o.loginBase } : {}), ...(o.tenant ? { tenant: o.tenant } : {}), ...(o.enclaveClaim ? { enclaveClaim: o.enclaveClaim } : {}), ...(o.vaultApi ? { vaultApi: o.vaultApi } : {}), sentinel: { follow: 'ask', onNewBuild: async () => { await sdk.builds.sync(); return sdk.builds.automatic } }, deviceName: String(o.deviceName || ''), live: false, _roomPass: roomPassClient, _renewSignIn: () => renewSession() })
233
+ // The worker gets the endpoint as an ABSOLUTE address. It runs from a pinned source held in memory (a blob:), where a
234
+ // relative one ('/api/space', a vault that serves its own Space API) has no base to resolve against: every fetch threw
235
+ // "Failed to parse URL" (CI 43560453677, after 580fdd9ca). Resolved here, against the vault's own page.
236
+ const endpoint = (() => { try { return new URL(sdk._endpoint, location.href).href } catch { return sdk._endpoint } })()
237
+ // ON DISK NO ROOM KEY IS CLEAR (vaultAtRest.js; the owner, 2026-11-13): the list keeps each link without its key and the key
238
+ // sealed, under a non-extractable key of this vault's own (IndexedDB); the backup state is sealed whole. An older vault's clear
239
+ // list is read as it is and written back sealed.
240
+ // A KEY THAT COULD NOT BE READ (sync sweep 2026-11-15 #3): deviceWrapKey retried and threw — the person is asked, and the vault never
241
+ // runs keyless over sealed data (it read the backup as off and a new master replaced it). "Not now" stops here; nothing is deleted.
242
+ let wrapKey = null
243
+ for (;;) {
244
+ try {
245
+ wrapKey = await deviceWrapKey()
246
+ // NO IndexedDB this launch (null) over storage that holds sealed data: the same as a read that failed — never keyless (sync sweep 11-18)
247
+ if (!wrapKey && (holdsSealed(st, { rooms: KEYS.rooms, backup: KEYS.backup }) || st.holdsSealed())) throw Object.assign(new Error('this vault\'s saved data could not be opened (no IndexedDB here just now)'), { code: 'device_key_unreadable' })
248
+ break
249
+ } catch (e) {
250
+ const again = await (typeof screens.confirm === 'function' ? screens.confirm({ title: 'Couldn\u2019t open this vault\u2019s saved data', text: 'This device did not let the vault read its storage just now. Nothing was deleted. Try again — or close the app and open it again.', ok: 'Try again', cancel: 'Not now' }) : Promise.resolve(window.confirm('Couldn\u2019t open this vault\u2019s saved data. Try again?'))).catch(() => false)
251
+ if (!again) throw e
252
+ }
253
+ }
254
+ await st.open(wrapKey) // the sealed secrets, opened into memory (and an older clear copy sealed) before anything reads one
255
+ const savedSession = read(st, KEYS.session, null)
256
+ if (savedSession) sdk.useSession(savedSession)
257
+ const atRest = createAtRest({ storage: st, key: wrapKey })
258
+ let rooms = await atRest.loadRooms(KEYS.rooms) // [{ room, link, title, at }] — in memory the link IS the key; it never leaves this origin
259
+ let vpush = null // notifications (`push: true`, vaultCorePush.js): every Space held lists this device, kept in step at each save
260
+ let pushAcctSecret = '' // the account's push tag secret the key worker holds (handDownPushAcct) — '' while no account is here
261
+ const saveRooms = () => { if (vpush) vpush.sync(rooms.map((r) => r.room)).catch(() => {}); return atRest.saveRooms(KEYS.rooms, rooms) } // in order; resolves once on disk
262
+ sdk._heldLaneRooms = (parent) => rooms.filter((r) => r.lane === parent).map((r) => r.room)
263
+ sdk._detachHeldLanes = async (parent) => {
264
+ for (const r of rooms) if (r.lane === parent) { delete r.lane; r.detachedLane = true }
265
+ await saveRooms()
266
+ emit({ ev: 'rooms', rooms: publicRooms() })
267
+ }
268
+ if (sdk.session?.email) await atRest.claimEmailMove(KEYS.backup, sdk.session.email)
269
+ const backupsAtStart = await atRest.loadBackups(KEYS.backup) // here, before the frame: nothing awaits between the frame and the page's hello listener
270
+ const publicRooms = () => rooms.map(({ room, title, at, lane, enc, link }) => ({ room, title: title || '', at, ...(lane ? { lane } : {}), ...(enc ? { tier: 'enclave' } : {}), ...(/[#&]lanes=1(?:&|$)/.test(String(link || '')) ? { lanes: true } : {}) })).sort((a, b) => (Number(b.at) || 0) - (Number(a.at) || 0)) // lane: the Space it is a private lane of; lanes: a private assistant for every member (its link says so — never the link itself)
271
+
272
+ // ── the key worker ───────────────────────────────────────────────────────────────────────────────────────────────
273
+ let worker = null, wseq = 0
274
+ const streaming = new Set() // rooms the page holds a live stream for (CALLS.stream); the socket lives in the worker
275
+ const wwait = new Map()
276
+ const signedIn = () => { const s = sdk.session; return !!(s && s.idToken && s.sign && !(s.exp && s.exp <= Date.now())) }
277
+ // the session key's PUBLIC id (agentIdentity.keyIdOf) — the page marks its own messages by it (space.isMine; sweep 11-07 #9)
278
+ const sessionKeyId = () => { const k = signedIn() ? sdk.session.sign.pub : null; return k && k.kty && k.crv && k.x != null && k.y != null ? `${k.kty}:${k.crv}:${k.x}:${k.y}` : '' }
279
+ // OPTION B's hints, fetched by THE WORKER's client — the one that sends this vault's room requests (sweep 11-07 #7: the SDK's
280
+ // own prefetch reached only this page's client, so the first sealed request fetched them inline). In the background, a few
281
+ // seconds after a sign-in / a renewal / a (re)started worker, then hourly — never right before a room request.
282
+ let idPrefetchT = null
283
+ function prefetchWorker(delayMs = 2000 + Math.floor(Math.random() * 8000)) {
284
+ try {
285
+ clearTimeout(idPrefetchT)
286
+ idPrefetchT = setTimeout(() => {
287
+ if (!worker || !signedIn()) return
288
+ try { worker.postMessage({ t: 'prefetchIdentity', token: sdk.session.idToken }) } catch { /* the next sealed request fetches them */ }
289
+ prefetchWorker(50 * 60_000 + Math.floor(Math.random() * 10 * 60_000))
290
+ }, delayMs)
291
+ } catch { /* no timers */ }
292
+ }
293
+ // PER-USER BILLING (sync sweep, 10-17 #5): the page hands its current user token over right before an op that can spend
294
+ // (CALLS.userToken); memory only, never stored. The worker asks for it under the reserved name '#account-billing'.
295
+ let pageUserToken = ''
296
+ const authFor = (room) => (room === '#account-billing' ? { ...(signedIn() ? { idToken: sdk.session.idToken, spk: sdk.session.sign.pub } : {}), ...(pageUserToken ? { userToken: pageUserToken } : {}) } : (signedIn() ? { idToken: sdk.session.idToken, spk: sdk.session.sign.pub } : {}))
297
+ const wcall = async (msg) => {
298
+ const target = (msg.t === 'op' || msg.t === 'create') ? await workerHost.ready() : worker
299
+ if (!target || target !== worker) throw Object.assign(new Error('the room worker was replaced'), { code: 'worker_restarted' })
300
+ return new Promise((res, rej) => {
301
+ const id = ++wseq
302
+ wwait.set(id, { res, rej })
303
+ try { target.postMessage({ id, ...msg }) } catch (err) { wwait.delete(id); rej(err) }
304
+ })
305
+ }
306
+ // a call waiting on a worker that is gone fails at once, named (a dead worker, a sign-out's new one): it can never be answered, and
307
+ // the push queue (vaultCorePush.js, one change at a time) waited for ever behind such a call (sync sweep 11-22 P8)
308
+ const failWaiting = (why) => { for (const [id, w] of wwait) { wwait.delete(id); try { w.rej(Object.assign(new Error(why), { code: 'worker_restarted' })) } catch { /* */ } } }
309
+ let workerRooms = [] // the rooms the worker says it holds a key for (its `presence`: ids only, never a key) — a sign-out forgets them all
310
+ const onWorker = (e) => {
311
+ const m = e.data || {}
312
+ if (m.t === 'presence') { if (Array.isArray(m.rooms)) workerRooms = m.rooms.filter((r) => typeof r === 'string' && r).slice(0, 5000); return }
313
+ if (m.authReq != null && isSigninRenewAsk(m.room)) { const a = m.authReq, w = worker; renewSession().then((v) => { try { w.postMessage({ t: 'authRes', a, v: v || {} }) } catch { /* a restarted worker asks again */ } }); return } // the sign-in renewed to name its app (above)
314
+ if (m.authReq != null && isRoomPassAsk(m.room)) { const a = m.authReq, w = worker; (roomPass ? roomPass.answer(m.room) : Promise.resolve({})).then((v) => { try { w.postMessage({ t: 'authRes', a, v: v?.retryable ? { retryable: true } : v && v.pass && v.psig ? { pass: v.pass, psig: v.psig } : {} }) } catch { /* a restarted worker asks again */ } }); return } // the room pass (above)
315
+ if (m.authReq != null) { worker.postMessage({ t: 'authRes', a: m.authReq, v: authFor(m.room) }); return }
316
+ if (m.attestReq != null) { worker.postMessage({ t: 'attestRes', a: m.attestReq, v: null }); return }
317
+ if (m.delReq != null) { const source = worker; sdk.erasure._commitFor(String(m.room || '')).then((v) => source.postMessage({ t: 'delRes', a: m.delReq, v: v || null }), () => source.postMessage({ t: 'delRes', a: m.delReq, v: null })); return } // the erase list's commitment
318
+ // ROOM STREAMS: the worker's events for a room the page asked to stream — the reply text as it grows, "poll now",
319
+ // "the turn ended". The same plaintext a poll's partialText already carries to the page; never a key.
320
+ if (m.t === 'stream') { if (streaming.has(m.room)) emit({ ev: 'stream', room: m.room, ...(m.ev ? { event: m.ev } : {}), ...('up' in m ? { up: !!m.up } : {}) }); return }
321
+ if (m.id != null && wwait.has(m.id)) { const w = wwait.get(m.id); wwait.delete(m.id); if (m.error) w.rej(Object.assign(new Error(m.error), { code: m.code, ...(m.verdict && typeof m.verdict === 'object' ? { verdict: m.verdict } : {}) })); else w.res(m.result) } // the verdict too: which stage of a build did not match (errExtra passes it on; sync sweep 11-09, 11-08 #28)
322
+ }
323
+ const identity = () => (signedIn() ? { email: sdk.session.email, googleIdToken: sdk.session.idToken, sign: sdk.session.sign } : null)
324
+ const seedIdentity = (room) => { const id = identity(); if (id) worker.postMessage({ t: 'rememberId', room, identity: id }) }
325
+ // A WORKER iOS RECLAIMED IS RESTARTED (sync sweep, 10-18 #7): the app's two hosts ping theirs; this one never did, so a dead
326
+ // handle swallowed every call and each hung for ever (vault_timeout on the page). A call waiting on the dead worker fails at
327
+ // once, named, and the page's next call reaches the new one. The heartbeat, the restart and the replay are the SAME host our
328
+ // hosted vault uses (vaultWorkerHost.js, docs/vault-core-convergence-review.md C1); what this vault replays is registered below.
329
+ // ★ THE KEY WORKER FROM A PINNED SOURCE (the owner, 2026-11-14: "Do it now"; docs/vault-core-convergence-review.md § 5), as our own
330
+ // vault: it was a Worker made from the URL of l1-worker.js — a file the browser fetched from this host at every start, checked by
331
+ // nothing (kit.json's hashes are read only when the kit is built), into the realm that holds every key. Its source now arrives as
332
+ // a MODULE (`l1-worker-src.js`: bundled by each SDK release, named with its sha384 in the kit page's import map) and runs from
333
+ // memory (vcWorker.js). Read ONCE, before the host and its heartbeat exist — a restart builds from the same string, synchronously
334
+ // (vcWorker.js: no network round trip in front of a worker the heartbeat may restart). Missing → the vault does not start: a URL
335
+ // fallback would be exactly the unpinned load this closes.
336
+ let workerSrc = ''
337
+ if (typeof o.makeWorker !== 'function') {
338
+ try { ({ SRC: workerSrc } = await import('./l1-worker-src.js')) } catch (e) { workerSrc = '' }
339
+ if (typeof workerSrc !== 'string' || workerSrc.length < 1000) throw Object.assign(new Error('the vault cannot start: its key worker (core/l1-worker-src.js) is missing or was refused — run the vault kit again'), { code: 'vault_worker_missing' })
340
+ }
341
+ const WORKER_AT_REST = 'wbvault:worker-at-rest' // set once the worker's store was sealed by the device key: later starts unseal
342
+ let workerDeviceKey = null, workerKeyMade = false
343
+ try { const dk = await deviceStorageKey(); if (dk && dk.raw) { workerDeviceKey = dk.raw; workerKeyMade = !!dk.made } } catch { /* no key: the store stays as before */ }
344
+ const workerHost = createWorkerHost({
345
+ make: () => (typeof o.makeWorker === 'function' ? o.makeWorker() : makeVerifiedWorker(workerSrc, '', { type: 'module' })),
346
+ onCurrent: (w) => { worker = w },
347
+ onMessage: onWorker,
348
+ onRestart: () => failWaiting('the room worker stopped and was restarted — try again'),
349
+ })
350
+ // THE CONFIDENTIAL TIER FIRST, awaited (sync sweep 2026-11-09 #1, as our hosted vault): the held snapshot — every confidential room,
351
+ // the newer attested key — before the open and any link. It used to be an EMPTY list here and the real one only after the links,
352
+ // so an op landing in between met a worker that held keys from its own store (l1-worker keysReady) and no confidential room.
353
+ // A PROTECTED DEVICE's worker opens its sealed store first (the lock's device key, held in this page only while unlocked)
354
+ if (vlock) workerHost.replay('protect', () => { const m = vlock.workerUnseal(); return m ? wcall(m) : null })
355
+ // THE KEY WORKER'S STORE, SEALED AT REST (the 11-21 sync sweep P8; owner, 2026-11-22: "do both"): with no passkey protection the worker
356
+ // wrote every room key to IndexedDB in the clear, against this vault's own rule (vaultAtRest.js: nothing on disk carries a room key in
357
+ // the clear). As our hosted vault: the device key (vaultDeviceKey.js, 32 bytes kept wrapped under a non-extractable key of this origin)
358
+ // seals the worker's store — the first time `seal` (a clear store is rewritten sealed), after that `unseal`. A protected device's
359
+ // passkey key takes precedence (the replay above); no IndexedDB → as before, clear (a key is never lost for want of a seal).
360
+ workerHost.replay('atRest', () => workerAtRest())
361
+ workerHost.replay('enclave', () => wcall(enclaveMsg()))
362
+ workerHost.replay('open', () => wcall({ t: 'open', room: null, mk: null, endpoint, app: o.app || 'vault', ...(o.tenant ? { tenant: o.tenant } : {}) }))
363
+ workerHost.replay('links', async w => {
364
+ for (const r of rooms) {
365
+ const p = linkParts(r.link)
366
+ if (!p || p.room !== r.room) continue
367
+ holdLink(w, p)
368
+ if (p.split && r.mk && await keyCommit(r.mk).catch(() => '') === p.commit) w.postMessage({ t: 'remember', room: r.room, mk: r.mk })
369
+ seedIdentity(r.room)
370
+ }
371
+ })
372
+ workerHost.replay('streams', (w) => { for (const room of streaming) w.postMessage({ t: 'streamOpen', room }) }) // a restarted worker (sign-out) picks the page's streams back up
373
+ workerHost.replay('pushSelf', (w) => { const e = vpush && vpush.endpoint(); if (e) w.postMessage({ t: 'setPushSelf', endpoint: e }) }) // this device's own posts do not tickle it
374
+ workerHost.replay('pushAcct', (w) => { if (pushAcctSecret) w.postMessage({ t: 'setPushAcct', secret: pushAcctSecret }) }) // …nor its account's other devices (handDownPushAcct)
375
+ workerHost.replay('prefetch', () => prefetchWorker())
376
+ function workerAtRest() {
377
+ if (!workerDeviceKey || !worker || (vlock && vlock.workerUnseal())) return null
378
+ let sealed = false; try { sealed = st.getItem(WORKER_AT_REST) === '1' } catch { /* */ }
379
+ // A DEVICE KEY MADE THIS START cannot open a store sealed under the one before it (sync sweep 2026-11-23 P8: `unseal` failed in
380
+ // silence and the worker then kept nothing): `seal` drops what no key opens and keeps the store under the new key, as our vault starts new
381
+ if (sealed && workerKeyMade) { sealed = false; workerKeyMade = false }
382
+ return wcall({ t: sealed ? 'unseal' : 'seal', key: workerDeviceKey, previews: true }).then(() => { try { st.setItem(WORKER_AT_REST, '1') } catch { /* */ } }).catch(() => { /* the store stays as it was; the next start tries again */ })
383
+ }
384
+ async function startWorker() { await workerHost.start() } // a new worker, replayed (at start and at sign-out)
385
+ // ── THE CONFIDENTIAL TIER: the vault attests the enclave with the SDK's own code (the published claim, the policy
386
+ // text, the Nitro document) and hands its worker the attested key. The worker seals a room's key only to a build
387
+ // Witbitz publishes — the SDK's rule (enclaveAccept.publishedKey): `trusted` is exactly the published live build.
388
+ // The rules for what the worker is told are vaultEnclaveHandoff.js (C2, shared with our hosted vault): the confidential rooms are
389
+ // a UNION that never shrinks in a worker's life (11-10 #1), the newer attested key wins (pass 9 X#1), and a new worker hears the
390
+ // held snapshot first (11-09 #1). Who attests stays here: this vault, never its page.
391
+ const encHandoff = createEnclaveHandoff({ trust: 'published' })
392
+ const creatingEnclaveRooms = new Set()
393
+ const encRooms = () => [...new Set([...creatingEnclaveRooms, ...rooms.filter(r => r.enc).map(r => r.room)])]
394
+ const isEncRoom = (room) => rooms.some((r) => r.room === room && r.enc)
395
+ // ★ THE VAULT'S OWN CLIENT KNOWS THE TIER TOO (sweep 11-06 #2, #3): only the worker learned it, so a call this page's client made
396
+ // itself (a turn's stop) went to the standard tier and was refused. Marked only once the enclave is attested: a marked room
397
+ // with no key would send its room key readable (enclaveReady). → whether the room may be called on the enclave from here.
398
+ const encReadyFor = (room) => enclaveReady({ confidential: isEncRoom(room), hasKey: () => !!sdk._enc.key, attest: () => encAttest(room), mark: () => { if (!sdk._enc.rooms.has(room)) sdk._enc.rooms.set(room, true) } })
399
+ function enclaveMsg() { // the SDK's attested state, merged into what the worker holds → the whole snapshot to send it
400
+ const e = sdk._enc, keys = {}
401
+ if (e.key) for (const r of encRooms()) if (!e.rooms.has(r)) e.rooms.set(r, true) // the page's client: the same tier the worker sends to
402
+ for (const [region, v] of e.byRegion) keys[region] = { key: v.key, attested: { ...v.attested, platform: v.platform } }
403
+ return encHandoff.offer({ key: e.key || null, attested: e.attested ? { ...e.attested, platform: e.platform } : null, keys, rooms: encRooms() })
404
+ }
405
+ function pushEnclave() {
406
+ if (!worker) return
407
+ worker.postMessage(enclaveMsg())
408
+ }
409
+ let encReady = null // one attestation at a time, shared
410
+ const encAttest = (room) => (encReady ||= sdk._encAttest(room).then(() => { pushEnclave() }).finally(() => { encReady = null }))
411
+ await startWorker()
412
+ if (vlock) vlock.setWorker((m) => wcall(m)) // the lock's seal / unseal / relock / unprotect reach whichever worker is current
413
+ // ── NOTIFICATIONS, opt-in twice (vaultCorePush.js; 2026-11-13): the builder starts the vault with `push: true`, the person turns
414
+ // them on in the vault's card (wb.vault.showNotifications()). Subscribing a Space is the vault's own worker op — never a page op.
415
+ if (o.push === true) {
416
+ vpush = (await import('./vaultCorePush.js')).createVaultPush({
417
+ storage: st, worker: typeof o.pushWorker === 'string' ? o.pushWorker : '/push-sw.js',
418
+ subscribe: (room, sub, quiet) => wop('subscribe', room, sub, '', quiet),
419
+ unsubscribe: (room, sub) => wop('unsubscribe', room, sub),
420
+ setSelf: (endpoint) => { try { worker.postMessage({ t: 'setPushSelf', endpoint }) } catch { /* the replay sends it to the next one */ } },
421
+ held: (room) => held(room),
422
+ onOpen: (room) => emit({ ev: 'notifOpen', room }),
423
+ // this device's address changed (loaded at start, turned on or off): the account service learns it now (Codex sweep 11-16 #2)
424
+ onChange: () => { try { const b = sdk.backup; if (b && b._v2 && b.enabled && b._s) b._v2.syncPush(b).catch(() => {}) } catch { /* */ } },
425
+ })
426
+ }
427
+
428
+ // ── an invite opened in THIS vault: …/space?room=<id>#mk=<key> — keep it, take the key out of the address bar ─────────
429
+ // ★ A HELD room's key is NEVER replaced by a link (security review, 2026-10-15): a crafted link with the right room and
430
+ // a wrong key would have written that key over the real one — a room drawn blank for good. A NEW room is joined only
431
+ // after the person says so (a link clicked elsewhere must not add Spaces silently).
432
+ let joined = null
433
+ const inv = linkParts(location.href)
434
+ const invLink = inv ? location.href : ''
435
+ if (inv) { try { history.replaceState(null, '', location.pathname.replace(/\/space$/, '/')) } catch { /* */ } } // the key leaves the address bar at once
436
+ // A COLD TAP on a notification (push-sw.js opens the vault at ?room=…&tap=1): the page reads it in its welcome (`notifOpen`)
437
+ const tapQ = vpush && !inv ? new URLSearchParams(location.search) : null
438
+ const tapRoom = tapQ && tapQ.get('tap') === '1' ? String(tapQ.get('room') || '').slice(0, 120) : ''
439
+ if (tapRoom) { try { history.replaceState(null, '', location.pathname) } catch { /* */ } }
440
+ const confirmWith = (q) => (typeof screens.confirm === 'function' ? screens.confirm(q) : Promise.resolve(window.confirm(q.text ? q.title + '\n\n' + q.text : q.title)))
441
+ async function joinInvite() {
442
+ if (!inv || rooms.some((r) => r.room === inv.room)) { if (inv) joined = inv.room; return } // already held: open it, keep its key
443
+ const ok = await confirmWith({ title: 'Join this Space?', text: 'Someone shared a Space with you. Join it on this device?', ok: 'Join', cancel: 'Not now' }).catch(() => false)
444
+ if (!ok) return
445
+ rooms = [{ room: inv.room, link: invLink, title: '', at: Date.now(), ...(/[?#&]enc=1(?:[&#?]|$)/.test(invLink) ? { enc: true } : {}), ...(inv.split ? { split: true } : {}) }, ...rooms]; await saveRooms()
446
+ pushEnclave()
447
+ holdLink(worker, inv); seedIdentity(inv.room); noteRoom(inv.room).catch(() => {})
448
+ joined = inv.room
449
+ emit({ ev: 'rooms', rooms: publicRooms() })
450
+ }
451
+
452
+ // ── the sign-in, kept and renewed here ────────────────────────────────────────────────────────────────────────────
453
+ const keepSession = () => { write(st, KEYS.session, sdk.session); for (const r of rooms) seedIdentity(r.room); prefetchWorker() }
454
+ let refreshTimer = null
455
+ const scheduleRefresh = () => {
456
+ clearTimeout(refreshTimer)
457
+ const s = sdk.session; if (!s || !s.exp) return
458
+ refreshTimer = setTimeout(async () => { try { const renewed = await sdk.refreshSession(); if (sdk._session !== renewed) return; keepSession(); emit({ ev: 'session', keyId: sessionKeyId() }); scheduleRefresh() } catch { if (sdk.session !== s) return; /* the next gated read asks to sign in — and once it lapses, the page is told (sync sweep 2026-10-28 #7: wb.vault.info said signed in after it expired) */ const at = (sdk.session && sdk.session.exp) || 0; refreshTimer = setTimeout(() => { if (!signedIn()) emit({ ev: 'signedOut', reason: 'expired' }) }, Math.max(0, at - Date.now()) + 1000) } }, Math.max(5000, s.exp - Date.now() - REFRESH_BEFORE_MS))
459
+ }
460
+ scheduleRefresh()
461
+ let signingIn = null // one sign-in screen at a time, however often the page asks
462
+ async function signIn() { if (!signingIn) signingIn = signInOnce().finally(() => { signingIn = null }); return signingIn }
463
+ async function signInOnce() {
464
+ if (signedIn()) return { email: sdk.session.email }
465
+ if (typeof screens.signIn !== 'function') throw Object.assign(new Error('this vault has no sign-in screen'), { code: 'no_screen' })
466
+ const epoch = privacyEpoch
467
+ const previous = sdk.session?.email || read(st, KEYS.session, null)?.email
468
+ async function accept(session) {
469
+ if (epoch !== privacyEpoch || wipeRun || peerSignedOut) throw Object.assign(new Error('The account changed during sign-in'), { code: 'account_changed' })
470
+ if (previous && previous.toLowerCase() !== session.email.toLowerCase()) await wipeSignedOut()
471
+ if (peerSignedOut) throw Object.assign(new Error('This vault was signed out in another tab'), { code: 'account_changed' })
472
+ const claimEpoch = privacyEpoch
473
+ if (await atRest.claimEmailMove(KEYS.backup, session.email)) backupMem = await atRest.loadBackups(KEYS.backup)
474
+ if (peerSignedOut || wipeRun || claimEpoch !== privacyEpoch) throw Object.assign(new Error('The account changed during sign-in'), { code: 'account_changed' })
475
+ sdk.useSession(session)
476
+ sdk._enrollInvite()
477
+ keepSession(); scheduleRefresh(); loadSiri(); loadBackup()
478
+ }
479
+ await screens.signIn({
480
+ email: '', // never prefilled by the page (security review): the person types their own address
481
+ google: (o.googleSignIn === true || o.authBroker) ? async () => {
482
+ const session = sdk._session
483
+ const { genKeypair, spkNonce } = await import('./entrySig.js')
484
+ const { brokerGoogleToken } = await import('./spaceEmailGate.js')
485
+ const sign = await genKeypair(), nonce = await spkNonce(sign.pub)
486
+ const result = await brokerGoogleToken({ nonce, broker: o.authBroker || 'https://auth.witbitz.chat' })
487
+ if (sdk._session !== session) throw Object.assign(new Error('the account changed during sign-in'), { code: 'account_changed' })
488
+ if (!result || !result.idToken || !result.email) throw Object.assign(new Error('Google sign-in was not completed'), { code: 'sign_in_cancelled' })
489
+ const { jwtPayload } = await import('./emailSignIn.js')
490
+ await accept({ email: result.email, idToken: result.idToken, exp: Number(jwtPayload(result.idToken).exp) * 1000, sign })
491
+ return { email: sdk.session.email }
492
+ } : undefined,
493
+ sendCode: async (email) => { await sdk.signIn({ email }) },
494
+ verify: async (email, code) => { await accept(await sdk._signInResult({ email, code })) },
495
+ })
496
+ if (!signedIn()) throw Object.assign(new Error('not signed in'), { code: 'sign_in_cancelled' })
497
+ emit({ ev: 'signedIn', email: sdk.session.email, keyId: sessionKeyId() })
498
+ return { email: sdk.session.email }
499
+ }
500
+
501
+ // ── the frame ────────────────────────────────────────────────────────────────────────────────────────────────────
502
+ const frame = document.createElement('iframe')
503
+ frame.src = pageUrl.href
504
+ frame.title = o.title || 'App'
505
+ frame.setAttribute('allow', "clipboard-write; microphone; publickey-credentials-create 'src'; publickey-credentials-get 'src'")
506
+ // No allow-top-navigation (security review): the page must not send the whole window — the vault — somewhere else.
507
+ frame.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads allow-modals')
508
+ frame.style.cssText = 'position:fixed;inset:0;width:100%;height:100%;border:0;display:' + (frameHidden ? 'none' : 'block')
509
+ ;(o.mount || document.body).append(frame)
510
+ frameEl = frame
511
+ const toPage = (msg) => { try { frame.contentWindow.postMessage({ ch: 'wbvault', ...msg }, pageOrigin) } catch { /* the page is gone */ } }
512
+ const emit = (msg) => toPage({ t: 'event', ...msg })
513
+ // what a direct client's error carries crosses too — status, reason, verdict — so a page reads a refusal the same in a vault
514
+ // (sync sweep 11-08 #28: only the message and code crossed); plain data only, bounded
515
+ const errExtra = (err) => {
516
+ const o = {}
517
+ if (Array.isArray(err?.unavailable)) o.unavailable = err.unavailable.filter(id => typeof id === 'string' && id.length <= 160).slice(0, 1000)
518
+ if (err && Number.isInteger(err.status)) o.status = err.status
519
+ if (err?.code === 'wrong_pin' && Number.isSafeInteger(err.next) && err.next >= 0) o.next = err.next
520
+ if (err && typeof err.reason === 'string') o.reason = err.reason.slice(0, 500)
521
+ if (err && err.verdict && typeof err.verdict === 'object') { try { const j = JSON.stringify(err.verdict); if (j.length <= 4000) o.verdict = JSON.parse(j) } catch { /* not plain data: left out */ } }
522
+ return o
523
+ }
524
+ const refuse = (id, error, code, extra = {}) => toPage({ t: 'res', id, error, code, ...extra })
525
+
526
+ const held = (room) => typeof room === 'string' && rooms.some((r) => r.room === room)
527
+ let creates = [] // when this page last created Spaces (CREATE_LIMIT)
528
+ let speechKeys = [] // when this page last asked for a speech key (SPEECH_LIMIT)
529
+
530
+ // ── the account, through the vault's session ────────────────────────────────────────────────────────────────────────
531
+ let _lockedOnce = false // move 3: one locking pass a launch (connections.lock)
532
+ let conns = read(st, KEYS.connections, []) // [{ id, label, host, callKey, account }] — the callKeys never go to the page
533
+ // ⛔ ANOTHER TAB OF THIS VAULT writes the same storage (state machines pass 9, K#1; vaultKeep.js tabStores): the three stores
534
+ // below were loaded once per tab, so a tab that had not seen an attach stamped it "removed here" at its next pass — gone on
535
+ // every device. Every write goes through put() (it is this tab's own); every look at the stores adopts what moved first.
536
+ const tabs = tabStores(st, [KEYS.connections, KEYS.siri, KEYS.a2a])
537
+ const put = (k, v) => { write(st, k, v); tabs.wrote(k) }
538
+ function adoptOtherTab () {
539
+ const moved = tabs.moved(); if (!moved.length) return
540
+ if (moved.includes(KEYS.connections)) conns = read(st, KEYS.connections, [])
541
+ const w = who(); if (!w) return
542
+ if (moved.includes(KEYS.siri)) { try { sdk.siri.restore((read(st, KEYS.siri, {}) || {})[w] || null) } catch { /* a malformed copy: keep ours */ } }
543
+ if (moved.includes(KEYS.a2a)) { try { sdk.a2a.restore((read(st, KEYS.a2a, {}) || {})[w] || null) } catch { /* as above */ } }
544
+ }
545
+ try { if (typeof addEventListener === 'function') addEventListener('storage', (e) => { if (e && (e.key === KEYS.connections || e.key === KEYS.connPending || e.key === KEYS.siri || e.key === KEYS.a2a)) st.refresh(e.key).then(adoptOtherTab, adoptOtherTab) }) } catch { /* no window (a test) */ }
546
+ const saveConns = () => { put(KEYS.connections, conns); keepSoon() }
547
+ // A CALL KEY WHOSE ATTACH ANSWER WAS LOST (sync sweep 2026-11-14 #5; state machines pass 9, N#7): the SDK keeps it PENDING in the store
548
+ // set here while the answer is out (connections.js postWithPendingKey); a lost answer left a connection the account lists and no key
549
+ // anywhere. Adopted when the account's list shows it (connections.list, below) — the rule the hosted vault uses (connPending.js).
550
+ let pendingWrites = Promise.resolve()
551
+ function updatePending(change) {
552
+ const run = async () => {
553
+ await st.refresh(KEYS.connPending)
554
+ const rows = read(st, KEYS.connPending, {}) || {}
555
+ change(rows)
556
+ const saved = JSON.stringify(rows)
557
+ st.setItem(KEYS.connPending, saved)
558
+ if (await st.durableItem(KEYS.connPending) !== saved) throw new Error('Could not save the pending connection key')
559
+ }
560
+ const write = () => globalThis.navigator?.locks ? navigator.locks.request('wbvault:pending-connection-keys', run) : run()
561
+ const next = pendingWrites.then(write)
562
+ pendingWrites = next.catch(() => {})
563
+ return next
564
+ }
565
+ setPendingKeyStore({
566
+ durable: true,
567
+ keep: (id, rec) => { const ownerEmail = who(); return updatePending(rows => { rows[id] = { ...rec, ownerEmail, at: Number(rec?.at) || Date.now() } }) },
568
+ drop: id => updatePending(rows => { delete rows[id] }),
569
+ })
570
+ const adoptPending = async (listedIds, acct) => {
571
+ const epoch = privacyEpoch, ownerEmail = who()
572
+ await st.refresh(KEYS.connPending)
573
+ if (epoch !== privacyEpoch || ownerEmail !== who()) return
574
+ const snapshot = read(st, KEYS.connPending, {}) || {}
575
+ const eligible = Object.fromEntries(Object.entries(snapshot).filter(([, k]) => !k?.ownerEmail || k.ownerEmail === ownerEmail))
576
+ const r = adoptPendingKeys(eligible, listedIds, {})
577
+ for (const [id, k] of r.adopt) {
578
+ if (!conns.some(c => c.account === acct && c.id === id && c.callKey)) {
579
+ conns = [{ id, label: k.label || '', host: k.host || '', callKey: k.callKey, account: acct }, ...conns]
580
+ }
581
+ }
582
+ if (r.adopt.length) saveConns()
583
+ let durable
584
+ try { durable = JSON.parse(await st.durableItem(KEYS.connections) || '[]') } catch { return }
585
+ if (epoch !== privacyEpoch || ownerEmail !== who() || !Array.isArray(durable)) return
586
+ await updatePending(pending => {
587
+ if (epoch !== privacyEpoch || ownerEmail !== who()) return
588
+ for (const [id, rec] of Object.entries(eligible)) {
589
+ if (r.pending[id] || JSON.stringify(pending[id]) !== JSON.stringify(rec)) continue
590
+ if (listedIds.includes(id) && !durable.some(c => c.account === acct && c.id === id && c.callKey === rec?.callKey)) continue
591
+ delete pending[id]
592
+ }
593
+ })
594
+ }
595
+ // Siri's state (the inbox private keys) is kept PER ACCOUNT: a second person signing in on this vault never gets the
596
+ // first one's keys, and the first one's come back when they sign in again.
597
+ const who = () => (signedIn() ? String(sdk.session.email || '').toLowerCase() : '')
598
+ const saveSiri = () => { const w = who(); if (!w) return; const all = read(st, KEYS.siri, {}); all[w] = sdk.siri.state; put(KEYS.siri, all); keepSoon() }
599
+ const saveA2A = () => { const w = who(); if (!w) return; const all = read(st, KEYS.a2a, {}); all[w] = sdk.a2a.state; put(KEYS.a2a, all); keepSoon() }
600
+ // ── THE SAME THREE ON EVERY DEVICE OF THE ACCOUNT (vaultKeep.js; sync sweep 2026-11-11 P7): a second device listed this account's
601
+ // connections but could not use one (`not_in_vault`), and could not open Siri or an outside agent's message. Synced, sealed,
602
+ // through the account's index room — only while the backup is on (it is what derives that room). One pass at a time; a pass
603
+ // that finds another account signed in when it lands keeps nothing.
604
+ let keepT = null, keepRun = null, keepAgain = 0, keepMoved = null
605
+ const KEEP_AGAIN_MAX = 3 // passes in a row for a vault that changed while one was out; past it the minute's pass takes over
606
+ let lastKeepFailure = null
607
+ function keepSoon (ms = 1500) { clearTimeout(keepT); keepT = setTimeout(() => { keepSync().catch(() => {}) }, ms) }
608
+ async function keepSync () {
609
+ if (keepRun) return keepRun
610
+ const owner = who(), master = sdk.backup._s?.master
611
+ keepRun = (async () => {
612
+ const w = who()
613
+ if (!w || !sdk.backup.enabled || !sdk.backup._s) return { ok: false, why: 'off' }
614
+ const acct = await sdk._account().catch(() => '')
615
+ if (!acct || who() !== w) return { ok: false, why: 'off' }
616
+ const loc = await sdk.account._where() // { room, mk, master, app }: `app` (the app's account-store key) → the keep is also the app's xindex2 (vaultKeep.js, phase 4)
617
+ try { await sdk.account._ensureRoom(loc) } catch (e) { return { ok: false, why: 'unreachable' } }
618
+ if (who() !== w) return { ok: false, why: 'moved' } // signed out during that round trip (pass 9, K#2): a pass over the EMPTIED stores stamped every lane and Siri gone, on every device
619
+ const allKeep = read(st, KEYS.keep, {}) || {}
620
+ const prev = allKeep[w] || null
621
+ // ⛔ WHAT IS KEPT AS `prev` AND WHAT IS APPLIED IS keepPass's WORD (vaultKeep.js; sync sweep 2026-11-12 #1 #2): the merged view
622
+ // only from a pass that saved while nothing changed here. It was recorded whatever the pass answered — after one failed
623
+ // save the next pass deleted the other devices' connections, Siri and outside agents on every device — and applied over
624
+ // a connection attached meanwhile.
625
+ keepMoved = null
626
+ const p = await keepPass({ loc, client: sdk._client, prev, read: () => { adoptOtherTab(); return { conns: conns.filter((c) => c.account === acct), siri: sdk.siri.state, a2a: sdk.a2a.state } },
627
+ settle: (p) => { // in keepPass's own step, right after it looked at the stores: no attach or detach can land in between
628
+ if (who() !== w || !p.record) return
629
+ if (p.apply) applyKeep(acct, p.apply) // into the stores FIRST: were it to throw, `prev` stays what the stores hold
630
+ const all2 = read(st, KEYS.keep, {}) || {}; all2[w] = p.record; write(st, KEYS.keep, all2)
631
+ } })
632
+ if (who() !== w) return { ok: false, why: 'moved' }
633
+ const ch = keepMoved; keepMoved = null; if (ch) pushAfterApply(w, ch) // what the apply moved at the Sentinel's side (K#8)
634
+ if (p.again && keepAgain < KEEP_AGAIN_MAX) { keepAgain++; keepSoon(300) } else if (!p.again) keepAgain = 0 // what changed meanwhile: now, not at the minute
635
+ return p
636
+ })()
637
+ try {
638
+ const result = await keepRun.catch(() => ({ ok: false, why: 'unavailable' }))
639
+ if (owner && master && who() === owner && sdk.backup._s?.master === master) {
640
+ const previous = lastKeepFailure?.error
641
+ const error = result.ok ? null : { message: 'Could not sync account settings', code: result.why || 'save_failed', status: result.status }
642
+ lastKeepFailure = error ? { owner, master, error } : null
643
+ if (previous?.code !== error?.code || previous?.status !== error?.status) emitAccount()
644
+ }
645
+ return result
646
+ } finally { keepRun = null }
647
+ }
648
+ // ⛔ WHAT THE SENTINEL HOLDS FOLLOWS THE MERGED VIEW (state machines pass 9, K#8): a change pushes the device's WHOLE record,
649
+ // so of two devices that changed a lane (or Siri) inside one interval the later push won at the Sentinel — a removed agent's
650
+ // token granted again, a new one's revoked — and after the keep merged them nothing pushed the merged record. Now an apply
651
+ // that changed what the Sentinel is sent (the public halves, the token hashes, the aliases, the key) pushes it, after the
652
+ // pass. A merged Siri with no key is a setup deleted on another device: it is revoked here too (a copy pushed after that
653
+ // delete would have granted the old key again).
654
+ const a2aSent = () => { try { return JSON.stringify(Object.entries(sdk.a2a._s.lanes).sort(([a], [b]) => (a < b ? -1 : 1)).map(([room, l]) => [room, l.handle, l.name, l.description, l.pub, l.peers.map((p) => [p.id, p.tokenHash, p.reply, !!p.job])])) } catch { return '' } }
655
+ const siriSent = () => { try { const s = sdk.siri.state; return JSON.stringify([s.token, s.defaultRoom, Object.entries(s.rooms).sort(([a], [b]) => (a < b ? -1 : 1)).map(([r, v]) => [r, v.alias, v.label, v.pub])]) } catch { return '' } }
656
+ function pushAfterApply (w, ch) { // after the pass, never inside it: the answer is the Sentinel's, the keep is already settled
657
+ if (who() !== w) return
658
+ if (ch.a2a) sdk.a2a._push().catch(() => { /* the next change, or the next apply that moves it, pushes again */ })
659
+ if (ch.siri) {
660
+ if (sdk.siri.state.token) sdk.siri._push().catch(() => { /* as above */ })
661
+ else if (ch.hadKey) sdk.siri.revoke().then(() => saveSiri(), () => { /* as above */ })
662
+ }
663
+ }
664
+ function applyKeep (acct, keep) { // the merged view into this vault — written straight to storage (no new stamp: it IS the merged state)
665
+ const v = viewOfKeep(keep), w = who()
666
+ const was = { a2a: a2aSent(), siri: siriSent(), hadKey: !!sdk.siri.state.token }
667
+ conns = [...v.conns.map((c) => ({ ...c, account: acct })), ...conns.filter((c) => c.account !== acct)]
668
+ put(KEYS.connections, conns)
669
+ if (v.siri) { try { sdk.siri.restore(v.siri); const all = read(st, KEYS.siri, {}); all[w] = sdk.siri.state; put(KEYS.siri, all) } catch { /* a malformed copy: keep ours */ } }
670
+ try { sdk.a2a.restore(v.a2a); const all = read(st, KEYS.a2a, {}); all[w] = sdk.a2a.state; put(KEYS.a2a, all) } catch { /* as above */ }
671
+ keepMoved = { a2a: a2aSent() !== was.a2a, siri: siriSent() !== was.siri, hadKey: was.hadKey } // read by keepSync after the pass (K#8)
672
+ }
673
+ const loadSiri = () => { // and A2A's: the same rule
674
+ const w = who()
675
+ sdk.siri.restore(w ? (read(st, KEYS.siri, {}) || {})[w] || null : null)
676
+ sdk.a2a.restore(w ? (read(st, KEYS.a2a, {}) || {})[w] || null : null)
677
+ // and the account's INVITE KEY for this vault's app (sdkRekey.js): kept here, never shown to the page; published once per launch
678
+ const inv = w ? (read(st, KEYS.invite, {}) || {})[w] || null : null
679
+ if (inv) { try { sdk.invite.restore(inv) } catch { /* a malformed copy: the next sign-in publishes a fresh one */ } }
680
+ if (signedIn()) { sdk._enrollInvite(); Promise.resolve(sdk._inviteP).then(saveInvite, () => {}) }
681
+ }
682
+ const saveInvite = () => { const w = who(); const v = sdk.invite.state; if (!w || !v) return; if (v.email && String(v.email).trim().toLowerCase() !== String(w).trim().toLowerCase()) return; const all = read(st, KEYS.invite, {}); all[w] = v; write(st, KEYS.invite, all) } // only a key minted for THIS address is kept under it (sync sweep 2026-11-23 #12)
683
+ loadSiri()
684
+ const a2aView = (room) => { const l = sdk.a2a._s.lanes[room]; return l ? { endpoint: sdk.a2a.endpoint, handle: l.handle, peers: l.peers.map(({ id, name, reply, job, own }) => ({ id, name, reply, ...(own ? { own: true } : {}), ...(job ? { job: true } : {}) })) } : null }
685
+ async function laneA2A(room, m, args) {
686
+ const it = rooms.find((x) => x.room === room)
687
+ const shim = new LaneA2A({ room, _mk: null, _client: workerClient, _sharedRoom: (it && it.lane) || null, _wb: sdk, on: () => {}, messages: [] })
688
+ let result
689
+ if (m === 'view') result = null
690
+ else if (m === 'pull') {
691
+ if (await isKeptSpace(shim._lane) && !sdk.a2a._s.lanes[room]) return { result: [], view: null }
692
+ await assertAgentTarget(shim._lane)
693
+ const c = sdk.a2a._s.lanes[room]
694
+ if (!c) result = []
695
+ else {
696
+ const r = await sdk.a2a._plain('a2apull', { handle: c.handle })
697
+ result = []
698
+ for (const x of Array.isArray(r.items) ? r.items : []) { const o = await openItem(c, x); if (o) result.push({ taskId: x.taskId, n: x.n, m: o.m, peer: { id: o.peer.id, name: o.peer.name, reply: o.peer.reply, ...(o.peer.job ? { job: true } : {}), ...(o.peer.own ? { own: true } : {}) } }) }
699
+ }
700
+ } else if (m === 'ack') { const a = args[0] || {}; result = await sdk.a2a._plain('a2aack', { items: [{ taskId: String(a.taskId || ''), n: Number(a.n) || 0 }] }) }
701
+ else if (m === 'reply') result = await shim.reply(args[0], args[1], args[2] || {})
702
+ else result = await shim[m](...args)
703
+ // THE TOKEN STAYS IN THE VAULT (sync sweep 2026-11-14 #3): it is the outside agent's bearer for as long as it lives, so it is shown
704
+ // once on the vault's own screen and the page gets the id only — as the Siri key (siriShortcut) and the hosted vault (vaultPeerTokens.js)
705
+ if (m === 'addPeer' && result) {
706
+ const v = a2aView(room), show = await screenFor('peerToken')
707
+ if (show && result.token) await show({ name: String(args[0] || ''), token: result.token, ...(v && v.handle ? { cardUrl: cardUrlOf(v.endpoint, v.handle), mcpUrl: mcpUrlOf(v.endpoint, v.handle) } : {}) })
708
+ result = { id: result.id, token: null, shown: !!(show && result.token) }
709
+ }
710
+ else if (result && typeof result === 'object' && 'cardUrl' in result) result = {}
711
+ saveA2A()
712
+ return { result, view: a2aView(room) }
713
+ }
714
+ // a signed webhook's path and a job agent's mark ride too (sweep 10-24 #5: dropped here, a webhook or job connection granted
715
+ // from a vault reached its Spaces as a plain API) — neither is a secret (connectionEntry.js roomConnection / roomJob)
716
+ const hookOf = (c) => ({ ...(c && typeof c.webhook === 'string' ? { webhook: c.webhook } : {}), ...(c && c.webhook && c.job && typeof c.job === 'object' ? { job: c.job } : {}) })
717
+ const pub = (c) => (c && typeof c === 'object' ? { id: c.id, label: c.label || '', host: c.host || '', account: c.account || '', ...(c.provider ? { provider: c.provider } : {}), ...(c.mcp ? { mcp: true } : {}), ...hookOf(c) } : c)
718
+ // The Shortcut KEY posts words into the person's Spaces for as long as it lives: it is shown only in the vault's own
719
+ // screen (siri.showKey → screens.siriKey), never handed to the page (security review). The page learns that one exists.
720
+ const siriShortcut = () => { const s = sdk.siri.shortcut; return { key: null, hasKey: !!s.key, endpoint: s.endpoint } }
721
+ // A Space for the vault's own use: the SDK's own code (grant, Siri) over the worker, which holds the key and signs.
722
+ const workerClient = {
723
+ keyless: true,
724
+ userResolve: (...args) => sdk._client.userResolve(...args),
725
+ userTag: (...args) => sdk._client.userTag(...args),
726
+ }
727
+ // never `stop`: the worker's op path calls client[op](room, mk, …), and spaceClient.stop(room, key) would post the ROOM KEY as
728
+ // the stop key (sync sweep, 10-16 #11 — latent: nothing calls it here). The page's own stop goes through CALLS, keyless.
729
+ // toolBook is the VAULT's own (space.connections.grant runs here, through roomAccount — toolBooks.js), never the page's: a page that
730
+ // posted one wrote a Space's tool list with no confirm (sync sweep 11-18)
731
+ const INTERNAL_OPS = [...PAGE_OPS, 'toolBook'].filter((op) => op !== 'stop')
732
+ // ── A SPACE RE-KEYED IN PLACE (sdkRekey.js, https://witbitz.chat/docs/sdk-people.md#members): an op with the room's old key is answered
733
+ // `stale_key`; the vault takes this account's grant (opened with ITS invite key — the page never sees either), hands the new key to
734
+ // the worker and runs the op once more. The page hears { ev:'key', room, kind:'rekeyed'|'removed'|'pending' }.
735
+ const keyWaits = new Map(), keyAdopting = new Map()
736
+ const relinkRoom = (room, k) => { const it = rooms.find((x) => x.room === room); if (!it || !it.link) return; delete it.mk; it.link = relink(it.link, k.userShare ? { userShare: k.userShare, commit: k.commit } : { mk: k.mk }); saveRooms(); noteRoom(room).catch(() => {}) }
737
+ // WHAT A (RE)LOADED PAGE MUST KNOW AT ONCE (sync sweep 11-09, 11-08 #27 half fixed): followKey says a room's 'removed' /
738
+ // 'pending' once, when it changes — a page that reloads never hears it again, so its new Space polled at full speed and
739
+ // never knew it was removed. The welcome carries what is held now (a grant that merely could not be read is not news).
740
+ const keyStatesNow = () => [...keyWaits].filter(([, w]) => w.why !== 'grant_unavailable').slice(-200).map(([room, w]) => ({ room, kind: w.why === 'removed' ? 'removed' : 'pending', ...(w.why !== 'removed' ? { reason: w.why } : {}) }))
741
+ function followKey(room) {
742
+ if (keyAdopting.has(room)) return keyAdopting.get(room)
743
+ const w = keyWaits.get(room)
744
+ if (w && Date.now() - w.at < 15000) return Promise.resolve(false)
745
+ const p = (async () => {
746
+ const g = await wcall({ t: 'op', op: 'grant', room, args: [] }).catch(() => null)
747
+ const it0 = rooms.find((x) => x.room === room)
748
+ const k = await openGrant(g, room, sdk.invite._key(), { gated: !!(it0 && /[#&]gate=email(?:&|$)/.test(String(it0.link || ''))) }) // a link Space: 'link_changed', never 'removed'
749
+ if (k.removed || k.wait) {
750
+ const why = k.removed ? 'removed' : k.wait
751
+ const was = keyWaits.get(room); keyWaits.set(room, { at: Date.now(), why })
752
+ if (why !== 'grant_unavailable' && (!was || was.why !== why)) emit({ ev: 'key', room, kind: k.removed ? 'removed' : 'pending', ...(k.wait ? { reason: k.wait } : {}) })
753
+ return false
754
+ }
755
+ if (k.userShare) await wcall({ t: 'rememberSplit', room, userShare: k.userShare, commit: k.commit, ep: k.epoch })
756
+ else await wcall({ t: 'remember', room, mk: k.mk, ep: k.epoch })
757
+ keyWaits.delete(room); relinkRoom(room, k)
758
+ emit({ ev: 'key', room, kind: 'rekeyed', epoch: k.epoch })
759
+ return true
760
+ })().catch(() => false).finally(() => keyAdopting.delete(room))
761
+ keyAdopting.set(room, p)
762
+ return p
763
+ }
764
+ sdk.invite._onRestore = () => keyWaits.clear() // a restored invite key: every Space waiting for one tries again at once
765
+ // THE SERVER SAYS THIS ROOM IS CONFIDENTIAL (agent/tierGuard.mjs: `confidential_room`, or a poll's `tier: 'enclave'`): the
766
+ // vault learns the tier from the answer, as the app does (l1.js learnTier) — `enc` came only from a `#enc=1` link or a
767
+ // create, so a room joined by an older link was never woken before a member change (sync sweep backlog P2)
768
+ const learnTier = (room, r) => {
769
+ if (!room || !saysConfidential(r)) return
770
+ const it = rooms.find((x) => x.room === room); if (!it || it.enc) return
771
+ it.enc = true; saveRooms(); try { pushEnclave() } catch { /* the next op re-sends the snapshot */ }
772
+ }
773
+ const opHealed = async (op, room, args) => {
774
+ const r = await wcall({ t: 'op', op, room, args })
775
+ learnTier(room, r)
776
+ if (!r || r.error !== 'stale_key' || op === 'grant' || op === 'rekey' || !(await followKey(room))) return r
777
+ return wcall({ t: 'op', op, room, args })
778
+ }
779
+ for (const op of INTERNAL_OPS) workerClient[op] = (room, _mk, ...args) => opHealed(op, room, args)
780
+ // A LANE ROOM IS OPENED AS A LANE (sync sweep, 10-16 #7): as a plain Space, lane.siri.collect posted Siri drops with no
781
+ // bridge to its shared room and none of the lane's actions or links. Keyless both ways — the worker holds both keys.
782
+ const roomSpace = (room) => {
783
+ const it = rooms.find((x) => x.room === room)
784
+ if (it && it.lane) return new Lane(workerClient, { room, mk: null, link: null, wb: sdk, live: false, poll: false, sharedRoom: it.lane, sharedMk: null })
785
+ return new Space(workerClient, { room, mk: null, link: null, wb: sdk, live: false, poll: false })
786
+ }
787
+ sdk._agentRoom = roomSpace
788
+ sdk._keepAgentConnection = async (conn, ownLink) => {
789
+ const session = sdk._session
790
+ const account = await sdk._account()
791
+ if (sdk._session !== session || (conn.account && conn.account !== account)) throw Object.assign(new Error('the account changed during assistant setup'), { code: 'account_changed' })
792
+ conns = [{ ...conn, account, ownLink }, ...conns.filter((c) => c.id !== conn.id || c.account !== account)]
793
+ saveConns()
794
+ }
795
+ sdk._forgetAgentConnection = async (id) => { const session = sdk._session, account = await sdk._account(); if (sdk._session !== session) throw Object.assign(new Error('the account changed during assistant cleanup'), { code: 'account_changed' }); conns = conns.filter((c) => c.id !== id || c.account !== account); saveConns() }
796
+ const wop = (op, room, ...args) => opHealed(op, room, args)
797
+ // ── a move (fork): the SDK's own fork(), run HERE over the worker — it needs the room's key (the new room's goes in the
798
+ // notice, sealed to each keeper's device) and the session's signing key, both the vault's
799
+ const keyedClient = { create: async (cfg, co = {}) => { const r = await wcall({ t: 'create', cfg, base: location.origin, returnMk: true, ...(co.split ? { split: true } : {}) }); return { room: r.room, mk: r.mk, links: [r.link], commit: r.commit, ...(co.split ? { userShare: linkParts(r.link).userShare } : {}) } } }
800
+ for (const op of [...INTERNAL_OPS, 'carry', 'rekey', 'grant']) keyedClient[op] = (room, _mk, ...args) => wop(op, room, ...args) // rekey/grant: a member change in place, below — never a page op
801
+ // ── a member change IN PLACE (sdkRekey.js): the SDK's own rule, run HERE over the worker, which makes and keeps the new key; the
802
+ // person confirms in the vault's pixels (a page script alone cannot change who is in, or the key)
803
+ async function inPlace(room, admission, rotate) {
804
+ if (!held(room)) throw Object.assign(new Error('vault: this vault holds no Space ' + String(room).slice(0, 40)), { code: 'not_in_vault' })
805
+ if (!signedIn()) throw Object.assign(new Error('vault: sign in first'), { code: 'sign_in_required' })
806
+ const it = rooms.find((x) => x.room === room)
807
+ const parts = linkParts(it.link) || {}
808
+ const emails = rotate ? [] : (admission && Array.isArray(admission.emails) ? admission.emails : []).map((x) => String(x).slice(0, 80))
809
+ const sp = new Space(keyedClient, { room, mk: parts.mk || null, link: it.link, wb: sdk, live: false, poll: false, gated: true, split: !!parts.split }) // a split room: no key here — the worker holds it
810
+ if (!rotate) { try { await assertNotKept(sp) } catch (e) { sp.close(); throw e } }
811
+ // A SLEEPING CONFIDENTIAL SPACE (sweep 10-25 #1): the SDK wakes one before its first read only when its OWN enclave list
812
+ // holds the room (sdkRekey changeable), and the vault keeps the tier in `rooms[].enc` — so wake it here and hand the worker
813
+ // the fresh attestation (as the open does, below), or the read is refused and the person sees "couldn't read the members".
814
+ if (it.enc) { try { await sdk._encWake(room, { tries: 8 }); pushEnclave() } catch { /* changeable's read says what is wrong */ } }
815
+ // MAY THIS PERSON? before asking them (sweep 10-23 #21: the vault asked "Change the members of …?" and then refused not_admin)
816
+ let cur = null
817
+ try { cur = await changeable(sp, rotate ? 'rotateKey' : 'changeMembers') } catch (e) { sp.close(); throw e }
818
+ // A ROLE CHANGE KEEPS THE KEY AND EVERYONE IN IT (sweep 10-24 #8; sdkRekey changeMembers `roles`): said as that, and no
819
+ // `rekeyed` after it — "anyone else can no longer read" was not true
820
+ // …decided as changeMembers decides it — the list after, hidden members counted (sweep 10-26 #3: the shown addresses alone
821
+ // made a default Space's role change "anyone else can no longer read", and a dropped hidden member "its members stay the same")
822
+ let plan = null
823
+ try { plan = rotate ? null : await planMembers(sp, admission, cur && cur.cfg) } catch (e) { sp.close(); throw e }
824
+ const roleOnly = !!(plan && plan.roles)
825
+ const ok = await confirmWith(roleOnly
826
+ ? { title: 'Change who manages ' + titleOf(room) + '?', text: 'Its members stay the same, and so does its key: only who may manage it changes.', ok: 'Change', cancel: 'Cancel' }
827
+ : rotate
828
+ ? { title: 'Change the key of ' + titleOf(room) + '?', text: 'Everyone in it gets the new key. A copy of the old key opens nothing written from now on.', ok: 'Change the key', cancel: 'Cancel' }
829
+ : { title: 'Change the members of ' + titleOf(room) + '?', text: 'Its members will be: ' + (emails.slice(0, 6).join(', ') || 'only you') + (emails.length > 6 ? ' and ' + (emails.length - 6) + ' more' : '') + '. Anyone else can no longer read what is written from now on.', ok: 'Change', cancel: 'Cancel' }).catch(() => false)
830
+ if (!ok) { sp.close(); throw Object.assign(new Error('cancelled'), { code: 'cancelled' }) }
831
+ try {
832
+ const r = rotate ? await rotateKey(sp) : await changeMembers(sp, admission)
833
+ it.link = sp.shareLink; saveRooms(); noteRoom(room).catch(() => {})
834
+ if (!r.roles) emit({ ev: 'key', room, kind: 'rekeyed', epoch: r.epoch })
835
+ const { link: _l, ...out } = r // the link carries the key: the page asks for it with share()
836
+ return out
837
+ } finally { sp.close() }
838
+ }
839
+ // A Space no longer moves (2.3.0; the owner, 2026-10-23: "only in place"): members change in place (inPlace, above).
840
+ async function fork() { throw Object.assign(new Error('vault: a Space no longer moves to a new room — members change in place (space.changeMembers)'), { code: 'use_change_members' }) }
841
+ // ── following a move: the notice is read from the ROOM (never taken from the page — a page could forge one pointing
842
+ // anywhere), judged with this vault's signing key by the rules the app and the SDK share (emailFork.js)
843
+ async function follow(room, id) {
844
+ if (!held(room)) throw Object.assign(new Error('vault: this vault holds no Space ' + String(room).slice(0, 40)), { code: 'not_in_vault' })
845
+ if (!signedIn()) return { followed: false }
846
+ const p = await readAllPages((since) => wop('pollSealed', room, undefined, since))
847
+ const e = ((p && p.entries) || []).find((x) => x && x.kind === 'fork' && x.id === String(id || ''))
848
+ if (!e) return { followed: false }
849
+ const cfg = await wop('getConfig', room)
850
+ // forkAuthority: in a room with no admins or owners, only a move SIGNED by its creator key is followed (the app's rule)
851
+ const v = await judgeMove(e, { cfg, signPriv: sdk.session.sign.priv, room, forkAuthority: (cfg && cfg.forkAuthority) || null })
852
+ if (!v) return { followed: false }
853
+ if (v.refuse) return { refused: String(v.refuse) }
854
+ const o = v.follow
855
+ // the link the notice carries must BE the room and key it names — else a later restart would remember a key the
856
+ // notice smuggled in for another (held) room (security review)
857
+ const lp = linkParts(o.link)
858
+ // a split-key room's link holds HALF a key and its commitment, never the key (sync sweep 10-15 #4: every split move
859
+ // was refused here): the half must commit to the key the notice carries — and only the half is kept, as an invite's
860
+ const linkOk = lp && lp.room === o.room && (lp.split ? !!lp.commit && lp.commit === (await keyCommit(o.mk).catch(() => '')) : lp.mk === o.mk)
861
+ if (!linkOk) return { refused: 'the move\'s link does not match its room' }
862
+ const govCfg = cfg || {}
863
+ const authority = (govCfg.admins && (govCfg.admins.emails || []).length) || (govCfg.owners && (govCfg.owners.emails || []).length) || govCfg.forkAuthority
864
+ // A CONFIDENTIAL move is refused BEFORE the person is asked (sync sweep, 10-18 #11: "Follow it there?" was asked, then refused)
865
+ if (/[?#&]enc=1(?:[&#?]|$)/.test(String(o.link || ''))) return { refused: 'a confidential move is not available in a vault yet', code: 'vault_unsupported' }
866
+ if (!authority && !held(o.room)) { // nobody in this room holds the move: the person decides
867
+ const ok = await confirmWith({ title: titleOf(room).replace(/^this Space$/, 'This Space') + ' moved to a new Space', text: 'Someone in it moved it. Follow it there?', ok: 'Follow', cancel: 'Not now' }).catch(() => false)
868
+ if (!ok) return { followed: false }
869
+ }
870
+ if (held(o.room)) return { room: o.room } // followed already
871
+ if (lp.split) holdLink(worker, lp); else worker.postMessage({ t: 'remember', room: o.room, mk: o.mk }); seedIdentity(o.room)
872
+ if (v.needsGovCheck) {
873
+ const gv = await checkNewRoomGov(() => wop('getConfig', o.room), e.gov, o.room) // a failed read is retried, and is not a mismatch (emailFork.checkNewRoomGov)
874
+ if (gv !== 'keeps') { await wcall({ t: 'forget', room: o.room }).catch(() => null); return gv === 'unreadable' ? { refused: 'the new room could not be read yet — try again', code: 'unreadable' } : { refused: 'the new room\'s owners or admins are not what the move declared' } }
875
+ }
876
+ const was = rooms.find((x) => x.room === room)
877
+ rooms = [{ room: o.room, link: o.link, title: (was && was.title) || '', at: Date.now(), ...(lp.split ? { split: true } : {}) }, ...rooms]; saveRooms(); noteRoom(o.room).catch(() => {})
878
+ emit({ ev: 'rooms', rooms: publicRooms() })
879
+ return { room: o.room }
880
+ }
881
+ // ── the guest book: this vault's device in each EMAIL-GATED room it holds, so a move finds it (Space._announce's rule)
882
+ const announced = new Set()
883
+ async function announce(room) {
884
+ const identity = sessionKeyId(), whoKey = room + '\n' + identity
885
+ if (!held(room) || !identity || announced.has(whoKey)) return { announced: false }
886
+ const cfg = await wop('getConfig', room).catch(() => null)
887
+ if (!cfg || cfg.admission !== 'email') return { announced: false }
888
+ // read back and announce again while the row (or the gate's record of it) is missing — two announces at once: the last wins
889
+ const self = selfRow({ signPub: sdk.session.sign.pub })
890
+ for (let i = 0; i < 3; i++) {
891
+ const r = await wop('state', room, ROSTER_DOC).catch(() => null)
892
+ if (!r || r.status !== 200 || sessionKeyId() !== identity || !held(room)) return { announced: false }
893
+ const { roster, changed } = ensureSelf(r.state, self)
894
+ if (!changed && !unseenIn(r.seen, self.id) && !entriesMissing(r.seen, self.id, room)) { announced.add(whoKey); return { announced: true } } // entries: one more announce per page, never retried
895
+ const written = await wop('state', room, ROSTER_DOC, { people: roster }, '', 'member', r.v || 0).catch(() => null)
896
+ if (written?.status === 409) continue
897
+ if (written?.status !== 200) return { announced: false }
898
+ announcedIn(room, self.id)
899
+ await new Promise((res) => setTimeout(res, 200 + Math.floor(Math.random() * 600)))
900
+ }
901
+ return { announced: false }
902
+ }
903
+ const titleOf = (room) => { const it = rooms.find((x) => x.room === room); return it && it.title ? '“' + it.title + '”' : 'this Space' }
904
+ // the device whose index entry names its key (spk), on an account on the service: signed out THERE too (accountCall's signOut)
905
+ const revokesAtService = (id) => { const b = sdk.backup, d = sdk.account._devices && sdk.account._devices[id]; return !!(d && typeof d.spk === 'string' && d.spk && b._v2 && b.service === 'account' && b.enabled) }
906
+ const confirmCall = async (ns, m, args, room, kept = false) => {
907
+ const a = args[0], q = {
908
+ 'portable.export': { title: 'Download this Space?', text: 'The unencrypted JSON file contains this Space’s conversation, attachments and settings.', ok: 'Download' },
909
+ 'backup.exportArchive': a === true ? { title: 'Download recovery keys?', text: 'Anyone with these keys can read the archived conversations. Store this file separately from the archive.', ok: 'Download keys' } : { title: 'Download encrypted conversations?', text: 'The file contains the encrypted ledgers for this account. Download the keys separately to read them offline.', ok: 'Download' },
910
+ 'connections.detach': { title: 'Remove this connection?', text: 'Every Space that uses it stops being able to.', ok: 'Remove' },
911
+ 'usernames.claim': { title: 'Take the username @' + String(a || '').replace(/^@/, '').slice(0, 40) + '?', text: (args[1] && args[1].publish) ? 'It will be listed, so people can find you by it.' : 'It is yours until you release it.', ok: 'Take it' },
912
+ 'usernames.release': { title: 'Release your username?', text: 'Someone else may take it.', ok: 'Release' },
913
+ 'siri.rotateKey': { title: 'Make a new Siri key?', text: 'The Shortcut stops working until you give it the new key.', ok: 'New key' },
914
+ 'siri.revoke': { title: 'Turn the Siri inbox off?', text: 'Siri stops delivering to every Space.', ok: 'Turn off' },
915
+ 'a2a.addPeer': { title: 'Let the outside agent “' + String(a || '').slice(0, 40) + '” reach this lane?', text: (args[1] && args[1].job === true) ? 'An agent that takes jobs: it reports here and reads no answer — its reports are told to you.' : (kept || args[1]?.reply === 'auto') ? 'Its messages will be answered by the assistant on its own, without asking you.' : 'You approve every answer before it is sent.', ok: 'Allow' }, // a job agent reads no answers (sweep 10-25 #9)
916
+ 'a2a.revoke': { title: 'Turn outside agents off?', text: 'Every lane\'s card and every agent\'s token stop working.', ok: 'Turn off' },
917
+ 'backup.remove': { title: 'Remove ' + titleOf(a) + ' from your account?', text: 'It goes from every device that keeps this account.', ok: 'Remove' },
918
+ 'account.forget': { title: 'Remove ' + titleOf(a) + ' from your account?', text: 'It goes from every device that keeps this account.', ok: 'Remove' },
919
+ // on the account service it is revoked at once, after the emailed code (accountCall's signOut, 94c06f12b); else it is marked in
920
+ // the index — either way it forgets the account the next time it is online (sync sweep 11-22 #17: it said "at its next sync")
921
+ 'account.signOut': { title: 'Sign that device out of your account?', text: (revokesAtService(a) ? 'It is signed out of your account at once — we email you a code to confirm — and forgets ' : 'It forgets your account and ') + 'your Spaces the next time it is online.', ok: 'Sign out' },
922
+ 'backup.signOutOthers': { title: 'Sign out all your other devices?', text: 'Every other device forgets your account and its Spaces the next time it opens. This device stays signed in. We email you a code to confirm.', ok: 'Sign them out' },
923
+ 'backup.newRecoveryCode': { title: 'Make a new recovery code?', text: 'Your current code stops working, and every other device is signed out. We email you a code to confirm, then show the new recovery code once.', ok: 'New code' },
924
+ 'backup.migrate': a?.silent === true || sdk.backup._s?.v2?.moveMode === 'signed' ? { title: 'Move this account with its signing key?', text: 'Your Spaces and recovery code stay the same. Other eligible devices can join using their existing account keys.', ok: 'Move account' } : { title: 'Move to the new account service?', text: 'Your Spaces and recovery code stay the same. Other devices are signed out and can restore on the new service. This legacy backup has no account key, so it moves with email-only trust; Advanced Backup remains unavailable.', ok: 'Move account' },
925
+ 'cloudDevice.enroll': { title: 'Sign the cloud device in?', text: 'We email a code so this secure cloud device can sign in to this app’s account. No Space is handed over yet.', ok: 'Send code' },
926
+ 'cloudDevice.register': { title: 'Add the cloud device to your account?', text: 'Register its public device key on the account service. You can sign it out later from Your devices. We email a code to confirm.', ok: 'Add device' },
927
+ 'cloudDevice.setBuilds': { title: 'Update the cloud device’s secure builds?', text: 'The cloud device will follow this account’s accepted secure-build list and automatic-acceptance choice.', ok: 'Update' },
928
+ 'cloudDevice.forget': { title: 'Sign out the cloud device?', text: 'It forgets this app’s account and stops keeping its Spaces always on. The Spaces and their history stay.', ok: 'Sign out' },
929
+ 'alwaysOn.enable': { title: 'Keep this Space always on?', text: 'Give its current link to your attested cloud device so it can run schedules and answer here while your devices are away.' + (a && a.disconnectLanes ? ' Its private assistants will disconnect.' : ''), ok: 'Keep always on' },
930
+ 'alwaysOn.disable': { title: 'Stop keeping this Space always on?', text: 'The cloud device stops its schedules and linked assistants disconnect. The Space and history stay.', ok: 'Stop keeping' },
931
+ 'keptAgent.link': { title: 'Link this kept assistant?', text: 'Your private assistant can send it jobs you approve. The always-on Space reports results back through your private assistant’s agent door. Both credentials stay in this vault.', ok: 'Link assistants' },
932
+ 'keptAgent.unlink': { title: 'Disconnect these assistants?', text: 'Both peer credentials and the connection are revoked. Rooms and history stay.', ok: 'Disconnect' },
933
+ 'backup.beginEmailMove': { title: 'Move your email to a new account?', text: 'Use this if you lost your recovery code and all your devices. After a waiting period you can start an empty account. Your old Spaces stay with the old account.', ok: 'Start email move' },
934
+ 'backup.finishEmailMove': { title: 'Create your new account?', text: 'Your address will move to an empty account. Keep the new recovery code shown on this device.', ok: 'Finish email move' },
935
+ 'backup.cancelPendingEmailMove': { title: 'Cancel this device’s email move?', text: 'The email address stays with the original account.', ok: 'Cancel move' },
936
+ 'backup.requestMoveTime': { title: 'Ask for more time on the email move?', text: 'The move waits until 30 days after it started, so you can recover your inbox. This can be done once and does not cancel the move.', ok: 'Ask for more time' },
937
+ 'backup.cancelEmailMove': { title: 'Cancel the email move?', text: 'We email a code to the account address. Proving you can read it cancels the move.', ok: 'Send code' },
938
+ 'invitations.resend': { title: 'Resend this Space’s invitation?', text: 'Send the current invitation to ' + String(a && (a.email || a.username) || 'this recipient').slice(0, 254) + '. This does not change who is admitted.', ok: 'Send invitation' },
939
+ 'backup.deleteAccount': { title: 'Delete your account?', text: 'Your account and its backup are deleted for good, and every device is signed out — this one too: it forgets your Spaces. We email you a code to confirm.', ok: 'Delete' },
940
+ // an MCP server's chosen tools may run WITHOUT asking (`auto`; the SDK's recommended ones when none are named) — the prompt
941
+ // says so instead of "always with your approval" (sweep 10-24 #7)
942
+ 'connections.grant': { title: 'Let the assistant in ' + titleOf(room) + ' use ' + (conns.find((c) => c.id === (a && a.id ? a.id : a)) || {}).label + '?', text: (conns.find((c) => c.id === (a && a.id ? a.id : a)) || {}).mcp && !(args[1] && Array.isArray(args[1].auto) && !args[1].auto.length) ? 'It can use this server\'s tools — some may run without asking you (the ones marked so) — and never sees the secret.' : 'It can call it — always with your approval — and never sees the secret.', ok: 'Allow' },
943
+ }[ns + '.' + m]
944
+ if (q && !(await confirmWith({ cancel: 'Cancel', ...q }).catch(() => false))) throw Object.assign(new Error('cancelled'), { code: 'cancelled' })
945
+ }
946
+ let askSeq = 0
947
+ const asks = new Map()
948
+ const askPage = (kind, data) => new Promise((res, rej) => {
949
+ const id = ++askSeq
950
+ const timer = setTimeout(() => { if (asks.delete(id)) rej(Object.assign(new Error('the page did not answer'), { code: 'vault_timeout' })) }, ASK_MS)
951
+ asks.set(id, { res, rej, timer })
952
+ toPage({ t: 'ask', id, kind, ...data })
953
+ })
954
+ // ── the BACKUP and the account INDEX: the vault's own (sdk.backup / sdk.account), over the Spaces this vault holds ─────
955
+ // Every Space the vault holds is recorded (noteRoom); a room another device added comes in, one it dropped from the
956
+ // account goes (fromBackup, after each sync). What the page sees is a VIEW — never a link, a key or the master secret.
957
+ const accountView = () => {
958
+ const b = sdk.backup, a = sdk.account
959
+ const syncError = a.lastError || (lastKeepFailure?.owner === who() && lastKeepFailure?.master === b._s?.master ? lastKeepFailure?.error : null)
960
+ return {
961
+ enabled: b.enabled, format: b.format, service: b.service, deviceId: a.deviceId, // service: 'account' (the Witbitz account service) | 'legacy' | null
962
+ rooms: b.rooms.map(({ room, kind, label, shared, archived, pinned }) => ({ room, kind, ...(pinned ? { pinned: true } : {}), ...(label ? { label } : {}), ...(shared ? { shared } : {}), ...(archived ? { archived: true } : {}) })),
963
+ devices: a.devices, links: a.links, lastError: syncError ? { message: String(syncError.message || syncError).slice(0, 200), ...(typeof syncError.code === 'string' ? { code: syncError.code.slice(0, 60) } : {}), ...(Number.isInteger(syncError.status) ? { status: syncError.status } : {}) } : null,
964
+ erasure: sdk.erasure.available,
965
+ gated: !!b.gated, // a restore and deleting the account need the emailed code as well (sync sweep 11-09 #24)
966
+ }
967
+ }
968
+ let privacyTimer = null, privacyRun = null, privacyEpoch = 0
969
+ const queuePushPrivacy = (delay = 100) => {
970
+ if (o.push !== true) return
971
+ clearTimeout(privacyTimer)
972
+ privacyTimer = setTimeout(async () => {
973
+ if (privacyRun) await privacyRun.catch(() => {})
974
+ await syncPushPrivacy().catch(() => {})
975
+ }, typeof delay === 'number' ? delay : 100)
976
+ }
977
+ async function syncPushPrivacy() {
978
+ if (o.push !== true || privacyRun || !sdk.backup.enabled) return privacyRun
979
+ const s0 = sdk.backup._s, who0 = who(), epoch = privacyEpoch
980
+ privacyRun = (async () => {
981
+ const [blocks, locks] = await Promise.all([sdk.account.blocks.get(), sdk.account.chatLocks.get()])
982
+ if (epoch !== privacyEpoch || sdk.backup._s !== s0 || who() !== who0) return
983
+ await mirrorLockedRooms(liveLocks(locks).map((l) => l.kind === 'code' ? 'code:' + l.target : l.target), idb)
984
+ if (vlock && !vlock.previewsAllowed()) { await idb.del(BLOCKS_SW_KEY); return }
985
+ const cached = read(st, learnedBlocksKey, null)
986
+ const active = new Set((blocks || []).filter(b => !b.gone && b.email).map(b => b.email))
987
+ const learned = Object.create(null)
988
+ if (cached?.account === who0) for (const email of active) {
989
+ if (Array.isArray(cached.entries?.[email])) learned[email] = [...cached.entries[email]]
990
+ }
991
+ let incomplete = false
992
+ if ((blocks || []).some((b) => b.email)) for (const r of rooms) {
993
+ const book = await wop('state', r.room, ROSTER_DOC).catch(() => null)
994
+ if (!book || book.status !== 200) { incomplete = true; continue }
995
+ for (const [sid, p] of Object.entries(book.seen || {})) {
996
+ const email = String(p?.email || '').trim().toLowerCase()
997
+ if (active.has(email)) (learned[email] ||= []).push(r.room + '|' + sid)
998
+ }
999
+ }
1000
+ const tokens = await blockTokens(blocks || [], learned)
1001
+ if (epoch !== privacyEpoch || sdk.backup._s !== s0 || who() !== who0) return
1002
+ if (vlock && !vlock.previewsAllowed()) await idb.del(BLOCKS_SW_KEY)
1003
+ else {
1004
+ const entries = Object.fromEntries([...active].map(email => [email, [...new Set(learned[email] || [])].slice(-500)]))
1005
+ write(st, learnedBlocksKey, { account: who0, entries })
1006
+ await idb.set(BLOCKS_SW_KEY, tokens)
1007
+ if (incomplete) queuePushPrivacy(30_000)
1008
+ }
1009
+ if (epoch !== privacyEpoch || sdk.backup._s !== s0 || who() !== who0) return
1010
+ })().finally(() => { privacyRun = null })
1011
+ return privacyRun
1012
+ }
1013
+ if (o.push === true) { sdk.account.blocks.on('change', queuePushPrivacy); sdk.account.chatLocks.on('change', queuePushPrivacy) }
1014
+ const emitAccount = () => { handDownPushAcct().catch(() => {}); queuePushPrivacy(); emit({ ev: 'account', view: accountView() }) }
1015
+ // THE ACCOUNT PUSH TAG (spaceClient pushAcctField; sync sweep 11-16 #14 — as our apps' notifications.js handDownPushAcct): every
1016
+ // device of the account derives one secret from its INDEX room key, so a turn from one tickles none of the others and an approval
1017
+ // reminder finds them. Here the index key is this page's (sdkAccount indexRoomOf), so the secret — a one-way derivation — goes to
1018
+ // the key worker. Only in a vault that sends notifications.
1019
+ async function handDownPushAcct() {
1020
+ if (!vpush) return
1021
+ const b = sdk.backup, m = b && b.enabled && b._s && b._s.master
1022
+ const secret = m ? await pushAcctSecretOf((await indexRoomOf(m)).mk) : ''
1023
+ if (secret === pushAcctSecret) return
1024
+ pushAcctSecret = secret
1025
+ try { worker.postMessage({ t: 'setPushAcct', secret }) } catch { /* the replay sends it to the next one */ }
1026
+ }
1027
+ // § 8.8: a signed-out device's push address leaves every Space this vault holds (op pushdrop — keyless; as our vault's withdrawPush)
1028
+ async function withdrawPushEverywhere(endpoints) {
1029
+ const eps = (endpoints || []).filter((x) => typeof x === 'string' && /^https:\/\//.test(x))
1030
+ let failed = 0
1031
+ for (const e of eps) for (const { room } of rooms) {
1032
+ if (/^tmp-/.test(room)) continue
1033
+ let ok = false
1034
+ try { const r = await fetch(endpoint, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ op: 'pushdrop', room, subscription: { endpoint: e } }) }); ok = r.status === 200 } catch { ok = false }
1035
+ if (!ok) failed++
1036
+ }
1037
+ return failed === 0
1038
+ }
1039
+ // ONE BACKUP PER ACCOUNT (security review): kept under the signed-in email ('' while nobody is signed in), so a second
1040
+ // person signing in on this vault never sees, saves to or syncs the first one's backup — it holds their room links.
1041
+ // SEALED ON DISK (vaultAtRest.js): opened once at start into memory, each account's write sealed alone (another account's entry
1042
+ // is carried over as it is on disk — another tab's write); another tab's change is opened again from the storage event.
1043
+ let backupMem = backupsAtStart
1044
+ const backups = () => ({ ...backupMem })
1045
+ try { if (typeof addEventListener === 'function') addEventListener('storage', (e) => { if (e && e.key === KEYS.backup) atRest.flushed().then(() => atRest.loadBackups(KEYS.backup)).then((b) => { backupMem = b }, () => {}) }) } catch { /* no window (a test) */ }
1046
+ let adopting = false
1047
+ let erasingHere = false // deleteAccount is running in this vault (its own sign-out is not announced twice)
1048
+ sdk.backup.onState = (s) => { if (adopting) return; const w = who(), all = backups(); if (s) all[w] = s; else delete all[w]; backupMem = all; atRest.putBackup(KEYS.backup, w, s || null); emitAccount() }
1049
+ sdk.account._syncSettled = emitAccount
1050
+ sdk.account.onChange = () => { fromBackup(); emitAccount(); keepSoon(200) }
1051
+ // another device signed this one out of the ACCOUNT (its index): the same wipe as the v2 path and a sign-out here. `reason: 'erased'`
1052
+ // (the account was deleted) reaches the page — our hosted vault says "Your account is deleted" (sync sweep 11-22 #6)
1053
+ // while THIS vault deletes the account, its own erase may reach here too: deleteAccount tells the page once (sync sweep 2026-11-23: twice)
1054
+ sdk.account.onSignedOut = (e) => { if (erasingHere) return; const why = e && ['erased', 'moved'].includes(e.reason) ? e.reason : ''; const tell = () => emit({ ev: 'accountSignedOut', ...(why ? { reason: why } : {}) }); wipeSignedOut().then(tell, tell) }
1055
+ // ── THE WITBITZ ACCOUNT SERVICE (sdkBackupV2.js; account recovery v2, as our own apps since 2026-11-15): with a tenant, NEW accounts
1056
+ // start there; an account already on the old store stays there; a restore asks it first. Its device keys: this origin's
1057
+ // IndexedDB, one per account. A new recovery code is kept on disk (read back) before it is activated.
1058
+ const persistNow = async (state) => {
1059
+ const w = who()
1060
+ backupMem = { ...backupMem, [w]: state }
1061
+ await atRest.putBackup(KEYS.backup, w, state)
1062
+ const back = (await atRest.loadBackups(KEYS.backup))[w]
1063
+ return !!back && back.master === state.master && JSON.stringify(back.v2) === JSON.stringify(state.v2)
1064
+ }
1065
+ sdk.backup._v2 = o.accountService === false ? null : accountService({ tenant: o.tenant, legacyRecovery: async email => {
1066
+ const session = sdk._session
1067
+ if (!session || who() !== email || typeof o.legacyRecovery !== 'function') return null
1068
+ const status = await sdk.account.sync()
1069
+ if (!status?.ok || status.signedOut || sdk._session !== session) return null
1070
+ const held = await o.legacyRecovery(email)
1071
+ return sdk._session === session ? held : null
1072
+ }, ...(typeof o.accountService === 'string' && o.accountService ? { base: o.accountService } : {}), fetch: (...a) => fetch(...a), keyStore: idbKeyStore('wbvault-acct'), persistNow, onRevoked: () => accountStatus(true), afterSignOut: (address) => { if (roomPass) roomPass.renewNow(address) },
1073
+ // the endpoint once the subscription is KNOWN (vpush.ready) — not known within 15 s: undefined, and nothing is sent (Codex 11-16 #2)
1074
+ ...(vpush ? { pushEndpoint: async () => ((await Promise.race([vpush.ready.then(() => true), new Promise((r) => setTimeout(() => r(false), 15000))])) ? (vpush.endpoint() || null) : undefined), withdrawPush: withdrawPushEverywhere } : {}) }) // § 8.8, only where this vault sends notifications (sync sweep 11-16 #14)
1075
+ roomPass = makeRoomPassHolder({
1076
+ on: () => roomPassSwitchOn(st),
1077
+ note: (line) => { try { console.info('witbitz vault: ' + line) } catch { /* */ } }, // why a request went without a pass, at most once a while (roomPass.js makeNoter; sync sweep 2026-11-23: this vault said nothing)
1078
+ account: () => { const b = sdk.backup, s = b && b._s; return b && b._v2 && b.enabled && s && s.v2 && s.v2.svc && s.v2.svc.acct ? { id: s.v2.svc.acct, ask: (email, sessionPub) => b._v2.roomPass(b, email, sessionPub), onRevoked: () => accountStatus(true) } : null },
1079
+ })
1080
+ // § 8.5 THE STATUS CHECK: at launch, on a return to the foreground (at most daily), at once after a refusal as signed out. A device
1081
+ // signed out elsewhere (or whose account was deleted) forgets the account here: its backup, and the Spaces it listed.
1082
+ let statusRun = null, warnedEmailMove = ''
1083
+ function accountStatus(force = false) {
1084
+ const b = sdk.backup
1085
+ if (erasingHere || statusRun || !b._v2 || !b._s || !b._s.v2) return statusRun
1086
+ const was = b.enabled, statusState = b._s
1087
+ statusRun = b._v2.status(b, { force, onSignedOut: async (gone) => {
1088
+ void gone // every held Space goes, not only the ones the account listed (the old rule left a Space made since on this device)
1089
+ if (erasingHere) return
1090
+ await wipeSignedOut()
1091
+ emit({ ev: 'accountSignedOut' })
1092
+ } }).then(async (r) => {
1093
+ // a first code whose activation's answer was lost, adopted now: the account starts here as it does at launch (review)
1094
+ if (!was && b.enabled) { noteDeviceSpk(); sdk.account.start(); keepSoon(500); for (const x of rooms) await noteRoom(x.room) }
1095
+ // F-01: a new code that was SHOWN but never activated was just dropped — the person may have written it down (sync sweep
1096
+ // 11-16 #13; our apps' words, acctV2VaultWiring.js / acctV2Wiring.js). Not awaited: the check is not held by the card.
1097
+ if (r && r.pending === 'dropped') confirmWith({ title: 'Your new recovery code was not activated', text: 'The connection dropped before it was. Your PREVIOUS recovery code still works — make a new code again if you want to replace it.', ok: 'OK', cancel: 'Close' }).catch(() => {})
1098
+ if (r && r.move && b._s === statusState) {
1099
+ const mark = r.move.reset + '|' + r.move.ready_at
1100
+ if (warnedEmailMove !== mark) {
1101
+ warnedEmailMove = mark
1102
+ const current = () => { if (b._s !== statusState) throw Object.assign(new Error('the account changed'), { code: 'account_changed' }) }
1103
+ screenFor('emailMove').then((screen) => { current(); return screen && screen({ move: r.move, address: accountAddress(), moreTime: () => { current(); return b.requestMoveTime() }, cancelMove: async () => { current(); return b.cancelEmailMove({ getCode: await emailCodeAsker('cancel-email-move', accountAddress) }) } }) }).catch(() => { warnedEmailMove = '' })
1104
+ }
1105
+ } else if (r && r.state === 'active') warnedEmailMove = ''
1106
+ }).catch(() => null).finally(() => { statusRun = null; emitAccount() })
1107
+ return statusRun
1108
+ }
1109
+ try { if (typeof document !== 'undefined') document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') accountStatus() }) } catch { /* no document (a test) */ }
1110
+ // this device's key on the account service, into its own index entry (sdkAccount.js `spk`), so another device can sign it out there
1111
+ function noteDeviceSpk () {
1112
+ const b = sdk.backup, state = b._s, epoch = privacyEpoch
1113
+ if (typeof b._v2?.deviceSpk === 'function') b._v2.deviceSpk(b).then((k) => {
1114
+ if (k && b._s === state && epoch === privacyEpoch) sdk.account._spk = k
1115
+ }).catch(() => {})
1116
+ }
1117
+ let buildsOwner = who()
1118
+ function loadBackup() {
1119
+ if (buildsOwner !== who()) { sdk.builds._resetAccount(); buildsOwner = who() }
1120
+ sdk.account.stop(); sdk.account._spk = null; sdk.account._devices = {}; sdk.account._loc = null
1121
+ adopting = true; try { sdk.backup._adopt(backups()[who()] || null) } finally { adopting = false }
1122
+ if (sdk.backup.enabled) { noteDeviceSpk(); sdk.account.start(); keepSoon(500) }
1123
+ emitAccount()
1124
+ accountStatus()
1125
+ }
1126
+ loadBackup()
1127
+ { const t = setInterval(() => { if (sdk.backup.enabled) keepSoon(0) }, 60_000); if (t && t.unref) t.unref() } // the other devices' changes: as often as the index
1128
+ async function eraseKey() { try { return await sdk.erasure._key() } catch { return null } }
1129
+ async function backupRoom(it) {
1130
+ const p = linkParts(it.link)
1131
+ if (!p || p.room !== it.room || it.room.startsWith('tmp-')) return null
1132
+ let mk
1133
+ if (p.split) {
1134
+ mk = it.mk && await keyCommit(it.mk) === p.commit ? it.mk : (await sdk._openLink(it.link)).mk
1135
+ if (!mk || await keyCommit(mk) !== p.commit) throw new Error('Could not back up the key for this split Space')
1136
+ }
1137
+ return { room: it.room, link: it.link, label: it.title, kind: it.lane ? 'lane' : 'space', shared: it.lane, ...(mk ? { mk } : {}) }
1138
+ }
1139
+ async function noteRoom(room) {
1140
+ const it = rooms.find((x) => x.room === room); if (!it) return
1141
+ const epoch = privacyEpoch, link = it.link
1142
+ if (sdk.backup.enabled) {
1143
+ const entry = await backupRoom(it)
1144
+ if (epoch !== privacyEpoch || it.link !== link || !rooms.includes(it)) return
1145
+ if (entry) sdk.backup.add({ room, shareLink: link, _sharedRoom: it.lane, _split: !!entry.mk, _mk: entry.mk }, { label: sdk.backup.rooms.find(x => x.room === room)?.label || it.title })
1146
+ }
1147
+ const k = await eraseKey() // the account's membership mark: another account's delete of this room is refused (sdkErase.js)
1148
+ if (k) wop('mark', room, await dropFor(k, room)).catch(() => null)
1149
+ sdk.erasure._seen({ room }) // and refile the erase list soon
1150
+ }
1151
+ async function dropRoom(room) {
1152
+ if (streaming.delete(room)) worker.postMessage({ t: 'streamClose', room })
1153
+ if (vpush) await vpush.drop(room).catch(() => {}) // off its notification list while the worker still holds its key
1154
+ await wcall({ t: 'forget', room }).catch(() => null)
1155
+ rooms = rooms.filter((x) => x.room !== room); saveRooms()
1156
+ emit({ ev: 'rooms', rooms: publicRooms() })
1157
+ }
1158
+ async function fromBackup() {
1159
+ if (!sdk.backup.enabled) return
1160
+ const epoch = privacyEpoch, accountState = sdk.backup._s
1161
+ const inAccount = new Map((sdk.backup._s?.rooms || []).map((b) => [b.room, b]))
1162
+ let added = false
1163
+ for (const b of inAccount.values()) {
1164
+ const p = linkParts(b.link); if (!p || p.room !== b.room) continue // a link that names another room is not taken in
1165
+ // a HELD room whose link this vault could not open from disk (its sealed key under a key it no longer has — vaultAtRest.js)
1166
+ // takes the account's: a key is never replaced by a link, but a room with none gets its own back
1167
+ const restoredMk = p.split && b.mk && await keyCommit(b.mk).catch(() => '') === p.commit ? b.mk : ''
1168
+ if (epoch !== privacyEpoch || accountState !== sdk.backup._s) return
1169
+ const had = rooms.find((x) => x.room === b.room)
1170
+ if (had) {
1171
+ if (b.label && b.label !== 'Space' && b.label !== b.room && (!had.title || had.title === 'Space' || had.title === b.room) && !had.renamed) {
1172
+ had.title = b.label
1173
+ added = true
1174
+ }
1175
+ if (had.lane && b.kind === 'space' && !b.shared && Number(b.at) > 0) {
1176
+ delete had.lane; had.detachedLane = true; added = true
1177
+ }
1178
+ if (!had.link) { had.link = b.link; holdLink(worker, p); seedIdentity(b.room); added = true }
1179
+ if (restoredMk && had.link === b.link && had.mk !== restoredMk) {
1180
+ had.mk = restoredMk; worker.postMessage({ t: 'remember', room: b.room, mk: restoredMk }); added = true
1181
+ }
1182
+ continue
1183
+ }
1184
+ rooms.push({ room: b.room, link: b.link, ...(restoredMk ? { mk: restoredMk } : {}), title: b.label || '', at: Number(b.at) || 0, ...(b.kind === 'lane' && b.shared ? { lane: b.shared } : {}), ...(/[?#&]enc=1(?:[&#?]|$)/.test(b.link) ? { enc: true } : {}), ...(p.split ? { split: true } : {}) })
1185
+ holdLink(worker, p)
1186
+ if (restoredMk) worker.postMessage({ t: 'remember', room: b.room, mk: restoredMk })
1187
+ seedIdentity(b.room); added = true
1188
+ }
1189
+ // a room the ACCOUNT dropped on another device (its tombstone is newer than this device's copy) is dropped here too
1190
+ const tomb = new Map(((sdk.backup._s && sdk.backup._s.tomb) || []).map((t) => [t.room, t.at]))
1191
+ for (const r of [...rooms]) if (!inAccount.has(r.room) && tomb.has(r.room) && tomb.get(r.room) >= (r.at || 0)) await dropRoom(r.room)
1192
+ if (added) { saveRooms(); pushEnclave(); emit({ ev: 'rooms', rooms: publicRooms() }) }
1193
+ }
1194
+ // THE EMAILED CODE the account service asks for, in the vault's own screen (screens.emailCode; ours when the builder's has none):
1195
+ // `purpose` words it; the screen resolves the code, or rejects (cancelled)
1196
+ const emailCodeAsker = async (purpose, address) => {
1197
+ const screen = await screenFor('emailCode')
1198
+ if (!screen) throw Object.assign(new Error('this vault has no email-code screen'), { code: 'no_screen' })
1199
+ return async () => { const c = await screen({ email: typeof address === 'function' ? address() : address, purpose }); if (!c) throw Object.assign(new Error('cancelled'), { code: 'cancelled' }); return String(c).trim() }
1200
+ }
1201
+ const accountAddress = () => { const s = sdk.backup._s; return (s && s.v2 && s.v2.svc && s.v2.svc.address) || (s && s.email) || (signedIn() ? sdk.session.email : '') }
1202
+ async function backupCall(m, args) {
1203
+ const b = sdk.backup
1204
+ if (m === 'beginEmailMove') {
1205
+ const epoch = privacyEpoch
1206
+ const email = accountAddress() || await (await emailCodeAsker('begin-email-move', ''))()
1207
+ const getCode = await emailCodeAsker('begin-email-move', email)
1208
+ if (privacyEpoch !== epoch) throw Object.assign(new Error('The account changed'), { code: 'account_changed' })
1209
+ return b.beginEmailMove({ email, getCode })
1210
+ }
1211
+ if (m === 'pendingEmailMove') return b.pendingEmailMove()
1212
+ if (m === 'cancelPendingEmailMove') return b.cancelPendingEmailMove({ getCode: await emailCodeAsker('cancel-email-move', accountAddress) })
1213
+ if (m === 'finishEmailMove') {
1214
+ const screen = await screenFor('recoveryCode')
1215
+ if (!screen) throw Object.assign(new Error('this vault has no recovery-code screen'), { code: 'no_screen' })
1216
+ const result = await b.finishEmailMove({ getCode: await emailCodeAsker('finish-email-move', accountAddress), showCode: code => screen({ code }) })
1217
+ noteDeviceSpk(); emitAccount()
1218
+ return result
1219
+ }
1220
+ if (m === 'exportArchive') {
1221
+ const { saveAccountArchive } = await import('./sdkExports.js')
1222
+ const epoch = privacyEpoch, session = sdk._session
1223
+ const selection = args[1] === undefined ? null : new Set(Array.isArray(args[1]) ? args[1] : [])
1224
+ if (selection && (selection.size > 1000 || [...selection].some(id => typeof id !== 'string' || !id || id.length > 160))) throw Object.assign(new Error('Invalid room selection'), { code: 'invalid_argument' })
1225
+ const heldById = new Map(rooms.map(r => [r.room, r]))
1226
+ const selected = (selection ? [...selection].map(id => heldById.get(id) || { room: id }) : rooms.slice()).filter(r => !r.room.startsWith('tmp-'))
1227
+ return saveAccountArchive(selected, async (r, keysOnly) => {
1228
+ if (!r.link) return {}
1229
+ const parts = linkParts(r.link)
1230
+ const key = parts?.split ? (await backupRoom(r))?.mk : parts?.mk
1231
+ if (!key || keysOnly) return { key }
1232
+ const saved = await workerClient.exportSealed(r.room, null)
1233
+ if (saved?.status !== 200) throw new Error('unavailable')
1234
+ return { key, ledger: saved.sealed, count: saved.count }
1235
+ }, args[0] === true, () => epoch === privacyEpoch && session === sdk._session)
1236
+ }
1237
+ if (m === 'protectRecoveryEmail') {
1238
+ const email = signedIn() && sdk.session.email
1239
+ if (!email) throw Object.assign(new Error('Sign in with the recovery address first.'), { code: 'sign_in_required' })
1240
+ const screen = await screenFor('protectRecoveryEmail')
1241
+ if (!screen) throw Object.assign(new Error('the recovery-email screen is unavailable'), { code: 'no_screen' })
1242
+ await screen({ email, purpose: 'protectEmail', restore: ({ code }) => b.protectRecoveryEmail({ code }) })
1243
+ emitAccount()
1244
+ return { enrolled: true }
1245
+ }
1246
+ if (m === 'manageSecurityKeys') {
1247
+ const show = await screenFor('securityKeys')
1248
+ if (!show) throw Object.assign(new Error('this vault has no security-key screen'), { code: 'no_screen' })
1249
+ const address = accountAddress()
1250
+ await show({ actions: b._v2.securityKeyActions(b), address, getCode: await emailCodeAsker('security-keys', address) })
1251
+ return { closed: true }
1252
+ }
1253
+ if (m === 'migrate') {
1254
+ if (args[0]?.silent === true) { const r = await b.migrate({ silent: true }); emitAccount(); return r }
1255
+ if (!b._v2) throw Object.assign(new Error('this vault must name its tenant to move accounts'), { code: 'migration_unavailable' })
1256
+ if (b._s && b._s.v2 && b._s.v2.svc && b._s.v2.moving) { const r = await b.migrate(); emitAccount(); return r }
1257
+ const screen = await screenFor('restore')
1258
+ if (!screen) throw Object.assign(new Error('this vault has no recovery-code screen'), { code: 'no_screen' })
1259
+ const run = restoreBridge((q, getCode) => b.migrate({ code: q.code, getCode }))
1260
+ let result
1261
+ await screen({ email: accountAddress(), purpose: 'migrate', restore: async (q) => { result = await run(q) } })
1262
+ emitAccount(); return result
1263
+ }
1264
+ if (m === 'enable') {
1265
+ const recoveryCodeScreen = await screenFor('recoveryCode')
1266
+ if (!recoveryCodeScreen) throw Object.assign(new Error('this vault has no recovery-code screen'), { code: 'no_screen' })
1267
+ // ON THE ACCOUNT SERVICE the code is shown BEFORE it is activated (inside enable), after the emailed code; the account's
1268
+ // address is the signed-in one, or the person types it in the email-code screen
1269
+ let email = signedIn() ? sdk.session.email : ''
1270
+ let v2 = {}
1271
+ if (b._v2 && (!b._s || b._s.v2)) { // none yet, or one the service made whose first code did not go through (finished now)
1272
+ if (!email && !b._s) { const ask = await screenFor('emailCode'); email = ask ? String((await ask({ email: '', purpose: 'create' })) || '').trim() : ''; if (!email) throw Object.assign(new Error('cancelled'), { code: 'cancelled' }) }
1273
+ v2 = { getCode: await emailCodeAsker('create', () => accountAddress() || email), showCode: (code) => recoveryCodeScreen({ code }) }
1274
+ }
1275
+ // a TYPED address goes to the service only: never enrolled as the old store's gate if the service refuses this vault (review)
1276
+ const epoch = privacyEpoch
1277
+ const initialRooms = (await Promise.all(rooms.map(backupRoom))).filter(Boolean)
1278
+ if (epoch !== privacyEpoch) throw Object.assign(new Error('The account changed'), { code: 'account_changed' })
1279
+ const r = await b.enable({ initialRooms, ...(signedIn() ? { email: sdk.session.email } : {}), ...(email && !signedIn() ? { address: email } : {}), ...v2 })
1280
+ if (b.enabled) noteDeviceSpk() // its key into its index entry now, not at the next launch (sync sweep 11-22 #16): until then a Sign out elsewhere only marked the index
1281
+ if (b.service !== 'account') await recoveryCodeScreen({ code: r.code })
1282
+ for (const x of rooms) await noteRoom(x.room)
1283
+ await b.save() // the old store: shown HERE, once; the page gets only that it is set up
1284
+ emitAccount()
1285
+ return { enabled: true }
1286
+ }
1287
+ if (m === 'restore') {
1288
+ const restoreScreen = await screenFor('restore')
1289
+ if (!restoreScreen) throw Object.assign(new Error('this vault has no restore screen'), { code: 'no_screen' })
1290
+ // the screen asks for the code (and, where the gate or the account service asks for it, the email and the emailed code) and
1291
+ // calls this; the account service's emailed code is asked through the same two calls (sdkBackupV2.js restoreBridge)
1292
+ const email = signedIn() ? sdk.session.email : ''
1293
+ let attemptedToken
1294
+ const run = restoreBridge((q, getCode) => {
1295
+ const session = sdk._session
1296
+ getCode.choose = async ({ action }) => {
1297
+ if (!session || attemptedToken === session.idToken) return null
1298
+ const proof = await restoreSignInProof(session, { action, email: q.email, origin: globalThis.location?.origin, base: typeof o.accountService === 'string' ? o.accountService : undefined })
1299
+ if (sdk._session !== session) throw Object.assign(new Error('the account changed during restore'), { code: 'account_changed' })
1300
+ if (proof) attemptedToken = session.idToken
1301
+ return proof
1302
+ }
1303
+ return b.restore({ code: q.code, email: q.email, ticket: q.ticket, emailCode: q.emailCode, ...(b._v2 ? { getCode } : {}) })
1304
+ })
1305
+ await restoreScreen({ email, signInLabel: (o.googleSignIn === true || o.authBroker) ? 'Continue with Google or email' : 'Continue with email', signIn: async () => (await signIn()).email, restore: async (q) => { await run(q) } })
1306
+ if (!b.enabled) throw Object.assign(new Error('not restored'), { code: 'cancelled' })
1307
+ noteDeviceSpk() // as after enable (sync sweep 11-22 #16)
1308
+ await fromBackup()
1309
+ emitAccount()
1310
+ accountStatus()
1311
+ return { rooms: accountView().rooms } // the rooms, as outside a vault (an array — a count made `.map` throw; sync sweep 11-09 #24); the view: no link, no key
1312
+ }
1313
+ if (m === 'remove') { b.remove(String(args[0] || '')); return {} }
1314
+ if (m === 'signOutOthers') { await b.signOutOthers({ getCode: await emailCodeAsker('signout', accountAddress) }); emitAccount(); return { ok: true } }
1315
+ if (m === 'cancelEmailMove') return b.cancelEmailMove({ getCode: await emailCodeAsker('cancel-email-move', accountAddress) })
1316
+ if (m === 'newRecoveryCode') {
1317
+ const recoveryCodeScreen = await screenFor('recoveryCode')
1318
+ if (!recoveryCodeScreen) throw Object.assign(new Error('this vault has no recovery-code screen'), { code: 'no_screen' })
1319
+ await b.newRecoveryCode({ getCode: await emailCodeAsker('newcode', accountAddress), showCode: (code) => recoveryCodeScreen({ code }) }) // shown HERE, once
1320
+ emitAccount()
1321
+ return { ok: true }
1322
+ }
1323
+ // DELETE THE ACCOUNT — THIS DEVICE FORGETS IT AS A SIGN-OUT DOES (sync sweep 11-22 P7; the owner, 2026-11-22: "same way" as the app,
1324
+ // whose Delete my account wipes the device): it kept this device's Spaces and session, while a sign-out from elsewhere wiped them
1325
+ // THE WHOLE ERASE, as the app's Delete my account (the owner, 2026-11-24): the account on the service (an emailed code), then what it
1326
+ // left outside its rooms, the Spaces only it used deleted and the shared ones left, the username and directory entry, the filed list.
1327
+ // The keys are this vault's, so it runs here (sdkErase.js on the vault's own client). A step that failed keeps the device: run it again.
1328
+ if (m === 'deleteAccount') {
1329
+ const names = (args[0] && Array.isArray(args[0].names) ? args[0].names : []).map((n) => String(n || '').trim().slice(0, 80)).filter(Boolean).slice(0, 20)
1330
+ // the username, the directory entry and the Sentinel's records are released under the account's SIGN-IN: asked here first, on the
1331
+ // vault's own screen, and it must be this account's address
1332
+ let address = String(accountAddress() || '').trim().toLowerCase()
1333
+ if (!signedIn()) {
1334
+ // AN ACCOUNT MADE BEFORE ANY SIGN-IN is kept under no address here; signing in switches to the signed-in address's account
1335
+ // (loadBackup). The one being deleted is carried across: kept under the address it signed in as, and gone from the no-address slot.
1336
+ const held = sdk.backup.state, heldWho = who()
1337
+ await signIn()
1338
+ if (!address && signedIn()) address = String(sdk.session.email || '').trim().toLowerCase()
1339
+ if (held && sdk.backup.enabled && sdk.backup.state && sdk.backup.state.master !== held.master) throw Object.assign(new Error('vault: sign-in opened another account; nothing was deleted'), { code: 'account_changed' })
1340
+ if (held && signedIn() && who() !== heldWho && String(sdk.session.email || '').trim().toLowerCase() === address && !sdk.backup.enabled) {
1341
+ sdk.backup._adopt(held) // onState keeps it under who()
1342
+ await atRest.putBackup(KEYS.backup, heldWho, null); const all = backups(); delete all[heldWho]; backupMem = all
1343
+ if (sdk.backup.enabled) { noteDeviceSpk(); sdk.account.start() }
1344
+ }
1345
+ }
1346
+ if (!signedIn() || String(sdk.session.email || '').trim().toLowerCase() !== address) throw Object.assign(new Error('vault: sign in as ' + (address || 'this account') + ' to delete it'), { code: 'sign_in_required' })
1347
+ erasingHere = true; let rep
1348
+ try {
1349
+ if (b.gated && b.service !== 'account') {
1350
+ const screen = await screenFor('restore')
1351
+ if (!screen) throw Object.assign(new Error('this vault has no recovery-code screen'), { code: 'no_screen' })
1352
+ await screen({ email: address, restore: async (q) => { rep = await sdk.erasure.deleteAccount({ names, ...q }) } })
1353
+ if (!rep) throw Object.assign(new Error('cancelled'), { code: 'cancelled' })
1354
+ } else rep = await sdk.erasure.deleteAccount({ names, getCode: await emailCodeAsker('delete', accountAddress) })
1355
+ if (!rep.failed.length) await wipeSignedOut()
1356
+ } finally { erasingHere = false }
1357
+ const report = { deleted: rep.deleted, left: rep.left, lapsing: rep.lapsing, failed: rep.failed, account: rep.account } // room ids and words: no key
1358
+ if (rep.failed.length) { emitAccount(); return { deleted: false, report } }
1359
+ emit({ ev: 'accountSignedOut', reason: 'erased' }); return { deleted: true, report }
1360
+ }
1361
+ if (m === 'save') {
1362
+ try { return await b.save() } catch (err) {
1363
+ if (err?.code !== 'backup_verification_required') throw err
1364
+ const screen = await screenFor('restore')
1365
+ if (!screen) throw err
1366
+ const account = b._s, email = account.email || accountAddress()
1367
+ let result
1368
+ await screen({ email, purpose: 'mergeBackup', restore: async proof => {
1369
+ if (b._s !== account) throw Object.assign(new Error('The account changed'), { code: 'account_changed' })
1370
+ result = await b.save(proof)
1371
+ } })
1372
+ if (!result) throw Object.assign(new Error('Backup verification cancelled'), { code: 'cancelled' })
1373
+ return result
1374
+ }
1375
+ }
1376
+ return b[m]()
1377
+ }
1378
+ const watchedSections = new Set() // the account sections the page has asked about: their changes are sent to it
1379
+ async function accountCall(m, args) {
1380
+ const a = sdk.account
1381
+ if (m === 'sync') { const r = await a.sync(); await fromBackup(); const kept = r?.signedOut || !who() || !sdk.backup.enabled ? { ok: true } : await keepSync().catch(() => null); emitAccount(); const view = accountView(); return { ok: !!(r?.ok && kept?.ok), rooms: view.rooms, devices: view.devices, ...(r && r.signedOut ? { signedOut: true } : {}) } }
1382
+ if (m === 'repairNames') {
1383
+ const epoch = privacyEpoch
1384
+ const healed = await a._repairNames(async ({ room }) => {
1385
+ if (!held(room) || epoch !== privacyEpoch) return null
1386
+ const [history, doc] = await Promise.all([
1387
+ readAllPages(since => wop('pollSealed', room, undefined, since)),
1388
+ wop('state', room, 'title').catch(() => null),
1389
+ ])
1390
+ if (epoch !== privacyEpoch || !held(room) || history.incomplete) return null
1391
+ return { entries: history.entries, doc }
1392
+ })
1393
+ if (healed && epoch === privacyEpoch) await fromBackup()
1394
+ emitAccount()
1395
+ return healed
1396
+ }
1397
+ if (m === 'previewEmptySpaces' || m === 'removeEmptySpaces') {
1398
+ const epoch = privacyEpoch, base = sdk._emptySpaceHooks()
1399
+ const hooks = { ...base,
1400
+ rooms: () => base.rooms().filter(r => held(r.room)),
1401
+ keep: room => base.keep(room) || rooms.some(r => r.room === room && r.lane || r.lane === room),
1402
+ read: async room => {
1403
+ if (!held(room) || epoch !== privacyEpoch) return null
1404
+ const config = await wop('getConfig', room, { plainMark: true })
1405
+ if (epoch === privacyEpoch && held(room) && (config?.help || config?.lane || config?.bridge)) return { excluded: true }
1406
+ const history = await readAllPages(since => wop('poll', room, undefined, since))
1407
+ return epoch === privacyEpoch && held(room) && config && !config.help && !config.lane && !config.bridge && history.status === 200 && !history.incomplete ? { config, entries: history.entries, etag: history.etag, selfEntries: await ownAdmissionEntries(config, signedIn() && sdk.session.email, () => wop('state', room, ROSTER_DOC)), selfHash: signedIn() ? await memberHash(sdk.session.email, room) : null } : null
1408
+ },
1409
+ forget: async room => { if (epoch === privacyEpoch && held(room)) { await base.forget(room); await dropRoom(room) } },
1410
+ }
1411
+ let unreadable = 0
1412
+ const found = await findEmptySpaces({ onUnreadable: () => { unreadable++ } }, hooks)
1413
+ if (m === 'previewEmptySpaces') return args[0]?.detailed === true ? { rooms: found, unreadable } : found
1414
+ const options = args[0]
1415
+ if (options?.confirm !== true || !Array.isArray(options.rooms)) throw Object.assign(new Error('Select empty Spaces to remove'), { code: 'confirmation_required' })
1416
+ const selected = found.filter(r => options.rooms.includes(r.room))
1417
+ if (selected.length) {
1418
+ const ok = await confirmWith({ title: 'Remove ' + selected.length + ' empty Spaces?', text: 'Spaces you created will be deleted on the server. Other Spaces will be removed only from your account.\n\n' + selected.map(r => r.title + ' (' + r.room + ')').join('\n'), ok: 'Remove Spaces', cancel: 'Cancel' })
1419
+ if (!ok || epoch !== privacyEpoch) throw Object.assign(new Error('Removal cancelled'), { code: 'cancelled' })
1420
+ }
1421
+ const report = await removeEmptySpaces(selected, hooks)
1422
+ const scanned = new Set(selected.map(r => r.room))
1423
+ for (const r of hooks.rooms()) if (options.rooms.includes(r.room) && !scanned.has(r.room)) report.kept.push({ title: r.title, why: 'could not confirm it is still empty and only yours' })
1424
+ return report
1425
+ }
1426
+ if (m === 'listDevices') return a.listDevices()
1427
+ if (m === 'signOutDevice' || (m === 'signOut' && String(args[0]).startsWith('service:'))) {
1428
+ const epoch = privacyEpoch, id = args[0]
1429
+ const row = (await a.listDevices()).find(d => d.id === id && !d.current)
1430
+ if (!row || epoch !== privacyEpoch) throw Object.assign(new Error('Choose another device on this account'), { code: 'unknown_device' })
1431
+ const ok = await confirmWith({ title: 'Sign out ' + (row.name || 'this device') + '?', text: 'It will lose access to this account and its Spaces.', ok: 'Sign out', cancel: 'Cancel' })
1432
+ if (!ok || epoch !== privacyEpoch) throw Object.assign(new Error('Device sign-out cancelled'), { code: 'cancelled' })
1433
+ const result = await a.signOutDevice(id, { getCode: await emailCodeAsker('signout', accountAddress) })
1434
+ emitAccount()
1435
+ return result
1436
+ }
1437
+ if (m === 'start') { a.start(args[0] || {}); return {} }
1438
+ if (m === 'section') { // one of the account's optional sections, run here on the vault's account; only its own calls (get / set / remove / merge)
1439
+ const [name, op, ...rest] = args, all = a._sections || {}
1440
+ const sec = typeof name === 'string' && Object.prototype.hasOwnProperty.call(all, name) ? all[name] : null
1441
+ if (!sec || !sec._calls.includes(op)) throw Object.assign(new Error('vault: account.' + String(name).slice(0, 20) + '.' + String(op).slice(0, 20) + ' is not available to the page'), { code: 'vault_refused' })
1442
+ if (!watchedSections.has(name)) { watchedSections.add(name); sec.on('change', (value) => emit({ ev: 'accountSection', section: name, value })) } // another device's change reaches the page
1443
+ const result = await sec[op](...rest.slice(0, 1))
1444
+ if (name === 'blocks' || name === 'chatLocks') {
1445
+ // A refresh already in flight may have read the list before this change.
1446
+ if (privacyRun) await privacyRun.catch(() => {})
1447
+ await syncPushPrivacy().catch(() => queuePushPrivacy(30_000))
1448
+ }
1449
+ return result
1450
+ }
1451
+ if (m === 'usage') { const o = args[0] && typeof args[0] === 'object' ? args[0] : {}; return a.usage(o.month !== undefined ? { month: o.month } : {}) } // folded with the vault's usage key, which the page never holds
1452
+ if (m === 'stop') { a.stop(); return {} }
1453
+ if (m === 'forget') { const room = String(args[0] || ''); a.forget(room); if (held(room)) await dropRoom(room); emitAccount(); return {} }
1454
+ if (m === 'noteLink' || m === 'dropLink') { // a link between two lanes THIS vault holds — any other pair is not the page's to record
1455
+ const x = String(args[0] || ''), y = String(args[1] || '')
1456
+ if (!held(x) || !held(y)) throw Object.assign(new Error('vault: this vault holds no such lanes'), { code: 'not_in_vault' })
1457
+ if (m === 'noteLink') a._noteLink(x, y, Number.isFinite(+args[2]) ? +args[2] : undefined); else a._dropLink(x, y)
1458
+ emitAccount(); return {}
1459
+ }
1460
+ // archive / rename / signOut — the index is written soon after. signOut takes the DEVICE only: a page passed `reason: 'erased'`
1461
+ // behind the confirm and the other device was told its account was deleted (sync sweep 11-22 P7)
1462
+ if (m === 'signOut') a.signOut(args[0]); else a[m](...args)
1463
+ // SIGN OUT AT THE SERVICE TOO (our app's revokeAtService; sync sweep 11-19 P8): marking the index alone left the device signed in to
1464
+ // the account service until it next synced. A device whose entry names its key (spk) is revoked there as well — the email code first.
1465
+ if (m === 'signOut') {
1466
+ const b = sdk.backup, d = a._devices && a._devices[args[0]]
1467
+ if (revokesAtService(args[0])) {
1468
+ try { await b._v2.signOutDevice(b, { spk: d.spk, getCode: await emailCodeAsker('signout', accountAddress) }); emitAccount(); return { revoked: true } }
1469
+ catch (e) { emitAccount(); return { revoked: false, error: String((e && e.code) || 'failed').slice(0, 40) } } // marked in the index: it signs out at its next sync
1470
+ }
1471
+ }
1472
+ emitAccount()
1473
+ return {}
1474
+ }
1475
+ async function account(ns, m, ...args) {
1476
+ const own = (o, k) => typeof k === 'string' && Object.prototype.hasOwnProperty.call(o, k)
1477
+ const spec = own(ACCOUNT_CALLS, ns) && own(ACCOUNT_CALLS[ns], m) ? ACCOUNT_CALLS[ns][m] : null
1478
+ if (!spec) throw Object.assign(new Error('vault: ' + String(ns).slice(0, 20) + '.' + String(m).slice(0, 30) + ' is not available to the page'), { code: 'vault_refused' })
1479
+ // the account service's own calls: refused BEFORE the person is asked to confirm (sync sweep 11-16 #15 — they confirmed, then
1480
+ // met not_on_service)
1481
+ if (ns === 'backup' && SERVICE_CALLS.has(m) && !(sdk.backup._v2 && sdk.backup.service === 'account' && sdk.backup.enabled)) throw Object.assign(new Error('witbitz: this call is for an account on the Witbitz account service, in a vault that names its tenant (wb.backup.service === \'account\')'), { code: 'not_on_service' })
1482
+ if (ns === 'cloudDevice' && m === 'register' && !(sdk.backup._v2 && sdk.backup.service === 'account' && sdk.backup.enabled)) throw Object.assign(new Error('register the cloud device from an account on the account service'), { code: 'not_on_service' })
1483
+ if (spec.confirm) {
1484
+ const epoch = privacyEpoch, owner = who()
1485
+ await confirmCall(ns, m, args)
1486
+ if (epoch !== privacyEpoch || owner !== who()) throw Object.assign(new Error('the account changed during confirmation'), { code: 'account_changed' })
1487
+ }
1488
+ if (ns === 'cloudDevice' && (m === 'enroll' || m === 'register')) return sdk.cloudDevice[m]({ getCode: await emailCodeAsker('cloud-device', accountAddress) })
1489
+ if (ns === 'backup') return backupCall(m, args)
1490
+ if (ns === 'account') return accountCall(m, args)
1491
+ if (ns === 'siri' && m === 'shortcut') return siriShortcut()
1492
+ if (ns === 'siri' && m === 'showKey') {
1493
+ const s = sdk.siri.shortcut
1494
+ if (!s.key) throw Object.assign(new Error('no Siri key yet — enable Siri in a Space first'), { code: 'no_key' })
1495
+ const siriKeyScreen = await screenFor('siriKey')
1496
+ if (!siriKeyScreen) throw Object.assign(new Error('this vault has no Siri key screen'), { code: 'no_screen' })
1497
+ await siriKeyScreen({ key: s.key, endpoint: s.endpoint })
1498
+ return { shown: true }
1499
+ }
1500
+ const callEpoch = privacyEpoch, callOwner = who()
1501
+ const r = ns === 'connections' && m === 'spacesUsing'
1502
+ ? await spacesUsingConnection(args[0], rooms.map(r => ({ room: r.room, shared: r.lane })), room => wop('getConfig', room, { plainMark: true }))
1503
+ : await sdk[ns][m](...args)
1504
+ if (callEpoch !== privacyEpoch || callOwner !== who()) throw Object.assign(new Error('The account changed'), { code: 'account_changed' })
1505
+ if (ns === 'connections' && (m === 'attach' || m === 'finishConnect' || m === 'attachMcp' || m === 'finishMcp') && r && r.id) { conns = [{ id: r.id, label: r.label || '', host: r.host || '', callKey: r.callKey, account: r.account || '', ...(r.provider ? { provider: r.provider } : {}), ...(r.mcp ? { mcp: true } : {}), ...hookOf(r) }, ...conns.filter((c) => c.id !== r.id)]; saveConns(); await adoptPending([r.id], r.account || await sdk._account()); return pub(r) }
1506
+ if (ns === 'connections' && m === 'detach') { conns = conns.filter((c) => c.id !== String(args[0] || '')); saveConns() }
1507
+ // GRANTABLE HERE (sync sweep 11-13 P7): the Sentinel lists every connection the account has, but a grant needs its callKey,
1508
+ // which only this vault's list holds (attached here, or kept from another device with the backup on) — the rest refuse
1509
+ // with not_in_vault. Each says which it is, so the page offers to grant only what will work.
1510
+ if (ns === 'connections' && m === 'list' && Array.isArray(r)) {
1511
+ const acct = await sdk._account()
1512
+ if (callEpoch !== privacyEpoch || callOwner !== who()) throw Object.assign(new Error('The account changed'), { code: 'account_changed' })
1513
+ await adoptPending(r.map((x) => x && x.id).filter(Boolean), acct) // a key whose attach answer was lost, now listed (#5)
1514
+ // MOVE 3: the old-form ones whose key this vault holds are locked under it (connWrap.js) — once a launch, in the background
1515
+ if (!_lockedOnce && r.some((x) => x && x.locked === false)) { _lockedOnce = true; sdk.connections.lock(Object.fromEntries(conns.filter((c) => c.account === acct && c.callKey).map((c) => [c.id, c.callKey]))).catch(() => { _lockedOnce = false }) }
1516
+ return r.map((x) => (x && typeof x === 'object' ? { ...x, grantable: conns.some((c) => c.id === x.id && c.account === acct) } : x))
1517
+ }
1518
+ if (ns === 'siri') { saveSiri(); if (m === 'rotateKey') return siriShortcut() }
1519
+ if (ns === 'a2a') saveA2A()
1520
+ return r
1521
+ }
1522
+ async function roomAccount(room, ns, m, ...args) {
1523
+ const own = (o, k) => typeof k === 'string' && Object.prototype.hasOwnProperty.call(o, k)
1524
+ const spec = own(ROOM_ACCOUNT_CALLS, ns) && own(ROOM_ACCOUNT_CALLS[ns], m) ? ROOM_ACCOUNT_CALLS[ns][m] : null
1525
+ if (!spec) throw Object.assign(new Error('vault: space.' + String(ns).slice(0, 20) + '.' + String(m).slice(0, 30) + ' is not available to the page'), { code: 'vault_refused' })
1526
+ if (!held(room)) throw Object.assign(new Error('vault: this vault holds no Space ' + String(room).slice(0, 40)), { code: 'not_in_vault' })
1527
+ if (ns === 'keptAgent' && (typeof args[0] !== 'string' || !held(args[0]))) throw Object.assign(new Error('vault: this vault must hold both assistants'), { code: 'not_in_vault' })
1528
+ if (ns === 'keptAgent' && (!rooms.find((x) => x.room === room).lane || rooms.find((x) => x.room === args[0]).lane)) throw Object.assign(new Error('link a private lane and a kept Space'), { code: 'invalid_argument' })
1529
+ let c = null
1530
+ if (ns === 'connections' && m === 'grant') {
1531
+ const id = String(args[0] && typeof args[0] === 'object' ? args[0].id : args[0] || '')
1532
+ const acct = await sdk._account()
1533
+ c = conns.find((x) => x.id === id && x.account === acct) // only this account's own connections
1534
+ if (!c) throw Object.assign(new Error('vault: no connection ' + id.slice(0, 40) + ' attached in this vault'), { code: 'not_in_vault' })
1535
+ }
1536
+ if (ns === 'a2a' && (m === 'setReply' || (m === 'addPeer' && args[1]?.reply === 'auto'))) {
1537
+ const sp = roomSpace(room)
1538
+ try { await assertNotKept(sp) } finally { sp.close() }
1539
+ }
1540
+ if (ns === 'a2a' && m === 'setReply' && args[1] === 'auto') await confirmWith({ title: 'Let the assistant answer this agent on its own?', text: 'Its answers will go without asking you.', ok: 'Allow', cancel: 'Cancel' }).then((ok) => { if (!ok) throw Object.assign(new Error('cancelled'), { code: 'cancelled' }) })
1541
+ if (spec.confirm) {
1542
+ const epoch = privacyEpoch, owner = who()
1543
+ let kept = false
1544
+ if (ns === 'a2a' && m === 'addPeer' && !rooms.find((r) => r.room === room)?.lane) {
1545
+ const sp = roomSpace(room)
1546
+ try { kept = await isKeptSpace(sp) } finally { sp.close() }
1547
+ }
1548
+ await confirmCall(ns, m, args, room, kept)
1549
+ if (epoch !== privacyEpoch || owner !== who() || !held(room)) throw Object.assign(new Error('the account or room changed during confirmation'), { code: 'account_changed' })
1550
+ }
1551
+ if (ns === 'connections' && m === 'grants') {
1552
+ const epoch = privacyEpoch, owner = who(), sp = roomSpace(room)
1553
+ try {
1554
+ const result = await sp.connections.grants()
1555
+ if (epoch !== privacyEpoch || owner !== who() || !held(room)) throw Object.assign(new Error('the account changed'), { code: 'account_changed' })
1556
+ return result
1557
+ } finally { sp.close() }
1558
+ }
1559
+ if (ns === 'a2a') return laneA2A(room, m, args)
1560
+ const sp = roomSpace(room)
1561
+ try {
1562
+ if (ns === 'roster') return await (m === 'list' ? sp.roster() : sp.admission())
1563
+ if (ns === 'portable') {
1564
+ const { saveRoomExport } = await import('./sdkExports.js')
1565
+ const epoch = privacyEpoch, it = held(room) && rooms.find((r) => r.room === room)
1566
+ return await saveRoomExport(sp, it?.enc ? 'enclave' : 'standard', () => epoch === privacyEpoch && !!held(room), it?.title || '')
1567
+ }
1568
+ if (ns === 'keptAgent') {
1569
+ const kept = roomSpace(args[0])
1570
+ try { return m === 'link' ? await sp.linkKept(kept, args[1] || {}) : await sp.unlinkKept(kept, args[1]) }
1571
+ finally { kept.close() }
1572
+ }
1573
+ if (ns === 'invitations') {
1574
+ await sp._gateConfig() // heal a stale worker key before reading the vault's current link
1575
+ const it = rooms.find((x) => x.room === room)
1576
+ sp.shareLink = it.link
1577
+ sp._title = it.title ? { title: it.title } : null
1578
+ return await sp.resendInvite(args[0])
1579
+ }
1580
+ if (ns === 'alwaysOn') {
1581
+ if (m === 'assertNotKept') { await assertNotKept(sp); return {} }
1582
+ if (m === 'enable') { await sp._gateConfig(); sp.shareLink = rooms.find((x) => x.room === room).link }
1583
+ const result = await sp.alwaysOn[m](...args)
1584
+ if (m === 'enable' && args[0]?.disconnectLanes) await CALLS.op('getConfig', room, { plainMark: true })
1585
+ return result
1586
+ }
1587
+ if (c) return await sp.connections.grant(c, args[1] || {})
1588
+ if (ns === 'siri' && m === 'collect') {
1589
+ const deliver = args[0] && args[0].deliver ? (text, meta) => askPage('siriDeliver', { room, text, meta }) : undefined
1590
+ const r = await sp.siri.collect(deliver ? { deliver } : {}); saveSiri(); return r
1591
+ }
1592
+ const r = await sp[ns][m](...args)
1593
+ if (ns === 'siri') { saveSiri(); if (r && typeof r === 'object' && 'key' in r) return { ...r, key: null, hasKey: !!r.key } } // the key stays in the vault (siri.showKey)
1594
+ return r
1595
+ } catch (e) { throw vaultSignInWords(e) } finally { sp.close() }
1596
+ }
1597
+ const mirrorOk = new Map() // lane room → true, once its Space was found not attested, or the lane attested too
1598
+ async function mirrorAllowed(lane, entries) {
1599
+ const it = rooms.find((x) => x.room === lane), shared = it && it.lane
1600
+ if (it?.detachedLane && Array.isArray(entries) && entries.some((e) => String(e?.id || '').startsWith('sh:') && !e.sourceRemoved)) throw Object.assign(new Error('vault: this private assistant was disconnected'), { code: 'lanes_disabled' })
1601
+ if (shared) {
1602
+ const cfg = await wop('getConfig', shared, { plainMark: true })
1603
+ if (!cfg || cfg.gated && !cfg.allow) throw Object.assign(new Error('vault: the shared Space policy could not be read'), { code: 'policy_unreadable' })
1604
+ if (cfg.lanes === false) throw Object.assign(new Error('vault: private assistants are disabled in the shared Space'), { code: 'lanes_disabled' })
1605
+ }
1606
+ if (mirrorOk.get(lane)) return
1607
+ if (!shared || typeof sdk._client.attestedRoom !== 'function') return
1608
+ const ask = async (r) => { try { if (isEncRoom(r)) await encReadyFor(r); return !!(await sdk._client.attestedRoom(r, null)) } catch { throw Object.assign(new Error('vault: whether this Space requires an attested app could not be read, so its lane is not copied to — try again'), { code: 'policy_unreadable' }) } }
1609
+ if ((await ask(shared)) && !(await ask(lane))) throw Object.assign(new Error('vault: this Space requires an attested app, so it is copied only into a lane that requires one too'), { code: 'attested' })
1610
+ mirrorOk.set(lane, true)
1611
+ }
1612
+ // ONE WIPE for every sign-out — the person's (CALLS.signOut) and one from another device (the account's status check / sync):
1613
+ // the session, the held Spaces' keys and the account's stores (Siri, outside agents, connections, backup) go, as our hosted
1614
+ // vault's wipeVaultAccount does (sync sweep 11-19/11-20 P7/P8: a remote sign-out kept them all, and the page could still reach
1615
+ // every Space). The page hears `accountSignedOut` / `signedOut`; a backup brings the Spaces back at the next sign-in.
1616
+ // ⛔ AS COMPLETE AS OURS (sync sweep 11-22 #3 #4; ours also reloads the page, so nothing stays in its memory either): each held Space
1617
+ // is dropped as dropRoom drops one — the page's stream closed, off the notification list, its key forgotten by the worker,
1618
+ // whose store reloaded every mk:/us: into the next worker (ours wipes that IndexedDB, vault-loader.js _idbWipe) — and what this
1619
+ // vault held for the account in memory goes too: its connections (callKeys), its backup state (the next saveConns() / save wrote
1620
+ // them back), this device's account-service key, the rooms waiting for a key.
1621
+ function wipeSignedOut() {
1622
+ if (!wipeRun) wipeRun = finishSignOut().finally(() => { wipeRun = null })
1623
+ return wipeRun
1624
+ }
1625
+ async function finishSignOut() {
1626
+ write(st, wipeMarker, true)
1627
+ try { sdk.account.stop() } catch { /* not started */ }
1628
+ privacyEpoch++
1629
+ sdk.builds._resetAccount()
1630
+ clearTimeout(privacyTimer)
1631
+ const forgetDevice = sdk.backup._v2?.forgetDevice
1632
+ const keyCleanup = (forgetDevice ? forgetDevice(sdk.backup) : idbKeyStore('wbvault-acct').clear()).then(() => null, (e) => e)
1633
+ try { sdk.signOut() } catch { /* already */ }
1634
+ for (const room of streaming) { try { worker.postMessage({ t: 'streamClose', room }) } catch { /* the worker is replaced below */ } }
1635
+ streaming.clear() // the replay re-opened each one in the new worker, and onWorker forwarded its events to the page
1636
+ const held0 = rooms.map((r) => r.room)
1637
+ rooms = []
1638
+ write(st, KEYS.session, null)
1639
+ if (vpush) await Promise.race([vpush.sync([]), new Promise((r) => setTimeout(r, WIPE_PUSH_MS))]).catch(() => {}) // while the worker still holds the keys
1640
+ await saveRooms()
1641
+ await wcall({ t: 'presenceQuery' }).catch(() => null) // which rooms the worker holds a key for (workerRooms) — the list may not name them all
1642
+ for (const room of new Set([...held0, ...workerRooms])) await wcall({ t: 'forget', room }).catch(() => null) // memory AND its store (awaited there)
1643
+ await wcall({ t: 'wipeKeys' }) // includes sealed keys which were neither listed nor unsealed
1644
+ workerRooms = []
1645
+ failWaiting('signed out — try again') // what waits on the worker that goes (P8): never answered
1646
+ conns = []; backupMem = {}; _lockedOnce = false; pageUserToken = ''
1647
+ try { sdk.account._spk = null } catch { /* */ } // or the NEXT account's index entry carried this one's device key
1648
+ try { sdk.invite._state = null; sdk.invite.status = undefined } catch { /* */ } // …and this one's invite private key (sync sweep 2026-11-23 #12): the next account's held_elsewhere slot saved it under the new address
1649
+ mirrorOk.clear(); keyWaits.clear()
1650
+ for (const k of Object.values(KEYS)) write(st, k, null)
1651
+ await st.flushed()
1652
+ await atRest.flushed()
1653
+ write(st, learnedBlocksKey, null)
1654
+ await idb.del(BLOCKS_SW_KEY); await idb.del(CHAT_LOCKED_SW_KEY)
1655
+ for (const k of Object.values(KEYS)) { try { (o.storage || localStorage).removeItem(k + ':unopened') } catch { /* unavailable storage */ } }
1656
+ loadSiri(); loadBackup(); clearTimeout(refreshTimer); await startWorker()
1657
+ emit({ ev: 'rooms', rooms: publicRooms() }); emitAccount()
1658
+ const keyError = await keyCleanup
1659
+ if (keyError) throw keyError
1660
+ write(st, wipeMarker, null)
1661
+ }
1662
+ // WHAT A SIGN-OUT HAS TO FORGET (sync sweep 11-22 #7): a sign-in, live or expired; a held Space; a connection; a backup; any store
1663
+ function onPeerSignOut(event) {
1664
+ if (event.key !== wipeMarker) return
1665
+ if (event.newValue === 'true' && !peerSignedOut) {
1666
+ peerSignedOut = true
1667
+ privacyEpoch++
1668
+ clearTimeout(refreshTimer); clearTimeout(privacyTimer); clearTimeout(idPrefetchT)
1669
+ sdk.account.stop(); sdk.signOut(); clearTimeout(sdk.backup._timer)
1670
+ rooms = []; streaming.clear(); conns = []; backupMem = {}
1671
+ frame.remove()
1672
+ workerHost.drop()
1673
+ failWaiting('Signed out in another tab')
1674
+ }
1675
+ if (peerSignedOut && event.newValue === null) location.reload()
1676
+ }
1677
+ if (typeof addEventListener === 'function') addEventListener('storage', onPeerSignOut)
1678
+
1679
+ const holdsAnything = () => read(st, wipeMarker, false) || signedIn() || rooms.length > 0 || conns.length > 0 || Object.keys(backupMem || {}).length > 0
1680
+ || Object.values(KEYS).some((k) => { const v = read(st, k, null); return v != null && (typeof v !== 'object' || (Array.isArray(v) ? v.length > 0 : Object.keys(v).length > 0)) })
1681
+ const CALLS = {
1682
+ async userToken(t) { pageUserToken = typeof t === 'string' && t.length <= 4096 ? t : ''; return true },
1683
+ async op(op, room, ...args) {
1684
+ if (!PAGE_OPS.has(op)) throw Object.assign(new Error('vault: ' + op + ' is not available to the page'), { code: 'vault_refused' })
1685
+ if (!held(room)) throw Object.assign(new Error('vault: this vault holds no Space ' + String(room).slice(0, 40)), { code: 'not_in_vault' })
1686
+ if (op === 'stop') { if (isEncRoom(room) && !(await encReadyFor(room))) return { status: 503, ok: false, error: 'enclave_unreachable' }; return sdk._client.stop(room, String(args[0] || '').slice(0, 200)) } // a turn's stop: keyless, named by the turn's own random stop key — to the room's own tier (sweep 11-06 #3)
1687
+ // AN ATTESTED SPACE IS COPIED ONLY INTO AN ATTESTED LANE (sync sweep 2026-11-15 #5; the app's mirrorLoop.js, the SDK's openLane): the
1688
+ // page's lane mirror posts here — refused when the lane's Space requires an attested app and the lane does not; a failed read refuses
1689
+ if (op === 'mirror') await mirrorAllowed(room, args[0])
1690
+ if (op === 'turn' && args.length > 1) args[1] = null // the identity is the vault's (the worker signs with it), never the page's
1691
+ // the account's usage RECEIPT is the vault's too (it holds the usage key): set here, whatever the page sent (2026-10-23)
1692
+ if (op === 'turn') { const o = args[2] && typeof args[2] === 'object' ? { ...args[2] } : {}; delete o.receipt; const k = sdk.account && typeof sdk.account._usageKey === 'function' ? sdk.account._usageKey() : null; if (k) { try { o.receipt = await receiptFor(k, room) } catch { /* the turn goes without one */ } } args[2] = o }
1693
+ // what lets a Space SPEND is granted only through the vault's own calls, after the person says yes (security review):
1694
+ // a page's settings write may not carry a connection, a funding grant or the move authority
1695
+ if (op === 'setConfig' && args[0] && typeof args[0] === 'object' && ['connections', 'funding', 'forkAuthority', 'admins', 'owners'].some((k) => k in args[0])) throw Object.assign(new Error('vault: connections, funding and who manages a Space go through the vault (changeMembers asks the person first)'), { code: 'vault_refused' }) // admins/owners: a role change in place since 443e1e9d — a page must not make it in the person's name unasked (sweep 10-23 #4)
1696
+ if (op === 'setConfig' && args[0]?.lanes === true) { const sp = roomSpace(room); try { await assertNotKept(sp) } finally { sp.close() } }
1697
+ const keyIn = (o) => o.bridgeMk != null || o.mk != null || o.identity != null
1698
+ for (const a of args) {
1699
+ if (!a || typeof a !== 'object') continue
1700
+ if (keyIn(a)) throw Object.assign(new Error('vault: a key or an identity is the vault\'s, not the page\'s'), { code: 'vault_refused' })
1701
+ if (a.bridgeRoom != null && !held(a.bridgeRoom)) throw Object.assign(new Error('vault: this vault holds no Space ' + String(a.bridgeRoom).slice(0, 40)), { code: 'not_in_vault' })
1702
+ if (op !== 'carry' && (a.bridgeRoom || a.viewSource)) {
1703
+ const lane = rooms.find(r => r.room === room)
1704
+ if (lane?.detachedLane || !lane?.lane || (a.bridgeRoom && lane.lane !== a.bridgeRoom) || (a.viewSource && lane.lane !== a.viewSource)) throw Object.assign(new Error('vault: this private assistant is disconnected'), { code: 'lanes_disabled' })
1705
+ }
1706
+ // linked rooms (a lane's tell_lane): each one held here; the worker fills in its key by room
1707
+ if (a.links != null) {
1708
+ if (!Array.isArray(a.links) || a.links.some((l) => !l || typeof l !== 'object')) throw Object.assign(new Error('vault: links are Spaces named by id'), { code: 'invalid_argument' })
1709
+ if (a.links.some(keyIn)) throw Object.assign(new Error('vault: a key is the vault\'s, not the page\'s'), { code: 'vault_refused' })
1710
+ if (a.links.some((l) => !held(l.room))) throw Object.assign(new Error('vault: a linked room must be a Space this vault holds'), { code: 'not_in_vault' })
1711
+ }
1712
+ }
1713
+ const isEnc = rooms.some((x) => x.room === room && x.enc)
1714
+ if (isEnc && !sdk._enc.byRegion.size) await encAttest(room).catch(() => null) // first use of a confidential room this session
1715
+ // a confidential room whose enclave key is STALE (the enclave was replaced: bad_mkseal) or not in hand yet (it was
1716
+ // asleep): attest and ask once more — the SDK's healingClient rule; ONCE per op, through the same worker (reattestOnce)
1717
+ let r = await reattestOnce({ enc: isEnc, run: () => wcall({ t: 'op', op, room, args }), reattest: () => encAttest(room).then(() => true, () => false) })
1718
+ // THE SERVER SAYS IT IS CONFIDENTIAL (sweep 11-06 P7, the root of #2/#3): a page op on a room the vault took for a regular
1719
+ // one — an older unmarked link — learns the tier (learnTier, as opHealed does) and runs once more on the enclave
1720
+ if (!isEnc && saysConfidential(r)) { learnTier(room, r); if (await encReadyFor(room)) r = await wcall({ t: 'op', op, room, args }) }
1721
+ if (r && (r.status === 401 || r.status === 200) && r.error === 'stale_key' && await followKey(room)) r = await wcall({ t: 'op', op, room, args }) // the Space was re-keyed in place: the vault takes its grant (followKey) and asks again
1722
+ // a SLEEPING confidential Space reads no settings: wake it and read once more (sweep 11-07 #8 — the page cannot: its
1723
+ // _isEnclave() is always false in a vault, so space.safeMedia.refresh() failed until something else woke it)
1724
+ if (op === 'getConfig' && isEnc && r == null) { try { await sdk._encWake(room, { tries: 8 }); pushEnclave(); r = await wcall({ t: 'op', op, room, args }) } catch { /* null: the page says it could not read */ } }
1725
+ if (op === 'getConfig') r = configForPage(r)
1726
+ const lanes = op === 'getConfig' ? r && r.lanes : op === 'setConfig' && r && r.status === 200 && args[0] ? args[0].lanes : undefined
1727
+ if (op === 'setConfig' && lanes === false) await disconnectRoomLanes(sdk, room)
1728
+ if (typeof lanes === 'boolean') {
1729
+ const it = rooms.find((x) => x.room === room)
1730
+ if (it && it.link) { const url = new URL(it.link); const hash = new URLSearchParams(url.hash.slice(1)); if (lanes) hash.set('lanes', '1'); else hash.delete('lanes'); url.hash = hash.toString(); const link = url.href; if (link !== it.link) { it.link = link; await saveRooms(); emit({ ev: 'rooms', rooms: publicRooms() }) } }
1731
+ }
1732
+ if (op === 'title' && r && typeof r.title === 'string') { const it = rooms.find((x) => x.room === room); const t = r.title.slice(0, 200); if (it && it.title !== t) { it.title = t; saveRooms() } }
1733
+ return r
1734
+ },
1735
+ async create(cfg, opts) { // opts { enclave, split }: the confidential tier, a split-key room; anything else is refused, never ignored
1736
+ if (opts !== undefined && opts !== null && (typeof opts !== 'object' || Object.keys(opts).some((k) => k !== 'enclave' && k !== 'split'))) throw Object.assign(new Error('vault: create takes { enclave, split } and nothing else'), { code: 'invalid_argument' })
1737
+ return makeRoom(cfg, null, { enclave: !!(opts && opts.enclave === true), split: !!(opts && opts.split === true) })
1738
+ },
1739
+ }
1740
+ async function makeRoom(cfg, lane, { enclave = false, split = false } = {}) {
1741
+ const epoch = privacyEpoch, owner = who()
1742
+ const current = () => { if (privacyEpoch !== epoch || who() !== owner) throw Object.assign(new Error('the account changed during creation'), { code: 'account_changed' }) }
1743
+ // SPLIT: the room's key is two halves — the link holds one, the builder's app-half function (/api/appshare on THIS
1744
+ // origin; spaces/templates/appshare) the other. A vault that serves none cannot make one (`appShare: true` says it does).
1745
+ if (split && !o.appShare) throw Object.assign(new Error('vault: this vault serves no app-half function — a split-key Space needs one at /api/appshare (startVault({ appShare: true }))'), { code: 'vault_unsupported' })
1746
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) throw Object.assign(new Error('vault: create takes a room config'), { code: 'invalid_argument' })
1747
+ const extra = Object.keys(cfg).filter((k) => !CREATE_FIELDS.has(k))
1748
+ if (extra.length) throw Object.assign(new Error('vault: not available in a vault: ' + extra.join(', ').slice(0, 80)), { code: 'vault_unsupported' })
1749
+ const now = Date.now(); creates = creates.filter((t) => now - t < CREATE_LIMIT.ms)
1750
+ if (creates.length >= CREATE_LIMIT.n) throw Object.assign(new Error('vault: too many new Spaces — wait a few minutes'), { code: 'rate_limited' })
1751
+ creates.push(now)
1752
+ if (cfg.direct !== undefined && (cfg.direct !== true || cfg.admission !== 'email')) throw Object.assign(new Error('vault: a direct chat is an email-gated Space'), { code: 'invalid_argument' })
1753
+ // Attest FIRST — loud on a configuration failure (no published claim: never mint a confidential room that pins
1754
+ // nothing), soft on a cold enclave (woken below) — then mint, wake, and hand the enclave its own sealed config.
1755
+ if (enclave) { await sdk._encAttestSoft(); pushEnclave() }
1756
+ const r = await wcall({ t: 'create', cfg, base: location.origin, ...(enclave && !split ? { enclave: true } : {}), ...(split ? { split: true, ...(sdk.backup.enabled ? { returnMk: true } : {}) } : {}), ...(sdk.backup.enabled ? { delAsk: true } : {}) })
1757
+ current()
1758
+ const mark = (l, m) => l + (l.includes('#') ? '&' : '#') + m
1759
+ let link = cfg.admission === 'email' ? mark(r.link, 'gate=email') : r.link // a gated Space's invite says so (inviteLinks.js): the joiner knows to sign in
1760
+ if (enclave) link = mark(link, 'enc=1') // and a confidential one, or a fresh client cannot know its tier
1761
+ if (cfg && cfg.lanes === true) link = mark(link, 'lanes=1') // and one that gives every member a private assistant, as the direct SDK's (sync sweep 2026-10-29 #3)
1762
+ if (enclave) {
1763
+ creatingEnclaveRooms.add(r.room)
1764
+ try {
1765
+ pushEnclave()
1766
+ await sdk._encWake(r.room); pushEnclave()
1767
+ if (!r.enclaveCreated && !(await sdk._encSealConfig(r.room, r.commit, r.configSealed))) throw Object.assign(new Error('vault: the new confidential Space could not receive its configuration'), { code: 'enclave_seal_failed' })
1768
+ } catch (err) {
1769
+ sdk._enc.rooms.delete(r.room)
1770
+ await wcall({ t: 'forget', room: r.room }).catch(() => {})
1771
+ throw err
1772
+ } finally { creatingEnclaveRooms.delete(r.room) }
1773
+ }
1774
+ current()
1775
+ const completeKey = split && r.mk && await keyCommit(r.mk) === linkParts(link)?.commit ? r.mk : null
1776
+ current()
1777
+ rooms = [{ room: r.room, link, ...(completeKey ? { mk: completeKey } : {}), title: '', at: Date.now(), ...(lane ? { lane } : {}), ...(enclave ? { enc: true } : {}), ...(split ? { split: true } : {}) }, ...rooms.filter(x => x.room !== r.room)]
1778
+ await saveRooms()
1779
+ current()
1780
+ seedIdentity(r.room); noteRoom(r.room).catch(() => {})
1781
+ emit({ ev: 'rooms', rooms: publicRooms() })
1782
+ return { room: r.room }
1783
+ }
1784
+ Object.assign(CALLS, {
1785
+ async rooms() { return publicRooms() },
1786
+ // a short-lived speech key (dictation 'stt', reading aloud 'tts'), minted with this vault's sign-in — or the page's
1787
+ // user token (its backend vouched for the user). The page streams to the speech model itself, as outside a vault.
1788
+ async speechKey(kind, userToken) {
1789
+ if (kind !== 'stt' && kind !== 'tts') throw Object.assign(new Error('vault: stt or tts'), { code: 'invalid_argument' })
1790
+ const now = Date.now(); speechKeys = speechKeys.filter((t) => now - t < SPEECH_LIMIT.ms)
1791
+ if (speechKeys.length >= SPEECH_LIMIT.n) return { status: 429, error: kind + '_rate_limited', retryAfterS: Math.max(1, Math.ceil((SPEECH_LIMIT.ms - (now - speechKeys[0])) / 1000)) } // each key costs money: a page minting in a loop is stopped here — the server's own code and wait, so the page says "try again in N s" (sync sweep, 10-16)
1792
+ const id = signedIn() ? sdk.session.idToken : ''
1793
+ const ut = typeof userToken === 'string' ? userToken.slice(0, 4000) : ''
1794
+ if (!id && !ut) return { status: 401, error: 'signin_required' } // before the budget: a refusal mints nothing, so it spends nothing (sync sweep 10-19)
1795
+ speechKeys.push(now)
1796
+ return sdk._client[kind](id, ut)
1797
+ },
1798
+ fork,
1799
+ follow,
1800
+ announce,
1801
+ changeMembers: (room, admission) => inPlace(room, admission, false),
1802
+ rotateKey: (room) => inPlace(room, null, true),
1803
+ // a private lane of a Space this vault holds: a Space of the member's own, recorded as that Space's lane
1804
+ async createLane(shared, cfg, o) {
1805
+ if (!held(shared)) throw Object.assign(new Error('vault: this vault holds no Space ' + String(shared).slice(0, 40)), { code: 'not_in_vault' })
1806
+ { const sp = roomSpace(shared); try { await assertNotKept(sp) } finally { sp.close() } }
1807
+ const sh = rooms.find((x) => x.room === shared)
1808
+ // A TEMPORARY ROOM HAS NO LANE (as the direct SDK and the app — roomState isTempRoom; sync sweep backlog P7): a lane is a
1809
+ // durable room, and its copies of the room would outlive the wipe
1810
+ if (sh && sh.lane) throw Object.assign(new Error('vault: a private lane has no lane of its own — ask from its Space'), { code: 'lane_of_lane' }) // as the direct SDK (sweep P1)
1811
+ if (String(shared).startsWith('tmp-') || (sh && sh.temporary)) throw Object.assign(new Error('vault: a temporary room has no private lane — the lane is a durable room, and its copies of the room would outlive the wipe'), { code: 'temporary_room' })
1812
+ // A VERIFIED SPACE'S LANE ADMITS ITS ONE MEMBER, whatever the page sent (laneConfig.js laneInherits; sync sweep 10-16 #1):
1813
+ // the vault decides it, so a page cannot make an open lane of a verified Space.
1814
+ // A SLEEPING CONFIDENTIAL SPACE is woken first, as the members change does (inPlace): asleep, the relay refuses op policy
1815
+ // and wakes nothing, so the read below failed every time and "try again" never helped (sync sweep 2026-11-03 #2)
1816
+ if (sh && sh.enc) { try { await sdk._encWake(shared, { tries: 8 }); pushEnclave() } catch { /* the read below says what is wrong */ } }
1817
+ let scfg = null; try { scfg = await wop('getConfig', shared, { plainMark: true }) } catch { scfg = null }
1818
+ // a plain room: read, and it has no settings — never when the vault's own link for it says verified (gate=email)
1819
+ const plain = !!(scfg && scfg.plain === true) && !(sh && /[#&]gate=email(?:&|$)/.test(String(sh.link || ''))); if (scfg && scfg.plain === true) scfg = null
1820
+ // the placeholder a verified Space's settings read gives before the sign-in admits ({ admission:'email', gated:true },
1821
+ // no allow) is not its settings: read as such, the lane got none of its Space's tools (sync sweep 2026-10-29 #9; the app: roomSync gatedStub)
1822
+ // …and it says the Space IS verified: wait, whatever the link says — read as "no settings", a verified Space whose link
1823
+ // carries no gate=email mark (an old invite, a restored link) got an OPEN lane (sync sweep 2026-10-31 #1)
1824
+ if (gatedStub(scfg)) throw Object.assign(new Error(signedIn() ? "vault: this Space is verified and its settings open only to an admitted member — you are signed in, but its gate has not admitted " + String(sdk.session.email || 'this email') + " yet, so its private lane cannot be made as strict as it — ask an admin of the Space, then try again" : "vault: this Space is verified and its settings open only once you are signed in and admitted, so its private lane cannot be made as strict as it yet — sign in, then try again"), { code: 'lane_wait' }) // the words for who is asking: 'sign in' to someone signed in sent them in circles (sync sweep 11-09)
1825
+ // a settings read that FAILED waits too, whatever the link says: a verified Space with no gate=email mark (an old invite,
1826
+ // a restored link) read as "no settings" got an open lane (sync sweep 2026-11-02 #3) — the vault fails closed
1827
+ // a PLAIN room is told apart by the read itself (spaceClient getConfig plainMark): its lane is made as the SDK and the app
1828
+ // make it (sync sweep 2026-11-03 #3: an open room joined from elsewhere could never get one). Anything else waits.
1829
+ // …but a read REFUSED because this member was removed, or because the room was re-keyed, is not "try again": the settings
1830
+ // read answers null for both (spaceClient getConfig), so a removed member waited for ever (sync sweep 11-09, 11-04 P7). The
1831
+ // room's grant tells them apart: removed → said by name; a new key taken → read once more.
1832
+ if (!scfg && !plain) {
1833
+ const took = await followKey(shared).catch(() => false)
1834
+ if (took) { try { scfg = await wop('getConfig', shared, { plainMark: true }) } catch { scfg = null } if (scfg && scfg.plain === true) scfg = null }
1835
+ const w = keyWaits.get(shared)
1836
+ if (w && w.why === 'removed') throw Object.assign(new Error('vault: you are no longer a member of this Space, so it has no private lane for you'), { code: 'removed' })
1837
+ }
1838
+ if (!scfg && !plain) throw Object.assign(new Error("vault: this Space's settings could not be read, so its private lane cannot be made as strict as it yet — try again"), { code: 'lane_wait' })
1839
+ if (scfg && scfg.lanes === false) throw Object.assign(new Error('vault: private lanes are disabled for this Space'), { code: 'lanes_disabled' })
1840
+ if (scfg && scfg.admission === 'email') {
1841
+ // the page asked for an OPEN lane (o.open, sdkVault): refused by name, never silently rewritten (sync sweep 10-19 #15)
1842
+ if (o && typeof o === 'object' && o.open === true) throw Object.assign(new Error("vault: this Space is verified, so its private lane must be too — an open lane would let anyone with its link read the member's private assistant. Omit `admission` to gate it to the signed-in member."), { code: 'lane_downgrade' })
1843
+ const inh = laneInherits(scfg, { email: signedIn() ? String(sdk.session.email || '').trim().toLowerCase() : '' })
1844
+ if (inh.wait) throw Object.assign(new Error('vault: this Space is verified, so its private lane is gated to you — sign in first'), { code: 'sign_in_required' })
1845
+ const { admins: _a, owners: _o, ...rest } = cfg && typeof cfg === 'object' ? cfg : {} // its one member only: no other admins or owners
1846
+ cfg = { ...rest, admission: 'email', allow: inh.gate.allow }
1847
+ }
1848
+ // AN ATTESTED SPACE (its owner policy requires an attested app): its lane is made only by the attested app (the Witbitz app on the
1849
+ // device) — refused here as the direct SDK refuses it
1850
+ // (privateLane, 'attested'); the vault made an ordinary lane of one (sync sweep 10-24, open until 10-26)
1851
+ let attested = false
1852
+ try { if (sh.enc) await encReadyFor(shared); attested = !!(await sdk._client.attestedRoom(shared, null)) } catch { throw Object.assign(new Error('vault: whether this Space requires an attested app could not be read, so its private lane waits — try again'), { code: 'lane_wait' }) } // a failed read is not 'not attested' (sync sweep 11-08) // op 'policy' is public: no room key rides (sweep 11-06 #2 — it went to the Lambda READABLE)
1853
+ if (laneInherits(scfg, { attested }).wait === 'attested') throw Object.assign(new Error('vault: this Space requires an attested app, so its private lane is made only by that app (the Witbitz app on the device), under the same rule — not by a vault'), { code: 'attested' })
1854
+ cfg = { ...(cfg && typeof cfg === 'object' ? cfg : {}), lane: true, region: roomRegion(shared) } /* region: its Space's, whatever the page sent — as the app and the direct SDK (sync sweep 2026-11-23) */ // a lane says so in its own sealed settings (laneConfig.js; sync sweep 11-19 P1)
1855
+ return makeRoom(cfg, shared, { enclave: !!sh.enc, split: !!sh.split }) // a lane is on its Space's tier and key model — never a silent downgrade
1856
+ },
1857
+ account,
1858
+ roomAccount,
1859
+ async answer(id, out) { const w = asks.get(id); if (!w) return { ok: false }; asks.delete(id); clearTimeout(w.timer); if (out && out.error) w.rej(Object.assign(new Error(String(out.error).slice(0, 200)), { code: 'page_refused' })); else w.res(out && out.result); return { ok: true } },
1860
+ // a live stream for a held Space while the page shows it (on: true), or no longer (on: false)
1861
+ async stream(room, on) {
1862
+ if (!held(room)) throw Object.assign(new Error('vault: this vault holds no Space ' + String(room).slice(0, 40)), { code: 'not_in_vault' })
1863
+ if (on && !streaming.has(room)) { streaming.add(room); worker.postMessage({ t: 'streamOpen', room }) }
1864
+ else if (!on && streaming.has(room)) { streaming.delete(room); worker.postMessage({ t: 'streamClose', room }) }
1865
+ return { streaming: streaming.has(room) }
1866
+ },
1867
+ async share(room, opts = {}) {
1868
+ const it = rooms.find((x) => x.room === room)
1869
+ if (!it || !it.link) throw Object.assign(new Error('vault: no link for that Space'), { code: 'not_in_vault' })
1870
+ if (it.lane) throw Object.assign(new Error('A private lane cannot be shared'), { code: 'private_lane' })
1871
+ if (typeof screens.share !== 'function') throw Object.assign(new Error('this vault has no share screen'), { code: 'no_screen' })
1872
+ await screens.share({ link: it.link, title: String((opts && opts.title) || it.title || '') })
1873
+ return { shown: true }
1874
+ },
1875
+ signIn,
1876
+ // THE LOCK SHEET (a vault started with `lock: true`): the person turns the lock and storage protection on or off in the vault's
1877
+ // own pixels; the page gets only the outcome { available, on, protect } — it can neither turn either on nor off
1878
+ async lockSettings() {
1879
+ if (!vlock) throw Object.assign(new Error('vault: this vault has no lock — its builder starts it with startVault({ lock: true })'), { code: 'vault_unsupported' })
1880
+ if (vlock.locked()) throw Object.assign(new Error('vault: the vault is locked'), { code: 'vault_locked' }) // the page behind the lock cover must not uncover it (review, 2026-11-13)
1881
+ return (asking.lock ||= vlock.showSheet().finally(() => { asking.lock = null })) // one sheet at a time, however often the page asks
1882
+ },
1883
+ // NOTIFICATIONS on this device (a vault started with `push: true`): the person says yes or no in the vault's card — that click
1884
+ // is the gesture the browser's permission prompt needs; the page gets only { available, on }
1885
+ async notifications() {
1886
+ if (!vpush) throw Object.assign(new Error('vault: this vault sends no notifications — its builder starts it with startVault({ push: true })'), { code: 'vault_unsupported' })
1887
+ return (asking.push ||= notificationsOnce().finally(() => { asking.push = null })) // one card at a time
1888
+ },
1889
+ async signOut() {
1890
+ // the PERSON confirms in the vault's own pixels: a page script alone cannot sign them out (security review). Whatever the sign-in:
1891
+ // once it had expired this returned at once, and the Spaces, their keys and the page's reach all stayed (sync sweep 11-22 #7)
1892
+ if (!holdsAnything()) return { signedIn: false }
1893
+ if (!(await confirmWith({ title: 'Sign out?', text: 'This device forgets your Spaces and your account. Your backup brings them back when you sign in again' + (sdk.backup && sdk.backup.enabled ? '.' : ' — and backup is OFF here, so a Space only this device holds is lost.'), ok: 'Sign out', cancel: 'Cancel' }).catch(() => false))) throw Object.assign(new Error('cancelled'), { code: 'cancelled' })
1894
+ // SIGN OUT ENDS THE PAGE'S REACH (docs/sdk-vault-mode.md: "cannot reach rooms after the user signs out in the vault"; sync sweep
1895
+ // 11-20 P7/P8): the held Spaces' keys and the account's stores go too — kept, the page still reached every Space, and the next
1896
+ // account's backup took them in (noteRoom). Our hosted vault's wipe (vault-loader.js wipeVaultAccount) does the same.
1897
+ const epoch = privacyEpoch, b = sdk.backup
1898
+ if (b.enabled) {
1899
+ try { await b.save() } catch {
1900
+ if (!await confirmWith({ title: 'Discard unsaved changes?', text: 'The final backup did not save. Stay signed in to retry or discard changes on this device.', ok: 'Discard and sign out', cancel: 'Stay signed in' })) throw Object.assign(new Error('Sign-out cancelled'), { code: 'cancelled' })
1901
+ }
1902
+ }
1903
+ if (epoch !== privacyEpoch) throw Object.assign(new Error('The account changed'), { code: 'account_changed' })
1904
+ await wipeSignedOut(); emit({ ev: 'signedOut' }); return { signedIn: false } },
1905
+ async whoami() { return signedIn() ? { signedIn: true, email: sdk.session.email, keyId: sessionKeyId() } : { signedIn: false } },
1906
+ async forget(room) {
1907
+ if (!held(room)) return { forgotten: false }
1908
+ // removing a Space's key from this device can lose it for good (no other copy): the PERSON confirms it (security review)
1909
+ const it = rooms.find((x) => x.room === room)
1910
+ const accountWide = sdk.backup.enabled
1911
+ if (!(await confirmWith({ title: 'Remove ' + (it && it.title ? '“' + it.title + '”' : 'this Space') + (accountWide ? ' from your account?' : ' from this device?'), text: accountWide ? 'This removes it from every device that syncs this account.' : 'Without its invite link you cannot open it here again.', ok: 'Remove', cancel: 'Keep' }).catch(() => false))) throw Object.assign(new Error('cancelled'), { code: 'cancelled' })
1912
+ await dropRoom(room)
1913
+ if (accountWide && sdk.backup.enabled) sdk.backup.remove(room) // and from the account, on every device
1914
+ return { forgotten: true }
1915
+ },
1916
+ })
1917
+
1918
+ // the lock sheet and the notifications card: ONE at a time, however often the page asks (as the sign-in screen)
1919
+ const asking = { lock: null, push: null }
1920
+ async function notificationsOnce() {
1921
+ const on = vpush.view().on
1922
+ const ok = await confirmWith(on
1923
+ ? { title: 'Turn off notifications?', text: 'This device stops getting a nudge when someone posts in your Spaces.', ok: 'Turn off', cancel: 'Keep them' }
1924
+ : { title: 'Get notifications on this device?', text: 'A nudge when someone posts in your Spaces. What it says is sealed until it reaches this device.', ok: 'Turn on', cancel: 'Not now' }).catch(() => false)
1925
+ if (!ok) return vpush.view()
1926
+ const v = on ? await vpush.disable() : await vpush.enable(rooms.map((r) => r.room))
1927
+ emit({ ev: 'push', push: v })
1928
+ return v
1929
+ }
1930
+
1931
+ if (read(st, wipeMarker, false)) await wipeSignedOut()
1932
+ const joining = joinInvite() // after the frame exists: the question shows over it
1933
+ let greeted = false
1934
+ window.addEventListener('message', async (e) => {
1935
+ if (e.origin !== pageOrigin || e.source !== frame.contentWindow) return // only the page this vault framed
1936
+ const d = e.data
1937
+ if (!d || d.ch !== 'wbvault') return
1938
+ if (d.t === 'hello') {
1939
+ toPage({ t: 'welcome', v: VAULT_PROTOCOL, billingPerCall: true, tenant: o.tenant || '', endpoint, signedIn: signedIn(), email: signedIn() ? sdk.session.email : '', keyId: sessionKeyId(), rooms: publicRooms(), siri: siriShortcut(), account: accountView(), keyStates: keyStatesNow(), ...(vlock ? { lock: vlock.view() } : {}), ...(vpush ? { push: vpush.view() } : {}), ...(tapRoom && held(tapRoom) ? { notifOpen: tapRoom } : {}) }) // lock / push: only a vault that offers them says anything
1940
+ if (!greeted) { greeted = true; if (typeof screens.ready === 'function') try { screens.ready() } catch { /* */ } joining.then(() => { if (joined) emit({ ev: 'joined', room: joined }) }) }
1941
+ return
1942
+ }
1943
+ if (d.t !== 'call' || typeof d.id !== 'number') return
1944
+ if (peerSignedOut) return
1945
+ if ((wipeRun || read(st, wipeMarker, false)) && d.op !== 'signOut' && d.op !== 'whoami') return refuse(d.id, 'Device sign-out must finish first.', 'signout_pending')
1946
+ const fn = Object.prototype.hasOwnProperty.call(CALLS, d.op) ? CALLS[d.op] : null
1947
+ if (!fn) return refuse(d.id, 'vault: unknown call ' + String(d.op).slice(0, 40), 'vault_refused')
1948
+ // a result's own words name the page's call too (wb.erasure.file's `skipped: 'signed out: wb.signIn first'` — sync sweep 2026-10-29 #10)
1949
+ const pageWords = (r) => (r && typeof r === 'object' && !Array.isArray(r) && typeof r.skipped === 'string' ? { ...r, skipped: r.skipped.replace(/\bwb\.signIn\b/g, 'wb.vault.signIn') } : r)
1950
+ try { toPage({ t: 'res', id: d.id, result: pageWords(await fn(...(Array.isArray(d.args) ? d.args : []))) }) }
1951
+ catch (err) { const code = (err && err.code) || 'vault_error'; let msg = String((err && err.message) || err); if (code === 'sign_in_required') msg = msg.replace(/\bwb\.signIn\b/g, 'wb.vault.signIn'); refuse(d.id, msg, code, errExtra(err)) } // the page signs in through the VAULT — its own SDK said wb.signIn, which the page refuses (sync sweep 2026-10-28 #6)
1952
+ })
1953
+ // the page never says hello: tell the person, in the vault's own pixels
1954
+ setTimeout(() => { if (!greeted && typeof screens.failed === 'function') try { screens.failed({ page: pageUrl.href }) } catch { /* */ } }, o.loadTimeoutMs || 20_000)
1955
+
1956
+ if (vpush) vpush.start(rooms.map((r) => r.room)).catch(() => {}) // a device that turned notifications on: its subscription, kept current
1957
+ return { frame, rooms: publicRooms, signedIn, worker: () => worker, _sdk: sdk, _store: st } // _sdk: tests stand a Sentinel in; _store: the sealed secrets as the vault reads them (tests)
1958
+ }