@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-kit.mjs ADDED
@@ -0,0 +1,354 @@
1
+ #!/usr/bin/env node
2
+ // vault-kit.mjs — build a VAULT KIT you host yourself (https://witbitz.chat/docs/sdk-keys.md#vault-mode). Node 18+, no packages.
3
+ //
4
+ // curl -O https://witbitz.chat/sdk/2.1.0/vault-kit.mjs
5
+ // node vault-kit.mjs ./vault --page https://app.acme.com/chat --vault https://vault.acme.com [--tenant t_…] [--brand Acme]
6
+ //
7
+ // It writes a folder for https://vault.acme.com: the vault keeps every room key; your app page (on its own origin) runs
8
+ // inside it and never holds one. Witbitz hosts nothing for it.
9
+ // index.html, space/index.html the vault page (space/ is where invite links land: …/space?room=…#mk=…) — rewritten every
10
+ // run: it PINS every script of the vault by its sha384 (an import map + its own script policy)
11
+ // vault.js YOURS: the configuration ┐ written once — a re-run keeps your edits AND pins them:
12
+ // screens.js YOURS: sign-in, share, didn't load ┘ edit them, then run the kit again
13
+ // core/ OURS: everything that touches a key — a re-run replaces ONLY this folder
14
+ // HEADERS.md the headers to serve it with (nginx / Caddy / Apache)
15
+ // README.md, kit.json what this is; the version, and each core file's sha384
16
+ // `--from` is where the core comes from: an SDK release URL (default: the release this file was published with — KIT_RELEASE), every file checked against that release's manifest — and the manifest itself against --manifest-sha <sha384-…>
17
+ // when given (the hash the docs publish for the release); or a folder (a Witbitz checkout's spaces/public).
18
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, statSync } from 'node:fs'
19
+ import { createHash } from 'node:crypto'
20
+ import { join, dirname } from 'node:path'
21
+
22
+ export const DEFAULTS = { endpoint: 'https://api.witbitz.chat/v1/space', loginBase: 'https://witbitz-spaces.pages.dev', from: 'https://witbitz.chat/sdk/latest/', enclaveClaim: 'https://witbitz-spaces.pages.dev/enclave-claim.json', accountService: 'https://api.witbitz.chat/v1' } // enclaveClaim: the confidential tier's published measurement (and its policy text, beside it)
23
+ export const KIT_RELEASE = '4.3.0' // tools/sdk-release.mjs stamps the version here, so a downloaded copy builds from ITS release
24
+ export function stampSdkAuth(src) {
25
+ return src.replaceAll('__' + 'SPACE_AUTH_BROKER' + '__', 'https://auth.witbitz.chat').replaceAll('__' + 'SPACE_AUTH_FORCE_BROKER' + '__', '0')
26
+ }
27
+ const STAMP = '?v=' + '__' + 'SPACES_BUILD' + '__' // spelled apart, so a release of this file does not read as a placeholder
28
+ const PLACEHOLDER = /__[A-Z][A-Z0-9_]{3,}__/
29
+ const PURE_NOTE = new RegExp('@__' + 'PURE__', 'g') // spelled apart, like STAMP: esbuild's annotation in a bundle
30
+ const ORIGIN = /^https:\/\/[a-z0-9.-]+(:\d+)?$/i
31
+ const originOf = (u) => { try { return new URL(u).origin } catch { return '' } }
32
+ const esc = (s) => JSON.stringify(String(s))
33
+ const sri = (s) => 'sha384-' + createHash('sha384').update(s).digest('base64')
34
+ const sha256 = (s) => 'sha256-' + createHash('sha256').update(s).digest('base64')
35
+ // Every sibling module a file names: a static or dynamic import of a ./ path, or a new URL of one (a worker, a worklet).
36
+ const SPEC = new RegExp(`(?:from\\s*|import\\s*\\(?\\s*|new URL\\(\\s*)['"]\\.\\/([\\w.-]+\\.m?js)(?:${STAMP.replace(/[?]/g, '\\?')})?['"]`, 'g')
37
+
38
+ export function parseArgs(argv) {
39
+ const o = { out: '', page: '', vault: '', tenant: '', brand: '', accent: '', endpoint: DEFAULTS.endpoint, loginBase: DEFAULTS.loginBase, from: '', manifestSha: '', appShare: false, lock: false }
40
+ for (let i = 0; i < argv.length; i++) {
41
+ const a = argv[i]
42
+ if (a === '--app-share') { o.appShare = true; continue } // a flag: you serve your app-half function at /api/appshare on the vault's origin (split-key Spaces)
43
+ if (a === '--google-sign-in') { o.googleSignIn = true; continue }
44
+ if (a === '--lock') { o.lock = true; continue } // a flag: the vault offers its users the lock and storage protection (wb.vault.showLock())
45
+ if (a === '--push') { o.push = true; continue } // a flag: the vault offers its users notifications (wb.vault.showNotifications()), through push-sw.js
46
+ if (a.startsWith('--')) { const k = a.slice(2).replace(/-([a-z])/g, (_, c) => c.toUpperCase()); o[k] = argv[++i] || '' } else if (!o.out) o.out = a
47
+ }
48
+ const err = []
49
+ if (!o.out) err.push('the output folder')
50
+ if (!/^https:\/\//.test(o.page) || !originOf(o.page)) err.push('--page, your app page (https URL)')
51
+ if (!ORIGIN.test(o.vault || '')) err.push('--vault, the vault\'s origin (https://vault.example.com, no path)')
52
+ if (o.page && o.vault && originOf(o.page) === o.vault) err.push('--page on ANOTHER origin than --vault (that wall is the point)')
53
+ if (o.tenant && !/^t_[0-9a-f]{32}$/.test(o.tenant)) err.push('--tenant as t_ + 32 hex')
54
+ if (o.accent && !/^#[0-9a-f]{3,8}$/i.test(o.accent)) err.push('--accent as a hex colour')
55
+ if (!ORIGIN.test(originOf(o.endpoint) || '')) err.push('--endpoint as an https URL')
56
+ if (o.authBroker && !ORIGIN.test(o.authBroker)) err.push('--auth-broker as an https origin')
57
+ return { o, err }
58
+ }
59
+
60
+ /** The vault's response headers — what the host must send, since only Cloudflare reads a _headers file. They stay the SAME across
61
+ * kit runs: the hash that changes lives in the page's own policy (vaultPage's <meta>), which narrows this one — `'unsafe-inline'`
62
+ * here only lets the page's inline import map run, and the page's policy admits it by its hash alone. */
63
+ // accountService: the Witbitz account service, where the vault keeps a NEW account (core/sdkBackupV2.js) — the same API domain as
64
+ // the default endpoint, named on its own so a vault with another endpoint still reaches it
65
+ export function headersFor({ page, endpoint = DEFAULTS.endpoint, loginBase = DEFAULTS.loginBase, enclaveClaim = DEFAULTS.enclaveClaim, accountService = DEFAULTS.accountService, authBroker = 'https://auth.witbitz.chat' }) {
66
+ const csp = [
67
+ "default-src 'self'", "script-src 'self' 'unsafe-inline'", "worker-src 'self' blob:", "style-src 'self' 'unsafe-inline'", "img-src 'self' data: blob:",
68
+ `connect-src 'self' ${[...new Set([originOf(endpoint), originOf(loginBase), originOf(enclaveClaim), originOf(accountService), originOf(authBroker)])].join(' ')}`,
69
+ `frame-src ${originOf(page)}`, "frame-ancestors 'none'", "base-uri 'self'", "object-src 'none'", "form-action 'none'",
70
+ ].join('; ')
71
+ // Cross-Origin-Opener-Policy: a page that opens the vault in a window gets no handle on it (docs/hosted-app-design.md §7, as
72
+ // Witbitz's own vault since 2026-10-25). `same-origin`, not `-allow-popups`: this vault opens no window of its own (sign-in is
73
+ // an email code; a connection's sign-in happens in your page).
74
+ return { 'Content-Security-Policy': csp, 'X-Frame-Options': 'DENY', 'Cross-Origin-Opener-Policy': 'same-origin', 'Referrer-Policy': 'no-referrer', 'X-Content-Type-Options': 'nosniff' }
75
+ }
76
+
77
+ /** A source of the core's files: a folder (a checkout's spaces/public) or an SDK release URL, checked against its manifest. */
78
+ export function folderSource(dir) {
79
+ return {
80
+ label: dir,
81
+ read: async (f) => {
82
+ if (f === WORKER_SRC && !existsSync(join(dir, f))) throw new Error(`vault-kit: ${join(dir, f)} is missing — it is generated: run \`node tools/build-verified-workers.mjs ${dir}\` first`)
83
+ return readFileSync(join(dir, f), 'utf8')
84
+ },
85
+ }
86
+ }
87
+ export async function releaseSource(base, { fetchImpl = (...a) => fetch(...a), pin = '' } = {}) {
88
+ const root = String(base).replace(/\/*$/, '/')
89
+ const mr = await fetchImpl(root + 'manifest.json')
90
+ if (!mr.ok) throw new Error(`vault-kit: no SDK release at ${root} (manifest.json: HTTP ${mr.status})`)
91
+ // The manifest comes from the same host as the files, so checking a file against it catches corruption, not a host
92
+ // that was taken over. `pin` (--manifest-sha) is the stronger check: the manifest's own sha384, published in the docs
93
+ // for each release — a manifest that is not that one is refused (security review, 2026-10-15).
94
+ const text = await mr.text()
95
+ const manifestSha = sri(text)
96
+ if (pin && pin !== manifestSha) throw new Error(`vault-kit: the manifest at ${root} is not the one you pinned (${manifestSha} ≠ ${pin}) — refusing to build from it`)
97
+ const manifest = JSON.parse(text)
98
+ return {
99
+ label: `${root} (SDK ${manifest.version})`, version: manifest.version, manifestSha, pinned: !!pin,
100
+ read: async (f) => {
101
+ const want = manifest.files && manifest.files[f]
102
+ if (!want) throw new Error(`vault-kit: ${f} is not in SDK ${manifest.version} — this release has no vault kit; use a newer one`)
103
+ const r = await fetchImpl(root + f)
104
+ if (!r.ok) throw new Error(`vault-kit: ${root + f}: HTTP ${r.status}`)
105
+ const body = await r.text()
106
+ if (sri(body) !== want) throw new Error(`vault-kit: ${f} does not match the release's manifest — refusing to build from it`)
107
+ return body
108
+ },
109
+ }
110
+ }
111
+
112
+ async function closureOf(entries, read) {
113
+ const seen = new Map(), queue = [...entries]
114
+ while (queue.length) {
115
+ const f = queue.shift()
116
+ if (seen.has(f)) continue
117
+ const src = stampSdkAuth((await read(f)).split(STAMP).join(''))
118
+ seen.set(f, src)
119
+ for (const m of src.matchAll(SPEC)) queue.push(m[1])
120
+ }
121
+ return seen
122
+ }
123
+
124
+ // THE VAULT LOADS ONLY PINNED SCRIPTS (the owner, 2026-11-14: "Do it now" — docs/vault-core-convergence-review.md § 5). Every script
125
+ // of the vault (core/, vault.js, screens.js, any module of yours in this folder) is named in an import map with its sha384, and the
126
+ // page's own policy admits no inline script but that map (by its hash). A file changed on the host
127
+ // after the kit ran — core/ or yours — is refused by the browser and the vault does not start. The KEY WORKER is no longer a file the
128
+ // browser fetches: its source is one of those pinned modules (core/l1-worker-src.js) and runs from memory (vcWorker.js), so
129
+ // `worker-src` needs `blob:`. A browser without import-map integrity runs the same files unchecked.
130
+ export const WORKER_SRC = 'l1-worker-src.js'
131
+ export const PAGE_MARK = '<!-- witbitz vault kit: pinned page -->'
132
+ function legacyPage(brand) { // what kits before the pinned page wrote once — replaced without a copy, it is ours
133
+ return `<!doctype html>
134
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
135
+ <title>${String(brand).replace(/[<&>"]/g, '')}</title>
136
+ <style>html,body{margin:0;height:100%;background:#fff}@media (prefers-color-scheme:dark){html,body{background:#111}}</style>
137
+ </head><body><script type="module" src="/vault.js"></script></body></html>
138
+ `
139
+ }
140
+ /** The page, with `integrity` ({ '/path.js': 'sha384-…' }) as its import map. → { html, policy } */
141
+ export function vaultPage(brand, integrity = {}) {
142
+ const map = JSON.stringify({ imports: {}, integrity: Object.fromEntries(Object.entries(integrity).sort(([a], [b]) => a.localeCompare(b))) }, null, 1)
143
+ // 'self' + the map's own hash: the import map is the page's one inline script; every file it loads is this host's, and each one the
144
+ // map names must match its sha384 or the browser refuses it. ('strict-dynamic' with hashes does not reach a module's imports.)
145
+ const policy = `script-src 'self' '${sha256(map)}'; worker-src 'self' blob:; object-src 'none'; base-uri 'self'`
146
+ const html = `<!doctype html>
147
+ ${PAGE_MARK}
148
+ <html lang="en"><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${policy}">
149
+ <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
150
+ <title>${String(brand).replace(/[<&>"]/g, '')}</title>
151
+ <style>html,body{margin:0;height:100%;background:#fff}@media (prefers-color-scheme:dark){html,body{background:#111}}</style>
152
+ <script type="importmap">${map}</script>
153
+ </head><body><script type="module" src="/vault.js"></script></body></html>
154
+ `
155
+ return { html, policy }
156
+ }
157
+ /** Every script in the vault folder a page may load (push-sw.js is a service worker — not a module, never in a map). */
158
+ function scriptsIn (root, readOut, listOut) {
159
+ const out = {}
160
+ for (const rel of listOut(root)) if (/\.m?js$/.test(rel) && rel !== 'push-sw.js') out['/' + rel] = sri(readOut(join(root, rel)))
161
+ return out
162
+ }
163
+ function walk (root, rel = '') {
164
+ const out = []
165
+ for (const n of readdirSync(join(root, rel))) {
166
+ if (n === 'node_modules' || n.startsWith('.')) continue
167
+ const r = rel ? rel + '/' + n : n
168
+ if (statSync(join(root, r)).isDirectory()) out.push(...walk(root, r)); else out.push(r)
169
+ }
170
+ return out
171
+ }
172
+
173
+ const sib = (f) => `'./${f}'` // written so the release tool's import scan does not take the template for an import of its own
174
+ /** push-sw.js — the vault's service worker, at its ROOT (a worker's scope is its folder): notifications only, over the shared
175
+ * core every Witbitz app's worker uses (core/sw-notif-core.js — the sealed preview opened with the room's notification key
176
+ * the vault's own key worker keeps, the tap routed to the open window). Ours, like core/: a re-run of the kit replaces it.
177
+ * Registered only by a vault started with `push: true`, once the person turns notifications on. */
178
+ export function pushWorker({ brand = 'this app' } = {}) {
179
+ const b = JSON.stringify(String(brand || 'this app').slice(0, 60))
180
+ return `// push-sw.js — this vault's notifications (vault-core.js \`push: true\`). Written by the Witbitz vault kit; a re-run replaces it.
181
+ importScripts('/core/sw-notif-core.js')
182
+ const BRAND = ${b}
183
+ self.addEventListener('install', () => self.skipWaiting())
184
+ self.addEventListener('activate', (e) => e.waitUntil(self.clients.claim()))
185
+ // no read of its own: the push carries the sealed preview (opened with the room's notification key), else the generic line
186
+ self.wbxWirePush({ describe: async () => null, generic: { title: BRAND, body: 'Something new in your Spaces — open ' + BRAND + ' to see it.' }, testBody: 'You’ll get a nudge here when someone posts in your Spaces.', intakeBody: 'Your assistant has a new message — open ' + BRAND + ' to read it.' })
187
+ // a tap: the open vault is focused and told the room (it tells your page: wb.vault.on('notifOpen')); none open → the vault at ?room=…&tap=1
188
+ self.wbxWireNotifClick({ coldUrl: (room) => (room ? '/?room=' + encodeURIComponent(room) + '&tap=1' : '/'), stashTap: false })
189
+ `
190
+ }
191
+
192
+ function vaultEntry({ page, tenant, brand, accent, endpoint, loginBase, appShare, lock, push, googleSignIn, authBroker }) {
193
+ return `// vault.js — YOUR vault's configuration. Edit freely; keep the call to startVault.
194
+ // The keys of every Space live in core/ (in a worker on this origin); your app page at PAGE never holds one.
195
+ import { startVault } from ${sib('core/vault-core.js')}
196
+ import { defaultScreens } from ${sib('screens.js')}
197
+
198
+ const PAGE = ${esc(page)} // your app — the only origin allowed to talk to this vault
199
+
200
+ startVault({
201
+ page: PAGE,
202
+ ${tenant ? `tenant: ${esc(tenant)}, // your tenant (public id): the Spaces this vault creates are yours, and your users' accounts are kept on the Witbitz account service as YOUR app's` : `// tenant: 't_…', // your tenant (public id): the Spaces this vault creates are yours, and your users' accounts are kept on the Witbitz account service as YOUR app's`}
203
+ // accountService: false, // keep NEW accounts on the old backup store, as before SDK 3.28; the service needs this vault's origin PROVEN on your tenant. Never turn it off once accounts are there (they could not be saved)
204
+ endpoint: ${esc(endpoint)},
205
+ loginBase: ${esc(loginBase)},${authBroker ? '\n authBroker: ' + esc(authBroker) + ',' : googleSignIn ? '\n googleSignIn: true,' : ''}
206
+ ${appShare ? `appShare: true, // you serve your app-half function at /api/appshare on this origin: split-key Spaces` : `// appShare: true, // serve your app-half function at /api/appshare on this origin, for split-key Spaces (createSpace({ key: 'split' }))`}
207
+ ${lock ? `lock: true, // your users may lock this vault with a passkey and encrypt its storage (your page opens the sheet: wb.vault.showLock())` : `// lock: true, // let your users lock this vault with a passkey and encrypt its storage (your page opens the sheet: wb.vault.showLock())`}
208
+ ${push ? `push: true, // your users may turn on notifications (your page asks: wb.vault.showNotifications(); the worker is push-sw.js)` : `// push: true, // let your users turn on notifications (your page asks: wb.vault.showNotifications(); the worker is push-sw.js)`}
209
+ brand: ${esc(brand || 'this app')}, // your name, on any screen a screens.js of yours does not have yet
210
+ screens: defaultScreens({ brand: ${esc(brand || 'this app')}${accent ? `, accent: ${esc(accent)}` : ''} }), // or your own: see screens.js
211
+ })
212
+ `
213
+ }
214
+
215
+ function readme({ page, vault, tenant, brand, endpoint, loginBase, authBroker }) {
216
+ const h = headersFor({ page, endpoint, loginBase, authBroker })
217
+ return `# ${brand || 'Your'} vault — a Witbitz vault kit
218
+
219
+ This folder is a vault: a small site you serve on **${vault}** that keeps the keys of every Space your users use, and
220
+ shows your app (**${page}**) inside it. Your app uses the Witbitz SDK in vault mode and never holds a key — not in its
221
+ memory, not in its storage, not in a link.
222
+
223
+ const wb = await Witbitz.inVault({ vault: '${vault}' }) // in your app page
224
+ const space = await wb.createSpace({ agent: { name: 'Assistant' } })
225
+ space.on('message', (m) => show(m))
226
+ await space.send('Hello')
227
+ await wb.vault.share(space) // the vault shows the invite link
228
+
229
+ ## What is yours, what is ours
230
+
231
+ | | |
232
+ |---|---|
233
+ | \`vault.js\` | yours — the configuration |
234
+ | \`screens.js\` | yours — sign-in, share, "didn't load". Restyle them or write your own (same functions, same promises) |
235
+ | \`index.html\`, \`space/index.html\` | ours — rewritten every run: they pin every script here by its sha384. **After you edit \`vault.js\`, \`screens.js\` or add a module, run the kit again** — it keeps your files and pins them; a file changed without that is refused by the browser |
236
+ | \`core/\` | ours — everything that touches a key. Don't edit it; re-run the kit tool to upgrade (it replaces only core/) |
237
+ | \`push-sw.js\` | ours — the notifications' service worker, used only with \`push: true\` in vault.js; a re-run replaces it |
238
+
239
+ Options in \`vault.js\` (or build flags): \`lock: true\` (\`--lock\`) lets your users lock the vault with a passkey and encrypt
240
+ its storage — your page opens the sheet with \`wb.vault.showLock()\`; \`push: true\` (\`--push\`) lets them turn on
241
+ notifications — \`wb.vault.showNotifications()\`. Off unless you turn them on.
242
+
243
+ ## Serving it
244
+
245
+ 1. Put the folder at the **root** of ${vault} (any static host: nginx, Caddy, Apache, a bucket, Cloudflare Pages).
246
+ 2. Send these headers on every response (HEADERS.md has them for nginx / Caddy / Apache):
247
+ ${Object.entries(h).map(([k, v]) => ` - \`${k}: ${v}\``).join('\n')}
248
+ 3. Your app page (${page}) must allow being framed by the vault: \`Content-Security-Policy: frame-ancestors ${vault}\`.
249
+ 4. ${tenant ? `Declare BOTH origins on your tenant (${tenant}): \`await admin.origins.declare(['${vault}', '${originOf(page)}'])\`.` : 'Declare both origins on your tenant (`admin.origins.declare([...])`) once you have one, so the Spaces this vault creates are yours.'}
250
+ The vault's worker makes the requests, so the server sees ${vault}.
251
+ **Prove the vault's origin** too (a file \`${vault}/.well-known/witbitz-tenant.txt\` holding your tenant id, or a DNS TXT record —
252
+ \`admin.origins.declare\` answers how): your users' accounts are kept on the Witbitz account service as your app's, and the service
253
+ takes your tenant only from a proven origin. Until it is proven, new accounts stay on the old backup store.
254
+ 5. Split-key Spaces (\`createSpace({ key: 'split' })\`): serve your app-half function at \`${vault}/api/appshare\` — copy
255
+ the template in https://witbitz.chat/docs/sdk-keys.md#split-key — and build with \`--app-share\` (or set \`appShare: true\` in vault.js).
256
+
257
+ ## What it promises — and what it does not
258
+
259
+ The keys stay in this vault's origin; your app page, its code and every package it loads cannot read them or keep
260
+ them for later, and cannot reach a Space once it is removed here. Removing a Space, signing out and joining from a link
261
+ are confirmed by the person in this vault's screens, not by your page. Your app still shows the conversation, so it
262
+ sees what it displays. And because you host this vault too, it protects keys from your app's code — not from you.
263
+
264
+ Docs: https://witbitz.chat/docs/sdk-keys.md#vault-mode
265
+ `
266
+ }
267
+
268
+ function headersDoc(o) {
269
+ const h = headersFor(o)
270
+ return `# Headers for the vault
271
+
272
+ Send these on EVERY response of the vault origin.
273
+
274
+ \`\`\`text
275
+ ${Object.entries(h).map(([k, v]) => `${k}: ${v}`).join('\n')}
276
+ \`\`\`
277
+
278
+ ## nginx
279
+
280
+ \`\`\`nginx
281
+ location / {
282
+ ${Object.entries(h).map(([k, v]) => ` add_header ${k} "${v}" always;`).join('\n')}
283
+ try_files $uri $uri/ /index.html;
284
+ }
285
+ \`\`\`
286
+
287
+ ## Caddy
288
+
289
+ \`\`\`caddy
290
+ header {
291
+ ${Object.entries(h).map(([k, v]) => ` ${k} "${v}"`).join('\n')}
292
+ }
293
+ try_files {path} {path}/ /index.html
294
+ file_server
295
+ \`\`\`
296
+
297
+ ## Apache (.htaccess)
298
+
299
+ \`\`\`apache
300
+ ${Object.entries(h).map(([k, v]) => `Header always set ${k} "${v}"`).join('\n')}
301
+ FallbackResource /index.html
302
+ \`\`\`
303
+ `
304
+ }
305
+
306
+ const defaultWrite = (p, s) => { mkdirSync(dirname(p), { recursive: true }); writeFileSync(p, s) }
307
+ /** Build the kit into o.out from `source` (folderSource / releaseSource). → { files, kept, from } */
308
+ export async function buildKit(o, source, { write = defaultWrite, exists = existsSync, readOut = (p) => readFileSync(p, 'utf8'), listOut = walk } = {}) {
309
+ const opts = { endpoint: DEFAULTS.endpoint, loginBase: DEFAULTS.loginBase, ...o }
310
+ const core = await closureOf(['vault-core.js', 'sw-notif-core.js'], source.read) // sw-notif-core: a classic script push-sw.js imports (no ES import names it); vault-core names l1-worker-src.js (the pinned key worker)
311
+ if (!core.has(WORKER_SRC)) throw new Error(`vault-kit: the core has no ${WORKER_SRC} (the key worker's pinned source) — this release predates the pinned kit; use a newer one`)
312
+ if (core.get('sdkExports.js')?.includes('function saveOfflineReader')) write(join(opts.out, 'core', 'decrypt.html'), await source.read('decrypt.html'))
313
+ const hashes = {}
314
+ for (const [f, src] of core) {
315
+ const left = src.replace(PURE_NOTE, '').match(PLACEHOLDER) // a bundler's purity note (the key worker's bundle) is not a build placeholder
316
+ if (left) throw new Error(`vault-kit: ${f} still carries the build placeholder ${left[0]}`)
317
+ write(join(opts.out, 'core', f), src)
318
+ hashes['core/' + f] = sri(src)
319
+ }
320
+ // YOURS: written once, never over your edits — an upgrade replaces only core/
321
+ const kept = []
322
+ const once = async (f, s) => { if (exists(join(opts.out, f))) kept.push(f); else write(join(opts.out, f), typeof s === 'function' ? await s() : s) }
323
+ await once('screens.js', async () => (await source.read('vault-screens.js')).split(STAMP).join('').replace("'./acctV2UiCore.js'", "'./core/acctV2UiCore.js'"))
324
+ await once('vault.js', vaultEntry(opts))
325
+ write(join(opts.out, 'push-sw.js'), pushWorker(opts)) // OURS, like core/ (inert until a vault with `push: true` registers it)
326
+ let upgraded = false; try { upgraded = exists(join(opts.out, 'kit.json')) && !JSON.parse(readOut(join(opts.out, 'kit.json'))).pinned } catch { /* */ } // a kit from before the pinned page: its host's headers need the one change
327
+ // THE PAGE, LAST: it pins every script now in the folder — core/ just written, and the builder's own files as they are on disk
328
+ const pinned = scriptsIn(opts.out, readOut, listOut)
329
+ const { html, policy } = vaultPage(opts.brand || 'Vault', pinned)
330
+ const replaced = []
331
+ for (const f of ['index.html', 'space/index.html']) {
332
+ const p = join(opts.out, f)
333
+ if (exists(p)) { const cur = readOut(p); if (!cur.includes(PAGE_MARK) && cur !== legacyPage(opts.brand || 'Vault') && !exists(p + '.bak')) { write(p + '.bak', cur); replaced.push(f) } } // a page the builder changed: kept beside it
334
+ write(p, html)
335
+ }
336
+ write(join(opts.out, 'HEADERS.md'), headersDoc(opts))
337
+ write(join(opts.out, 'README.md'), readme(opts))
338
+ write(join(opts.out, 'kit.json'), JSON.stringify({ kit: 1, from: source.label, ...(source.version ? { sdk: source.version } : {}), ...(source.manifestSha ? { manifest: source.manifestSha } : {}), built: new Date().toISOString(), page: opts.page, vault: opts.vault, files: hashes, pinned, policy }, null, 2) + '\n')
339
+ return { files: core.size, kept, from: source.label, pinned: Object.keys(pinned).length, replaced, upgraded }
340
+ }
341
+
342
+ /** The command line. `localDir`: a checkout's spaces/public (tools/vault-kit.mjs passes it); else a release URL. */
343
+ export async function main(argv = process.argv.slice(2), { localDir = '' } = {}) {
344
+ const { o, err } = parseArgs(argv)
345
+ if (err.length) { console.error('vault-kit: need ' + err.join('; ') + '\n\n node vault-kit.mjs <outdir> --page https://app.acme.com/chat --vault https://vault.acme.com [--tenant t_…] [--brand Acme] [--from <release URL or folder>]'); process.exitCode = 2; return }
346
+ const from = o.from || localDir || (KIT_RELEASE !== 'dev' ? `https://witbitz.chat/sdk/${KIT_RELEASE}/` : DEFAULTS.from)
347
+ const source = /^https?:\/\//.test(from) ? await releaseSource(from, { pin: o.manifestSha }) : folderSource(from)
348
+ const r = await buildKit(o, source)
349
+ console.log(`vault-kit: ${o.out} — core ${r.files} files from ${r.from}${r.kept.length ? '; kept your ' + r.kept.join(', ') : ''}; ${r.pinned} scripts pinned in index.html — run the kit again after you edit one; read ${join(o.out, 'README.md')}`)
350
+ if (r.replaced.length) console.log(`vault-kit: ${r.replaced.join(', ')} had your changes — the kit writes these pages now (they pin your scripts); yours are kept as ${r.replaced.map((f) => f + '.bak').join(', ')}`)
351
+ if (r.upgraded) console.log("vault-kit: ⚠ this kit pins its scripts — update your host's headers from HEADERS.md once (script-src adds 'unsafe-inline', worker-src adds blob:), or the vault will not start")
352
+ if (source.manifestSha) console.log(`vault-kit: manifest ${source.manifestSha} — ${source.pinned ? 'matches your pin' : 'compare it with the one published for SDK ' + source.version + ' (https://witbitz.chat/docs/sdk-keys.md#vault-mode), or pass --manifest-sha to require it'}`)
353
+ }
354
+ if (typeof process !== 'undefined' && process.argv && import.meta.url === `file://${process.argv[1]}`) main().catch((e) => { console.error(String((e && e.message) || e)); process.exitCode = 1 })
@@ -0,0 +1,263 @@
1
+ // vault-screens.js — the DEFAULT screens of a builder-hosted vault (docs/sdk-vault-mode.md). A builder replaces any of
2
+ // them: each is a function vault-core.js calls with what it needs, and resolves when the person is done.
3
+ //
4
+ // signIn({ email, sendCode(email), verify(email, code) }) → resolves once verify() succeeded (or rejects: cancelled)
5
+ // share({ link, title }) → shows the invite link to copy / share; resolves when closed
6
+ // confirm({ title, text, ok, cancel }) → resolves true / false (removing a Space, signing out, joining one)
7
+ // recoveryCode({ code }) → shows the account's recovery code ONCE; resolves when the person is done
8
+ // restore({ email, restore({ code, email?, ticket?, emailCode? }) }) → takes a recovery code (and, where the backup's gate
9
+ // asks, the email and the code mailed to it); resolves once restored
10
+ // emailCode({ email, purpose }) → the code the Witbitz account service emailed to `email` (a new account,
11
+ // signing out other devices, a new recovery code, deleting the account —
12
+ // `purpose`: 'create' | 'signout' | 'newcode' | 'delete'); with no `email`,
13
+ // asks for the address and resolves THAT. Rejects: cancelled
14
+ // siriKey({ key, endpoint }) → shows the Siri Shortcut's key to put in the Shortcut; resolves when done
15
+ // peerToken({ name, token, cardUrl, mcpUrl }) → shows an outside agent's token ONCE (with the assistant's address); resolves when done
16
+ // failed({ page }) → the page did not load
17
+ // ready() → the page said hello (hide a splash, if you drew one)
18
+ // lockUi() → ONLY for a vault started with `lock: true`: puts the lock screen and
19
+ // the lock sheet in the page, hidden. Yours may restyle them freely, but
20
+ // keep the element ids (spaceLock.js drives them): #lockscreen
21
+ // (#unlockBtn #lockErr #lockReset, and a <p> it words) · #lockset
22
+ // (#lockToggle #lockOn #lockOff #lockAuto #lockProtect #lockProtectMsg
23
+ // #lockMsg #lockDesc #lockToggleLbl #lockClose)
24
+ //
25
+ // Plain DOM, no framework, styles scoped under .wbv- so a builder's own CSS is not disturbed. Text is set with
26
+ // textContent — an email or a title is never parsed as HTML.
27
+
28
+ const CSS = `
29
+ .wbv-scrim{position:fixed;inset:0;z-index:2147483000;background:rgba(0,0,0,.38);display:flex;align-items:center;justify-content:center;padding:16px;font:15px/1.4 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif}
30
+ .wbv-card{width:min(420px,100%);background:var(--wbv-bg,#fff);color:var(--wbv-fg,#111);border-radius:22px;padding:22px 20px 18px;box-shadow:0 12px 40px rgba(0,0,0,.25);display:flex;flex-direction:column;gap:12px}
31
+ .wbv-card h2{margin:0;font-size:19px;font-weight:650}
32
+ .wbv-card p{margin:0;color:var(--wbv-muted,#666)}
33
+ .wbv-card input{font:inherit;font-size:16px;padding:12px 14px;border-radius:12px;border:1px solid var(--wbv-line,#ddd);background:var(--wbv-field,#f6f6f6);color:inherit;width:100%;box-sizing:border-box}
34
+ .wbv-row{display:flex;gap:8px;justify-content:flex-end}
35
+ .wbv-btn{font:inherit;font-weight:600;border:0;border-radius:999px;padding:10px 18px;cursor:pointer;background:var(--wbv-field,#eee);color:inherit}
36
+ .wbv-btn.wbv-go{background:var(--wbv-accent,#111);color:#fff}
37
+ .wbv-err{color:#d33;min-height:1.2em;font-size:14px}
38
+ @media (prefers-color-scheme: dark){.wbv-card{--wbv-bg:#262626;--wbv-fg:#f2f2f2;--wbv-muted:#aaa;--wbv-line:#3a3a3a;--wbv-field:#333}}
39
+ .wbv-lock{background:var(--wbv-cover,#f2f2f2)}
40
+ @media (prefers-color-scheme: dark){.wbv-lock{--wbv-cover:#111}}
41
+ .wbv-card label{display:flex;gap:10px;align-items:center}
42
+ .wbv-card input[type=checkbox]{width:auto;padding:0}
43
+ .wbv-card select{font:inherit;padding:8px 10px;border-radius:10px;border:1px solid var(--wbv-line,#ddd);background:var(--wbv-field,#f6f6f6);color:inherit}
44
+ .wbv-sw{min-width:52px}.wbv-sw[aria-checked=true]{background:var(--wbv-accent,#111);color:#fff}
45
+ `
46
+ let styled = false
47
+ const style = (accent) => {
48
+ if (!styled) { const s = document.createElement('style'); s.textContent = CSS; document.head.append(s); styled = true }
49
+ if (accent) document.documentElement.style.setProperty('--wbv-accent', accent)
50
+ }
51
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }
52
+ function card(title, sub) {
53
+ const scrim = el('div', 'wbv-scrim'), c = el('div', 'wbv-card')
54
+ c.setAttribute('role', 'dialog'); c.setAttribute('aria-modal', 'true')
55
+ c.append(el('h2', '', title)); if (sub) c.append(el('p', '', sub))
56
+ scrim.append(c); document.body.append(scrim)
57
+ return { scrim, c, close: () => scrim.remove() }
58
+ }
59
+
60
+ /** The default screens, in your brand. @param {{ brand?: string, accent?: string }} [o] */
61
+ export function defaultScreens({ brand = 'this app', accent = '' } = {}) {
62
+ style(accent)
63
+ return {
64
+ signIn({ email = '', sendCode, verify, google }) {
65
+ return new Promise((resolve, reject) => {
66
+ const { c, close } = card('Sign in to ' + brand, 'We email you a six-digit code.')
67
+ const input = el('input'); input.type = 'email'; input.autocomplete = 'email'; input.placeholder = 'you@example.com'; input.value = email
68
+ const err = el('div', 'wbv-err')
69
+ if (typeof google === 'function') {
70
+ const button = el('button', 'wbv-btn', 'Continue with Google')
71
+ button.onclick = async () => { button.disabled = true; try { const result = await google(); close(); resolve(result) } catch { err.textContent = 'Google sign-in did not finish. Try again, or use your email.'; button.disabled = false } }
72
+ c.append(button)
73
+ }
74
+ const row = el('div', 'wbv-row'), cancel = el('button', 'wbv-btn', 'Cancel'), go = el('button', 'wbv-btn wbv-go', 'Email me a code')
75
+ row.append(cancel, go); c.append(input, err, row)
76
+ let addr = '', step = 'email'
77
+ cancel.onclick = () => { close(); reject(Object.assign(new Error('cancelled'), { code: 'sign_in_cancelled' })) }
78
+ go.onclick = async () => {
79
+ err.textContent = ''; go.disabled = true
80
+ try {
81
+ if (step === 'email') {
82
+ addr = input.value.trim()
83
+ await sendCode(addr)
84
+ step = 'code'; input.value = ''; input.type = 'text'; input.inputMode = 'numeric'; input.autocomplete = 'one-time-code'; input.placeholder = '6-digit code'
85
+ go.textContent = 'Sign in'
86
+ c.querySelector('p').textContent = 'We sent a code to ' + addr + '.'
87
+ } else {
88
+ await verify(addr, input.value.trim())
89
+ close(); resolve({ email: addr })
90
+ }
91
+ } catch (e) { err.textContent = step === 'email' ? 'Could not send a code to that address.' : 'That code did not work. Check it and try again.' }
92
+ go.disabled = false; input.focus()
93
+ }
94
+ input.onkeydown = (e) => { if (e.key === 'Enter') go.click() }
95
+ input.focus()
96
+ })
97
+ },
98
+ share({ link, title = '' }) {
99
+ return new Promise((resolve) => {
100
+ const { c, close } = card(title ? 'Invite to ' + title : 'Invite someone', 'Anyone with this link can join. Send it only to people you mean to.')
101
+ const input = el('input'); input.readOnly = true; input.value = link
102
+ const row = el('div', 'wbv-row'), done = el('button', 'wbv-btn', 'Done'), copy = el('button', 'wbv-btn wbv-go', 'Copy link')
103
+ row.append(done)
104
+ if (navigator.share) { const sh = el('button', 'wbv-btn', 'Share…'); sh.onclick = () => navigator.share({ url: link, title: title || brand }).catch(() => {}); row.append(sh) }
105
+ row.append(copy); c.append(input, row)
106
+ copy.onclick = async () => { try { await navigator.clipboard.writeText(link); copy.textContent = 'Copied' } catch { input.select() } }
107
+ done.onclick = () => { close(); resolve() }
108
+ })
109
+ },
110
+ confirm({ title, text = '', ok = 'OK', cancel = 'Cancel' }) {
111
+ return new Promise((resolve) => {
112
+ const { c, close } = card(title, text)
113
+ const row = el('div', 'wbv-row'), no = el('button', 'wbv-btn', cancel), yes = el('button', 'wbv-btn wbv-go', ok)
114
+ no.onclick = () => { close(); resolve(false) }
115
+ yes.onclick = () => { close(); resolve(true) }
116
+ row.append(no, yes); c.append(row); yes.focus()
117
+ })
118
+ },
119
+ recoveryCode({ code }) {
120
+ return new Promise((resolve) => {
121
+ const { c, close } = card('Your recovery code', 'Keep it somewhere safe — it is the only way to get your Spaces back on a new device. It is shown once.')
122
+ const box = el('input'); box.readOnly = true; box.value = code; box.style.fontFamily = 'ui-monospace,Menlo,monospace'; box.style.letterSpacing = '.06em'
123
+ const row = el('div', 'wbv-row'), copy = el('button', 'wbv-btn', 'Copy'), done = el('button', 'wbv-btn wbv-go', 'I saved it')
124
+ copy.onclick = async () => { try { await navigator.clipboard.writeText(code); copy.textContent = 'Copied' } catch { box.select() } }
125
+ done.onclick = () => { close(); resolve() }
126
+ row.append(copy, done); c.append(box, row)
127
+ })
128
+ },
129
+ emailCode({ email = '', purpose = '' }) {
130
+ return new Promise((resolve, reject) => {
131
+ const asksAddress = !email
132
+ const noCode = purpose === 'create' ? ' If this email already has a ' + brand + ' account, nothing is sent — restore it with your recovery code instead.' : ''
133
+ const { c, close } = card(asksAddress ? 'Your email' : 'Check your email', asksAddress ? 'The email address of your ' + brand + ' account. We’ll send it a code.' : 'We sent a 6-digit code to ' + email + '.' + noCode)
134
+ const input = el('input')
135
+ if (asksAddress) { input.type = 'email'; input.autocomplete = 'email'; input.placeholder = 'you@example.com' } else { input.inputMode = 'numeric'; input.autocomplete = 'one-time-code'; input.placeholder = '6-digit code' }
136
+ const row = el('div', 'wbv-row'), cancel = el('button', 'wbv-btn', 'Cancel'), go = el('button', 'wbv-btn wbv-go', asksAddress ? 'Send me a code' : 'Continue')
137
+ row.append(cancel, go); c.append(input, row)
138
+ cancel.onclick = () => { close(); reject(Object.assign(new Error('cancelled'), { code: 'cancelled' })) }
139
+ go.onclick = () => { const v = input.value.trim(); if (!v) { input.focus(); return } close(); resolve(v) }
140
+ input.onkeydown = (e) => { if (e.key === 'Enter') go.click() }
141
+ input.focus()
142
+ })
143
+ },
144
+ siriKey({ key }) {
145
+ return new Promise((resolve) => {
146
+ const { c, close } = card('Your Siri key', 'Put it in the Shortcut. Anyone who has it can send words into your Spaces — make a new one if it leaks.')
147
+ const box = el('input'); box.readOnly = true; box.value = key; box.style.fontFamily = 'ui-monospace,Menlo,monospace'
148
+ const row = el('div', 'wbv-row'), copy = el('button', 'wbv-btn', 'Copy'), done = el('button', 'wbv-btn wbv-go', 'Done')
149
+ copy.onclick = async () => { try { await navigator.clipboard.writeText(key); copy.textContent = 'Copied' } catch { box.select() } }
150
+ done.onclick = () => { close(); resolve() }
151
+ row.append(copy, done); c.append(box, row)
152
+ })
153
+ },
154
+ // an outside agent's token: what the agent presents as its bearer for as long as it lives — shown here, never to the page
155
+ // (sync sweep 2026-11-14 #3; the hosted vault does the same, vaultPeerTokens.js)
156
+ peerToken({ name = '', token, cardUrl = '', mcpUrl = '' }) {
157
+ return new Promise((resolve) => {
158
+ const { c, close } = card('Token for ' + (name || 'the outside agent'), 'Give it to the agent with your assistant\u2019s address. It is shown once — anyone who has it can message your assistant; remove the agent if it leaks.')
159
+ const field = (v) => { const b = el('input'); b.readOnly = true; b.value = v; b.style.fontFamily = 'ui-monospace,Menlo,monospace'; return b }
160
+ const box = field(token)
161
+ const row = el('div', 'wbv-row'), copy = el('button', 'wbv-btn', 'Copy token'), done = el('button', 'wbv-btn wbv-go', 'Done')
162
+ copy.onclick = async () => { try { await navigator.clipboard.writeText(token); copy.textContent = 'Copied' } catch { box.select() } }
163
+ done.onclick = () => { close(); resolve() }
164
+ row.append(copy, done)
165
+ c.append(box, ...[mcpUrl, cardUrl].filter(Boolean).map(field), row)
166
+ })
167
+ },
168
+ async securityKeys({ actions, address, getCode }) {
169
+ const { renderAdvanced } = await import('./acctV2UiCore.js')
170
+ const screens = this
171
+ return new Promise((resolve) => {
172
+ const { c, close } = card('Account security keys', address)
173
+ c.parentElement.style.zIndex = '2147481000'
174
+ const panel = el('div'), done = el('button', 'wbv-btn', 'Done')
175
+ c.append(panel, done)
176
+ const confirm = (q) => screens.confirm({ title: 'Account security keys', text: q.message, ok: q.confirmLabel, cancel: q.cancelLabel || 'Cancel' })
177
+ const notify = (message) => screens.confirm({ title: 'Account security keys', text: message, ok: 'OK', cancel: '' })
178
+ const render = () => { panel.replaceChildren(); renderAdvanced(panel, actions, address, render, { confirm, notify, getCode }) }
179
+ done.onclick = () => { close(); resolve() }
180
+ render()
181
+ })
182
+ },
183
+ emailMove({ move, address = '', moreTime, cancelMove }) {
184
+ return new Promise((resolve) => {
185
+ const { c, close } = card('Someone is moving your email address', 'Someone who can read ' + (address || 'your email') + ' asked to move it to a new, empty account. Your Spaces stay here, but this email will stop signing in to this account on ' + new Date(move.ready_at * 1000).toLocaleString() + '.')
186
+ const err = el('div', 'wbv-err'), row = el('div', 'wbv-row')
187
+ const later = el('button', 'wbv-btn', 'Not now'), cancel = el('button', 'wbv-btn wbv-go', 'Cancel the move'), more = el('button', 'wbv-btn', 'Ask for more time')
188
+ row.append(later, cancel); if (!move.objected) row.append(more); c.append(err, row)
189
+ later.onclick = () => { close(); resolve() }
190
+ const run = async (fn) => { for (const b of [later, cancel, more]) b.disabled = true; try { await fn(); close(); resolve() } catch (e) { err.textContent = e && e.code === 'cancelled' ? '' : 'Could not update the move. Try again.'; for (const b of [later, cancel, more]) b.disabled = false } }
191
+ cancel.onclick = () => run(cancelMove)
192
+ more.onclick = () => run(moreTime)
193
+ })
194
+ },
195
+ protectRecoveryEmail(args) { return this.restore({ ...args, purpose: 'protectEmail' }) },
196
+ restore({ email = '', restore, purpose = 'restore', signIn, signInLabel = 'Continue with Google or email' }) {
197
+ return new Promise((resolve, reject) => {
198
+ const moving = purpose === 'migrate', protecting = purpose === 'protectEmail', merging = purpose === 'mergeBackup'
199
+ const { c, close } = card(merging ? 'Verify your backup' : protecting ? 'Protect your backup' : moving ? 'Move your account' : 'Restore your Spaces', merging ? 'Enter your recovery code to merge the latest backup with the Spaces on this device.' : protecting ? 'Enter your recovery code to enroll ' + email + ' as its recovery email.' : moving ? 'Type this account’s recovery code. We’ll verify its recovery email, keep your Spaces and code, and sign out the other devices.' : 'Type your recovery code.')
200
+ const input = el('input'); input.placeholder = 'XXXX-XXXX-…'; input.autocomplete = 'off'
201
+ const err = el('div', 'wbv-err')
202
+ const row = el('div', 'wbv-row'), cancel = el('button', 'wbv-btn', 'Cancel'), go = el('button', 'wbv-btn wbv-go', merging ? 'Verify and save' : protecting ? 'Protect backup' : moving ? 'Move account' : 'Restore')
203
+ row.append(cancel, go); c.append(input, err, row)
204
+ let code = '', addr = email, ticket = '', step = 'code'
205
+ if (!moving && typeof signIn === 'function') {
206
+ const identity = el('button', 'wbv-btn', signInLabel)
207
+ c.insertBefore(identity, input)
208
+ identity.onclick = async () => { identity.disabled = true; try { addr = String(await signIn() || ''); identity.textContent = addr ? 'Signed in as ' + addr : signInLabel } catch { err.textContent = 'Sign-in did not finish. Try again.' } finally { identity.disabled = false } }
209
+ }
210
+ cancel.onclick = () => { close(); reject(Object.assign(new Error('cancelled'), { code: 'cancelled' })) }
211
+ const ask = (what, placeholder, type = 'text') => { step = what; input.value = ''; input.type = type; input.placeholder = placeholder; input.focus() }
212
+ go.onclick = async () => {
213
+ err.textContent = ''; go.disabled = true
214
+ try {
215
+ if (step === 'code') code = input.value.trim()
216
+ else if (step === 'email') addr = input.value.trim()
217
+ await restore(step === 'emailCode' ? { code, email: addr, ticket, emailCode: input.value.trim() } : { code, email: addr || undefined })
218
+ close(); resolve()
219
+ } catch (e) {
220
+ const k = e && e.code
221
+ if (k === 'email_required') { c.querySelector('p').textContent = 'This backup also needs the email it was set up with.'; ask('email', 'you@example.com', 'email') }
222
+ else if (k === 'email_code_required') { ticket = e.ticket || ''; c.querySelector('p').textContent = 'We emailed a code to ' + addr + '.'; ask('emailCode', '6-digit code') }
223
+ else err.textContent = k === 'bad_code' || k === 'not_found' ? 'That recovery code did not open a backup.' : k === 'email_code_wrong' ? 'That email code did not work.' : 'The backup could not be restored. Try again.'
224
+ }
225
+ go.disabled = false
226
+ }
227
+ input.onkeydown = (e) => { if (e.key === 'Enter') go.click() }
228
+ input.focus()
229
+ })
230
+ },
231
+ lockUi() {
232
+ if (document.getElementById('lockscreen')) return
233
+ const hidden = (n) => { n.style.display = 'none'; return n }
234
+ const withId = (n, id) => { n.id = id; return n }
235
+ // the LOCK SCREEN: opaque, over everything — the page is not framed (or is hidden) behind it
236
+ const scr = hidden(withId(el('div', 'wbv-scrim wbv-lock'), 'lockscreen')), c = el('div', 'wbv-card')
237
+ const reset = hidden(withId(el('button', 'wbv-btn', 'Start over'), 'lockReset'))
238
+ const rowL = el('div', 'wbv-row'); rowL.append(reset, withId(el('button', 'wbv-btn wbv-go', 'Unlock'), 'unlockBtn'))
239
+ c.append(el('h2', '', brand + ' is locked'), el('p', '', ''), withId(el('div', 'wbv-err'), 'lockErr'), rowL); scr.append(c)
240
+ // the LOCK SHEET: the switch, when it locks again, and "Also protect this device's storage"
241
+ const set = hidden(withId(el('div', 'wbv-scrim'), 'lockset')), s = el('div', 'wbv-card')
242
+ s.setAttribute('role', 'dialog'); s.setAttribute('aria-modal', 'true')
243
+ const head = el('div', 'wbv-row'); head.style.justifyContent = 'space-between'; head.style.alignItems = 'center'
244
+ const sw = withId(el('button', 'wbv-btn wbv-sw', ''), 'lockToggle'); sw.setAttribute('role', 'switch'); sw.setAttribute('aria-checked', 'false')
245
+ head.append(withId(el('h2', '', 'Lock'), 'lockToggleLbl'), sw)
246
+ const auto = withId(el('select'), 'lockAuto')
247
+ for (const [v, t] of [['0', 'only when it opens'], ['1', 'after 1 minute away'], ['5', 'after 5 minutes away'], ['15', 'after 15 minutes away'], ['60', 'after an hour away']]) { const o = el('option', '', t); o.value = v; auto.append(o) }
248
+ const lAuto = el('label', '', 'Lock '); lAuto.append(auto)
249
+ const box = withId(el('input'), 'lockProtect'); box.type = 'checkbox'
250
+ const lBox = el('label'); lBox.append(box, el('span', '', 'Also protect this device’s storage — your keys are encrypted until you unlock'))
251
+ const rowS = el('div', 'wbv-row'); rowS.append(hidden(withId(el('button', 'wbv-btn', 'Turn off'), 'lockOff')), hidden(withId(el('button', 'wbv-btn', 'Turn on'), 'lockOn')), withId(el('button', 'wbv-btn wbv-go', 'Done'), 'lockClose'))
252
+ s.append(head, withId(el('p', '', ''), 'lockDesc'), lAuto, lBox, withId(el('p', '', ''), 'lockProtectMsg'), withId(el('div', 'wbv-err'), 'lockMsg'), rowS); set.append(s)
253
+ document.body.append(scr, set)
254
+ },
255
+ failed({ page }) {
256
+ const { c } = card(brand + ' didn’t load', 'Check your connection and try again.')
257
+ const row = el('div', 'wbv-row'), again = el('button', 'wbv-btn wbv-go', 'Try again')
258
+ again.onclick = () => location.reload(); row.append(again); c.append(row)
259
+ void page
260
+ },
261
+ ready() {},
262
+ }
263
+ }