@witbitz/sdk 0.0.0-stage → 4.4.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 (236) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +221 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +228 -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/agentDoorTools.js +28 -0
  23. package/attestedBox.js +30 -0
  24. package/attestedRooms.js +78 -0
  25. package/awsKey.js +98 -0
  26. package/backupRecord.js +106 -0
  27. package/backupVault.js +97 -0
  28. package/blocks.js +115 -0
  29. package/blocksPush.js +64 -0
  30. package/browseSeal.js +103 -0
  31. package/cbor.js +225 -0
  32. package/changePush.js +75 -0
  33. package/chatLock.js +165 -0
  34. package/chatLockSw.js +13 -0
  35. package/cloudDeviceBuilds.js +11 -0
  36. package/cloudDevicePins.js +33 -0
  37. package/cloudDeviceSeal.js +53 -0
  38. package/codeAttachments.js +100 -0
  39. package/codeBrowse.js +224 -0
  40. package/codeCache.js +149 -0
  41. package/codeCloud.js +650 -0
  42. package/codeCloudKeys.js +112 -0
  43. package/codeCommands.js +167 -0
  44. package/codeComputers.js +389 -0
  45. package/codeEgress.js +123 -0
  46. package/codeFilesRoutes.js +17 -0
  47. package/codeFolders.js +116 -0
  48. package/codeHistory.js +76 -0
  49. package/codeLanguage.js +54 -0
  50. package/codeMkdir.js +8 -0
  51. package/codeModes.js +59 -0
  52. package/codeOrphanKeys.js +42 -0
  53. package/codeOutputs.js +141 -0
  54. package/codeProgress.js +54 -0
  55. package/codeRelay.js +505 -0
  56. package/codeSent.js +68 -0
  57. package/codeSentinel.js +86 -0
  58. package/codeSubagents.js +107 -0
  59. package/codeTransport.js +317 -0
  60. package/codeUndo.js +48 -0
  61. package/compress.js +24 -0
  62. package/config.js +11 -0
  63. package/connCatalog.js +164 -0
  64. package/connDisp.js +76 -0
  65. package/connOtherWays.js +74 -0
  66. package/connPending.js +16 -0
  67. package/connWrap.js +53 -0
  68. package/connectionEntry.js +89 -0
  69. package/connections.js +561 -0
  70. package/credits.js +30 -0
  71. package/csAttest.js +112 -0
  72. package/decrypt.html +384 -0
  73. package/deviceAttest.js +527 -0
  74. package/deviceCall.js +54 -0
  75. package/deviceKeyCore.js +41 -0
  76. package/deviceSeal.js +59 -0
  77. package/e2ee.js +323 -0
  78. package/eat.js +103 -0
  79. package/emailFork.js +275 -0
  80. package/emailSignIn.js +81 -0
  81. package/emptySpaces.js +111 -0
  82. package/encSource.js +55 -0
  83. package/enclaveAccept.js +214 -0
  84. package/enclaveClaim.js +241 -0
  85. package/enclaveRoute.js +102 -0
  86. package/enclaveSnapshotMerge.js +44 -0
  87. package/entrySig.js +165 -0
  88. package/env.js +73 -0
  89. package/eraseFile.js +58 -0
  90. package/followImage.js +86 -0
  91. package/healNames.js +45 -0
  92. package/idb.js +113 -0
  93. package/idbSeal.js +119 -0
  94. package/indexGone.js +12 -0
  95. package/invite.js +51 -0
  96. package/inviteEnroll.js +67 -0
  97. package/inviteSend.js +68 -0
  98. package/jobAgents.js +87 -0
  99. package/keptMerge.js +91 -0
  100. package/l1-worker-src.js +2 -0
  101. package/l1-worker.js +894 -0
  102. package/laneAssociation.js +68 -0
  103. package/laneConfig.js +58 -0
  104. package/laneLinkCore.js +177 -0
  105. package/ledgerView.js +64 -0
  106. package/manifest.json +239 -0
  107. package/mcpRecommended.js +25 -0
  108. package/memberChange.js +125 -0
  109. package/mirrorBatch.js +47 -0
  110. package/mkseal.js +101 -0
  111. package/nativePush.js +153 -0
  112. package/nitroVerify.js +220 -0
  113. package/noble-p256.js +27 -0
  114. package/notice.js +116 -0
  115. package/notifKey.js +58 -0
  116. package/offlineBundle.js +62 -0
  117. package/ohttp.js +177 -0
  118. package/opRouting.js +10 -0
  119. package/opencodeWire.js +282 -0
  120. package/oprf.js +70 -0
  121. package/ownAgentLink.js +96 -0
  122. package/ownerPolicy.js +117 -0
  123. package/package.json +273 -4
  124. package/pdfOptions.js +13 -0
  125. package/pdfText.js +107 -0
  126. package/pdfjs.mjs +28 -0
  127. package/pdfjs.worker.mjs +28 -0
  128. package/pollVerdict.js +33 -0
  129. package/prefetchPoll.js +60 -0
  130. package/protectedLocal.js +426 -0
  131. package/pushCore.js +42 -0
  132. package/recovery.js +107 -0
  133. package/regions.js +42 -0
  134. package/removedMessage.js +11 -0
  135. package/renameRefusal.js +9 -0
  136. package/replyQuote.js +34 -0
  137. package/reqEnvelope.js +126 -0
  138. package/roomDefaultPrefs.js +76 -0
  139. package/roomDelete.js +109 -0
  140. package/roomEmbed.js +111 -0
  141. package/roomName.js +177 -0
  142. package/roomPass.js +256 -0
  143. package/roomRoster.js +305 -0
  144. package/roomSettings.js +61 -0
  145. package/roomState.js +58 -0
  146. package/roomStreamClient.js +115 -0
  147. package/rosterCount.js +52 -0
  148. package/rosterHash.js +13 -0
  149. package/rowSchema.js +113 -0
  150. package/safeMedia.js +116 -0
  151. package/safeMediaPins.js +17 -0
  152. package/schedulesDoc.js +78 -0
  153. package/sdkA2A.js +524 -0
  154. package/sdkAccount.js +483 -0
  155. package/sdkAccountDoc.js +89 -0
  156. package/sdkAccountSections.js +332 -0
  157. package/sdkAgui.js +141 -0
  158. package/sdkAttest.js +34 -0
  159. package/sdkBackup.js +507 -0
  160. package/sdkBackupV2.js +630 -0
  161. package/sdkBrowserPrivate.js +28 -0
  162. package/sdkBuilds.js +208 -0
  163. package/sdkCloudDevice.js +221 -0
  164. package/sdkComputers.js +1009 -0
  165. package/sdkDictation.js +232 -0
  166. package/sdkErase.js +288 -0
  167. package/sdkExports.js +71 -0
  168. package/sdkInvitations.js +34 -0
  169. package/sdkKeptAgent.js +188 -0
  170. package/sdkLaneLink.js +205 -0
  171. package/sdkPlan.js +96 -0
  172. package/sdkProtect.js +228 -0
  173. package/sdkRedact.js +36 -0
  174. package/sdkRekey.js +340 -0
  175. package/sdkReport.js +68 -0
  176. package/sdkSafeMedia.js +255 -0
  177. package/sdkSchedules.js +39 -0
  178. package/sdkSpeech.js +71 -0
  179. package/sdkTemporaryRooms.js +123 -0
  180. package/sdkTurn.js +117 -0
  181. package/sdkVault.js +180 -0
  182. package/sealShare.js +18 -0
  183. package/sealedNames.js +64 -0
  184. package/sealedReceipt.js +17 -0
  185. package/sentinelRelease.js +155 -0
  186. package/shamir.js +85 -0
  187. package/sharedViews.js +52 -0
  188. package/sheetChrome.js +450 -0
  189. package/siri.js +278 -0
  190. package/spaceClient.js +1429 -0
  191. package/spaceConfig.js +81 -0
  192. package/spaceEmailGate.js +813 -0
  193. package/spaceExport.js +125 -0
  194. package/spaceFork.js +216 -0
  195. package/spaceLock.js +358 -0
  196. package/spacePasskey.js +180 -0
  197. package/spaceTemplates.js +99 -0
  198. package/speechOut.js +102 -0
  199. package/splitKeyClient.js +90 -0
  200. package/store.js +656 -0
  201. package/streamHint.js +36 -0
  202. package/sttCloud.js +220 -0
  203. package/sttWorklet.js +38 -0
  204. package/sw-notif-core.js +540 -0
  205. package/tempList.js +48 -0
  206. package/tinfoilVerifier.js +78 -0
  207. package/toolBooks.js +31 -0
  208. package/toolRules.js +52 -0
  209. package/turnCerts.js +254 -0
  210. package/turnFeed.js +58 -0
  211. package/turnVerdict.js +37 -0
  212. package/usageReceipts.js +176 -0
  213. package/usageSummary.js +90 -0
  214. package/util.js +181 -0
  215. package/vault-core.js +2326 -0
  216. package/vault-kit.mjs +354 -0
  217. package/vault-screens.js +261 -0
  218. package/vaultAtRest.js +208 -0
  219. package/vaultCoreLock.js +111 -0
  220. package/vaultCorePush.js +140 -0
  221. package/vaultDeviceKey.js +95 -0
  222. package/vaultEnclaveHandoff.js +114 -0
  223. package/vaultKeep.js +287 -0
  224. package/vaultSealedStore.js +77 -0
  225. package/vaultWorkerHost.js +117 -0
  226. package/vcWorker.js +34 -0
  227. package/voiceAttest.js +50 -0
  228. package/voiceCert.js +51 -0
  229. package/witbitz-admin.d.ts +135 -0
  230. package/witbitz-admin.js +529 -0
  231. package/witbitz-admin.mjs +1460 -0
  232. package/witbitz-sdk.d.ts +1197 -0
  233. package/witbitz-sdk.js +4258 -0
  234. package/workerClient.js +16 -0
  235. package/workerLiveness.js +21 -0
  236. package/x509.js +218 -0
package/vaultAtRest.js ADDED
@@ -0,0 +1,208 @@
1
+ // vaultAtRest.js — what the BUILDERS' vault (vault-core.js) keeps on disk carries no room key in the clear
2
+ // (docs/sdk-vault-mode.md § At rest; the owner, 2026-11-13, decision 5 of docs/vault-core-convergence-review.md).
3
+ //
4
+ // The vault keeps, in its own origin's localStorage: the room list (`wbvault:rooms`, one invite link per Space — the link IS
5
+ // the key: `#mk=` or a split room's half `#us=`), and the account backup's state per account (`wbvault:backup` — its master
6
+ // opens every key, its rooms carry links and keys). Both were plain JSON. Here:
7
+ // · a room entry keeps its link WITHOUT the key (`href`, the `mk=` / `us=` values emptied in place, every other mark kept) and
8
+ // the key SEALED beside it (`ks`); the link is rebuilt, byte for byte, when it is loaded into the vault's memory;
9
+ // · a backup state is sealed whole, per account; another account's entry is carried over as it is (another tab's write).
10
+ // Sealed under `key`, an AES-GCM CryptoKey (deviceSeal.js does the sealing): by default a NON-EXTRACTABLE key this vault makes
11
+ // once and keeps in its origin's IndexedDB (`deviceWrapKey`). That is the at-rest level the key worker's own IndexedDB has
12
+ // on an unprotected device — a copy of the localStorage alone, a sync of it, a search of it for `#mk=`, finds no key; a copy
13
+ // of the whole browser profile still does. Against that, the person's passkey lock (vaultProtect.js) is the answer.
14
+ //
15
+ // Read-through, never a destructive switch: an entry an older vault wrote (`link`, clear) is read as it is and written back
16
+ // sealed; an entry no key here opens is KEPT, keyless (the backup refills its link); with no key at all (no IndexedDB: an
17
+ // iPhone in Lockdown Mode, a private window that refuses it) the list is written as before — a key is never lost for want
18
+ // of a seal.
19
+ import { seal, open, isSealed } from './deviceSeal.js'
20
+
21
+ const SECRET = /([#&])(mk|us)=([^&]*)/g // the fragment params that ARE a key (or a split room's half of one)
22
+
23
+ /** `…#mk=K&gate=email` → { href: '…#mk=&gate=email', secret: { mk: 'K' } }; null when the link carries no key. */
24
+ export function splitLink (link) {
25
+ if (typeof link !== 'string' || !link.includes('#')) return null
26
+ const i = link.indexOf('#'), head = link.slice(0, i), frag = link.slice(i)
27
+ const secret = {}
28
+ const keyless = frag.replace(SECRET, (_, sep, name, v) => { if (v) secret[name] = v; return sep + name + '=' })
29
+ return Object.keys(secret).length ? { href: head + keyless, secret } : null
30
+ }
31
+ /** The inverse of splitLink: each emptied key param gets its value back, in place. */
32
+ export function joinLink (href, secret) {
33
+ return String(href).replace(/([#&])(mk|us)=(?=&|$)/g, (m, sep, name) => (secret && typeof secret[name] === 'string' ? sep + name + '=' + secret[name] : m))
34
+ }
35
+
36
+ /** The vault's own sealing key: a non-extractable AES-GCM key kept in this origin's IndexedDB, made once (the first of two
37
+ * tabs to make it wins: `add`, then read back). null when there is no IndexedDB to keep it in.
38
+ * ⛔ A READ THAT FAILED IS NOT "NO KEY" (sync sweep 2026-11-15 #3; our vault's 12a425b16, the owner's iPhone 11-14): iOS fails an
39
+ * IndexedDB open now and then. Every error answered null, the vault ran with no key, the sealed backup state read as "off", and
40
+ * turning backup on made a new master and code. Now a failed read is tried again, and one that keeps failing THROWS
41
+ * (code `device_key_unreadable`) — the caller asks the person, it never runs keyless over sealed data. */
42
+ const WRAP_RETRY_MS = [150, 400, 900]
43
+ export async function deviceWrapKey ({ idb = (typeof indexedDB !== 'undefined' ? indexedDB : null), name = 'wbvault-at-rest', wait = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {
44
+ if (!idb || !(globalThis.crypto && crypto.subtle)) return null
45
+ let last = null
46
+ for (let i = 0; i <= WRAP_RETRY_MS.length; i++) {
47
+ if (i) await wait(WRAP_RETRY_MS[i - 1])
48
+ try { return await wrapKeyOnce(idb, name) } catch (e) { last = e }
49
+ }
50
+ throw Object.assign(new Error('this vault\'s saved data could not be opened (' + String((last && (last.name || last.message)) || last || 'IndexedDB') .slice(0, 120) + ')'), { code: 'device_key_unreadable' })
51
+ }
52
+ async function wrapKeyOnce (idb, name) {
53
+ let db = null
54
+ try {
55
+ db = await new Promise((res, rej) => { const r = idb.open(name, 1); r.onupgradeneeded = () => r.result.createObjectStore('k'); r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error) })
56
+ const get = () => new Promise((res, rej) => { const q = db.transaction('k', 'readonly').objectStore('k').get('wrap'); q.onsuccess = () => res(q.result || null); q.onerror = () => rej(q.error) })
57
+ let k = await get()
58
+ if (!k) {
59
+ const made = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])
60
+ await new Promise((res) => { const t = db.transaction('k', 'readwrite'); t.objectStore('k').add(made, 'wrap'); t.oncomplete = res; t.onabort = res; t.onerror = (e) => { try { e.preventDefault() } catch { /* */ } } })
61
+ k = await get()
62
+ }
63
+ if (k && k.type === 'secret') return k
64
+ throw Object.assign(new Error('no usable key in IndexedDB'), { name: 'NoKey' })
65
+ } finally { try { db && db.close() } catch { /* */ } }
66
+ }
67
+
68
+ const read = (st, k) => { try { const v = st.getItem(k); return v ? JSON.parse(v) : null } catch { return null } }
69
+ 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 */ } }
70
+ const isState = (x) => !!(x && typeof x === 'object' && !Array.isArray(x) && typeof x.master === 'string')
71
+
72
+ /** @param {{ storage: Storage, key: CryptoKey|null }} o */
73
+ /** Does this storage hold anything sealed — a room's key, an account's backup state? A vault with NO key (no IndexedDB this launch)
74
+ * must not run over it: it would read the backup as off (sync sweep 11-18; our vault asks there too). */
75
+ export function holdsSealed (storage, { rooms, backup } = {}) {
76
+ const list = rooms ? read(storage, rooms) : null
77
+ if (Array.isArray(list) && list.some((e) => e && isSealed(e.ks))) return true
78
+ const b = backup ? read(storage, backup) : null
79
+ return !!(b && typeof b === 'object' && !Array.isArray(b) && Object.values(b).some((v) => isSealed(v)))
80
+ }
81
+
82
+ export function createAtRest ({ storage, key, currentRoom = () => true }) {
83
+ let chain = Promise.resolve()
84
+ const onDisk = (fn) => { const p = chain.then(fn); chain = p.catch(() => {}); return p }
85
+ const sealedOf = new Map()
86
+ const snapshots = new Map()
87
+ const signature = rows => new Map(rows.map(r => [r.room, JSON.stringify(r)])) // room → { secret (JSON), ks } — an unchanged key is not sealed again on every save
88
+ // ⛔ AN ENTRY THIS KEY CANNOT OPEN (another key's, or no key at all: IndexedDB failed at start) is carried over AS IT IS on every
89
+ // save — read as keyless and written as `rest`, the next save erased its sealed key for good (review, 2026-11-13).
90
+ const unopened = new Map() // room → { href, ks }
91
+
92
+ async function entryOut (r) {
93
+ const { link, mk, ...rest } = r
94
+ if (link === undefined && unopened.has(r.room)) { const u = unopened.get(r.room); return { ...rest, href: u.href, ks: u.ks } }
95
+ const s = key ? splitLink(link) : null
96
+ if (!s) return link === undefined ? rest : { ...rest, link } // no key here (or a keyless link): as before
97
+ if (mk && s.secret.us) s.secret.whole = mk
98
+ const sj = JSON.stringify(s.secret), had = sealedOf.get(r.room)
99
+ const ks = had && had.secret === sj ? had.ks : await seal(key, s.secret)
100
+ sealedOf.set(r.room, { secret: sj, ks })
101
+ return { ...rest, href: s.href, ks }
102
+ }
103
+ async function entryIn (e) {
104
+ if (!e || typeof e !== 'object' || typeof e.room !== 'string') return null
105
+ const { href, ks, ...rest } = e
106
+ if (!isSealed(ks)) return { ...rest } // an older vault's entry (`link` in it), or a keyless one
107
+ let secret = null
108
+ try { secret = key ? await open(key, ks) : null } catch { secret = null }
109
+ if (!secret || typeof secret !== 'object') { unopened.set(e.room, { href, ks }); return { ...rest } } // sealed under a key this vault does not have: keyless in memory, kept as it is on disk
110
+ unopened.delete(e.room)
111
+ sealedOf.set(e.room, { secret: JSON.stringify(secret), ks })
112
+ return { ...rest, link: joinLink(href, secret), ...(secret.us && secret.whole ? { mk: secret.whole } : {}) }
113
+ }
114
+ return {
115
+ /** The room list, links whole (in memory only). An older clear list is written back sealed at once. */
116
+ async loadRooms (k) {
117
+ const raw = read(storage, k)
118
+ const list = Array.isArray(raw) ? raw : []
119
+ const out = (await Promise.all(list.map(entryIn))).filter(Boolean)
120
+ snapshots.set(k, signature(out))
121
+ if (key && list.some((e) => e && typeof e.link === 'string' && splitLink(e.link))) this.saveRooms(k, out)
122
+ return out
123
+ },
124
+ /** Write the list — the links' keys sealed. In the order called; resolves once this one is on disk. */
125
+ saveRooms (k, rooms, strict = false, replaceAll = false) {
126
+ const snap = (Array.isArray(rooms) ? rooms : []).map((r) => ({ ...r }))
127
+ return onDisk(async () => {
128
+ const encoded = await Promise.all(snap.map(entryOut))
129
+ const next = signature(snap)
130
+ const commit = () => {
131
+ const previous = snapshots.get(k)
132
+ const disk = read(storage, k)
133
+ const rows = new Map((Array.isArray(disk) ? disk : []).filter(currentRoom).map(r => [r.room, r]))
134
+ if (replaceAll || !previous) rows.clear()
135
+ else for (const [room, baseline] of previous) {
136
+ if (!next.has(room) && rows.get(room)?.forgetMark === JSON.parse(baseline).forgetMark) rows.delete(room)
137
+ }
138
+ for (const row of encoded) {
139
+ if (!currentRoom(row)) continue
140
+ const old = rows.get(row.room)
141
+ const migrating = key && old?.link && row.ks
142
+ if (replaceAll || !previous || previous.get(row.room) !== next.get(row.room) || migrating) rows.set(row.room, row)
143
+ }
144
+ const list = [...rows.values()]
145
+ const raw = JSON.stringify(list)
146
+ try {
147
+ storage.setItem(k, raw)
148
+ if (storage.getItem(k) !== raw) throw new Error('vault room list was not saved')
149
+ snapshots.set(k, next)
150
+ } catch (error) { if (strict) throw error }
151
+ }
152
+ const locks = globalThis.navigator?.locks
153
+ if (locks) await locks.request('witbitz:room-registry:' + k, commit)
154
+ else commit()
155
+ })
156
+ },
157
+ /** Every account's backup state (the vault's `wbvault:backup` = { email: state }), opened. */
158
+ async loadBackups (k) {
159
+ const raw = read(storage, k)
160
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw) || 'master' in raw) return {}
161
+ const out = {}
162
+ let clear = false
163
+ for (const [email, v] of Object.entries(raw)) {
164
+ if (isState(v)) { out[email] = v; clear = true; continue } // an older vault's: read through
165
+ if (!isSealed(v) || !key) continue
166
+ try { const s = await open(key, v); if (isState(s)) out[email] = s } catch { /* another key's: left on disk, not ours to read */ }
167
+ }
168
+ if (clear && key) for (const [email, s] of Object.entries(out)) if (isState(raw[email])) this.putBackup(k, email, s)
169
+ return out
170
+ },
171
+ /** Move a matching signed-out email request to the signed-in account in one storage write. */
172
+ claimEmailMove(k, email) {
173
+ const owner = String(email || '').trim().toLowerCase()
174
+ return onDisk(async () => {
175
+ const before = read(storage, k), slot = before?.['']
176
+ if (!owner || !slot || before[owner]) return false
177
+ let draft = slot
178
+ if (isSealed(slot) && key) { try { draft = await open(key, slot) } catch { return false } }
179
+ if (!isState(draft) || !draft.v2?.resetDraft || String(draft.email || '').toLowerCase() !== owner) return false
180
+ const all = read(storage, k)
181
+ if (!all || all[owner] || JSON.stringify(all['']) !== JSON.stringify(slot)) return false
182
+ delete all['']
183
+ all[owner] = slot
184
+ storage.setItem(k, JSON.stringify(all))
185
+ return true
186
+ })
187
+ },
188
+ /** One account's state (null removes it); the other accounts' entries are carried over as they are on disk. */
189
+ putBackup (k, email, state) {
190
+ return onDisk(async () => {
191
+ const v = state == null ? null : key ? await seal(key, state) : state
192
+ const now = read(storage, k)
193
+ const all = now && typeof now === 'object' && !Array.isArray(now) && !('master' in now) ? now : {}
194
+ // ⛔ a sealed state THIS key cannot open (its master opens every room key in the account's backup) is never written over
195
+ // and lost: it is kept aside first, under `<k>:unopened` (review, 2026-11-13)
196
+ const was = all[email]
197
+ if (isSealed(was)) {
198
+ let ours = false; try { ours = !!(key && isState(await open(key, was))) } catch { ours = false }
199
+ if (!ours) { const aside = read(storage, k + ':unopened'); write(storage, k + ':unopened', { ...(aside && typeof aside === 'object' && !Array.isArray(aside) ? aside : {}), [email]: was }) }
200
+ }
201
+ if (v == null) delete all[email]; else all[email] = v
202
+ write(storage, k, all)
203
+ })
204
+ },
205
+ /** Resolves once every write made so far is on disk. */
206
+ flushed: () => chain,
207
+ }
208
+ }
@@ -0,0 +1,111 @@
1
+ // vaultCoreLock.js — THE LOCK AND DEVICE STORAGE PROTECTION of a builders' vault (vault-core.js; docs/sdk-vault-mode.md § The lock;
2
+ // the owner, 2026-11-13: "Do all including #5"). Loaded ONLY for a vault started with `lock: true` — a vault without it never
3
+ // fetches this file, nor anything it imports — and on only once the PERSON turns it on, in the vault's own sheet
4
+ // (wb.vault.showLock()): first the lock (a passkey covers the page at every launch), then "Also protect this device's storage".
5
+ //
6
+ // Nothing here is new machinery: it is our own vault's (vault-loader.js vaultProtectHooks), wired for this one:
7
+ // spaceLock.js the lock, its sheet, the passkey ceremonies, the write-ahead switch-on, Start over
8
+ // sdkProtect.js the protection passkey → the 32 device-key bytes (its own user handle; the SDK's wb.protect derives the same way)
9
+ // protectedLocal.js this origin's localStorage sealed under that key, under OPAQUE names — every `wbvault:*` entry included;
10
+ // only the lock config (`vault:lock`) stays readable, since the lock screen reads it before any passkey
11
+ // l1-worker.js the key worker seals its own store (seal / unseal / relock / unprotect), as it does in our vaults
12
+ // What this vault adds: it waits for the unlock BEFORE it reads anything or frames the page (`boot`), and a lock that engages
13
+ // while it runs (away too long) RELOADS it — the vault's memory holds every link, so the only lock that drops them is a new
14
+ // launch behind the lock screen.
15
+ import { makeLock } from './spaceLock.js'
16
+ import { enrollProtectKey, unlockProtectKey, webauthnPasskey } from './sdkProtect.js'
17
+ import { clearLocalForBuilderReset, installProtectedLocal, protectedLocalActive, protectedLocalReady, unlockProtectedLocal, relockProtectedLocal, unprotectProtectedLocal } from './protectedLocal.js'
18
+ import { BLOCKS_SW_KEY } from './blocksPush.js'
19
+ import { idb } from './idb.js'
20
+ import { migrateIdbProtection, armIdbProtection, moveToOpaqueNames, unprotectIdb, setIdbProtection } from './idbSeal.js' // the worker's IndexedDB: what it does not seal itself (a room's read position, cnt:) moves under opaque names too
21
+
22
+ export const resetMarker = 'witbitz-builder-reset-pending'
23
+ export async function finishBuilderReset () {
24
+ clearLocalForBuilderReset(resetMarker)
25
+ sessionStorage.clear()
26
+ if (typeof indexedDB === 'undefined') return false
27
+ const results = await Promise.all(['spaces', 'wbvault-at-rest', 'wbvault-acct'].map(name => new Promise(resolve => {
28
+ const q = indexedDB.deleteDatabase(name)
29
+ q.onsuccess = () => resolve(true)
30
+ q.onerror = q.onblocked = () => resolve(false)
31
+ })))
32
+ if (!results.every(Boolean)) return false
33
+ localStorage.removeItem(resetMarker)
34
+ return true
35
+ }
36
+
37
+ export const LOCK_KEY = 'vault:lock' // a name protectedLocal keeps clear (STAYS_CLEAR): read before any passkey
38
+
39
+ /**
40
+ * @param {object} o
41
+ * @param {string} o.brand the vault's name, in the sheet and on the passkeys
42
+ * @param {() => void} o.mountUi puts #lockscreen / #lockset in the page (screens.lockUi)
43
+ * @param {(why?: string) => void} o.hide hide the builder's page (the lock covers it)
44
+ * @param {() => void} o.show
45
+ * @param {(view: object) => void} [o.onState] the lock's state changed (→ the page, `ev:'lock'`)
46
+ * @param {(q: object) => Promise<boolean>} o.confirm the vault's confirm screen (Start over)
47
+ */
48
+ export function createVaultLock ({ brand = 'this app', mountUi, hide, show, onState, confirm, onUnprotected, beforeProtect, reload = () => location.reload() }) {
49
+ installProtectedLocal() // idempotent: its own import already switched it on, on a protected device
50
+ let raw = null, previews = false, workerCall = null, released = null, onReleased = null, running = false
51
+ const passkey = webauthnPasskey({ rpName: brand, userName: brand + ' — device protection' }) // never "Witbitz Spaces" in a builder's users' keychain
52
+ const lock = makeLock({
53
+ storeKey: LOCK_KEY,
54
+ appName: brand,
55
+ // a lock that ENGAGES while the vault runs (away too long — `why` is set; the sheet's own call passes none) restarts it behind the
56
+ // lock screen, protected or not: the vault's memory holds every link, and the page behind a mere cover kept calling (review)
57
+ cover: { onEngage: (why) => { hide(why); if (running && why) reload() }, onRelease: () => { show(); if (onReleased) { const f = onReleased; onReleased = null; f() } } },
58
+ onState: () => { try { onState && onState(view()) } catch { /* the page is gone */ } },
59
+ protect: {
60
+ enroll: async (label) => { const k = await enrollProtectKey(label, { passkey }); return { credId: k.credId, mode: k.mode, secret: k.raw } },
61
+ unlock: async (credId) => { const c = lock.cfg(); const k = await unlockProtectKey(credId, c.protect && c.protect.mode, { passkey }); return { credId: k.credId, secret: k.raw } },
62
+ // ON, in our vault's order: this origin's localStorage (protectedLocal moves every entry under an opaque name), the worker
63
+ // (a key arriving meanwhile is written sealed), then the rest of the worker's IndexedDB under opaque names
64
+ onProtect: async (secret, o) => { if (beforeProtect) await beforeProtect(); raw = secret; previews = !!(o && o.previews); if (!previews) await idb.del(BLOCKS_SW_KEY); await unlockProtectedLocal(secret, { switchOn: true }); if (workerCall) await workerCall({ t: 'seal', key: secret, previews }); await migrateIdbProtection(idb, secret) },
65
+ onUnlock: async (secret, o) => { raw = secret; previews = !!(o && o.previews); await unlockProtectedLocal(secret); await armIdbProtection(secret); moveToOpaqueNames(idb).catch(() => {}); if (workerCall) await workerCall({ t: 'unseal', key: secret, previews }) },
66
+ onPreviews: async (on) => { previews = !!on; if (!on) await idb.del(BLOCKS_SW_KEY); if (workerCall) await workerCall({ t: 'previews', on: previews }) },
67
+ // a lock that engages while the vault RUNS: start again behind the lock screen (the vault's memory holds the links). At a
68
+ // launch nothing was unlocked yet: nothing to drop, no reload.
69
+ onLock: () => { raw = null; relockProtectedLocal(); setIdbProtection({ active: true, key: null }); if (workerCall) workerCall({ t: 'relock' }).catch(() => {}) }, // the reload follows from the cover (onEngage), at a launch none
70
+ onUnprotect: async (secret) => { await unprotectProtectedLocal(secret); await unprotectIdb(idb, secret); if (workerCall) await workerCall({ t: 'unprotect', key: secret }); raw = null; try { if (onUnprotected) await onUnprotected() } catch { /* */ } },
71
+ // A PROTECTED device whose passkey is gone can never open its sealed copy: this origin starts over (the Spaces live in the
72
+ // account backup and the other devices)
73
+ startOver: async () => {
74
+ if (!(await confirm({ title: 'Start over on this device?', text: 'This copy can’t be unlocked anymore, so it will be cleared. Your Spaces stay in your account — restore them with your recovery code.', ok: 'Start over', cancel: 'Cancel' }).catch(() => false))) return
75
+ localStorage.setItem(resetMarker, '1')
76
+ reload()
77
+ },
78
+ },
79
+ })
80
+ const view = () => { const c = lock.cfg(); return { available: true, on: !!c.on, protect: !!(c.on && c.protect && c.protect.on) } }
81
+ return {
82
+ /** Before the vault reads anything: the lock screen at every launch while the lock is on; resolves once it is unlocked
83
+ * (on a protected device, once the passkey has opened this origin's storage). */
84
+ async boot () {
85
+ mountUi()
86
+ lock.wireVisibility()
87
+ if (!lock.cfg().on) { running = true; return } // turned on later in the sheet, it then engages while running
88
+ released = new Promise((res) => { onReleased = res })
89
+ lock.engage('launch')
90
+ if (lock.isLocked()) await released
91
+ if (protectedLocalActive()) await protectedLocalReady()
92
+ running = true
93
+ },
94
+ /** The worker exists: from now on the hooks reach it. */
95
+ setWorker (fn) { workerCall = fn },
96
+ /** What a NEW worker must hear before anything else (replayed at every start / restart): the device key, on a protected device. */
97
+ workerUnseal: () => (raw ? { t: 'unseal', key: raw, previews } : null),
98
+ previewsAllowed: () => !view().protect || previews,
99
+ /** The lock sheet — resolves with the lock's state when the person closes it. */
100
+ showSheet () {
101
+ return new Promise((resolve) => {
102
+ lock.showSheet(); show() // the sheet is a card over the page: only a real lock hides it
103
+ const cl = document.getElementById('lockClose')
104
+ const done = () => { if (cl) cl.removeEventListener('click', done); resolve(view()) }
105
+ if (cl) cl.addEventListener('click', done); else resolve(view())
106
+ })
107
+ },
108
+ view,
109
+ locked: () => lock.isLocked(),
110
+ }
111
+ }
@@ -0,0 +1,140 @@
1
+ // vaultCorePush.js — NOTIFICATIONS FROM A BUILDERS' VAULT (vault-core.js; docs/sdk-vault-mode.md § Notifications; the owner,
2
+ // 2026-11-13: "Do all including #5"). Loaded ONLY for a vault started with `push: true` — a vault without it never fetches this
3
+ // file — and on only once the PERSON says yes, in the vault's own card (wb.vault.showNotifications()).
4
+ //
5
+ // What it does is what our hosted vault does, with the same pieces: the browser's subscription with Witbitz's PUBLIC push key
6
+ // (config.js — the server signs every tickle with its private half), made the robust way (pushCore.js: the iOS lessons), then
7
+ // registered on each Space the vault holds through the vault's OWN key worker (`subscribe` / `unsubscribe` — never page ops).
8
+ // Witbitz's server already tickles every device a room lists, so nothing new runs there. The service worker is the kit's
9
+ // push-sw.js over the shared sw-notif-core.js: it opens the sealed preview with the room's notification key the key worker
10
+ // keeps in this origin's IndexedDB (generic text when the device's storage is protected), and routes a tap.
11
+ //
12
+ // The page learns { available, on } and, when a notification is tapped, which Space (`notifOpen`) — only one this vault holds.
13
+ import { swRegBounded, subscribeRobust } from './pushCore.js'
14
+ import { VAPID_PUBLIC_KEY } from './config.js'
15
+
16
+ export const PUSH_KEY = 'wbvault:push' // { on, endpoint, rooms: [the Spaces this device is listed on] } — this device's setting
17
+
18
+ /**
19
+ * @param {object} o
20
+ * @param {Storage} o.storage
21
+ * @param {(room: string, sub: object, quiet: boolean) => Promise<object>} o.subscribe through the vault's key worker
22
+ * @param {(room: string, sub: object) => Promise<object>} o.unsubscribe
23
+ * @param {(endpoint: string) => void} o.setSelf the key worker's turns skip this device (its own posts do not tickle it)
24
+ * @param {(room: string) => boolean} o.held
25
+ * @param {(room: string) => void} o.onOpen a tapped notification's Space (warm)
26
+ * @param {string} [o.worker] the service worker's path (default /push-sw.js, the kit's)
27
+ */
28
+ export function createVaultPush ({ storage, subscribe, unsubscribe, setSelf, held, onOpen, onChange = null, worker = '/push-sw.js', nav = (typeof navigator !== 'undefined' ? navigator : null), N = (typeof Notification !== 'undefined' ? Notification : null) }) {
29
+ const read = () => { try { const v = JSON.parse(storage.getItem(PUSH_KEY) || 'null'); return v && typeof v === 'object' ? v : { on: false } } catch { return { on: false } } }
30
+ const save = (v) => { try { storage.setItem(PUSH_KEY, JSON.stringify(v)) } catch { /* a full store: on for this session */ } }
31
+ let sub = null, chain = Promise.resolve()
32
+ // KNOWN: start() has finished (a subscription loaded, or found off / unsupported). Until then this device's endpoint is NOT KNOWN —
33
+ // the account service must not be told "none" (Codex sweep 2026-11-16 #2). `changed` runs after every change of it.
34
+ let readyOk = null
35
+ const ready = new Promise((r) => { readyOk = r })
36
+ const changed = () => { readyOk(); try { if (typeof onChange === 'function') onChange() } catch { /* */ } }
37
+ const serial = (fn) => { const p = chain.then(fn); chain = p.catch(() => {}); return p } // one change of the list at a time
38
+ const supported = () => !!(nav && nav.serviceWorker && N && typeof globalThis.PushManager !== 'undefined')
39
+ const view = () => ({ available: true, on: !!read().on })
40
+ const json = (s) => (s && typeof s.toJSON === 'function' ? s.toJSON() : s)
41
+ // what an unsubscribe names: the live subscription, else the endpoint this device was listed under (the server drops by endpoint) —
42
+ // a revoked permission or a missing worker must not leave every Space tickling a device that turned notifications off (review)
43
+ const named = (st) => (sub ? json(sub) : st && st.endpoint ? { endpoint: st.endpoint } : null)
44
+ // ⛔ A SPACE IS TAKEN OFF ITS LIST ONLY WHEN THE SERVER SAYS SO (review, 2026-11-13): a failed unsubscribe (offline) is kept in
45
+ // `off` and tried again at the next start — three starts, then it is let go (a Space whose key is gone can never be asked).
46
+ // → whether it is settled (taken off, or refused for good by the server).
47
+ const takeOff = async (room, s) => { const a = s ? await unsubscribe(room, s).catch(() => null) : null; return !!(a && a.status >= 200 && a.status < 500) }
48
+ const stillOff = (st, room) => { const off = (Array.isArray(st.off) ? st.off : []).filter((o) => o && o.room !== room); return [...off, { room, n: 0 }].slice(-200) }
49
+
50
+ // THE LIST, kept in step: every Space held is listed, a Space dropped is taken off — the vault calls it after each change
51
+ // `loud`: the first Space listed asks the server for its "Notifications are on" push — the person's proof it works, now
52
+ function sync (rooms, { loud = false } = {}) {
53
+ return serial(async () => {
54
+ let st = read(); if (!st.on || !sub) return
55
+ const want = new Set(rooms), had = new Set(Array.isArray(st.rooms) ? st.rooms : [])
56
+ for (const r of want) if (!had.has(r)) { const a = await subscribe(r, json(sub), !loud).catch(() => null); if (a && a.status === 200) { had.add(r); loud = false } }
57
+ for (const r of [...had]) if (!want.has(r)) { had.delete(r); if (!(await takeOff(r, json(sub)))) st = { ...st, off: stillOff(st, r) } }
58
+ save({ ...read(), rooms: [...had], ...(st.off ? { off: st.off } : {}) })
59
+ })
60
+ }
61
+ try { // a TAP on a warm vault: sw-notif-core focuses this window and posts the room
62
+ nav && nav.serviceWorker && nav.serviceWorker.addEventListener('message', (e) => {
63
+ const d = e && e.data
64
+ if (d && d.ch === 'notif-open' && typeof d.room === 'string' && d.room && held(d.room)) onOpen(d.room)
65
+ })
66
+ } catch { /* no service workers here */ }
67
+ return {
68
+ view,
69
+ sync,
70
+ endpoint: () => (sub ? sub.endpoint : ''),
71
+ /** Resolves once start() knows this device's endpoint (or that there is none). */
72
+ ready,
73
+ /** A Space about to be forgotten: off its list NOW, while the key worker still holds its key (after, the request has none). */
74
+ drop (room) {
75
+ return serial(async () => {
76
+ const st = read(), rs = Array.isArray(st.rooms) ? st.rooms : []
77
+ if (!rs.includes(room)) return
78
+ const done = await takeOff(room, named(st))
79
+ save({ ...read(), rooms: rs.filter((r) => r !== room), ...(done ? {} : { off: stillOff(read(), room) }) })
80
+ })
81
+ },
82
+ /** At start: a device that turned notifications on keeps its subscription (and the worker, its current bytes). */
83
+ async start (rooms) {
84
+ try { return await this._start(rooms) } finally { changed() } // known now, whatever the outcome
85
+ },
86
+ /** @private */
87
+ async _start (rooms) {
88
+ if (!read().on) return this._retryOff() // turned off with a list it could not reach: try those once more
89
+ if (!supported()) return
90
+ if (N.permission !== 'granted') { await this.disable(); return } // revoked in the browser's settings: off, and off every list (review)
91
+ await serial(async () => { // what an earlier unsubscribe could not reach, once more
92
+ const st = read(), s = named(st), off = []
93
+ for (const o of Array.isArray(st.off) ? st.off : []) if (o && !(await takeOff(o.room, s)) && o.n < 2) off.push({ room: o.room, n: o.n + 1 })
94
+ save({ ...read(), off })
95
+ })
96
+ try { await nav.serviceWorker.register(worker); const r = await subscribeRobust(await swRegBounded({ path: worker, sw: nav.serviceWorker }), VAPID_PUBLIC_KEY); sub = r.sub } catch { sub = null }
97
+ if (!sub) return
98
+ setSelf(sub.endpoint)
99
+ if (sub.endpoint !== read().endpoint) save({ ...read(), endpoint: sub.endpoint, rooms: [] }) // a new subscription: every Space lists it again
100
+ return sync(rooms)
101
+ },
102
+ /** On — call it right after the person's click (the permission prompt needs that gesture). */
103
+ async enable (rooms) {
104
+ if (!supported()) throw Object.assign(new Error('vault: this browser cannot receive notifications here'), { code: 'push_unavailable' })
105
+ const perm = N.permission === 'granted' ? 'granted' : await N.requestPermission()
106
+ if (perm !== 'granted') throw Object.assign(new Error('vault: notifications were not allowed'), { code: 'push_denied' })
107
+ await nav.serviceWorker.register(worker)
108
+ const reg = await swRegBounded({ path: worker, sw: nav.serviceWorker })
109
+ const r = await subscribeRobust(reg, VAPID_PUBLIC_KEY)
110
+ if (!r.sub) throw Object.assign(new Error('vault: the push service did not answer — ' + r.err), { code: 'push_unavailable' })
111
+ sub = r.sub; setSelf(sub.endpoint)
112
+ save({ on: true, endpoint: sub.endpoint, rooms: [] })
113
+ await sync(rooms, { loud: true })
114
+ changed()
115
+ return view()
116
+ },
117
+ /** Off: every Space takes this device off its list, then the subscription goes. */
118
+ async disable () {
119
+ await serial(async () => {
120
+ const st = read(), s = named(st), off = []
121
+ for (const r of [...(Array.isArray(st.rooms) ? st.rooms : []), ...(Array.isArray(st.off) ? st.off.map((o) => o && o.room) : [])].filter(Boolean)) if (!(await takeOff(r, s))) off.push({ room: r, n: 0 })
122
+ try { if (sub) await sub.unsubscribe() } catch { /* the push service forgets it on its own */ }
123
+ sub = null; setSelf('')
124
+ save(off.length && st.endpoint ? { on: false, endpoint: st.endpoint, off } : { on: false }) // what could not be reached is tried again at the next start
125
+ })
126
+ changed()
127
+ return view()
128
+ },
129
+ /** @private an OFF device's leftovers — the Spaces an earlier "off" could not reach (start() runs it while off) */
130
+ async _retryOff () {
131
+ await serial(async () => {
132
+ const st = read(); if (st.on || !Array.isArray(st.off) || !st.off.length) return
133
+ const off = []
134
+ for (const o of st.off) if (o && !(await takeOff(o.room, named(st))) && o.n < 2) off.push({ room: o.room, n: o.n + 1 })
135
+ save(off.length ? { ...st, off } : { on: false })
136
+ })
137
+ return view()
138
+ },
139
+ }
140
+ }
@@ -0,0 +1,95 @@
1
+ // THE HOSTED VAULT'S DEVICE STORAGE KEY (docs/vault-at-rest-and-invites-plan.md § 1, phase 1). 32 random bytes made once per vault
2
+ // origin and kept WRAPPED (AES-GCM) under a NON-extractable key in this origin's IndexedDB — the builders' vault's pattern
3
+ // (vaultAtRest.deviceWrapKey). At every launch the vault unwraps it with no prompt and hands the bytes to the same three sealers
4
+ // passkey protection uses (protectedLocal, the key worker, idbSeal): a copy, sync or search of the saved data alone finds no room
5
+ // key. It does NOT stand against malware that copies the whole browser profile (the wrapping key is in it) — the passkey does.
6
+ //
7
+ // null when there is no IndexedDB (Lockdown Mode, some private windows): the vault stays as it is, clear — never a key lost for want
8
+ // of a seal (the builders' vault's rule). A wrapped key the wrapping key cannot open (IndexedDB half cleared) also answers null and
9
+ // `lost: true`: the sealed entries cannot be opened, and the caller treats the device as new.
10
+ const DB = 'wbvault-device-key'
11
+ const reqP = (r) => new Promise((res, rej) => { r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error) })
12
+
13
+ /** The sealing switch's clear marker (protectedLocal.js STAYS_CLEAR): set once this vault's storage was sealed by the device key, so
14
+ * the next launch's protectedLocal starts sealed (reads wait for the unlock) instead of passing through. */
15
+ export const AT_REST_MARK = 'vault:atrest'
16
+
17
+ // ⛔ A READ THAT FAILED IS NOT A KEY THAT IS GONE (the owner's iPhone, 2026-11-14 12:43:56Z: "My account was reset"). Any error here
18
+ // answered null — the same answer as "this browser has no IndexedDB" — and the vault, finding its storage sealed, took it for a lost
19
+ // key and dropped every sealed entry, the account record among them. iOS fails IndexedDB opens now and then (a page woken from the
20
+ // background: "Connection to Indexed Database server lost"). So: a failed read is tried again (`tries`), and one that keeps failing
21
+ // answers `{ raw: null, error }` — the caller deletes nothing on it. `made` is true only when THIS call wrote the key: an `add` that
22
+ // lost to an existing one (a read that came back empty for a moment) is not a new key.
23
+ const RETRY_MS = [150, 400, 900]
24
+
25
+ // THE OS KEY STORE MAY WAIT FOR THE PERSON (the owner's WSL, 2026-11-22): a keyring never set up asks for a password in a window of its own
26
+ // (GNOME Keyring's prompt — on WSL it can open behind the app), and the read waits for that answer. It used to wait in silence under the
27
+ // loading screen until the boot watch said "didn't finish loading" and offered a Repair that cannot help. Now: the wait is marked
28
+ // `data-unlocking` (the boot watch holds its verdict, vault-boot-guard.js), the loading screen says what it waits for, and a key store
29
+ // that never answers ends in an error (the caller's "Couldn't open your saved data" — Try again), never a hang.
30
+ export const KEY_WAIT_MS = 180000
31
+ const KEY_WAIT_SAY_MS = 3000
32
+ export async function waitForKeyStore (call, ms = KEY_WAIT_MS) {
33
+ const doc = typeof document !== 'undefined' ? document : null
34
+ const root = doc && doc.documentElement
35
+ let said = null, sayT = 0, endT = 0
36
+ try { if (root) root.setAttribute('data-unlocking', 'keyring') } catch { /* */ }
37
+ sayT = setTimeout(() => {
38
+ try {
39
+ const t = doc && doc.querySelector('#bootLoad .bl-txt')
40
+ if (t) { said = t.textContent; t.textContent = 'Waiting for your keyring… If a window asks for a keyring password, answer it — it may be behind this one.' }
41
+ } catch { /* */ }
42
+ }, KEY_WAIT_SAY_MS)
43
+ try {
44
+ return await Promise.race([typeof call === 'function' ? call() : call, new Promise((resolve) => { endT = setTimeout(() => resolve({ error: 'the keyring did not answer in ' + Math.round(ms / 1000) + ' s' }), ms) })])
45
+ } finally {
46
+ clearTimeout(sayT); clearTimeout(endT)
47
+ try { if (root && root.getAttribute('data-unlocking') === 'keyring') root.removeAttribute('data-unlocking') } catch { /* */ }
48
+ try { const t = said != null && doc.querySelector('#bootLoad .bl-txt'); if (t) t.textContent = said } catch { /* */ }
49
+ }
50
+ }
51
+ /** @returns {Promise<{ raw: Uint8Array, made: boolean, os?: true } | { raw: null, lost: true } | { raw: null, error: string } | null>} */
52
+ export async function deviceStorageKey ({ desktop = globalThis.WitbitzDesktop, idb = (typeof indexedDB !== 'undefined' ? indexedDB : null), subtle = (globalThis.crypto && crypto.subtle), tries = RETRY_MS.length + 1, wait = (ms) => new Promise((r) => setTimeout(r, ms)), keyWaitMs = KEY_WAIT_MS } = {}) {
53
+ // THE DESKTOP APP (desktop/keyStore.mjs, Linux and the Mac): the key is kept by the operating system's key store (the Keychain, the
54
+ // Secret Service), not beside the files it seals — a copy of the app's files opens nothing. Its `error` is this function's (the caller
55
+ // deletes nothing); a desktop app with no usable key store (Linux without a keyring) falls back to this origin's own key below.
56
+ if (desktop && typeof desktop.storageKey === 'function') {
57
+ let r = null
58
+ try { r = await waitForKeyStore(() => desktop.storageKey(), keyWaitMs) } catch (e) { r = { error: String((e && e.message) || e).slice(0, 200) } }
59
+ if (r && typeof r.raw === 'string' && r.raw) {
60
+ const raw = Uint8Array.from(atob(r.raw.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0))
61
+ if (raw.length === 32) return { raw, made: !!r.made, os: true }
62
+ return { raw: null, error: 'desktop key: bad length' }
63
+ }
64
+ // `refused`: the key store answered and would not open the key saved here (made under a keyring since replaced) — not "no keyring"
65
+ if (!(r && /^no_(keystore|keyring)$/.test(String(r.error)))) return { raw: null, error: 'desktop key: ' + String((r && r.error) || 'no answer').slice(0, 160), ...(/^(keystore_refused|bad_key)/.test(String(r && r.error)) ? { refused: true } : {}) }
66
+ }
67
+ if (!idb || !subtle) return null
68
+ let last = null
69
+ for (let i = 0; i < tries; i++) {
70
+ if (i) await wait(RETRY_MS[Math.min(i - 1, RETRY_MS.length - 1)])
71
+ try { return await readOnce(idb, subtle) } catch (e) { last = e }
72
+ }
73
+ return { raw: null, error: String((last && (last.name ? last.name + ': ' : '') + (last.message || '')) || last || 'unknown').slice(0, 200) }
74
+ }
75
+
76
+ async function readOnce (idb, subtle) {
77
+ let db = null
78
+ try {
79
+ db = await new Promise((res, rej) => { const r = idb.open(DB, 1); r.onupgradeneeded = () => r.result.createObjectStore('k'); r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error) })
80
+ const get = (k) => reqP(db.transaction('k', 'readonly').objectStore('k').get(k)).then((v) => v || null)
81
+ // `add`, never `put`: two tabs making it at once — the first wins, both read back the same one
82
+ const add = (k, v) => new Promise((res) => { const t = db.transaction('k', 'readwrite'); t.objectStore('k').add(v, k); t.oncomplete = () => res(true); t.onabort = () => res(false); t.onerror = (e) => { try { e.preventDefault() } catch { /* */ } } }) // true: this call wrote it
83
+ let wrap = await get('wrap')
84
+ if (!wrap) { await add('wrap', await subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])); wrap = await get('wrap') }
85
+ if (!wrap || wrap.type !== 'secret') return null
86
+ let made = false, sealed = await get('sealed')
87
+ if (!sealed) {
88
+ const raw = crypto.getRandomValues(new Uint8Array(32)), iv = crypto.getRandomValues(new Uint8Array(12))
89
+ made = await add('sealed', { iv, ct: new Uint8Array(await subtle.encrypt({ name: 'AES-GCM', iv }, wrap, raw)) })
90
+ sealed = await get('sealed')
91
+ if (!sealed) throw new Error('the device key could not be read back')
92
+ }
93
+ try { return { raw: new Uint8Array(await subtle.decrypt({ name: 'AES-GCM', iv: sealed.iv }, wrap, sealed.ct)), made } } catch { return { raw: null, lost: true } }
94
+ } finally { try { db && db.close() } catch { /* */ } }
95
+ }