@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/l1-worker.js ADDED
@@ -0,0 +1,894 @@
1
+ // spaces/public/l1-worker.js — A2a of the thin-L1 migration (docs/verified-client-l1-interface.md):
2
+ // the mk-CUSTODY KERNEL as a Web Worker. It hosts the sealed-ledger client, holds the room mk, and does
3
+ // all mk-crypto (keyFields) + entry signing (turn's identity JWK). The main thread posts SEMANTIC ops
4
+ // ({op, room, args}); mk NEVER posts back out — a main-thread (L3) compromise cannot read this realm's
5
+ // memory. spaceClient + its whole dep chain (e2ee/entrySig/mkseal/ownerPolicy/rosterHash/spaceConfig/
6
+ // invite) are localStorage/DOM-free, so they run here unmodified.
7
+ //
8
+ // FLAG-GATED: only used when the page is opened with ?l1worker=1 (l1.js). Default OFF → the A1 direct
9
+ // façade runs and this worker is never spawned. Ships safe; validate behind the flag before enabling.
10
+ //
11
+ // Auth stays on the main thread (localStorage-backed cachedEmailAuth): when the client needs auth for a
12
+ // room, `auth(room)` round-trips to the main thread via {authReq}. The enclave tier (mkPub/enclave) is
13
+ // read SYNCHRONOUSLY by keyFields, so we keep a pushed snapshot {enclaveKey, enclaveRooms} and read it
14
+ // locally rather than round-trip.
15
+ import { routingIndex } from './opRouting.js'
16
+ import { prefetchUsable, positionOf, prefetchAnswer, prefetchHashKey } from './prefetchPoll.js'
17
+ import { makeSpaceClient, setAttestProvider, setPushSelf, setPushAcct, pushAcctSecretOf, viewingTag } from './spaceClient.js'
18
+ import { idb } from './idb.js'
19
+ import { armIdbNaming, setIdbNaming } from './idbSeal.js' // §NAMES (docs/desktop-protection.md phase 2): this realm's store keeps opaque names on a protected device
20
+ import { _hasGzip, _jsonBytes, gunzipB64, gzipB64 } from './compress.js' // Atlas index docs: gzip/absorb/inject worker-side
21
+ import { combineShares, commit as commitMk } from './e2ee.js' // §9 split-key: reconstruct mk = userShare ⊕ appShare inside the worker (confinement mode)
22
+ import { deriveNotifKey } from './notifKey.js'
23
+ import { importRaw as importSealKey, sealIf, open as openSealed, isSealed } from './deviceSeal.js' // DEVICE STORAGE PROTECTION (docs/device-storage-protection.md): with the switch on, every key this worker persists is ciphertext under a key held only HERE, in memory
24
+ import { sealDoc, openDoc, isSealedDoc, rawSealKey } from './accountSeal.js' // acctSeal / acctOpen: room messages sealed under the account key (roomMail.js); rawSealKey: the temp index's own seal key
25
+ import { editTempList, addToTempList, removeFromTempList, keylessTempList, isTempRoomId } from './tempList.js' // the temporary-Spaces list, kept HERE for the hosted app (op tempList)
26
+ import { makeAccountStore } from './accountStores.js' // the account's sync docs SEALED on the device (docs/sdk-convergence.md § The account stores)
27
+ import { openRoomStream } from './roomStreamClient.js' // ROOM STREAMS: the socket lives HERE, beside the key it derives from (docs/change-inbox.md § Room streams)
28
+ import { roomRegion, DEFAULT_REGION } from './regions.js' // a room's region is in its id — its enclave's key seals it
29
+ import { opensEnvelopes, sealsIdentity } from './reqEnvelope.js' // does a live enclave open the sealed request envelope
30
+ import { gatedKey } from './enclaveAccept.js' // the user's accepted builds: the SAME seal gate as enclave.js, run here because mk is sealed HERE // §Phase-4: mirror NK=HKDF(mk,'notif') to idb HERE (the confined kernel) so vault-sw.js gets a preview key for SPLIT rooms — whose mk only ever materializes in this worker, never the main-thread loader (that's why split rooms showed the generic nudge)
31
+ import { signInOf, SIGNIN_RENEW_AUTH } from './roomPass.js' // the room pass: which sign-in a request carries (the page answers for it)
32
+ // One room's stream socket here (the key never leaves): events go up to the page; `tag` names this device as viewing it.
33
+ // A CARRIED ENTRY (roomStreamClient `tail`): kept here, beside the key, for the poll the event asks for — the page gets the event
34
+ // without the box. room → { count, box, at }; used once, for a poll from count-1, within FRAME_TAIL_MS.
35
+ const frameTails = new Map()
36
+ const FRAME_TAIL_MS = 30000
37
+ function openStreamHere (room, mk, grants, tag) {
38
+ return openRoomStream({ mk, grants: Array.isArray(grants) ? grants : null, tag, onEvent: (ev) => {
39
+ if (ev && ev.tail) { frameTails.set(room, { ...ev.tail, at: Date.now() }); const { tail, ...rest } = ev; ev = rest }
40
+ self.postMessage({ t: 'stream', room, ev })
41
+ }, onState: (up) => self.postMessage({ t: 'stream', room, up }) })
42
+ }
43
+
44
+ let client = null
45
+ let clientRealm = '' // the realm (endpoint · app · tenant) `client` was made for — 'open' keeps it within one (sweep 11-07 #6)
46
+ // ⛔ The account's sync docs (index, index2, pipes, …) carry every room key — sealed under acctKey before they leave
47
+ // (accountStores.js). acctKey comes from the page that owns this worker (regular app) or the vault hosting it (tenant).
48
+ let acctKey = null
49
+ let oldAcctKeys = [] // the account keys of PREVIOUS masters (accountStores.js oldKeys: documents sealed before a new master)
50
+ const unzipDoc = async (st) => (st && typeof st === 'object' && typeof st.z === 'string') ? await gunzipB64(st.z).catch(() => null) : st
51
+ const acct = makeAccountStore({ call: (...a) => client.state(...a), key: async () => acctKey, oldKeys: async () => oldAcctKeys })
52
+ // THE TEMPORARY-SPACES LIST (tempRooms.js; the owner, 2026-11-13: "Do 1+3+4"): in the hosted app the vault hands this worker the
53
+ // temp index's pointer (op tempHold — { room, sk }, its key into `mks`), and the frame reads and edits the list through op tempList,
54
+ // keyless. The list carries every temp room's key, sealed under the pointer's own random key `sk` (as the page seals it).
55
+ let tempPtr = null
56
+ const tempStore = makeAccountStore({ call: (...a) => client.state(...a), key: async () => (tempPtr && tempPtr.sk ? rawSealKey(tempPtr.sk) : null) })
57
+ const TEMP_SK = /^[A-Za-z0-9_-]{43}$/
58
+ // ROOM STREAMS: room → { s, holders }. The stream client needs mk, so it runs in this realm; only EVENTS go out — the
59
+ // reply text as it grows (the same plaintext a poll's partialText already carries out), "poll now", "the turn ended".
60
+ // Several frames can share this worker (the hoisted vault: the app + a lane panel), hence a holder count.
61
+ const grantsByRoom = new Map()
62
+ const streams = new Map()
63
+ function rekeyStream(room, mk) {
64
+ const held = streams.get(room)
65
+ if (!held?.s || held.mk === mk) return
66
+ held.s.stop()
67
+ grantsByRoom.delete(room)
68
+ held.mk = mk
69
+ held.grants = null
70
+ held.s = openStreamHere(room, mk, null, held.tag)
71
+ }
72
+ const streamFeed = (room, result) => {
73
+ const h = streams.get(room)
74
+ if (!result || result.status !== 200) return
75
+ if (Array.isArray(result.streamGrants)) grantsByRoom.set(room, result.streamGrants)
76
+ if (!h) return
77
+ if (Array.isArray(result.streamGrants)) { h.s?.setGrants(result.streamGrants); h.grants = result.streamGrants }
78
+ h.s?.sync(typeof result.partialText === 'string' ? result.partialText : '')
79
+ }
80
+ const mks = new Map() // room → mk — the worker's authoritative key store (A2b); mk never posts back out
81
+ // §9 SPLIT-KEY (confinement mode): a split room's key store is the user's userShare + the commit. resolveMk fetches the
82
+ // app half from the same-origin tenant backend, combines, verifies the commit, and CACHES the reconstructed mk in `mks`
83
+ // — so every mk-using op below works unchanged. The vault/worker never holds K_eco (that unwrap is the backend's job).
84
+ const splits = new Map() // room → { userShare, commit }
85
+ // §PERSIST (2026-09-01): mirror BOTH maps to this origin's idb and reload at boot. iOS reclaims workers under memory
86
+ // pressure; the heartbeat recreates one, but everything the old worker had ABSORBED (index-doc userShares, resolved mks)
87
+ // lived only in memory — so there was a window where opens failed ('key hasn't reached this device'). A recreated worker
88
+ // now self-restores instantly. The signout/reset path wipes this store (vault-loader _idbWipe) — the audit still holds.
89
+ // §PROTECT (docs/device-storage-protection.md). `sealKey` is the device's AES key, imported from raw bytes the page derived from
90
+ // its passkey (PRF/largeBlob) and sent over postMessage — non-extractable here, never written anywhere. While it is set, every
91
+ // persisted key is sealed; at boot, sealed entries are PARKED until the page unlocks and sends the key again; `relock` drops
92
+ // the maps and the key from memory. With the switch off (no key, no sealed entries) every store is byte-identical to before.
93
+ let sealKey = null
94
+ let storageEpoch = 0, storageWiped = false
95
+ let nkClear = false // §PREVIEWS (opt-in under protection): the push-preview keys (nk:) are written CLEAR so a locked device's tickle still shows sender + first line; everything else stays sealed
96
+ let protectedAtRest = false // sealed entries were seen at boot (or `seal` ran): the store is protected — NEVER write a clear key over it
97
+ const parked = new Map() // idb key ('mk:'/'us:'/'nk:' + room) → sealed blob awaiting the device key
98
+ // A key that reaches a protected-but-locked worker (the page re-sends a room key it still holds at open) stays in memory
99
+ // only; the `unseal` that follows persists everything held, sealed. Without protection: the clear write, as always.
100
+ // VOLATILE ROOMS (docs/emulated-attested-rooms.md; "attested rooms cannot be watched offline"): an attested room's key is held in
101
+ // this map only — never written, and anything an older build wrote is removed (op `volatile`). The page names them first.
102
+ const volatile = new Set()
103
+ const postAttNk = (room, nk) => { if (!room || !nk || String(room).startsWith('tmp-')) return; try { self.postMessage({ t: 'attNk', room, nk }) } catch { /* */ } }
104
+ const roomOfKey = (k) => String(k).slice(String(k).indexOf(':') + 1)
105
+ const persist = (k, v) => {
106
+ const epoch = storageEpoch
107
+ return storageWiped || volatile.has(roomOfKey(k)) ? Promise.resolve() : keysReady.then(() => ((!sealKey && protectedAtRest) ? undefined : sealIf(sealKey, v).then((stored) => epoch === storageEpoch && !storageWiped ? idb.set(k, stored) : undefined))).catch(() => {})
108
+ } // a wipe also cancels keys whose asynchronous sealing was still running
109
+ // AN ATTESTED ROOM'S PREVIEW KEY (the owner, 2026-11-24: "the notification preview for attested rooms doesn't work"): its room key stays
110
+ // in this worker's memory, so the vault — whose service worker and native shell show the notification — never learned its preview key.
111
+ // The vault gets the PREVIEW KEY alone (it opens a notification's preview, never the room): `attNk`. Nothing is written here.
112
+ const persistNk = (room, nk) => storageWiped ? Promise.resolve() : volatile.has(room) ? (postAttNk(room, nk), Promise.resolve()) : (nkClear ? keysReady.then(() => storageWiped ? undefined : idb.set('nk:' + room, nk)).catch(() => {}) : protectedAtRest ? keysReady.then(() => idb.delRaw('nk:' + room)).catch(() => {}) : persist('nk:' + room, nk))
113
+ // A ROOM'S KEY EPOCH (docs/key-rotation-design.md § (b)): a verified room re-keyed in place counts its keys. Kept per room
114
+ // (not secret: a count) so a key arriving from the account index can be refused when it is OLDER than the one held — a
115
+ // device that had not yet learned the new key, writing the index, must not put the old key back (never backwards).
116
+ const eps = new Map()
117
+ const noteEp = (room, ep) => { const n = Number(ep) || 0; if (room && n > (eps.get(room) || 0)) { eps.set(room, n); if (!volatile.has(room)) idb.set('ep:' + room, n).catch(() => {}) } }
118
+ // NEVER BACKWARDS: a key for a room this worker holds a NEWER key of (a higher epoch) is refused — the hosted vault re-seeds
119
+ // every key it holds at each launch with no epoch, an old link carries its old key, the index of a device that had not yet
120
+ // learned the change carries the old one. A room never re-keyed has epoch 0 everywhere: nothing is refused (as before).
121
+ const backwards = (room, held, incoming, ep) => held !== incoming && (Number(ep) || 0) < (eps.get(room) || 0) // nothing held is no exception: a dropped old key re-seeded without an epoch must not come back
122
+ // THE VAULT LEARNS A RE-KEYED ROOM'S KEY (`keyEpoch`): the hosted vault keeps its own copy of every key (its keyring, the
123
+ // account cache) and seeds a fresh worker from it — told here, it holds the new key and its epoch (vault-loader.js), and
124
+ // never hands the frame or the next worker the old one. Only a key with an epoch, only when it changed. The vault page is
125
+ // this worker's owner and already holds every key; the regular app's page ignores the message.
126
+ const tellEpoch = (room, ep, key) => { if (volatile.has(room) || String(room).startsWith('tmp-')) return; try { self.postMessage({ t: 'keyEpoch', room, ep, ...key }) } catch { /* */ } } // never a memory-only (attested) or temporary room's key: the vault would keep it in its account cache
127
+ const keep = (room, mk, ep) => { if (backwards(room, mks.get(room), mk, ep)) return false; if ((Number(ep) || 0) > 0 && (mks.get(room) !== mk || Number(ep) > (eps.get(room) || 0))) tellEpoch(room, Number(ep), { mk }); if (ep) noteEp(room, ep); mks.set(room, mk); rekeyStream(room, mk); persist('mk:' + room, mk); deriveNotifKey(mk).then((nk) => persistNk(room, nk)).catch(() => {}) } // + NK mirror: every mk the kernel holds (normal OR reconstructed-split) yields a push-preview key, so a background notification for THIS room shows sender+text (vault-sw.js notifPreview), not the generic nudge
128
+ // WHY a room has no key, per room — the worker's own verdict rides the no_key answer (the owner's trail said only "no key on
129
+ // this device" while the index held a share for every room, 2026-10-03).
130
+ const APPSHARE_URL = (() => { try { const o = self.location && self.location.origin; return (o && o !== 'null') ? o + '/api/appshare' : '/api/appshare' } catch (e) { return '/api/appshare' } })()
131
+ const noKeyWhy = new Map()
132
+ const noKeyReason = (room) => 'no key on this device' + (noKeyWhy.has(room) ? ' — ' + noKeyWhy.get(room) : '')
133
+ // Every DIFFERENT split share seen for a room, besides the held one. The index absorb replaces a held share on every read
134
+ // (seconds apart), so a share seeded from the room's own link was shadowed by the index's copy within a breath; resolveMk
135
+ // tries them all against the server's half and promotes the one whose commitment holds.
136
+ const splitAlts = new Map()
137
+ // A NEWER SHARE MAKES THE HELD KEY OLD (the owner, 2026-10-22: "the second device did not follow"): a split room's grant is the
138
+ // new user half; the full key this worker held is the room's OLD key, and resolveMk prefers a held key — so every read went
139
+ // out with it, came back stale_key, and the device fetched its grant for ever. It is dropped; the next read rebuilds the
140
+ // key from the new share and the app's half, checked against the room's commitment (resolveMk).
141
+ // A HELD KEY THAT IS NOT THE SHARE'S (the owner's second device, 2026-10-22): an older worker kept a re-keyed split room's OLD
142
+ // key beside its new share, on disk — and the held key wins in resolveMk. For a re-keyed split room (epoch > 0) the held key
143
+ // must be the one the share's commitment names; if not, it is dropped and the key rebuilt from the share and the app half.
144
+ // Checked once per key (a hash), never for a room that was not re-keyed.
145
+ const heldOk = new Map() // room → the held key that was checked against the share's commitment
146
+ async function heldMatchesShare (room, have) {
147
+ const sp = splits.get(room)
148
+ if (!sp || !sp.commit || !((eps.get(room) || 0) > 0) || heldOk.get(room) === have) return true
149
+ let ok = false
150
+ try { ok = (await commitMk(have)) === sp.commit } catch { ok = false }
151
+ if (ok) { heldOk.set(room, have); return true }
152
+ dropOldKey(room); return false
153
+ }
154
+ const dropOldKey = (room) => { if (!mks.has(room)) return; const h = streams.get(room); if (h) { h.s?.stop(); h.mk = null; h.grants = null }; grantsByRoom.delete(room); mks.delete(room); keysReady.then(() => idb.del('mk:' + room)).catch(() => {}) }
155
+ const keepSplit = (room, sp, ep) => { if (backwards(room, splits.get(room) && splits.get(room).userShare, sp.userShare, ep)) return false; if ((Number(ep) || 0) > 0 && ((splits.get(room) || {}).userShare !== sp.userShare || Number(ep) > (eps.get(room) || 0))) { tellEpoch(room, Number(ep), { split: { userShare: sp.userShare, commit: sp.commit || '' } }); if (Number(ep) > (eps.get(room) || 0) || (splits.get(room) || {}).userShare !== sp.userShare) dropOldKey(room) } if (ep) noteEp(room, ep); const held = splits.get(room); if (held && held.userShare !== sp.userShare) { const alts = splitAlts.get(room) || []; if (!alts.some((a) => a.userShare === held.userShare)) splitAlts.set(room, [held, ...alts].slice(0, 4)) } splits.set(room, sp); persist('us:' + room, sp) }
156
+ // The mirror of keep/keepSplit, and the thing that makes "delete this Space" mean anything: without it the app cleared
157
+ // localStorage while the WORKER kept the key — in memory AND in idb, from which a freshly-created worker reloads it at
158
+ // boot (the idb.entries('mk:') restore below). So a deleted room's key came BACK on the next page load. Clears every
159
+ // trace: the live maps, the persisted mk, the derived notification key, and the split half.
160
+ const forget = (room) => {
161
+ grantsByRoom.delete(room); streams.get(room)?.s?.stop(); streams.delete(room)
162
+ mks.delete(room); splits.delete(room); eps.delete(room)
163
+ for (const prefix of ['mk:', 'us:', 'nk:']) parked.delete(prefix + room)
164
+ lastPos.delete(room); heldOk.delete(room); splitAlts.delete(room)
165
+ return Promise.all(['mk:', 'nk:', 'us:', 'ep:', 'cnt:'].map(prefix => idb.delStrict(prefix + room)))
166
+ }
167
+ async function resolveMk(room) {
168
+ // ⚑ WAIT for the idb key map. EVERY page load starts a FRESH worker (plus browsers evict them), and the map loads
169
+ // asynchronously — so a room opened before that load finishes resolves against an EMPTY map and reports "no key". The
170
+ // user sees "This link is missing its key" while the key sits in idb the whole time (hasMk reads false too: presence
171
+ // hasn't published yet). Platform-independent — desktop and Android hit it as readily as iOS. keysReady settles once,
172
+ // so this costs nothing after boot. THE cold-start race behind the recurring missing-key report.
173
+ try { await keysReady } catch { /* load failed → fall through to the stores as they stand */ }
174
+ const have = mks.get(room); if (have && await heldMatchesShare(room, have)) return have
175
+ const sp = splits.get(room); if (!sp) { noKeyWhy.set(room, 'no split share held'); return undefined }
176
+ let r = null
177
+ try {
178
+ // ABSOLUTE, on this worker's own origin. The vault spawns this worker from a blob: URL, and a relative URL cannot be
179
+ // resolved against one — WebKit: "URL is not valid or contains user credentials." So the app half was NEVER fetched
180
+ // from the hoisted worker: every room that reached a device as a split share through the index read no_key (the owner's
181
+ // fresh install, 2026-10-03). A blob worker's origin is its creator's, so this lands on the vault's /api/appshare.
182
+ const x = await fetch(APPSHARE_URL, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ op: 'get', room }) }) // op 'get': the builder's template (spaces/templates/appshare) needs it; Witbitz's own function reads any non-create as a get
183
+ if (!x.ok) { noKeyWhy.set(room, 'app half: HTTP ' + x.status); return undefined }
184
+ r = await x.json()
185
+ } catch (e) { noKeyWhy.set(room, 'app half: ' + String((e && e.message) || e).slice(0, 60)); return undefined } // offline / tenant down → no key
186
+ if (!r || !r.appShare) { noKeyWhy.set(room, 'app half: no share in the answer'); return undefined }
187
+ const cands = [sp, ...(splitAlts.get(room) || [])]
188
+ for (const c of cands) { // §6.4 commit-check, over every share seen for the room (held first)
189
+ const mk = combineShares(c.userShare, r.appShare)
190
+ if (mk && (!c.commit || (await commitMk(mk)) === c.commit)) { if (c !== sp) keepSplit(room, c); keep(room, mk, c === sp ? eps.get(room) : 0); noKeyWhy.delete(room); return mk } // an alternate that holds becomes the held share
191
+ }
192
+ noKeyWhy.set(room, 'commitment mismatch: ' + cands.length + ' share(s) tried against the server half' + (r.commit ? ' (server commit ' + String(r.commit).slice(0, 8) + '…)' : ''))
193
+ return undefined
194
+ }
195
+ // §ID-CONFINE: the per-room SIGNING IDENTITY (the priv key that authors turns) lives HERE, not on the app main thread.
196
+ // Seeded by the vault (rememberId) from the account backup / at create+join; the turn op signs with it so the app never
197
+ // holds — or passes up — the private signing key. An invite/open room's id is {name, sign:{priv,pub?}, grant, gk}; an
198
+ // email room's is {email, sign:{priv,pub}, googleIdToken}. Never posts back out (same discipline as mk).
199
+ const ids = new Map() // room → identity (priv included)
200
+ let encKey = null // pushed enclave snapshot
201
+ let encKeys = {} // { region: { key, attested } } — each room seals to ITS region's enclave (docs/multi-region.md)
202
+ let encAttested = null // {pcrs, policyVersion, platform:{pcrs}} — the live attestation the room blocks are checked against
203
+ let encTrusted // the builds THIS USER accepted (trustedBuilds.js, pushed with the snapshot); undefined = not known yet → the gate refuses
204
+ const encRooms = new Set()
205
+ const authWaiters = new Map()
206
+ let aseq = 0
207
+ const attestWaiters = new Map()
208
+ // a create's DELETION COMMITMENT, asked of the vault that started this worker (vault-core.js) — never of a page
209
+ const delWaiters = new Map()
210
+ let dseq = 0, delAsking = 0
211
+ const askDel = (room) => new Promise((resolve) => {
212
+ const a = ++dseq
213
+ delWaiters.set(a, resolve)
214
+ self.postMessage({ delReq: a, room })
215
+ setTimeout(() => { if (delWaiters.delete(a)) resolve(null) }, 5000) // no answer: the room is made without one, as before
216
+ })
217
+ let atseq = 0
218
+
219
+ // Mirror WHICH rooms we hold a key for (room ids only — never the keys) so the main thread can answer
220
+ // hasMk(room) synchronously without holding mk (A2b presence mirror, feeds A2c value-eviction).
221
+ const publishPresence = () => self.postMessage({ t: 'presence', rooms: [...new Set([...mks.keys(), ...splits.keys()])], rk: 2, tl: 1 }) // tl: this worker keeps the temp-Spaces list (ops tempHold / tempList) — a hosted frame on a newer build than its vault checks it // rk: what this worker can re-key in place — 2 = split rooms (only the user's half) + never backwards + keyEpoch to its vault; a hosted frame on a newer build checks it (the vault's worker follows Official) // §9: a split room counts as "held" (userShare present; mk reconstructed on demand)
222
+
223
+ // Load the COMPLETE, persistent map from idb at boot (rememberMk mirrors every mk under 'mk:'+room).
224
+ // This makes hasMk correct across sessions without the main thread ever pushing keys.
225
+ // ⚑ keysReady: indexWrite MUST await this. The load is async, and indexWrite DROPS any room whose key this worker doesn't
226
+ // hold — so an index push that lands before the map is loaded (iOS evicts workers aggressively; a fresh one starts empty)
227
+ // would strip EVERY room's key from the shared index doc in a single write, account-wide and unrecoverable.
228
+ // §NAMES: a store already kept under opaque names (the flag, or any `p:` key) is protected: the names go on, LOCKED, before the
229
+ // scan — the scan then finds nothing until the unlock gives the key, and no clear key is ever written meanwhile.
230
+ const namesReady = Promise.all([idb.getRaw('protectedNames'), idb.keysRaw('p:')]).then(([f, ks]) => { if (f || (ks && ks.length)) { setIdbNaming({ on: true }); protectedAtRest = true } }).catch(() => {})
231
+ const keysReady = namesReady.then(() => Promise.all([
232
+ idb.entries('mk:').then((es) => { let n = 0; for (const [k, v] of es) if (isSealed(v)) { parked.set(k, v); protectedAtRest = true } else if (v) { mks.set(k.slice(3), v); n++ } if (n) publishPresence() }).catch(() => {}), // a sealed entry waits for the device key (§PROTECT)
233
+ idb.entries('ep:').then((es) => { for (const [k, v] of es) { const n = Number(v); if (n > 0) eps.set(k.slice(3), n) } }).catch(() => {}), // key epochs (noteEp)
234
+ idb.entries('us:').then((es) => { let n = 0; for (const [k, v] of es) if (isSealed(v)) { parked.set(k, v); protectedAtRest = true } else if (v && v.userShare) { splits.set(k.slice(3), v); n++ } if (n) publishPresence() }).catch(() => {}), // reload the split shares too — the reclaim-window fix
235
+ ]))
236
+
237
+ // auth shim → main thread (which holds the localStorage-backed cachedEmailAuth)
238
+ const AUTH_WAIT_MS = 20_000 // longer than a silent renewal (the email session's /refresh), far shorter than for ever
239
+ const auth = (room) => {
240
+ // §ID-CONFINE: when we HOLD the room's email identity ({email, sign:{priv,pub}, googleIdToken}), resolve the gated-room
241
+ // READ auth ({idToken, spk}) HERE — so the token never has to travel to the app (no authReq round-trip). Rooms we don't
242
+ // hold (flag off / not yet seeded / invite rooms) fall back to the main-thread shim, unchanged. Inert until an email
243
+ // identity is seeded (nothing does so yet — the email slice wires the vault seed).
244
+ const id = ids.get(room)
245
+ if (id && id.googleIdToken && id.sign && id.sign.pub) return Promise.resolve({ idToken: id.googleIdToken, spk: id.sign.pub })
246
+ return new Promise((resolve) => {
247
+ const a = ++aseq
248
+ authWaiters.set(a, resolve)
249
+ self.postMessage({ authReq: a, room })
250
+ // A request nobody answers (the frame it went to is gone — liveFrames.js) must not hold the read for ever: after
251
+ // AUTH_WAIT_MS it goes out unsigned, exactly as when the page answers "no sign-in", and the room says so.
252
+ setTimeout(() => { const w = authWaiters.get(a); if (w) { authWaiters.delete(a); w({}) } }, AUTH_WAIT_MS)
253
+ })
254
+ }
255
+
256
+ // attestation shim → main thread (which reaches the L1 vault that mints client-release attestations). A verified room's
257
+ // material read runs HERE (mk stays worker-side), so the worker's spaceClient asks the main thread for the attestation.
258
+ const attestShim = (room, o) => new Promise((resolve) => {
259
+ const a = ++atseq
260
+ attestWaiters.set(a, resolve)
261
+ self.postMessage({ attestReq: a, room, ...(o && typeof o === 'object' ? { o: { read: o.read === true, challenge: typeof o.challenge === 'string' ? o.challenge : undefined } } : {}) }) // o: an attested READ (docs/emulated-attested-rooms.md step 2)
262
+ })
263
+ setAttestProvider(attestShim)
264
+
265
+ // The origin's small kv database, shared with the service worker (sw-notif-core.js uses the same name/store): the
266
+ // push handler leaves a PREFETCHED poll answer here and reads the room's position from here. Every call is bounded —
267
+ // a hung database must never hold a poll.
268
+ const IDB_WAIT = 2500
269
+ const idbOpen = () => new Promise((res) => { const t = setTimeout(() => res(null), IDB_WAIT); try { const r = indexedDB.open('spaces', 1); r.onupgradeneeded = () => { try { r.result.createObjectStore('kv') } catch { /* */ } }; r.onsuccess = () => { clearTimeout(t); const db = r.result; db.onversionchange = () => db.close(); res(db) }; r.onerror = () => { clearTimeout(t); res(null) } } catch { clearTimeout(t); res(null) } })
270
+ const idbGet = async (k) => { try { const db = await idbOpen(); if (!db) return null; return await new Promise((res) => { const t = setTimeout(() => res(null), IDB_WAIT); const q = db.transaction('kv', 'readonly').objectStore('kv').get(k); q.onsuccess = () => { clearTimeout(t); res(q.result || null) }; q.onerror = () => { clearTimeout(t); res(null) } }) } catch { return null } }
271
+ const idbSet = async (k, v) => { try { const db = await idbOpen(); if (!db) return false; return await new Promise((res) => { const t = setTimeout(() => res(false), IDB_WAIT); const q = db.transaction('kv', 'readwrite').objectStore('kv').put(v, k); q.onsuccess = () => { clearTimeout(t); res(true) }; q.onerror = () => { clearTimeout(t); res(false) } }) } catch { return false } }
272
+ const idbDel = async (k) => { try { const db = await idbOpen(); if (!db) return false; return await new Promise((res) => { const t = setTimeout(() => res(false), IDB_WAIT); const q = db.transaction('kv', 'readwrite').objectStore('kv').delete(k); q.onsuccess = () => { clearTimeout(t); res(true) }; q.onerror = () => { clearTimeout(t); res(false) } }) } catch { return false } }
273
+ const lastPos = new Map() // room → the position last written to cnt:<room> (write only on change)
274
+ const prefetchChecked = new Set() // rooms whose prefetch slot this worker has looked at
275
+ const prefetchFlag = new Set() // rooms the service worker announced a fresh prefetch for
276
+ let prefetchLookUntil = 0 // after a 'wakeup' (the page came to the foreground) every poll looks, for a few seconds: the first poll of a resumed page is already on its way before any tap message, and the push's announcement is lost while iOS holds the page suspended
277
+ try { const pfc = new BroadcastChannel('wb-prefetch'); pfc.onmessage = (e) => { const r = e && e.data && e.data.room; if (typeof r === 'string') prefetchFlag.add(r) } } catch { /* no BroadcastChannel: the first-poll check still runs */ }
278
+
279
+ self.onmessage = async (e) => {
280
+ const m = e.data || {}
281
+ switch (m.t) {
282
+ case 'delRes': {
283
+ const w = delWaiters.get(m.a)
284
+ if (w) { delWaiters.delete(m.a); w(typeof m.v === 'string' ? m.v : null) }
285
+ return
286
+ }
287
+ case 'authRes': {
288
+ const w = authWaiters.get(m.a)
289
+ if (w) { authWaiters.delete(m.a); w(m.v || {}) }
290
+ return
291
+ }
292
+ case 'attestRes': {
293
+ const w = attestWaiters.get(m.a)
294
+ if (w) { attestWaiters.delete(m.a); w(m.v || null) }
295
+ return
296
+ }
297
+ case 'enclave': { // main pushes {key, attested, acceptance, rooms} at open + on wake/re-attest
298
+ encKey = m.key || null
299
+ encAttested = m.attested || null
300
+ encKeys = (m.keys && typeof m.keys === 'object') ? m.keys : {}
301
+ const snap = (m.acceptance && typeof m.acceptance === 'object') ? m.acceptance : {}
302
+ encTrusted = Array.isArray(snap.trusted) ? snap.trusted : undefined
303
+ encRooms.clear()
304
+ for (const r of (m.rooms || [])) encRooms.add(r)
305
+ if (m.id != null) self.postMessage({ id: m.id, result: true })
306
+ return
307
+ }
308
+ // ── §PROTECT (docs/device-storage-protection.md): the device key arrives as 32 raw bytes, is imported non-extractable, and lives only here.
309
+ case 'seal': { // {id, key} → switch ON: hold the key, rewrite every persisted key sealed
310
+ try {
311
+ sealKey = await importSealKey(m.key); protectedAtRest = true; nkClear = !!m.previews
312
+ await keysReady
313
+ // Sealed entries parked at boot while protection was OFF are an earlier setup's leftovers: no lock names their key,
314
+ // so nothing can open them — and the next unlock would throw on the first one and stay locked. They go.
315
+ for (const k of parked.keys()) { try { await idb.delRaw(k) } catch { /* */ } }
316
+ parked.clear()
317
+ // …and a leftover sealed nk: — the boot scan parks only mk:/us:, so it stayed, and an unlock with no other sealed key
318
+ // re-reads the store and throws on it (the vault drops all three, vault-loader dropStaleKeys; sync sweep backlog P6)
319
+ for (const [k, v] of await idb.entries('nk:')) if (isSealed(v)) { try { await idb.delRaw(k) } catch { /* */ } }
320
+ await armIdbNaming(m.key)
321
+ let n = 0
322
+ for (const [room, mk] of mks) { await persist('mk:' + room, mk); n++; try { await persistNk(room, await deriveNotifKey(mk)) } catch { /* no nk → no sealed nk */ } }
323
+ for (const [room, sp] of splits) { await persist('us:' + room, sp); n++ }
324
+ self.postMessage({ id: m.id, result: { sealed: n } })
325
+ } catch (err) { sealKey = null; self.postMessage({ id: m.id, error: 'seal: ' + String((err && err.message) || err) }) }
326
+ return
327
+ }
328
+ case 'unseal': { // {id, key} → unlock: open every parked (or persisted) sealed entry into the maps
329
+ try {
330
+ const t0 = performance.now(), ms = {} // where the unlock's time goes (spaceAtRest.js prints it): the owner's iPhone, 96 ms here
331
+ const key = await importSealKey(m.key); nkClear = !!m.previews
332
+ await keysReady; ms.ready = performance.now() - t0; await armIdbNaming(m.key); ms.names = performance.now() - t0
333
+ if ((await idb.keysRaw('p:')).length && !(await idb.nameIndex()).length) { setIdbNaming({ on: true }); throw new Error('this key opens nothing here') } // §NAMES: a wrong key reads no name — refuse, and stay locked (never write under its names)
334
+ ms.check = performance.now() - t0
335
+ if (!parked.size) for (const pfx of ['mk:', 'us:', 'nk:']) for (const [k, v] of await idb.entries(pfx)) if (isSealed(v)) parked.set(k, v) // after a relock the maps are empty: re-read the sealed store
336
+ ms.read = performance.now() - t0; ms.n = parked.size
337
+ let n = 0
338
+ // ALL AT ONCE, then into the maps (2026-11-17: one by one, WebKit's WebCrypto costs a thread hop per key — ~450 rooms on the
339
+ // owner's iPhone): a wrong key THROWS → nothing opened, the page shows the lock again
340
+ const all = [...parked], vals = await Promise.all(all.map(([, blob]) => openSealed(key, blob)))
341
+ all.forEach(([k], i) => {
342
+ const v = vals[i]
343
+ if (k.startsWith('mk:')) { mks.set(k.slice(3), v); n++ } else if (k.startsWith('us:')) { if (v && v.userShare) { splits.set(k.slice(3), v); n++ } } // nk: is derived from mk at keep(); nothing to hold in memory
344
+ })
345
+ parked.clear(); sealKey = key; protectedAtRest = true
346
+ for (const [room, mk] of mks) { persist('mk:' + room, mk); deriveNotifKey(mk).then((nk) => persistNk(room, nk)).catch(() => {}) } // keys that reached the locked worker (the page re-sent them at open) are persisted sealed now
347
+ for (const [room, sp] of splits) persist('us:' + room, sp)
348
+ ms.open = performance.now() - t0
349
+ if (n) publishPresence()
350
+ self.postMessage({ id: m.id, result: { opened: n, ms } })
351
+ } catch (err) { self.postMessage({ id: m.id, error: 'unseal: ' + String((err && err.message) || err) }) }
352
+ return
353
+ }
354
+ case 'previews': { // {id, on} → §PREVIEWS toggled while unlocked: rewrite every nk: clear (on) or sealed (off)
355
+ nkClear = !!m.on
356
+ try { if (sealKey) for (const [room, mk] of mks) { try { await persistNk(room, await deriveNotifKey(mk)) } catch { /* */ } } } catch { /* */ }
357
+ if (m.id != null) self.postMessage({ id: m.id, result: { previews: nkClear } })
358
+ return
359
+ }
360
+ case 'memoryOnly': { // {id} → a room link on an unsecured computer: keys stay in memory, persist() writes nothing
361
+ protectedAtRest = true; sealKey = null; setIdbNaming({ on: true }) // names on, no key: every write is dropped
362
+ if (m.id != null) self.postMessage({ id: m.id, result: true })
363
+ return
364
+ }
365
+ case 'relock': { // {id} → the lock engaged: nothing usable stays in memory
366
+ if (sealKey) { mks.clear(); splits.clear(); parked.clear(); sealKey = null; setIdbNaming({ on: true }); publishPresence() } // unprotected devices keep their maps — a relock means nothing to them
367
+ if (m.id != null) self.postMessage({ id: m.id, result: true })
368
+ return
369
+ }
370
+ case 'unprotect': { // {id, key} → switch OFF: open everything and write it back in the clear
371
+ try {
372
+ const key = await importSealKey(m.key)
373
+ await keysReady; await armIdbNaming(m.key)
374
+ // §NAMES: take every key from under its opaque name (or its real name, if the page moved it back first), then names off
375
+ const held = []
376
+ for (const pfx of ['mk:', 'us:']) for (const [k, v] of await idb.entries(pfx)) { held.push([k, v]); await idb.del(k) }
377
+ setIdbNaming({ on: false })
378
+ for (const [k, v] of await idb.entries('nk:')) if (isSealed(v)) held.push([k, v])
379
+ for (const [k, v] of held) { const clear = isSealed(v) ? await openSealed(key, v) : v; await idb.set(k, clear); if (k.startsWith('mk:')) mks.set(k.slice(3), clear); else if (k.startsWith('us:') && clear && clear.userShare) splits.set(k.slice(3), clear) }
380
+ parked.clear(); sealKey = null; protectedAtRest = false; nkClear = false; publishPresence()
381
+ for (const [room, mk] of mks) deriveNotifKey(mk).then((nk) => persistNk(room, nk)).catch(() => {}) // the preview keys a protected device did not keep
382
+ self.postMessage({ id: m.id, result: true })
383
+ } catch (err) { self.postMessage({ id: m.id, error: 'unprotect: ' + String((err && err.message) || err) }) }
384
+ return
385
+ }
386
+ case 'presenceQuery': { // say which keys are held now, once the stored ones are in (a late frame asks: the tenant launch, 2026-10-16)
387
+ await keysReady; publishPresence()
388
+ if (m.id != null) self.postMessage({ id: m.id, result: true })
389
+ return
390
+ }
391
+ case 'wipeKeys': { // root-vault only: parked/opaque keys count even when no room list can name them
392
+ storageWiped = true; storageEpoch++
393
+ await keysReady
394
+ for (const h of streams.values()) h.s?.stop()
395
+ streams.clear(); grantsByRoom.clear()
396
+ mks.clear(); splits.clear(); parked.clear(); splitAlts.clear(); eps.clear(); heldOk.clear(); lastPos.clear()
397
+ ids.clear()
398
+ try { await idb.clearStrict(); self.postMessage({ id: m.id, result: true }) }
399
+ catch (error) { self.postMessage({ id: m.id, error: String(error?.message || error) }) }
400
+ finally { publishPresence() }
401
+ return
402
+ }
403
+ case 'volatile': { // {rooms} → these rooms' keys are memory-only from now on: drop what is stored, write nothing
404
+ for (const r of (Array.isArray(m.rooms) ? m.rooms : [])) if (typeof r === 'string' && r && !volatile.has(r)) { volatile.add(r); keysReady.then(() => Promise.all([idb.del('mk:' + r), idb.del('us:' + r)])).catch(() => {}) } // its preview key stays (attNk): the room key never did
405
+ if (m.id != null) self.postMessage({ id: m.id, result: true })
406
+ return
407
+ }
408
+ case 'remember': { // {room, mk} → store a key in the map (the worker becomes the mk store)
409
+ // AFTER the boot scan: the stored key and its epoch are loaded first, so a launch's re-seed (no epoch) is judged against
410
+ // them — before, the scan put the new key back in memory and the re-seed's queued write put the old one on disk
411
+ keysReady.then(() => { if (m.room && m.mk) { keep(m.room, m.mk, m.ep); publishPresence() } if (m.id != null) self.postMessage({ id: m.id, result: true }) }) // m.ep: a re-keyed room's epoch (space.js adoptRoomKey)
412
+ return
413
+ }
414
+ case 'create': { // {id, cfg, base} → mint a Space HERE (vault-core.js, docs/sdk-vault-mode.md): its key is born in
415
+ // this worker and kept here; the reply carries the room and its share link (the vault keeps the link — it is the
416
+ // key — and hands its page only the room id). The client must be open (endpoint/app) first.
417
+ try {
418
+ if (!client) throw new Error('l1-worker: create before open')
419
+ // a SPLIT room is made through the builder's app-half function on this worker's own origin (the same one resolveMk asks)
420
+ const via = m.split ? async (body) => { const x = await fetch(APPSHARE_URL, { method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); const j = await x.json().catch(() => ({})); return { ...(j && typeof j === 'object' ? j : {}), status: x.status } } : null
421
+ if (m.delAsk) delAsking++
422
+ let r
423
+ try { r = await client.create(m.cfg || {}, { base: m.base || undefined, ...(m.enclave ? { enclave: true } : {}), ...(via ? { split: true, via } : {}) }) } finally { if (m.delAsk) delAsking-- }
424
+ if (!r || !r.room || !r.mk) throw new Error('create: ' + String((r && (r.error || r.status)) || 'no room'))
425
+ if (m.split) { if (!r.userShare) throw new Error('create: the app-half function gave no share'); keepSplit(r.room, { userShare: r.userShare, commit: r.commit || '' }) }
426
+ keep(r.room, r.mk); publishPresence()
427
+ const link0 = (r.links && r.links[0]) || null
428
+ // a split room's link is the user's HALF (#us=…&spc=…), never the key; a confidential room's sealed config (ciphertext) rides back for the enclave's own copy
429
+ const link = m.split && link0 ? String(link0).split('#')[0] + '#us=' + encodeURIComponent(r.userShare) + (r.commit ? '&spc=' + encodeURIComponent(r.commit) : '') : link0
430
+ self.postMessage({ id: m.id, result: { room: r.room, link, ...(r.enclaveCreated === true ? { enclaveCreated: true } : {}), commit: r.commit || null, ...(r.configSealed ? { configSealed: r.configSealed } : {}), ...(m.returnMk ? { mk: r.mk } : {}) } }) // returnMk: the vault's own move needs the new key for its notice
431
+ } catch (err) { self.postMessage({ id: m.id, error: String((err && err.message) || err) }) }
432
+ return
433
+ }
434
+ case 'forget': { // {room} → DROP the key. AWAITS the idb deletes before replying: the caller holds
435
+ // navigation until it resolves, and a dedicated worker dies with its page — a fire-and-forget delete could be
436
+ // cut off mid-write, leaving the key in idb for the next worker to reload.
437
+ try {
438
+ await keysReady
439
+ if (m.room) await forget(m.room)
440
+ if (m.id != null) self.postMessage({ id: m.id, result: true })
441
+ } catch (error) {
442
+ if (m.id != null) self.postMessage({ id: m.id, error: String(error?.message || error) })
443
+ } finally { publishPresence() }
444
+ return
445
+ }
446
+ case 'setPushAcct': { // {room} = the account's INDEX room → derive the account push secret from ITS key, here,
447
+ // where the key lives (the page holds only the room id). Turns and subscriptions then carry the account tag, so the
448
+ // server skips the poster's OTHER devices too (spaceClient pushAcctField).
449
+ // {secret}: the secret itself (a one-way derivation, never a key), from a page that holds the index key on its own thread —
450
+ // the builders' vault (vault-core.js; sync sweep 11-16 #14). '' clears it (signed out).
451
+ try {
452
+ if (typeof m.secret === 'string') { if (m.secret === '' || /^[A-Za-z0-9_-]{43}$/.test(m.secret)) setPushAcct(m.secret) }
453
+ else { const mk = m.room ? (mks.get(m.room) || await resolveMk(m.room)) : ''; setPushAcct(await pushAcctSecretOf(mk || '')) }
454
+ } catch { /* */ }
455
+ if (m.id != null) self.postMessage({ id: m.id, result: true })
456
+ return
457
+ }
458
+ case 'prefetchIdentity': { // {token} → this worker's client fetches the sign-in's hints now (option B; sweep 11-06 #9)
459
+ try { if (client && typeof client.prefetchIdentity === 'function') await client.prefetchIdentity(String(m.token || '')) } catch { /* */ }
460
+ if (m.id != null) self.postMessage({ id: m.id, result: true })
461
+ return
462
+ }
463
+ case 'setPushSelf': { // {endpoint} → set THIS worker's spaceClient pushSelf. Turns are composed + POSTed
464
+ // HERE (the worker's own spaceClient instance), so the main-thread setPushSelf never reached the POST — the turn
465
+ // went out with no endpoint and the server fell back to the coarse author-NAME rule, skipping every device sharing
466
+ // the sender's name. With the endpoint, the server skips only THIS device (mode=endpoint) and tickles the others.
467
+ try { setPushSelf(m.endpoint || '') } catch { /* */ }
468
+ // A stream opened before the endpoint arrived carries no viewing tag: reopen it with one (the server then skips this
469
+ // device's tickle for the room on screen). Same room, same key; only the socket's name changes.
470
+ for (const [room, h] of streams) {
471
+ try { const tag = await viewingTag(room); if (tag && tag !== h.tag && h.mk) { h.s?.stop(); h.s = openStreamHere(room, h.mk, h.grants || null, tag); h.tag = tag } } catch { /* the old socket stays */ }
472
+ }
473
+ if (m.id != null) self.postMessage({ id: m.id, result: true })
474
+ return
475
+ }
476
+ case 'serveKeyPort': { // {room} + a transferred MessagePort → send this room's mk DOWN the port so a SIBLING
477
+ // realm's worker (a same-origin docked lane panel) can adopt it WITHOUT the key ever crossing either main thread.
478
+ // Fire-and-forget: no RPC reply — the port carries the answer ({mk:null} if we don't hold it → the caller falls back).
479
+ const sp = e.ports && e.ports[0]
480
+ if (sp && m.room) { try { const mk = mks.get(m.room) || await resolveMk(m.room); sp.postMessage({ room: m.room, mk: mk || null }) } catch { try { sp.postMessage({ room: m.room, mk: null }) } catch { /* */ } } }
481
+ return
482
+ }
483
+ case 'adoptKeyPort': { // {id, room} + a transferred MessagePort → RECEIVE this room's mk over the port (sent by a
484
+ // sibling realm's worker) and store it in the key map. The main thread only relayed an opaque port; the key never
485
+ // touches L2. Reply {ok} on the RPC channel once stored (false on a null answer / timeout) so the caller can fall back.
486
+ const { id: aid, room: aroom } = m; const ap = e.ports && e.ports[0]
487
+ if (!ap || !aroom) { if (aid != null) self.postMessage({ id: aid, result: { ok: false } }); return }
488
+ let settled = false
489
+ const settle = (ok) => { if (settled) return; settled = true; try { ap.close() } catch { /* */ } if (aid != null) self.postMessage({ id: aid, result: { ok } }) }
490
+ ap.onmessage = (ev) => { const d = (ev && ev.data) || {}; if (d.mk && d.room === aroom) { keep(aroom, d.mk); publishPresence(); settle(true) } else settle(false) }
491
+ setTimeout(() => settle(false), m.timeoutMs > 0 ? m.timeoutMs : 8000) // the SERVING side may need a live appshare fetch to reconstruct a split mk (resolveMk) — 1.5s lost that race on cellular and read as 'parent:no'
492
+ return
493
+ }
494
+ case 'wakeup': { prefetchLookUntil = Date.now() + 8000; return } // the page came to the foreground (vault-loader.js / space.js onVisibility): look for a push-time prefetch on the polls that follow
495
+ case 'ping': { self.postMessage({ t: 'pong', n: m.n | 0 }); return } // liveness heartbeat — the vault detects a RECLAIMED worker (iOS memory pressure) and recreates it; without this a dead handle ate every message silently and rooms stopped opening
496
+ case 'rememberSplit': { // {room, userShare, commit} → hold the user's HALF here (the confined split store); mk reconstructs on demand via resolveMk. The main thread never keeps the userShare in a live variable.
497
+ keysReady.then(() => { if (m.room && m.userShare) { keepSplit(m.room, { userShare: m.userShare, commit: m.commit || '' }, m.ep); publishPresence() } if (m.id != null) self.postMessage({ id: m.id, result: true }) }) // after the boot scan, as `remember`
498
+ return
499
+ }
500
+ case 'rememberId': { // {room, identity} → hold the room's SIGNING IDENTITY here (the confined identity store). The turn op signs with it; the private signing key never crosses back to the app. Seeded by the vault at create/join and from the account backup. NB the identity travels as `identity` (not `id` — `id` is the RPC sequence field).
501
+ if (m.room && m.identity && m.identity.sign && m.identity.sign.priv) ids.set(m.room, m.identity)
502
+ if (m.id != null) self.postMessage({ id: m.id, result: true })
503
+ return
504
+ }
505
+ case 'ensureMk': { // {id, room} → reconstruct the room's mk HERE (fetch appShare ⊕ combine, commit-checked) + cache it; return only a BOOLEAN availability. mk never crosses back to the main thread — this is the split-room OPEN check without de-confining the key.
506
+ const { id, room } = m
507
+ try { const mk = await resolveMk(room); self.postMessage({ id, result: { ok: !!mk } }) }
508
+ catch (err) { self.postMessage({ id, error: 'ensureMk: ' + String((err && err.message) || err) }) }
509
+ return
510
+ }
511
+ case 'inviteLink': { // {id, room, base, suffix} → the invite link, with the split key fragment (#us=…&spc=…) INJECTED here from the confined store. Main thread supplies only the non-secret base/suffix; it never sees the userShare. null if we hold no split for the room.
512
+ const { id, room, base, suffix } = m
513
+ try {
514
+ const sp = splits.get(room)
515
+ const link = (sp && sp.userShare)
516
+ ? (base + '#us=' + encodeURIComponent(sp.userShare) + (sp.commit ? '&spc=' + encodeURIComponent(sp.commit) : '') + (suffix || ''))
517
+ : null
518
+ self.postMessage({ id, result: { link } })
519
+ } catch (err) { self.postMessage({ id, error: 'inviteLink: ' + String((err && err.message) || err) }) }
520
+ return
521
+ }
522
+ case 'open': { // capture the room's mk here; (re)create the client bound to this realm
523
+ try {
524
+ if (m.room && m.mk) keep(m.room, m.mk)
525
+ // ONE CLIENT PER REALM (sync sweep 2026-11-07 #6): a room open in the SAME realm (endpoint · app · tenant) keeps the client
526
+ // it has — what it learned (option B's prefetched `idextras` hints, gated/verified rooms, older key chains) is the
527
+ // sign-in's and the rooms', not this open's. A new client on every open threw the hints away, so the first sealed request
528
+ // after each open fetched them inline — the timing option B rules out. Every other option reads this worker's state live.
529
+ const realm = JSON.stringify([m.endpoint || '/space', m.app || '', m.tenant || ''])
530
+ if (client && clientRealm === realm) { publishPresence(); self.postMessage({ id: m.id, result: true }); return }
531
+ clientRealm = '' // set again only once the new client is made
532
+ client = makeSpaceClient({
533
+ endpoint: m.endpoint || '/space',
534
+ app: m.app,
535
+ ...(m.tenant ? { tenant: m.tenant } : {}), // a builder's vault (vault-core.js): the Spaces it creates are its tenant's
536
+ auth,
537
+ mkPub: (r) => (encRooms.has(r) ? (() => { const e = encKeys[roomRegion(r)] || (roomRegion(r) === DEFAULT_REGION ? { key: encKey, attested: encAttested } : {}); return gatedKey({ key: e.key || null, trusted: encTrusted, attested: e.attested || null, platform: e.attested && e.attested.platform, room: r }) })() : null), // r's OWN region's key; another region's is never borrowed // trusted undefined until the account's list is known → the gate refuses
538
+ enclave: (r) => encRooms.has(r),
539
+ envelope: (r) => { if (!encRooms.has(r)) return false; const e = encKeys[roomRegion(r)] || (roomRegion(r) === DEFAULT_REGION ? { attested: encAttested } : {}); return opensEnvelopes(e.attested) }, // the sealed request envelope (reqEnvelope.js): this room's live enclave opens it
540
+ identity: (r) => { if (!encRooms.has(r)) return false; const e = encKeys[roomRegion(r)] || (roomRegion(r) === DEFAULT_REGION ? { attested: encAttested } : {}); return sealsIdentity(e.attested) }, // option B: it takes the sign-in from inside
541
+ // A Spaces ACCOUNT's turn token (accountBilling.js) — asked of the page through the auth channel under a reserved
542
+ // name, only when an op can spend. No answer / no session ⇒ '' ⇒ the turn bills as before.
543
+ userToken: async () => { const v = await auth('#account-billing'); return (v && typeof v.userToken === 'string') ? v.userToken : '' },
544
+ // A builder's VAULT (vault-core.js) with an account backup: a create carries the deletion commitment, which only the
545
+ // vault can make (it holds the erase key — sdkErase.js). Asked only while a create that said `delAsk` runs.
546
+ delCommit: (r) => (delAsking > 0 ? askDel(r) : Promise.resolve(null)), // a promise either way: spaceClient .catch()es it
547
+ // THE ROOM PASS (docs/device-gate-design.md): the page holds it (roomPassWiring.js) — asked under the reserved name
548
+ // '#room-pass' with this request's op, room and sign-in (its email and key, never the token); {} = none (off)
549
+ roomPass: {
550
+ fieldsFor: async (body, o) => { const si = signInOf(body); if (!si) return {}; const v = await auth('#room-pass:' + JSON.stringify({ op: body.op, room: body.room, email: si.email, spk: si.spk, ...(o && Number.isFinite(o.ts) ? { ts: o.ts } : {}) })); return v && v.pass && v.psig ? { pass: v.pass, psig: v.psig } : {} }, // ts: this realm's sealNow — the server's clock as learned here
551
+ renew: async (body) => { const si = signInOf(body); if (si) return auth('#room-pass:' + JSON.stringify({ renew: true, email: si.email })) },
552
+ },
553
+ // A SIGN-IN THAT NAMES NO APP (docs/device-gate-design.md § 12.1, `pass: app_unnamed`): renewed by whoever holds it — the
554
+ // page, or the vault for an identity it seeded here — and, when it is one held here, kept here renewed too
555
+ renewSignIn: async (body) => {
556
+ const room = body && body.room
557
+ if (!room || !signInOf(body)) return null
558
+ const v = await auth(SIGNIN_RENEW_AUTH + ':' + room)
559
+ if (v?.retryable) return { retryable: true }
560
+ if (!v || typeof v.idToken !== 'string' || !v.spk) return null
561
+ const id = ids.get(room)
562
+ if (id && id.sign && JSON.stringify(id.sign.pub) === JSON.stringify(v.spk)) ids.set(room, { ...id, googleIdToken: v.idToken })
563
+ return { idToken: v.idToken, spk: v.spk }
564
+ },
565
+ })
566
+ clientRealm = realm
567
+ publishPresence()
568
+ self.postMessage({ id: m.id, result: true })
569
+ } catch (err) {
570
+ self.postMessage({ id: m.id, error: 'open: ' + String((err && err.message) || err) })
571
+ }
572
+ return
573
+ }
574
+ case 'acctSeal': // {obj} → a doc sealed under the ACCOUNT key (the server never holds it) · null without the key
575
+ case 'acctOpen': { // {doc} → its object · null when it will not open here
576
+ ;(async () => {
577
+ try {
578
+ if (!acctKey) return self.postMessage({ id: m.id, result: null })
579
+ const result = m.t === 'acctSeal' ? await sealDoc(acctKey, m.obj) : (isSealedDoc(m.doc) ? await openDoc(acctKey, m.doc) : null)
580
+ self.postMessage({ id: m.id, result })
581
+ } catch { self.postMessage({ id: m.id, result: null }) }
582
+ })()
583
+ return
584
+ }
585
+ case 'acctKey': { // the account-store key (accountSeal.appStoreKey) — from the page's backup master, or the hosting vault's
586
+ acctKey = m.key || null
587
+ oldAcctKeys = Array.isArray(m.old) ? m.old.filter(Boolean) : []
588
+ if (m.id != null) self.postMessage({ id: m.id, result: { ok: !!acctKey } })
589
+ return
590
+ }
591
+ case 'indexRead': { // Atlas: read an index doc, ABSORB room→mk pointers into the key store, return KEYLESS
592
+ const { id, indexRoom, indexMk, name } = m
593
+ // ⛔ keyless: the caller does not own this worker — the hosted app frame, through its vault (§HOIST; the vault
594
+ // sets it on every relayed read of a frame that says so). It gets NO key back: no mkeys mirror, only which rooms are split
595
+ // (`splits`: room → its commit, which is not secret — roomState isSplitRoom reads it) (the owner, 2026-11-13; docs/sdk-convergence.md)
596
+ const keylessAsk = !!m.keyless
597
+ try {
598
+ if (!client) throw new Error('l1-worker: indexRead before open')
599
+ await keysReady // so hasMk/presence reflect the FULL map right after an absorb (a half-loaded map reads as "no key")
600
+ if (indexMk && !mks.get(indexRoom)) { keep(indexRoom, indexMk); publishPresence() } // the app passes the index ROOM's key so we can open the doc even when it was adopted from a backup
601
+ const r = await acct.get(indexRoom, mks.get(indexRoom) || indexMk, name, { plainOpen: unzipDoc }) // SEALED on the device (accountStores.js); the plain doc read through until it moves
602
+ if (!(r && r.status === 200 && r.state)) { self.postMessage({ id, result: { status: (r && r.status) || 0, state: null } }); return }
603
+ let st = r.state
604
+ const mirror = {} // → the main thread's localStorage cache (see below); `rooms` itself stays KEYLESS as before
605
+ const splitRooms = {} // room → commit: which listed rooms are split, with no share (what a keyless caller is told)
606
+ if (st && typeof st === 'object' && st.rooms && typeof st.rooms === 'object') {
607
+ const keyless = {}; let replaced = 0 // held split shares the doc's copy differs from (see keepSplit / splitAlts)
608
+ for (const rm of Object.keys(st.rooms)) { const e = st.rooms[rm] || {}; if (e.deleted) { const { mk: _dmk, ep: _dep, split: _ds, userShare: _du, commit: _dc, ...rest } = e; keyless[rm] = rest; continue } /* a DELETED Space's key is never taken back (2026-11-12: it returned on every sync and the delete ran again) */ if (e.split && e.userShare) { const held = splits.get(rm); if (keepSplit(rm, { userShare: e.userShare, commit: e.commit || '' }, e.ep) !== false) { if (held && held.userShare !== e.userShare) replaced++; mirror[rm] = { split: true, userShare: e.userShare, commit: e.commit || '' } } splitRooms[rm] = String(((splits.get(rm) || {}).commit) || e.commit || ''); const { split: _s, userShare: _u, commit: _c, ep: _sep, ...rest } = e; keyless[rm] = rest } else { if (e.mk && (mks.get(rm) === e.mk || (Number(e.ep) || 0) >= (eps.get(rm) || 0))) { keep(rm, e.mk, e.ep); mirror[rm] = { mk: e.mk } } const { mk, ep: _ep, ...rest } = e; keyless[rm] = rest } } // ABSORB — never a key OLDER than the one held (noteEp) → strip the key (mk, or a split room's userShare+commit)
609
+ publishPresence()
610
+ { const all = Object.keys(st.rooms); const bare = all.filter((rm) => { const e = st.rooms[rm] || {}; return !e.deleted && !(e.split && e.userShare) && !e.mk && !mks.has(rm) && !splits.has(rm) }); self.postMessage({ t: 'note', line: 'index read: ' + all.length + ' rooms · ' + (all.length - bare.length) + ' with a key here · ' + (bare.length ? 'NO KEY for ' + bare.map((rm) => rm.slice(0, 10)).join(' ') : 'none keyless') + (replaced ? ' · ' + replaced + ' held share(s) differ from the index copy' : '') }) } // the trail says which listed rooms this device cannot open — a fresh device's rooms read 401/422 for a day and nothing said why (2026-10-03)
611
+ st = { ...st, rooms: keyless }
612
+ }
613
+ // ⚑ MIRROR the absorbed keys back to the main thread so it can cache them in localStorage, exactly as a room you
614
+ // CREATE or JOIN here already does (space.js rememberMk writes both stores). Without this, an index-synced room's
615
+ // key lived ONLY in the worker: the open path's synchronous first check missed it and every open had to round-trip
616
+ // the worker (~600ms) while every other room opened instantly — the same key, two storage paths, two speeds.
617
+ // This is a deliberate step AWAY from mk-confinement, chosen knowingly: the device already holds every
618
+ // create/join key in localStorage, so confining only index-synced keys bought no real protection while costing
619
+ // consistency. Real confinement means moving ALL keys into the worker (l1 `evictmk` / confineExistingLaneKeys),
620
+ // not leaving one arrival path out.
621
+ // ⛔ …but NEVER to a keyless caller (above): in the hosted app this answer crossed into the app frame and carried every
622
+ // room key and split share of the account on every index sync. It gets `splits` alone.
623
+ if (name === 'index' && st && typeof st === 'object') {
624
+ for (const field of ['pipesRoom', 'msgsRoom']) {
625
+ const ptr = st[field]
626
+ if (!ptr?.room) continue
627
+ if (ptr.mk) keep(ptr.room, ptr.mk)
628
+ if (keylessAsk) st = { ...st, [field]: { room: ptr.room } }
629
+ }
630
+ publishPresence()
631
+ }
632
+ self.postMessage({ id, result: { status: 200, state: st, splits: splitRooms, ...(keylessAsk ? {} : { mkeys: mirror }), ...(Number.isInteger(r.v) ? { v: r.v } : {}) } }) // v: the version a write names (accountStores put ifV)
633
+ } catch (err) { self.postMessage({ id, error: 'indexRead: ' + String((err && err.message) || err) }) }
634
+ return
635
+ }
636
+ case 'indexWrite': { // Atlas: build the index doc INJECTING each room's mk from the key store; gzip if large
637
+ const { id, indexRoom, indexMk, name, patch, summary, by, ifV } = m
638
+ try {
639
+ if (!client) throw new Error('l1-worker: indexWrite before open')
640
+ await keysReady // NEVER write the index from a half-loaded key map — an empty `mks` would strip every room's key (below)
641
+ if (indexMk && !mks.get(indexRoom)) { keep(indexRoom, indexMk); publishPresence() } // index ROOM key passed by the app (adopted-from-backup case)
642
+ let p = { ...(patch || {}) }
643
+ let previousIndex
644
+ if (p.rooms && typeof p.rooms === 'object') {
645
+ // PRESERVE keys we don't hold. The patch arrives KEYLESS (indexRead strips keys before handing it up), so a room
646
+ // whose key is missing from THIS worker used to be dropped outright — silently deleting that key from the shared
647
+ // doc for every device, with no way back. Read the CURRENT doc first and carry its key material over verbatim
648
+ // (and absorb it, self-healing this worker). Only a room whose key exists NOWHERE is dropped, as before.
649
+ let cur = {}
650
+ try {
651
+ let s = null; const rr = await acct.get(indexRoom, mks.get(indexRoom) || indexMk, name, { plainOpen: unzipDoc })
652
+ if (rr && rr.status === 200 && rr.state) s = rr.state
653
+ previousIndex = s
654
+ if (s && s.rooms && typeof s.rooms === 'object') cur = s.rooms
655
+ } catch { /* read failed → fall back to inject-what-we-hold (the pre-existing behaviour) */ }
656
+ const rooms = {}
657
+ for (const rm of Object.keys(p.rooms)) {
658
+ const e = p.rooms[rm] || {}
659
+ if (e.deleted) { const { mk: _dmk, ep: _dep, split: _ds, userShare: _du, commit: _dc, ...rest } = e; rooms[rm] = rest; continue } // a deleted Space's entry carries no key (2026-11-12): the doc stops handing it back
660
+ if (splits.has(rm)) { const sp = splits.get(rm); rooms[rm] = { ...e, split: true, userShare: sp.userShare, ...(sp.commit ? { commit: sp.commit } : {}), ...(eps.get(rm) ? { ep: eps.get(rm) } : {}) }; continue }
661
+ const mk = mks.get(rm)
662
+ if (mk) { rooms[rm] = { ...e, mk, ...(eps.get(rm) ? { ep: eps.get(rm) } : {}) }; continue } // + the key's epoch (noteEp)
663
+ const prev = cur[rm] // we hold no key — keep whatever the doc already carries, and absorb it
664
+ if (prev && prev.split && prev.userShare) { keepSplit(rm, { userShare: prev.userShare, commit: prev.commit || '' }, prev.ep); rooms[rm] = { ...e, split: true, userShare: prev.userShare, ...(prev.commit ? { commit: prev.commit } : {}), ...(prev.ep ? { ep: prev.ep } : {}) }; continue }
665
+ if (prev && prev.mk) { keep(rm, prev.mk, prev.ep); rooms[rm] = { ...e, mk: prev.mk, ...(prev.ep ? { ep: prev.ep } : {}) }; continue }
666
+ // no key here and none in the doc → drop (unchanged)
667
+ }
668
+ p.rooms = rooms
669
+ publishPresence()
670
+ }
671
+ // ⛔ SEALED on the device — the doc carries every room key (accountStores.js); without the account key nothing is written
672
+ if (name === 'index') for (const field of ['pipesRoom', 'msgsRoom']) {
673
+ const ptr = p[field]
674
+ if (!ptr?.room || ptr.mk) continue
675
+ const saved = previousIndex?.[field]
676
+ const mk = (saved?.room === ptr.room && saved.mk) || mks.get(ptr.room)
677
+ if (!mk) throw new Error('The account room key is unavailable. Retry sync.')
678
+ p[field] = { room: ptr.room, mk }
679
+ }
680
+ const r = await acct.put(indexRoom, mks.get(indexRoom) || indexMk, name, p, summary, by, { ifV }) // ifV: only over the version the app merged
681
+ self.postMessage({ id, result: { status: (r && r.status) || 0, bytes: _jsonBytes(p), z: true, ...(r && r.error ? { error: r.error } : {}) } })
682
+ } catch (err) { self.postMessage({ id, error: 'indexWrite: ' + String((err && err.message) || err) }) }
683
+ return
684
+ }
685
+ case 'pipesRead': { // Atlas pipes: read the pipes doc, ABSORB each pipe's shared+lane room→mk into the store, return KEYLESS
686
+ const { id, pipesRoom, pipesMk, name } = m
687
+ try {
688
+ if (!client) throw new Error('l1-worker: pipesRead before open')
689
+ if (pipesMk && !mks.get(pipesRoom)) { keep(pipesRoom, pipesMk); publishPresence() }
690
+ const r = await acct.get(pipesRoom, mks.get(pipesRoom) || pipesMk, name) // SEALED on the device (accountStores.js)
691
+ if (!(r && r.status === 200 && r.state)) { self.postMessage({ id, result: { status: (r && r.status) || 0, state: null } }); return }
692
+ let st = r.state
693
+ if (st && typeof st === 'object' && st.pipes && typeof st.pipes === 'object') {
694
+ const keyless = {}
695
+ for (const s of Object.keys(st.pipes)) { const pp = st.pipes[s] || {}; const out = { ...pp }
696
+ if (pp.shared && pp.shared.room) { if (pp.shared.mk) keep(pp.shared.room, pp.shared.mk); const { mk, ...rest } = pp.shared; out.shared = rest }
697
+ if (pp.lane && pp.lane.room) { if (pp.lane.mk) keep(pp.lane.room, pp.lane.mk); const { mk, ...rest } = pp.lane; out.lane = rest }
698
+ // lane-to-lane rows (docs/spaces-linked-lanes.md): two lane endpoints, absorbed the same way
699
+ for (const k of ['laneA', 'laneB']) { const ep = pp[k]; if (ep && ep.room) { if (ep.mk) keep(ep.room, ep.mk); const { mk, ...rest } = ep; out[k] = rest } }
700
+ keyless[s] = out }
701
+ publishPresence(); st = { ...st, pipes: keyless }
702
+ }
703
+ self.postMessage({ id, result: { status: 200, state: st, ...(Number.isInteger(r.v) ? { v: r.v } : {}) } }) // v: the version a write names (accountStores put ifV)
704
+ } catch (err) { self.postMessage({ id, error: 'pipesRead: ' + String((err && err.message) || err) }) }
705
+ return
706
+ }
707
+ case 'pipesWrite': { // Atlas pipes: build the pipes doc INJECTING each pipe's shared+lane mk from the store
708
+ const { id, pipesRoom, pipesMk, name, patch, summary, by, ifV } = m
709
+ try {
710
+ if (!client) throw new Error('l1-worker: pipesWrite before open')
711
+ if (pipesMk && !mks.get(pipesRoom)) { keep(pipesRoom, pipesMk); publishPresence() }
712
+ let pp = { ...(patch || {}) }
713
+ if (pp.pipes && typeof pp.pipes === 'object') {
714
+ const pipes = {}
715
+ for (const s of Object.keys(pp.pipes)) { const e = pp.pipes[s] || {}; const out = { ...e }
716
+ if (e.shared && e.shared.room) { const mk = mks.get(e.shared.room); out.shared = mk ? { ...e.shared, mk } : e.shared }
717
+ if (e.lane && e.lane.room) { const mk = mks.get(e.lane.room); out.lane = mk ? { ...e.lane, mk } : e.lane }
718
+ for (const k of ['laneA', 'laneB']) { const ep = e[k]; if (ep && ep.room) { const mk = mks.get(ep.room); out[k] = mk ? { ...ep, mk } : ep } } // lane-to-lane rows: both lanes' keys injected
719
+ pipes[s] = out }
720
+ pp.pipes = pipes
721
+ }
722
+ const r = await acct.put(pipesRoom, mks.get(pipesRoom) || pipesMk, name, pp, summary, by, { ifV }) // ⛔ sealed — the doc carries lane + shared keys
723
+ self.postMessage({ id, result: { status: (r && r.status) || 0, ...(r && r.error ? { error: r.error } : {}) } })
724
+ } catch (err) { self.postMessage({ id, error: 'pipesWrite: ' + String((err && err.message) || err) }) }
725
+ return
726
+ }
727
+ case 'tempHold': { // {ptr: {room, mk, sk}} → hold the temp index (its key memory-only, beside the others) → {ok, room}
728
+ // From the hosted vault only in practice (its replay, its `index` answer, a frame's hand-over it relays after keeping the
729
+ // pointer itself — vault-loader.js). No sk → refused: a list sealed under a key nobody keeps would be lost.
730
+ const p = m.ptr || {}
731
+ const ok = isTempRoomId(p.room) && typeof p.mk === 'string' && !!p.mk && typeof p.sk === 'string' && TEMP_SK.test(p.sk)
732
+ keysReady.then(() => {
733
+ if (ok) { keep(p.room, p.mk); tempPtr = { room: p.room, sk: p.sk }; publishPresence() } // kept as an opened room's key is (the frame's copy lived in the vault's app store before); the vault re-hands the pointer to a new worker
734
+ if (m.id != null) self.postMessage({ id: m.id, result: { ok, room: ok ? p.room : null } })
735
+ })
736
+ return
737
+ }
738
+ case 'tempList': { // {do: 'read' | 'add' | 'remove', add?: {room, title, mk?, userShare?, commit?}, rooms?, by} → {status, room, rooms (KEYLESS)}
739
+ // Every listed room's key is ABSORBED here (as an open of the room puts it here — its preview key too); the caller gets the
740
+ // list without them (keylessTempList) and opens the rooms through this worker.
741
+ const { id } = m
742
+ const answer = (result) => self.postMessage({ id, result })
743
+ ;(async () => {
744
+ try {
745
+ if (!client) throw new Error('l1-worker: tempList before open')
746
+ await keysReady
747
+ if (!tempPtr) return answer({ status: 0, error: 'no_pointer' })
748
+ const p = tempPtr, pmk = mks.get(p.room) || await resolveMk(p.room).catch(() => null)
749
+ if (!pmk) return answer({ status: 0, error: 'no_key', room: p.room })
750
+ const absorb = (list) => { for (const e of list) { if (!e || !isTempRoomId(e.room)) continue; if (e.mk) keep(e.room, e.mk); else if (e.userShare) keepSplit(e.room, { userShare: e.userShare, commit: e.commit || '' }) } publishPresence() }
751
+ let list = null
752
+ if (m.do === 'read') {
753
+ const r = await tempStore.get(p.room, pmk, 'rooms')
754
+ if (!(r && r.status === 200)) return answer({ status: (r && r.status) || 0, room: p.room })
755
+ list = r.state && Array.isArray(r.state.rooms) ? r.state.rooms : null // null: no list there — the caller keeps what it has
756
+ } else if (m.do === 'add') {
757
+ const a = m.add || {}, room = a.room
758
+ if (!isTempRoomId(room)) return answer({ status: 0, error: 'not_temp', room: p.room })
759
+ const sp = splits.get(room)
760
+ const fresh = a.mk ? { mk: a.mk } : a.userShare ? { userShare: a.userShare, commit: a.commit || '' } : (sp && sp.userShare) ? { userShare: sp.userShare, commit: sp.commit || '' } : mks.get(room) ? { mk: mks.get(room) } : null // the caller's material, else what this worker holds
761
+ list = await editTempList(tempStore, p.room, pmk, (all) => addToTempList(all, { room, title: typeof a.title === 'string' ? a.title.slice(0, 120) : '', fresh }), m.by)
762
+ if (!list) return answer({ status: 0, room: p.room })
763
+ } else if (m.do === 'remove') {
764
+ const rooms = (Array.isArray(m.rooms) ? m.rooms : []).filter(isTempRoomId)
765
+ list = await editTempList(tempStore, p.room, pmk, (all) => removeFromTempList(all, rooms), m.by)
766
+ if (!list) return answer({ status: 0, room: p.room })
767
+ } else throw new Error('tempList: unknown ' + String(m.do))
768
+ if (list) absorb(list)
769
+ answer({ status: 200, room: p.room, rooms: list ? keylessTempList(list) : null })
770
+ } catch (err) { self.postMessage({ id, error: 'tempList: ' + String((err && err.message) || err) }) }
771
+ })()
772
+ return
773
+ }
774
+ case 'streamOpen': {
775
+ const { room } = m
776
+ const grants = m.grants || grantsByRoom.get(room)
777
+ let held = streams.get(room)
778
+ if (held) {
779
+ held.holders++
780
+ if (Array.isArray(grants)) { held.grants = grants; held.s?.setGrants(grants) }
781
+ return
782
+ }
783
+ held = { holders: 1, mk: null, s: null, tag: '', grants: Array.isArray(grants) ? grants : null }
784
+ streams.set(room, held)
785
+ try {
786
+ await keysReady
787
+ const mk = (typeof m.mk === 'string' && m.mk) || mks.get(room) || await resolveMk(room)
788
+ if (streams.get(room) !== held) return
789
+ if (!mk) { streams.delete(room); return }
790
+ const tag = await viewingTag(room).catch(() => '')
791
+ if (streams.get(room) !== held) return
792
+ held.tag = tag; held.mk = mks.get(room) || mk
793
+ held.s = openStreamHere(room, held.mk, held.grants, tag)
794
+ } catch (error) { if (streams.get(room) === held) streams.delete(room) }
795
+ return
796
+ }
797
+ case 'streamClose': {
798
+ const held = streams.get(m.room)
799
+ if (held && --held.holders <= 0) { held.s?.stop(); streams.delete(m.room) }
800
+ return
801
+ }
802
+ case 'op': { // {id, op, room, args} → client[op](room, mks[room], …args) → {id, result}
803
+ const { id, op, room, args } = m
804
+ try {
805
+ if (!client) throw new Error('l1-worker: op before open')
806
+ try { await keysReady } catch { /* same cold-start race as resolveMk: never run an op against a half-loaded map */ }
807
+ if (typeof client[op] !== 'function') throw new Error('l1-worker: unknown op ' + op)
808
+ const aa = args || []
809
+ // §ID-CONFINE: turn signature is (room, message, identity, opts). When the app sends NO identity (idconfine on),
810
+ // sign with the identity CONFINED here (seeded by the vault) so the private signing key never leaves L1. A room we
811
+ // hold no identity for stays unsigned (open/legacy), unchanged. Only substitutes when the arg is absent — an app
812
+ // that still passes identity (flag off / email turn) is untouched.
813
+ if (op === 'turn' && (aa[1] == null) && ids.has(room)) aa[1] = ids.get(room)
814
+ const index = routingIndex(op)
815
+ if (index >= 0 && aa[index] && typeof aa[index] === 'object') {
816
+ const route = { ...aa[index] }
817
+ aa[index] = route
818
+ if (route.bridgeRoom && !route.bridgeMk) {
819
+ const key = mks.get(route.bridgeRoom) || await resolveMk(route.bridgeRoom)
820
+ if (key) route.bridgeMk = key
821
+ }
822
+ if (op === 'turn' && Array.isArray(route.links)) {
823
+ route.links = await Promise.all(route.links.map(async link => {
824
+ if (!link?.room || link.mk) return link
825
+ const key = mks.get(link.room) || await resolveMk(link.room).catch(() => null)
826
+ return key ? { ...link, mk: key } : link
827
+ }))
828
+ }
829
+ }
830
+ const mkHere = await resolveMk(room) // §9: reconstruct a split room's mk (fetch appShare + combine) on demand
831
+ let result = null
832
+ let pfNote = '' // what the prefetch lookup found, for the page's tap timeline ('' = not looked up)
833
+ const afterTap = !!(aa[2] && typeof aa[2] === 'object' && aa[2].afterTap) // the page says this poll follows a notification tap
834
+ if ((op === 'poll' || op === 'pollSealed') && mkHere && typeof client.decodeSealed === 'function' && (afterTap || Date.now() < prefetchLookUntil || prefetchFlag.has(room) || !prefetchChecked.has(room))) {
835
+ // PREFETCHED AT PUSH TIME (prefetchPoll.js): the service worker fetched this room's new sealed entries when the
836
+ // notification arrived. The first poll asking from that same position is answered from them at once, and the
837
+ // network is still asked in the background — for freshness, and so the change inbox the first poll carries
838
+ // is still registered with the server. Looked up on a room's FIRST poll in this worker's life (a cold start
839
+ // after the tap) and whenever the service worker announced one (the worker was alive through the push).
840
+ prefetchChecked.add(room); prefetchFlag.delete(room)
841
+ let pfKey = 'prefetch:' + room, pf = await idbGet(pfKey)
842
+ if (!pf) { pfKey = await prefetchHashKey(room); pf = await idbGet(pfKey) } // a TAIL, kept under a hash of the room (no position was known)
843
+ if (!pf) pfNote = 'none stored'
844
+ else {
845
+ idbDel(pfKey) // once, whatever the verdict
846
+ const why = prefetchUsable(pf, aa[1] | 0)
847
+ if (why) pfNote = why + (why === 'position moved' ? ' (stored since ' + pf.sinceCount + ', asked since ' + (aa[1] | 0) + ')' : '')
848
+ else {
849
+ const pfAns = prefetchAnswer(pf, aa[1] | 0)
850
+ if (!pfAns) pfNote = 'the tail does not reach this position'
851
+ else try { const out = await client.decodeSealed(room, mkHere, aa[1] | 0, pfAns); if (out && out.status === 200) { result = { ...out, prefetched: true }; pfNote = pf.tail ? 'used (a tail from ' + pf.sinceCount + ')' : 'used'; client[op](room, mkHere, ...aa).catch(() => {}) } else pfNote = 'decoded to status ' + (out && out.status) } catch (e) { result = null; pfNote = 'decode failed: ' + String((e && e.message) || e).slice(0, 60) }
852
+ }
853
+ }
854
+ }
855
+ // THE ENTRY THE STREAM CARRIED (frameTails): a poll from exactly count-1 is answered from it at once — decoded with the
856
+ // key here, the decoder the network path uses — and the network is still asked behind it (as for a prefetch).
857
+ if (!result && (op === 'poll' || op === 'pollSealed') && mkHere && typeof client.decodeSealed === 'function' && frameTails.has(room)) {
858
+ const ft = frameTails.get(room); frameTails.delete(room)
859
+ if (ft && Date.now() - ft.at < FRAME_TAIL_MS && (aa[1] | 0) === ft.count - 1) {
860
+ try {
861
+ const out = await client.decodeSealed(room, mkHere, ft.count - 1, { status: 200, changed: true, count: ft.count, from: ft.count - 1, sealed: JSON.stringify({ v: 3, from: ft.count - 1, count: ft.count, boxes: [ft.box] }) })
862
+ if (out && out.status === 200) { result = { ...out, fromFrame: true }; client[op](room, mkHere, ...aa).catch(() => {}) }
863
+ } catch { /* the network answers below */ }
864
+ }
865
+ }
866
+ if (!result && op === 'poll' && !mkHere) result = { status: 401, error: 'no_key', reason: noKeyReason(room) } // a keyless plaintext read: the server refuses it with a BARE 401 ({} — no error field, measured 2026-10-03), which the page could not tell from anything. Say it here, and spare the round trip.
867
+ if (op === 'rekey' && splits.has(room)) aa[0] = { ...(aa[0] || {}), split: { userShare: splits.get(room).userShare } } // a SPLIT room rotates only the user's half (spaceClient.rekey)
868
+ if (!result) result = await client[op](room, mkHere, ...aa)
869
+ if (op === 'rekey' && result && result.status === 200 && result.newShare) { keepSplit(room, { userShare: result.newShare, commit: result.newCommit }, result.epoch); keep(room, result.newMk, result.epoch); publishPresence(); const { newMk: _nm, ...up } = result; result = { ...up, split: true } } // the full key stays HERE (the hosted rule: the frame never holds mk)
870
+ else if (op === 'rekey' && result && result.status === 200 && result.newMk) { keep(room, result.newMk, result.epoch); publishPresence() } // A ROOM RE-KEYED IN PLACE (docs/key-rotation-design.md § (b)): this realm made the new key; it holds it from now on
871
+ if (op === 'pollSealed' && !mkHere && result && result.status === 422) result = { ...result, error: 'no_key', reason: noKeyReason(room) } // the boxes came back and nothing here can open them: not a WRONG key — NO key (the owner's lock banner blamed the invite)
872
+ // A WRONG REMEMBERED KEY IS NOT THE ROOM'S KEY. resolveMk takes the remembered plain key before the split entry, and
873
+ // the remembered one is persisted here (idb mk:<room>) — so a wrong plain key, however it arrived, beat the correct,
874
+ // commit-checked split key on every launch: the owner's confidential room drawn blank for weeks (2026-10-03), its
875
+ // ten boxes opening fine with the key the split rebuilds. A read answering 422 'undecodable' from a room that HAS a
876
+ // split entry drops the remembered key, rebuilds from the split (appShare ⊕ userShare, commit-checked) and asks once more.
877
+ if ((op === 'poll' || op === 'pollSealed') && result && result.status === 422 && result.reason === 'undecodable' && splits.has(room) && mks.has(room)) {
878
+ const stale = mks.get(room); mks.delete(room); idb.del('mk:' + room).catch(() => {})
879
+ const fresh = await resolveMk(room).catch(() => undefined)
880
+ if (fresh && fresh !== stale) { const again = await client[op](room, fresh, ...aa); if (again && typeof again === 'object') result = { ...again, rekeyed: true } }
881
+ else if (stale) keep(room, stale) // nothing better — put it back rather than leave the room keyless
882
+ }
883
+ if (pfNote && result && typeof result === 'object') result = { ...result, prefetchNote: pfNote }
884
+ if (op === 'poll' || op === 'pollSealed') { const pos = positionOf(result); const last = lastPos.get(room); if (pos && (!last || last.etag !== pos.etag || last.count !== pos.count)) { lastPos.set(room, pos); if (!protectedAtRest) idbSet('cnt:' + room, pos) /* §NAMES: a protected device keeps no room-named position (the push prefetch is off there) */ } }
885
+ if (op === 'poll' || op === 'pollSealed') streamFeed(room, result) // a streaming room: the poll's reply text + fresh grants re-sync the stream
886
+ try { self.postMessage({ id, result }) } // structured-clone can throw on a non-cloneable result
887
+ catch (ce) { self.postMessage({ id, error: 'result-clone(' + op + '): ' + String((ce && ce.message) || ce) }) }
888
+ } catch (err) { // a tagged refusal (enclave_not_accepted) keeps its code + verdict so the app can show WHICH stage mismatched
889
+ self.postMessage({ id, error: op + ': ' + String((err && err.message) || err), ...(err && err.code ? { code: err.code, verdict: err.verdict || null, room: err.room || null } : {}) })
890
+ }
891
+ return
892
+ }
893
+ }
894
+ }