@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
@@ -0,0 +1,540 @@
1
+ // sw-notif-core.js — the SHARED service-worker notification core, importScripts()'d by BOTH spaces/public/sw.js (the
2
+ // regular / L2-app SW) and spaces/public/vault-sw.js (the tenant VAULT SW, served AS /sw.js on the vault origin). It
3
+ // holds the parts that MUST behave identically in both apps, so a fix lands in ONE place instead of two separate files
4
+ // (a one-sided edit to this contract silently shipped to only one app — see docs/spaces-convergence-plan.md):
5
+ // • wbxUb64 — base64url → bytes
6
+ // • wbxIdbGet/wbxIdbSet — the IndexedDB kv helpers (a SW can't read localStorage, so the page mirrors keys into idb)
7
+ // • wbxOpenEnvelope — AES-GCM v1-envelope open, PARAMETERISED by the symmetric key: the regular SW passes the
8
+ // room mk (opens the ledger) OR the notif-only NK; the vault SW only ever passes NK.
9
+ // • wbxWireNotifClick — the notificationclick → focus + {ch:'notif-open'} relay (the "opens the wrong room on iOS"
10
+ // fix), parameterised by the cold-open URL and whether to stash the tap (vault only).
11
+ //
12
+ // • wbxWirePush — the `push` handler (since 2026-10-18): each worker passes only its own preview read (the
13
+ // regular app may open the ledger with mk; the vault holds NK alone) and its words
14
+ // • wbxPollForTap — the push's one network read, keeping the tap's prefetch
15
+ // • the edge and the pins — wbxMatchesPin, wbxFetchShellOurs, wbxLiveBuildIs, wbxClean, wbxOfflinePage, the schedule
16
+ //
17
+ // What DOESN'T live here: each worker's CACHE LAYOUT. The regular app serves Official and Beta builds from folders
18
+ // (/b/<build>/), tops its cache up in slices and sweeps by channel; the vault serves only the tip, its precache verified
19
+ // against the pins in its own shell. Different by design — each worker keeps its install/activate/fetch.
20
+ //
21
+ // Classic (non-module) worker: everything attaches to `self` so the importing SW can call it after importScripts().
22
+ // build-vault.sh MUST copy this into the vault bundle — its importScripts closure check FATALs the build otherwise.
23
+ // Both SWs import it network-fresh as `/sw-notif-core.js?v=<build>`, so a new deploy always re-imports the new bytes.
24
+
25
+ self.wbxUb64 = (s) => { let t = String(s || '').replace(/-/g, '+').replace(/_/g, '/'); t += '='.repeat((4 - (t.length % 4)) % 4); const b = atob(t); const o = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) o[i] = b.charCodeAt(i); return o }
26
+
27
+ // The page mirrors keys (mk:<room>, nk:<room>) and the tapped-room stash into IndexedDB precisely because a service
28
+ // worker cannot read localStorage.
29
+ // ★ BOUNDED (2026-10-02): on an iPhone a page frozen in the background mid-transaction holds this database until it
30
+ // resumes, and a worker awaiting it waits with it — measured as every WARM tap in the tenant app (whose vault, with the
31
+ // app framed, writes here constantly) lost while cold taps and a frame-less vault's warm taps arrived. No caller may hang
32
+ // on storage: past IDB_WAIT a read answers null and a write answers false.
33
+ const IDB_WAIT = 2500
34
+ self.wbxIdbGet = (key) => new Promise((resolve) => {
35
+ setTimeout(() => resolve(null), IDB_WAIT)
36
+ try {
37
+ const r = indexedDB.open('spaces', 1)
38
+ r.onsuccess = () => { const db = r.result; db.onversionchange = () => db.close(); try { const rq = db.transaction('kv', 'readonly').objectStore('kv').get(key); rq.onsuccess = () => resolve(rq.result || null); rq.onerror = () => resolve(null) } catch { resolve(null) } }
39
+ r.onerror = () => resolve(null)
40
+ r.onupgradeneeded = () => { try { r.result.createObjectStore('kv') } catch { /* already there */ } }
41
+ } catch { resolve(null) }
42
+ })
43
+ self.wbxIdbSet = (key, value) => new Promise((resolve) => {
44
+ setTimeout(() => resolve(false), IDB_WAIT)
45
+ try {
46
+ const r = indexedDB.open('spaces', 1)
47
+ r.onsuccess = () => { const db = r.result; db.onversionchange = () => db.close(); try { const rq = db.transaction('kv', 'readwrite').objectStore('kv').put(value, key); rq.onsuccess = () => resolve(true); rq.onerror = () => resolve(false) } catch { resolve(false) } }
48
+ r.onerror = () => resolve(false)
49
+ r.onupgradeneeded = () => { try { r.result.createObjectStore('kv') } catch { /* already there */ } }
50
+ } catch { resolve(false) }
51
+ })
52
+
53
+ // THE WORKER'S OWN TRAIL (2026-10-01): every push it receives and every tap, written BEFORE anything can bail — a tap
54
+ // whose notification carries no room used to leave no trace at all, and the owner's trail came back empty on both halves
55
+ // with nothing to say which hand never ran. The vault reads it back with its own lines (tapTrailQuery). Device-only,
56
+ // last 20, no content: a room's first characters and what kind of push it was. `V` is the importing worker's build.
57
+ // ONE WRITER AT A TIME (2026-10-05): it is a read-modify-write, and two notes in the same Promise.all (a push's line beside
58
+ // another) each read the old list and the second write dropped the first line — a probe's `push test` vanished from the
59
+ // very trail that was meant to show it. Every note joins one chain; the line is stamped when it is ASKED for.
60
+ let _swTrailChain = Promise.resolve()
61
+ self.wbxNoteSw = (line) => {
62
+ const entry = { at: Date.now(), b: (typeof V !== 'undefined' ? V : '?'), line: String(line).slice(0, 160) }
63
+ _swTrailChain = _swTrailChain.then(async () => {
64
+ try {
65
+ const a = await self.wbxIdbGet('swTrail')
66
+ const list = Array.isArray(a) ? a : []
67
+ list.push(entry)
68
+ while (list.length > 20) list.shift()
69
+ await self.wbxIdbSet('swTrail', list)
70
+ } catch { /* a diagnostic must never be the thing that breaks a push or a tap */ }
71
+ })
72
+ return _swTrailChain
73
+ }
74
+
75
+ // WHAT THE WORKER PUT ON SCREEN FROM A PUSH (the owner's decision, 2026-10-02, after a day of measurements: in the tenant
76
+ // app a tap on a push notification never reaches this worker while the app is running, though iOS does consume it — the
77
+ // notification leaves the list). So the vault reads this record on each foreground and compares it with what is still
78
+ // showing (vault-loader.js _inferVanished): EXACTLY ONE gone → that room was tapped. Bounded idb; {room, tag, at}, one
79
+ // entry per tag (a re-shown tag replaced its notification). A click this worker DOES receive forgets the entry.
80
+ // `id` is THIS showing's own mark (the worker puts it in the notification's data too): iOS keeps GHOSTS of long-gone
81
+ // notifications in getNotifications() — the owner's list held two stale 'space-test' entries for hours — so a fresh
82
+ // notification that shares a ghost's TAG would read as "still showing" and a consumed tap could never be inferred.
83
+ self.wbxNoteShown = async (room, tag, id, dest = {}) => {
84
+ if (!tag || !(room || dest.code || dest.intake)) return
85
+ try {
86
+ const a = await self.wbxIdbGet('notifShown')
87
+ const list = (Array.isArray(a) ? a : []).filter((x) => x && x.tag !== tag)
88
+ list.push({ room, tag, id: id || '', at: Date.now(), ...(dest.card ? { card: dest.card } : {}), ...(dest.code ? { code: dest.code } : {}), ...(dest.intake ? { intake: 1 } : {}) })
89
+ while (list.length > 12) list.shift()
90
+ await self.wbxIdbSet('notifShown', list)
91
+ } catch { /* */ }
92
+ }
93
+ self.wbxForgetShown = async (tag, id) => {
94
+ if (!tag && !id) return
95
+ const hit = (x) => x && ((id && x.id === id) || (tag && x.tag === tag))
96
+ try { const a = await self.wbxIdbGet('notifShown'); if (Array.isArray(a) && a.some(hit)) await self.wbxIdbSet('notifShown', a.filter((x) => !hit(x))) } catch { /* */ }
97
+ }
98
+
99
+ // Minimal AES-GCM open for the v1 envelope — the same shape as e2ee.js, inlined because a service worker can't share the
100
+ // page's module graph. Iterates the envelope's recipient slots with the passed symmetric key (mk opens the room slot,
101
+ // NK opens the `notif` slot); returns the plaintext string or null (fail-closed — a wrong key opens nothing).
102
+ self.wbxOpenEnvelope = async (env, key) => {
103
+ try {
104
+ const ikm = await crypto.subtle.importKey('raw', self.wbxUb64(key), 'HKDF', false, ['deriveKey'])
105
+ const wrapKey = await crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: new TextEncoder().encode('memwrap') }, ikm, { name: 'AES-GCM', length: 256 }, false, ['decrypt'])
106
+ for (const slot of Object.keys(env.recipients || {})) {
107
+ const r = env.recipients[slot]
108
+ if (!r || !r.iv || !r.w) continue
109
+ try {
110
+ const cek = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: self.wbxUb64(r.iv) }, wrapKey, self.wbxUb64(r.w))
111
+ const k = await crypto.subtle.importKey('raw', cek, { name: 'AES-GCM' }, false, ['decrypt'])
112
+ const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: self.wbxUb64(env.iv) }, k, self.wbxUb64(env.ct))
113
+ return new TextDecoder().decode(pt)
114
+ } catch { /* wrong slot — try the next */ }
115
+ }
116
+ } catch { /* fall through to the generic notification */ }
117
+ return null
118
+ }
119
+
120
+ // THE PREVIEW RIDES THE PUSH (the owner, 2026-10-08: "So let's do option 1" — WhatsApp's shape). The payload's `notif` is
121
+ // the newest entry's preview sealed under NK = HKDF(mk,'notif') (agent/notif.mjs); the page mirrored NK to idb as
122
+ // `nk:<room>` (notifKey.js). Opened HERE, before any fetch: an email-gated room refuses this worker's keyless read, so
123
+ // that path could only ever show the generic line. → { title, body } or null (no key, nothing carried, or it won't open).
124
+ // "Show message preview" (notifPreview.js): OFF on this device → no notification opens a preview, carried or fetched.
125
+ self.wbxPreviewAllowed = async () => { try { return (await self.wbxIdbGet('notifPreview')) !== false } catch { return true } }
126
+ self.wbxPreviewFromPush = async (room, notif) => {
127
+ if (!room || typeof notif !== 'string' || !notif) return null
128
+ try {
129
+ const nk = await self.wbxIdbGet('nk:' + room)
130
+ if (!nk) return null
131
+ const o = JSON.parse((await self.wbxOpenEnvelope(JSON.parse(notif), nk)) || 'null')
132
+ if (!o) return null
133
+ const text = String(o.preview || '').replace(/[#*`>]/g, '').trim()
134
+ return { title: String(o.who || '') || 'Someone', body: text ? text.slice(0, 140) : 'sent something', ...(typeof o.k === 'string' ? { k: o.k } : {}), ...(typeof o.u === 'string' ? { u: o.u } : {}) }
135
+ } catch { return null }
136
+ }
137
+
138
+ // NO NOTIFICATION FROM A PERSON YOU BLOCKED (blocksPush.js; docs/report-and-block.md §4 (b)). The page leaves the blocked proofs as
139
+ // hashes under 'blocks:sw'; the opened preview names its writer (`k` the signing key, `u` a verified @username — agent/notif.mjs).
140
+ // wbxBlockToken MUST stay byte-identical to blocksPush.blockToken (a test asserts it).
141
+ self.wbxBlockToken = async (s) => {
142
+ const d = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(String(s))))
143
+ let b = ''; for (let i = 0; i < 16; i++) b += d[i].toString(16).padStart(2, '0')
144
+ return b
145
+ }
146
+ self.wbxBlockedSender = async (room, d) => {
147
+ try {
148
+ if (!room || !d || (!d.k && !d.u)) return false
149
+ const list = await self.wbxIdbGet('blocks:sw')
150
+ if (!Array.isArray(list) || !list.length) return false
151
+ const mine = await Promise.all([d.k ? self.wbxBlockToken('s:' + room + '|' + d.k) : null, d.u ? self.wbxBlockToken('u:' + String(d.u).toLowerCase()) : null])
152
+ return mine.some((t) => t && list.includes(t))
153
+ } catch { return false }
154
+ }
155
+
156
+ // "WAITING FOR YOUR APPROVAL" (docs/approval-reminders.md; agent/approvalRemind.mjs). The push for a waiting card or a waiting
157
+ // Code ask → { title, body, tag, data } to show, or null when the push is something else. A ROOM reminder is
158
+ // { room, remind: 1, card, notif } — the text sealed under the room's NK, as a message preview; a CODE reminder is
159
+ // { code: 1, n } — sealed by this device's computer under this device's own key (idb 'codeRemindKey', codeRemind.js).
160
+ // A reminder that will not open still says what it is; "Show message preview" off keeps the line generic.
161
+ self.wbxCodeRemindOpen = async (n) => {
162
+ try {
163
+ const raw = await self.wbxIdbGet('codeRemindKey')
164
+ if (!raw || typeof n !== 'string') return null
165
+ const b = self.wbxUb64(n)
166
+ const k = await crypto.subtle.importKey('raw', self.wbxUb64(raw), { name: 'AES-GCM' }, false, ['decrypt'])
167
+ const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: b.slice(0, 12), additionalData: new TextEncoder().encode('witbitz-code-remind') }, k, b.slice(12))
168
+ const o = JSON.parse(new TextDecoder().decode(pt))
169
+ return o && typeof o === 'object' ? o : null
170
+ } catch { return null }
171
+ }
172
+ self.wbxWaitingNotice = async (p) => {
173
+ if (!p || typeof p !== 'object') return null
174
+ const allowed = await self.wbxPreviewAllowed()
175
+ const s = (v, n) => String(v == null ? '' : v).replace(/[\u0000-\u001f]/g, ' ').trim().slice(0, n)
176
+ if (p.remind && typeof p.room === 'string' && p.room) {
177
+ const d = allowed && !(await self.wbxChatLocked(p.room)) ? await self.wbxPreviewFromPush(p.room, p.notif) : null
178
+ return { title: 'Waiting for your approval', body: d && d.body && d.body !== 'sent something' ? d.body : 'Open the Space to approve or deny it.', tag: 'remind-' + p.room, data: { room: p.room, card: s(p.card, 40) } }
179
+ }
180
+ if (p.code) {
181
+ const o = await self.wbxCodeRemindOpen(p.n)
182
+ const code = o ? { computer: s(o.computer, 80), session: s(o.session, 120) } : {}
183
+ const body = o && allowed && !(await self.wbxChatLocked('code:' + code.computer + '/' + code.session)) ? [s(o.where, 60), s(o.what, 120)].filter(Boolean).join(' · ') : ''
184
+ return { title: 'Code is waiting for your approval', body: body || 'Open Code to approve or deny it.', tag: 'code-remind-' + (code.session || 'any'), data: { code } }
185
+ }
186
+ return null
187
+ }
188
+
189
+ // Wire the notificationclick handler. cfg = { coldUrl(room) => string, stashTap: boolean }.
190
+ // coldUrl — where to launch when NO window is open (regular: /space?room=…; vault: /vault-loader?room=…).
191
+ // stashTap — stash the tapped room to idb so the page's foreground re-check routes it even when iOS drops the
192
+ // SW→client postMessage to a resuming PWA. Both apps set it: the vault reads it in vault-loader.js, the
193
+ // regular app in notifTap.js (2026-10-01 — before that the regular app opened the LAST room on iOS).
194
+ self.wbxWireNotifClick = (cfg) => {
195
+ const coldUrl = cfg.coldUrl
196
+ const stashTap = !!cfg.stashTap
197
+ // iOS may report a tap as a CLOSE (or close it unseen) — either way the trail should say so, not stay silent.
198
+ self.addEventListener('notificationclose', (e) => { const d = (e.notification && e.notification.data) || {}; e.waitUntil(self.wbxNoteSw('close ' + (d.room ? String(d.room).slice(0, 10) : '(no room)'))) })
199
+ self.addEventListener('notificationclick', (e) => {
200
+ e.notification.close()
201
+ const data = e.notification.data || {}
202
+ const room = data.room || ''
203
+ const isCall = !!data.call // §CALL: a "started a call" tickle — also open the room's meeting link
204
+ const card = typeof data.card === 'string' ? data.card : '' // a "waiting for your approval" reminder: the card to show
205
+ const code = data.code && typeof data.code === 'object' ? data.code : null // …or the Code session it waits in
206
+ const intake = data.intake ? 1 : 0 // "New message for your assistant": no room on the wire — the app collects and opens where it went (space.js openIntakeTap)
207
+ const invite = data.invite ? 1 : 0 // "New Space invite": no room on the wire either — the app reads its inbox and opens the Space it brought (space.js openInviteTap)
208
+ const url = coldUrl(room)
209
+ const label = data.diag ? 'tap on the TEST notification shown by the ' + data.diag : 'tap ' + (room ? room.slice(0, 10) : '— the notification carries NO room') + (isCall ? ' (call)' : '')
210
+ e.waitUntil((async () => {
211
+ // ★★ ROUTE FIRST, STORE AFTER. This handler used to write the tap record and its log line BEFORE focusing the app —
212
+ // and a write can wait on a database the frozen page still holds (see IDB_WAIT). Then nothing at all happened:
213
+ // no log line, no focus, no room. The tap is the user's; storage is bookkeeping.
214
+ const t0 = Date.now()
215
+ const all = await self.clients.matchAll({ type: 'window', includeUncontrolled: true })
216
+ let c = null, focused = false, posted = false
217
+ if (all.length) {
218
+ // A warm PWA (esp. iOS) has ONE window; navigate()/openWindow() would only RE-FOCUS it on its LAST room without
219
+ // switching — the reported "opens the wrong room" bug. So focus it and POST the tickle's room: the first-party
220
+ // app listens on navigator.serviceWorker ('notif-open' → openRoomInApp); the vault-loader relays it DOWN to the
221
+ // app iframe (vcHandoff 'notifOpen'). A window already ON this room is just focused. `call` rides along so the
222
+ // page shows its "Join call" affordance.
223
+ c = all.find((w) => room && w.url.includes('room=' + room)) || all[0]
224
+ try { if ('focus' in c) { await c.focus(); focused = true } } catch (err) { /* */ }
225
+ if (room || code || intake || invite) { try { c.postMessage({ ch: 'notif-open', room, call: isCall ? 1 : 0, ...(card ? { card } : {}), ...(code ? { code } : {}), ...(intake ? { intake } : {}), ...(invite ? { invite } : {}) }); posted = true } catch (err) { /* */ } }
226
+ } else if (self.clients.openWindow) {
227
+ try { await self.clients.openWindow(url) } catch (err) { /* */ } // cold: no window → launch at the cold URL (the room); the page's "Join call" banner covers the call link
228
+ }
229
+ // …then the bookkeeping, each step bounded (wbxIdbGet/Set give up after IDB_WAIT).
230
+ await self.wbxNoteSw(label + ' · routed in ' + (Date.now() - t0) + ' ms')
231
+ await self.wbxForgetShown(e.notification.tag, e.notification.data && e.notification.data.id) // this tap was delivered — the vault must not infer it again from its absence
232
+ // The stash: the loader re-reads it on every foreground, so a postMessage iOS dropped still routes.
233
+ if ((room || code || intake || invite) && stashTap) await self.wbxIdbSet('notifTap', { room, at: Date.now(), call: isCall ? 1 : 0, ...(card ? { card } : {}), ...(code ? { code } : {}), ...(intake ? { intake } : {}), ...(invite ? { invite } : {}) })
234
+ // THE TAP TRAIL (tapTrail.js): what the worker found and did, for the page to read back into the device log.
235
+ if (room) await self.wbxIdbSet('notifTapSeen', all.length ? { at: Date.now(), room, windows: all.length, onRoom: !!(c && c.url.includes('room=' + room)), focused, posted } : { at: Date.now(), room, windows: 0, cold: true })
236
+ // §CALL: open the meeting link LAST so the call is in the foreground and the PWA (now on the room) sits behind
237
+ // it. The URL is read from DEVICE idb (mirrored by the page — 'zoom:<room>'), never from the push wire. Best
238
+ // effort: iOS may decline an external openWindow from a SW, in which case the page's "Join call" banner covers it.
239
+ if (all.length && isCall && room && self.clients.openWindow) { try { const z = await self.wbxIdbGet('zoom:' + room); if (z && /^https:\/\//i.test(z)) await self.clients.openWindow(z) } catch (err) { /* */ } }
240
+ })())
241
+ })
242
+ }
243
+
244
+ // IS THIS ROOM ON SCREEN? (2026-10-03 — "When I am in the chat … I still get the tickle".) A visible window AND the
245
+ // page's own `viewing` record ({ room, at }, spaces/public/viewingBeacon.js), believed for VIEWING_FRESH_MS. The record
246
+ // beats the window URL: a cold tap leaves the vault at ?room=<the tapped room> long after the user moved on. With no
247
+ // record at all (an older page), the URL decides, as before.
248
+ const VIEWING_FRESH_MS = 30_000
249
+ self.wbxViewing = async (room) => {
250
+ if (!room) return false
251
+ let list = []
252
+ try { list = await self.clients.matchAll({ type: 'window', includeUncontrolled: true }) } catch { list = [] }
253
+ const shown = list.filter((c) => c && (c.focused || c.visibilityState === 'visible'))
254
+ if (!shown.length) return false
255
+ const v = await self.wbxIdbGet('viewing')
256
+ if (v && typeof v === 'object' && Number(v.at) > 0) return Date.now() - Number(v.at) < VIEWING_FRESH_MS && v.room === room
257
+ return shown.some((c) => String(c.url || '').includes(room))
258
+ }
259
+ // iOS: a push must SHOW something (or the permission is revoked) and `silent` is ignored — so for the room on screen,
260
+ // show it and then close it at once. Closes every notification with that tag (iOS keeps same-tag ghosts).
261
+ self.wbxQuietIfViewing = async (room, tag) => {
262
+ try {
263
+ if (!(await self.wbxViewing(room))) return false
264
+ const ns = await self.registration.getNotifications({ tag })
265
+ for (const n of ns) { try { n.close() } catch { /* */ } }
266
+ return true
267
+ } catch { return false }
268
+ }
269
+
270
+ // THE NUMBER ON THE APP'S ICON (appBadge.js; the owner, 2026-10-25: iOS never badges an icon by itself). The page keeps the
271
+ // rooms it shows as unread under 'badge'; a push for a room NOT on screen adds it here, so the number rises while the app is
272
+ // closed, and the page's next count replaces the list. No badge API, or no permission: nothing happens.
273
+ // ⚑ A PROTECTED device keeps nothing under a room's name in the clear (idbSeal.js §NAMES), and this worker holds no key: there
274
+ // it leaves the number alone — the page, unlocked, sets it from its own count.
275
+ self.wbxBadgeAdd = async (room) => {
276
+ try {
277
+ if (await self.wbxIdbGet('protectedNames')) return 0
278
+ const rec = await self.wbxIdbGet('badge')
279
+ const rooms = rec && Array.isArray(rec.rooms) ? rec.rooms.filter((r) => typeof r === 'string') : []
280
+ if (!rooms.includes(room) && rooms.length < 200) rooms.push(room)
281
+ await self.wbxIdbSet('badge', { rooms, at: Date.now() })
282
+ if (self.navigator && typeof self.navigator.setAppBadge === 'function') await self.navigator.setAppBadge(rooms.length)
283
+ return rooms.length
284
+ } catch { return 0 }
285
+ }
286
+
287
+ // ── THE PUSH HANDLER, ONCE (convergence review step 6, 2026-10-18) ───────────────────────────────────────────────────
288
+ // Until today each worker kept its own; they drifted (the vault marked every showing with an id against iOS's ghosts and
289
+ // noted calls and tests for tap inference, the regular app did not; the regular app silenced the room on screen, the
290
+ // vault only closed it). What stays per worker is what differs BY DESIGN — how a message's preview is read (the regular
291
+ // app may open the ledger with mk; the vault holds only NK) and the app's own words:
292
+ // cfg = { describe(room) → { title, body } | null, generic: { title, body }, testBody }
293
+ // ★ iOS REQUIRES a visible notification for every push (`userVisibleOnly`): every path ends in showNotification.
294
+ const WBX_ALERT_THROTTLE_MS = 120000 // at most one ALERTING notification per room per 2 minutes; sooner ones show silently
295
+ // THE CHAT LOCK: the page leaves the locked Spaces' ids as SHA-256 hashes under 'chatlocked:sw' (chatLockSw.js) — a locked chat's
296
+ // notice says only the generic line. Hash-compared, so the list names no Space even where storage is not sealed.
297
+ self.wbxChatLocked = async (room) => {
298
+ try {
299
+ const list = await self.wbxIdbGet('chatlocked:sw'); if (!Array.isArray(list) || !list.length) return false
300
+ const h = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode('chatlock|' + room)))).map((b) => b.toString(16).padStart(2, '0')).join('')
301
+ return list.includes(h)
302
+ } catch { return false }
303
+ }
304
+ self.wbxWirePush = (cfg) => self.addEventListener('push', (e) => {
305
+ let p = {}; try { p = (e.data && e.data.json && e.data.json()) || {} } catch { /* malformed → generic */ }
306
+ if (!p || typeof p !== 'object') p = {}
307
+ const room = typeof p.room === 'string' ? p.room : ''
308
+ const sealedPreview = typeof p.notif === 'string' ? p.notif : ''
309
+ const art = { icon: '/icon-192.png', badge: '/icon-192.png' }
310
+ const idFor = (tag) => tag + ':' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6) // THIS showing's mark: ghosts share tags, never ids
311
+ e.waitUntil((async () => {
312
+ if (p.remind || p.code) { // "WAITING FOR YOUR APPROVAL" — a room's card or a Code ask (wbxWaitingNotice)
313
+ await self.wbxNoteSw('push remind ' + (p.code ? 'code' : room.slice(0, 10)))
314
+ const w = (await self.wbxWaitingNotice(p)) || { title: 'Waiting for your approval', body: 'Open the app to answer.', tag: 'remind', data: {} }
315
+ const id = idFor(w.tag)
316
+ await self.wbxNoteShown(w.data.room || '', w.tag, id, w.data)
317
+ return self.registration.showNotification(w.title, { body: w.body, tag: w.tag, data: { ...w.data, id }, ...art, renotify: true })
318
+ }
319
+ // A MESSAGE WAITS IN THE ACCOUNT'S INTAKE (agent/messageIntake.mjs wake list; the owner, 2026-11-09: no notification when Claude Code
320
+ // wrote to the private lane). Content-free by construction: the box is sealed to the account's devices and nobody on the way knows
321
+ // who sent it. The tap opens the app (no room: the message room is not one to show), which collects it into its Space.
322
+ if (p.intake) {
323
+ await self.wbxNoteSw('push intake')
324
+ const id = idFor('intake'); await self.wbxNoteShown('', 'intake', id, { intake: 1 })
325
+ return self.registration.showNotification('New message for your assistant', { body: cfg.intakeBody || 'An agent you let in (or Siri) sent your assistant a message. Open the app to read it.', tag: 'intake', data: { intake: 1, id }, ...art, renotify: true })
326
+ }
327
+ const kind = p.test ? 'test' : p.invite ? 'invite' : p.call ? 'call' : 'message'
328
+ await self.wbxNoteSw('push ' + kind + ' ' + (room ? room.slice(0, 10) : '(no room)'))
329
+ // The confirmation sent when someone turns notifications ON: unambiguous on purpose — a room's last message here
330
+ // would look like a real one and confirm nothing.
331
+ if (p.test) { const id = idFor('space-test'); await self.wbxNoteShown(room, 'space-test', id); return self.registration.showNotification('Notifications are on', { body: cfg.testBody, tag: 'space-test', data: { room, id }, ...art }) }
332
+ // A content-free INVITE tickle: the box key is not here, so just ask them to open (the page polls the inbox).
333
+ // The tap says `invite` (2026-11-12, the owner: "After pressing it it doesn't open the new room"): the page reads its inbox and
334
+ // opens the Space the newest invite brought (inviteTap.js) — the worker still names none, it cannot.
335
+ if (p.invite) { const id = idFor('space-invite'); return self.registration.showNotification('New Space invite', { body: 'Someone invited you to a Space — open to see it.', tag: 'space-invite', data: { invite: 1, id }, ...art }) }
336
+ // §CALL: content-free {room, call:1}; the tap opens the room AND its meeting link (device idb, never the wire). Always alerts.
337
+ if (p.call) { const tag = room ? 'call-' + room : 'call'; const id = idFor(tag); await self.wbxNoteShown(room, tag, id); return self.registration.showNotification('📞 Call started', { body: 'Someone started a video call — tap to join.', tag, data: { room, call: 1, id }, ...art, renotify: true }) }
338
+ // THE NEWEST ENTRY THE PUSH CARRIED (2026-10-20; webPush.mjs payloadFor): filed as the room's prefetch, so the tap draws it
339
+ // with no read — the only way in a room that requires sign-in, where this worker's own read is refused.
340
+ const tailKept = room ? await self.wbxStoreCarriedTail(room, p.tail) : false
341
+ // The preview the push CARRIED (sealed under NK) first; the worker's own read only when it did not — but that read
342
+ // still runs for the tap's prefetch, after the notification is up (below).
343
+ const allowed = await self.wbxPreviewAllowed() // "Show message preview" off → the line only
344
+ const opened = room ? await self.wbxPreviewFromPush(room, sealedPreview) : null // opened even with previews off: it names its writer
345
+ // A PERSON YOU BLOCKED: shown silently with the plain line and closed at once (iOS requires a showing) — no sound, no badge.
346
+ if (opened && await self.wbxBlockedSender(room, opened)) {
347
+ const tag = 'blocked-' + room, id = idFor(tag)
348
+ await self.registration.showNotification(cfg.generic.title, { body: cfg.generic.body, tag, data: { room, id }, ...art, silent: true })
349
+ try { for (const n of await self.registration.getNotifications({ tag })) n.close() } catch { /* */ }
350
+ await self.wbxNoteSw('closed at once — from a person you blocked')
351
+ return
352
+ }
353
+ // A LOCKED CHAT (chatLockSw.js; docs/chat-lock-plan.md): the plain line only — no name, no words, no read of its own
354
+ const locked = room ? await self.wbxChatLocked(room) : false
355
+ const carried = allowed && !locked ? opened : null
356
+ const fetched = carried || !room || locked ? null : await cfg.describe(room)
357
+ const d = allowed && !locked ? (carried || fetched) : null
358
+ // ALERT or update quietly ("don't notify" is not an option on iOS — "don't buzz" is). Stamped only on an alert, or a
359
+ // continuous conversation keeps pushing the window forward and never alerts again.
360
+ const last = room ? Number(await self.wbxIdbGet('notifAt:' + room)) || 0 : 0
361
+ const viewing = room ? await self.wbxViewing(room) : false
362
+ const silent = viewing || (!!room && Date.now() - last < WBX_ALERT_THROTTLE_MS)
363
+ if (!silent && room) await self.wbxIdbSet('notifAt:' + room, Date.now())
364
+ const tag = room || 'space' // collapse repeats from the same room rather than stacking
365
+ const id = idFor(tag)
366
+ // Recorded for the page (strayPush.js: a room this device cannot open asks to be taken off its list) and for tap inference.
367
+ await self.wbxNoteShown(room, tag, id)
368
+ await self.registration.showNotification(d ? d.title : cfg.generic.title, { body: d ? d.body : cfg.generic.body, tag, data: { room, id }, ...art, silent, renotify: !silent })
369
+ // …and iOS ignores `silent`: the room on screen is closed at once (it was shown, which is what iOS requires).
370
+ if (viewing && await self.wbxQuietIfViewing(room, tag)) await self.wbxNoteSw('closed at once — the room is on screen')
371
+ else if (room) await self.wbxBadgeAdd(room) // the number on the app's icon counts it until it is read (appBadge.js)
372
+ // The push carried the preview, so describe() did not run: run it now for its PREFETCH — after the notification is up,
373
+ // so a slow or refused fetch never delays or blanks what is shown.
374
+ if (carried && room && !tailKept) { try { await cfg.describe(room) } catch { /* the tap's prefetch is best-effort */ } }
375
+ })())
376
+ })
377
+
378
+ // PREFETCH FOR THE TAP (prefetchPoll.js), the one network read a push makes: ask since the room's last known position (the
379
+ // L1 worker keeps cnt:<room>) so the answer is the new entries only, keep it so the room's first poll after the tap is
380
+ // answered at once, and say what became of it in the worker trail. Returns the server's answer (its `notif` / `sealed`
381
+ // for the caller's preview) or null.
382
+ self.wbxPollForTap = async (endpoint, room) => {
383
+ const cnt = await self.wbxIdbGet('cnt:' + room)
384
+ let since = cnt && Number.isInteger(cnt.count) ? { sinceCount: cnt.count } : {}
385
+ const ask1 = async (extra) => { const r = await fetch(endpoint, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ op: 'pollsealed', room, ...extra }) }); let b = null; try { b = await r.json() } catch { b = null } return { res: r, j: b } }
386
+ // A CONFIDENTIAL room: the worker keeps no tier mark, so the first read goes to the regular tier, which answers it with the tier
387
+ // said (agent/tierGuard.mjs — and none of the room's entries). Asked again where the room lives, once; every later ask goes there
388
+ // (sync sweep 11-09: the tap's prefetch of a confidential room fetched nothing). Content-blind either way: no key rides.
389
+ let encl = false
390
+ const ask = async (extra) => { let a = await ask1(encl ? { ...extra, enclave: true } : extra); if (!encl && a.j && a.j.tier === 'enclave') { encl = true; a = await ask1({ ...extra, enclave: true }) } return a }
391
+ // NO POSITION KNOWN (a protected device keeps none; a first push): ask the room's COUNT — a position past the end answers
392
+ // with no entries and the total — then its last WBX_PREFETCH_TAIL, kept as a TAIL under a hash of the room
393
+ // (prefetchPoll.js; 2026-10-20, the owner's phone waited 9 s for a tapped message). Content-blind, no server change.
394
+ let tail = false, first = null
395
+ if (since.sinceCount === undefined) {
396
+ first = await ask({ sinceCount: 1e9 })
397
+ if (first.res.ok && first.j && Number.isInteger(first.j.count)) { since = { sinceCount: Math.max(0, first.j.count - WBX_PREFETCH_TAIL) }; tail = true }
398
+ }
399
+ if (since.sinceCount === undefined) { await self.wbxNoteSw('prefetch ' + room.slice(0, 10) + ': no position known, and the room gave no count'); return (first && first.j) || null }
400
+ const { res, j } = await ask(since)
401
+ let pfNote = ''
402
+ if (!res.ok) pfNote = 'server answered ' + res.status
403
+ else if (!j || !j.changed) pfNote = 'nothing new since ' + since.sinceCount
404
+ else if (typeof j.sealed !== 'string') pfNote = 'answer carried no sealed slice'
405
+ else if (j.sealed.length > 400000) pfNote = 'too large to keep (' + Math.round(j.sealed.length / 1024) + ' KB)'
406
+ else {
407
+ const hashed = tail || !!(await self.wbxIdbGet('protectedNames')) // a protected device keeps nothing under a room's name
408
+ const key = hashed ? await self.wbxPrefetchHashKey(room) : 'prefetch:' + room
409
+ const { notif, ...rest } = j
410
+ const ok = await self.wbxIdbSet(key, { at: Date.now(), sinceCount: since.sinceCount, ...(tail ? { tail: true } : {}), r: { status: res.status, ...rest } })
411
+ try { new BroadcastChannel('wb-prefetch').postMessage({ room }) } catch { /* a closed channel: the worker looks on its next first poll */ }
412
+ pfNote = !ok ? 'COULD NOT KEEP it' : (tail ? 'kept the last ' + (j.count - since.sinceCount) + ' of ' + j.count + ' (no position known)' : 'kept ' + (j.count - since.sinceCount) + ' new') + (hashed ? ', under a hash of the room' : '')
413
+ }
414
+ await self.wbxNoteSw('prefetch ' + room.slice(0, 10) + ': ' + pfNote)
415
+ return j || null
416
+ }
417
+ // A carried { count, box } → the same TAIL record wbxPollForTap keeps, under the room's hash. → true when kept.
418
+ self.wbxStoreCarriedTail = async (room, t) => {
419
+ if (!t || typeof t !== 'object' || !Number.isInteger(t.count) || t.count < 1 || typeof t.box !== 'string' || t.box.length > 4000) return false
420
+ const from = t.count - 1
421
+ const sealed = JSON.stringify({ v: 3, from, count: t.count, boxes: [t.box] })
422
+ const ok = await self.wbxIdbSet(await self.wbxPrefetchHashKey(room), { at: Date.now(), sinceCount: from, tail: true, r: { status: 200, changed: true, count: t.count, from, sealed } })
423
+ try { new BroadcastChannel('wb-prefetch').postMessage({ room }) } catch { /* the worker looks on its next first poll */ }
424
+ await self.wbxNoteSw('prefetch ' + room.slice(0, 10) + ': ' + (ok ? 'the push carried the newest entry (' + t.count + ')' : 'COULD NOT KEEP the carried entry'))
425
+ return !!ok
426
+ }
427
+ const WBX_PREFETCH_TAIL = 30 // ⇄ prefetchPoll.js PREFETCH_TAIL
428
+ // ⇄ prefetchPoll.js prefetchHashKey — the same key, or the L1 worker never finds a tail.
429
+ self.wbxPrefetchHashKey = async (room) => {
430
+ const d = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode('wb-prefetch\n' + String(room || ''))))
431
+ return 'prefetch:h:' + Array.from(d.slice(0, 16), (b) => b.toString(16).padStart(2, '0')).join('')
432
+ }
433
+ // A one-line preview from an opened envelope's { who, preview } (Markdown marks stripped).
434
+ self.wbxOneLine = (s) => String(s || '').replace(/[#*`>]/g, '').trim()
435
+ self.wbxPreviewOf = (who, text) => { const t = self.wbxOneLine(text); return { title: String(who || '') || 'Someone', body: t ? t.slice(0, 140) : 'sent something' } }
436
+
437
+ // ── THE EDGE AND THE PINS, ONCE ──────────────────────────────────────────────────────────────────────────────────────
438
+ // §EDGE CONVERGENCE (the owner, 2026-10-06: "we can wait for the new version"): a Pages deploy reaches the edge over
439
+ // seconds, and an edge still on the previous build answers another build's bytes. Both workers wait it out, ~11 s.
440
+ self.wbxSleep = (ms) => new Promise((r) => setTimeout(r, ms))
441
+ self.WBX_EDGE_RETRY_MS = [300, 600, 1000, 1500, 2000, 2500, 3000]
442
+ const _wbxB64 = (buf) => { let s = ''; const u = new Uint8Array(buf); for (let i = 0; i < u.length; i++) s += String.fromCharCode(u[i]); return btoa(s) }
443
+ // Do these bytes match an SRI pin ("sha384-… sha256-…")? Any one token matching is enough.
444
+ self.wbxMatchesPin = async (buf, pin) => {
445
+ for (const tok of String(pin).trim().split(/\s+/)) {
446
+ const m = /^(sha256|sha384|sha512)-(.+)$/.exec(tok); if (!m) continue
447
+ if (_wbxB64(await crypto.subtle.digest(m[1].replace('sha', 'SHA-'), buf)) === m[2]) return true
448
+ }
449
+ return false
450
+ }
451
+ // A cached copy with its `redirected` flag set is a NETWORK ERROR when served to a navigation: a fresh Response over the body.
452
+ self.wbxClean = (r) => (r && r.redirected ? new Response(r.body, { status: r.status, statusText: r.statusText, headers: r.headers }) : r)
453
+ // Is `b` the build the live /sw.js carries? Then the network is not lagging — this worker is the older one — and waiting
454
+ // would only delay the fallback. Unreadable → false (= wait: the lag is the likelier story).
455
+ self.wbxLiveBuildIs = async (b) => {
456
+ try { const t = await (await fetch(new Request('/sw.js?vc=' + Date.now(), { cache: 'no-store' }))).text(); const m = /const V = '([^']+)'/.exec(t); return !!m && m[1] === b } catch { return false }
457
+ }
458
+ // The network's shell, accepted only when it is THIS build's (or carries no stamp); another build's is waited out.
459
+ // o = { V, shellBuildOf(html) → build | '', putCache(req, res), onWait(b, i) }
460
+ self.wbxFetchShellOurs = async (req, key, first, o) => {
461
+ let r = null
462
+ for (let i = 0; i <= self.WBX_EDGE_RETRY_MS.length; i++) {
463
+ try { r = i === 0 && first ? await first : await fetch(new Request(req.url, { cache: 'reload', credentials: 'same-origin' })) } catch { return null }
464
+ if (!r || !r.ok) return null
465
+ let b = ''; try { b = o.shellBuildOf(await r.clone().text()) } catch { return null }
466
+ if (!b || b === o.V) { if (i > 0) o.putCache(new Request(key), r.clone()); return r }
467
+ if (i === 0 && await self.wbxLiveBuildIs(b)) return null // the edge is CONVERGED on that build and WE are the stale worker
468
+ if (o.onWait) o.onWait(b, i)
469
+ if (i < self.WBX_EDGE_RETRY_MS.length) await self.wbxSleep(self.WBX_EDGE_RETRY_MS[i])
470
+ }
471
+ return null
472
+ }
473
+ // NEVER HAND A TOP-LEVEL OPEN TO THE BROWSER'S OWN ERROR PAGE. `Response.error()` for a shell navigation paints Safari's
474
+ // "your iPhone is not connected to the internet" — nothing anyone can act on (the owner, three times on 2026-09-17). A
475
+ // worker with nothing to serve says so itself: the build, the reason, every cache with its count. A 503 with a body —
476
+ // nothing caches it or mistakes it for the shell — and "Try again" reloads back through the same worker.
477
+ self.wbxOfflinePage = async (V, why) => {
478
+ let state = 'no caches'
479
+ try {
480
+ const parts = []
481
+ for (const k of await caches.keys()) parts.push(k + ':' + (await (await caches.open(k)).keys()).length)
482
+ if (parts.length) state = parts.join(' · ')
483
+ } catch (e) { state = 'caches unreadable' }
484
+ const esc = (s) => String(s).replace(/[<>&]/g, (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;' }[c]))
485
+ const html = '<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>You’re offline</title>' +
486
+ '<body style="margin:0;font:16px/1.5 system-ui,-apple-system,sans-serif;color:#111;background:#fff"><div style="min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;padding:40px 24px;gap:14px;box-sizing:border-box">' +
487
+ '<h2 style="margin:0;font-size:20px">You’re offline</h2>' +
488
+ '<p style="color:#666;margin:0;max-width:22rem">This device hasn’t saved the app yet. Open it once with a connection and it will be here offline after that.</p>' +
489
+ '<button onclick="location.reload()" style="font:inherit;font-weight:600;padding:12px 20px;border:0;border-radius:12px;background:#111;color:#fff">Try again</button>' +
490
+ '<div style="color:#999;font-size:12px">worker ' + esc(V) + ' · ' + esc(why) + ' · ' + esc(state) + '</div></div>'
491
+ return new Response(html, { status: 503, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' } })
492
+ }
493
+ // A worker's own failures in its trail (a worker has no console anyone reads).
494
+ self.wbxWireErrors = () => {
495
+ self.addEventListener('error', (e) => { self.wbxNoteSw('worker error: ' + ((e && e.message) || e)) })
496
+ self.addEventListener('unhandledrejection', (e) => { self.wbxNoteSw('worker rejection: ' + String((e && e.reason && e.reason.message) || (e && e.reason) || '?')) })
497
+ }
498
+
499
+ // THE TAP TEST'S WORKER HALF (crashTrail.js "Test a notification tap"; both workers since 2026-10-25). The page shows one test
500
+ // notification itself and asks this worker to show its own — and, for the room on screen, one dressed exactly like a push for
501
+ // it (tag = the room, data = { room }) but shown with no push. One tap each splits "push-shown notifications lose their tap"
502
+ // from "every notification of this app does" (the tenant app's taps, 2026-10).
503
+ self.wbxWireDiagShow = () => {
504
+ self.addEventListener('message', (e) => {
505
+ const d = e && e.data
506
+ if (!d || d.ch !== 'diag-show') return
507
+ // Round 2: the plain worker notification's tap ARRIVED (owner, 09:26:53) while no push-shown tap ever has. So a second
508
+ // one is dressed EXACTLY like a push for the room on screen — tag = the room, data = { room } — but shown with no push.
509
+ // Plain arrives + dressed lost ⇒ the room tag/data is the cause; both arrive ⇒ it is being shown from a PUSH.
510
+ const room = typeof d.room === 'string' ? d.room : ''
511
+ const show = (title, opts, what) => self.registration.showNotification(title, opts).then(() => self.wbxNoteSw('shown: TEST notification by the ' + what), (err) => self.wbxNoteSw('could not show the ' + what + ' TEST notification: ' + ((err && err.message) || err)))
512
+ e.waitUntil(Promise.all([
513
+ show('Test from the worker', { body: 'Tap this one', tag: 'diag-worker', data: { diag: 'worker' }, icon: '/icon-192.png', badge: '/icon-192.png' }, 'worker'),
514
+ room ? show('Test shaped like a message', { body: 'Tap this one as well', tag: room, data: { room, diag: 'worker, shaped like a push for ' + room.slice(0, 10) }, icon: '/icon-192.png', badge: '/icon-192.png' }, 'worker, shaped like a push') : null,
515
+ ]))
516
+ })
517
+ }
518
+
519
+ // ★★ A STORED PAGE KEEPS ITS SECURITY HEADERS (docs/hosted-app-design.md §8; 2026-10-25; both workers). The hash stores keep the
520
+ // bytes once per hash, so the headers cannot ride with them (the same bytes may be served at two addresses): each release's
521
+ // LIST records, per entry, the headers that protect a document or a worker — its CSP above all, which our pages carry only
522
+ // as a header. Without this a page answered from a store ran with NO CSP (measured live, both engines;
523
+ // spaces/test/storeKeepsHeaders.test.mjs).
524
+ self.WBX_SEC_HEADERS = ['content-security-policy', 'content-security-policy-report-only', 'x-frame-options', 'referrer-policy', 'permissions-policy', 'x-content-type-options', 'cross-origin-opener-policy', 'cross-origin-embedder-policy', 'cross-origin-resource-policy', 'allow-csp-from', 'report-to', 'reporting-endpoints']
525
+ /** The security headers of a response that carries a policy (a page, a worker) → { name → value }, or null. A PAGE (`text/html`)
526
+ * is always recorded when `recordPages` — {} when it carried none — so "recorded, none" differs from "kept before headers were". */
527
+ self.wbxSecHeadersOf = (h, recordPages = false) => {
528
+ if (!h.get('content-security-policy') && !h.get('content-security-policy-report-only') && !h.get('x-frame-options')) return recordPages && /^text\/html/i.test(h.get('content-type') || '') ? {} : null
529
+ const o = {}; for (const n of self.WBX_SEC_HEADERS) { const v = h.get(n); if (v) o[n] = v } return o
530
+ }
531
+ /** A stored file as a fresh Response with the headers its entry was recorded with. A document recorded with none (kept before
532
+ * headers were) is marked `x-wb-noheaders`: online, a navigation takes the network's copy (which carries them) instead. */
533
+ self.wbxWithSecHeaders = (r, sec) => {
534
+ const headers = new Headers(r.headers)
535
+ if (sec) for (const [n, v] of Object.entries(sec)) headers.set(n, v)
536
+ else if (/^text\/html/i.test(headers.get('content-type') || '')) headers.set('x-wb-noheaders', '1')
537
+ return new Response(r.body, { status: 200, headers })
538
+ }
539
+ /** A stored page recorded with no security headers, while the network may be there: take the network's copy. */
540
+ self.wbxStaleHeaders = (r) => !!(r && r.headers.get('x-wb-noheaders') && self.navigator.onLine !== false)
package/tempList.js ADDED
@@ -0,0 +1,48 @@
1
+ // tempList.js — THE TEMPORARY-SPACES LIST's edits, as pure functions (no DOM, no storage): the page runs them on its own pointer
2
+ // (tempRooms.js) and the hosted vault's worker runs them on the pointer it holds (l1-worker.js `tempList`), so the hosted app
3
+ // frame never holds the temp index's key or a temp room's key (the owner, 2026-11-13: "Do 1+3+4"; docs/sdk-convergence.md
4
+ // § who holds the room key). The list is [{ room, title, at, mk | userShare+commit }], newest first, at most TEMP_LIST_MAX.
5
+
6
+ export const TEMP_LIST_MAX = 100
7
+ export const isTempRoomId = (r) => typeof r === 'string' && r.startsWith('tmp-') && r.length <= 64
8
+
9
+ // ⛔ THE LIST IS EDITED, NEVER WRITTEN BLIND (2026-11-08, docs/state-machines.md I10 / A#4): read with the version, refuse to write
10
+ // over a list that could not be read (unknown is not empty), apply the change to what is stored, write only over that version
11
+ // (accountStores put ifV): another write in between → read and apply again. `change(list)` → the new list, or null (nothing to
12
+ // write). → the list written (or the stored one, when nothing changed), or null.
13
+ export async function editTempList (store, room, mk, change, by = '') {
14
+ for (let i = 0; i < 3; i++) {
15
+ const r = await store.get(room, mk, 'rooms')
16
+ if (!(r && r.status === 200)) return null
17
+ const cur = r.state && Array.isArray(r.state.rooms) ? r.state.rooms : []
18
+ const next = change(cur)
19
+ if (!next) return cur
20
+ const w = await store.put(room, mk, 'rooms', { rooms: next }, 'temp rooms', by || '', Number.isInteger(r.v) ? { ifV: r.v } : {})
21
+ if (w && w.status === 409) continue
22
+ return w && w.status === 200 ? next : null
23
+ }
24
+ return null
25
+ }
26
+
27
+ // AN ADD (or an UPDATE: auto-title, rename) keeps the room's position and its material. Reopen material: `fresh` ({ mk } or
28
+ // { userShare, commit }) when the caller has it; else the existing entry's. ★ A title-only update on a resumed room has no fresh
29
+ // material (the key is in the worker, the shares were never kept) — reusing the entry's lets it through ("temp rooms stay
30
+ // 'Space'"). Nothing to record at all (a new room we could never reopen) → null: nothing is written.
31
+ export function addToTempList (all, { room, title, fresh }) {
32
+ const was = all.find((r) => r && r.room === room)
33
+ const reopen = (fresh && fresh.mk) ? { mk: fresh.mk }
34
+ : (fresh && fresh.userShare) ? { userShare: fresh.userShare, commit: fresh.commit || '' }
35
+ : (was && was.mk) ? { mk: was.mk }
36
+ : (was && was.userShare) ? { userShare: was.userShare, commit: was.commit }
37
+ : null
38
+ if (!reopen) return null
39
+ const prev = all.filter((r) => r && r.room !== room)
40
+ const entry = { room, title: title || (was && was.title) || 'Space', at: (was && was.at) || Date.now(), ...reopen }
41
+ return [entry, ...prev].slice(0, TEMP_LIST_MAX)
42
+ }
43
+
44
+ export const removeFromTempList = (all, rooms) => { const gone = new Set(rooms); return all.filter((r) => r && !gone.has(r.room)) }
45
+
46
+ // What a caller that does not hold the keys is told: each entry without its material, marked `held` (the worker holds it).
47
+ export const keylessTempList = (list) => (Array.isArray(list) ? list : []).filter((e) => e && isTempRoomId(e.room))
48
+ .map(({ mk: _mk, userShare: _us, commit: _c, ...rest }) => ({ ...rest, held: 1 }))