@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/pollVerdict.js ADDED
@@ -0,0 +1,33 @@
1
+ // pollVerdict.js — what a poll answer MEANS, decided one way for the Spaces app and the SDK (docs/sdk-convergence.md,
2
+ // phase 4a). Each used to classify refusals itself, and they drifted: the SDK read a refusal inside a 200 (a host front
3
+ // that flattened every status) as a refusal, the app as an empty room. Each side still decides what to SHOW for a verdict.
4
+ // ok · cannot_open (422 — this key opens nothing; code 'no_key' when nothing here holds a key) · no_key (401, the
5
+ // worker's own refusal of a keyless read) · stale_key (the enclave cannot open the key or the envelope we sealed to it) ·
6
+ // verified_client · gated (an email gate) · warming (the enclave is starting) · unavailable (not judged just now: retry) ·
7
+ // not_found · refused (anything else) ·
8
+ // no_answer
9
+ export function pollVerdict (r) {
10
+ if (!r) return { kind: 'no_answer', code: 'no_answer' }
11
+ if (r.status === 200 && !r.error) return { kind: 'ok' }
12
+ const code = r.error ? String(r.error) : r.status === 422 ? 'undecodable' : 'http_' + r.status
13
+ const v = (kind) => ({ kind, code, ...(r.reason ? { reason: r.reason } : {}) })
14
+ if (r.status === 422) return v('cannot_open')
15
+ if (r.error === 'no_key') return v('no_key')
16
+ // bad_envelope: the request ENVELOPE (reqEnvelope) was sealed to an enclave since replaced — the same stale key, one layer out
17
+ // (2026-11-09: after a turn cutover the app read 400 bad_envelope once a second and never re-attested until relaunched).
18
+ if (r.error === 'bad_mkseal' || r.error === 'bad_envelope') return v('stale_key')
19
+ if (r.error === 'envelope_stale') return { kind: 'refused', code: 'envelope_stale', reason: 'This device’s clock is more than a minute off, so the confidential Space refused the request — set the clock to the right time (automatic), then try again.' } // the device's clock (pass 7, T#2; the same words as turnVerdict CLOCK_REASON)
20
+ if (r.error === 'no_verified_client') return v('verified_client')
21
+ // ★ ONLY THE EMAIL GATE'S REFUSAL IS "gated" (sync sweep, 2026-10-10). Every 403 used to read as gated, and the app then
22
+ // marked the room verified FOR GOOD — but a read is also refused 403 for an enclave build the room has not accepted
23
+ // (enclave_not_accepted) or an owner policy that does not verify (policy_invalid): an open room then asked for a
24
+ // sign-in for ever. The gate answers not_authorized (no or wrong sign-in, revoked) or gate_unreadable.
25
+ if (r.status === 403 && (r.error === 'not_authorized' || r.error === 'gate_unreadable')) return v('gated')
26
+ if (r.error === 'enclave_warming' || r.warming) return v('warming')
27
+ // NOT JUDGED (sync sweep 11-11): the sign-in's verifier, the room's tier or its store could not be checked just now — a retryable 503,
28
+ // never a refusal (no banner, no slowed poll): ask again
29
+ if (r.status === 503 && (r.error === 'verifier_unavailable' || r.error === 'tier_unknown' || r.error === 'store_unavailable')) return v('unavailable')
30
+ if (r.error === 'deleting') return v('unavailable') // its creator's delete is finishing (agent/roomDeleting.mjs): the next read hears 410, or the room again
31
+ if (r.status === 404 && r.error === 'not_found') return v('not_found')
32
+ return v('refused')
33
+ }
@@ -0,0 +1,60 @@
1
+ // spaces/public/prefetchPoll.js — the rules for answering a room's first poll from what the service worker PREFETCHED
2
+ // when the push arrived (the owner, 2026-10-02: a tapped notification took over a second to show its message — the
3
+ // room was drawn from cache, THEN the server was asked). Pure, so the L1 worker's use of it is testable here.
4
+ // • the worker records the room's position after every successful poll: cnt:<room> = { etag, count }
5
+ // • the push handler asks pollsealed since that count and stores prefetch:<room> = { at, sinceCount, r }
6
+ // • the first poll since then, asking from the SAME count, is answered from `r` (decoded with mk, the same decoder
7
+ // the network path uses) — once; the network is still asked right after, so nothing can go stale.
8
+ // • NO POSITION (2026-10-20 — the owner's phone, protected storage: every push said "no position known", so a tapped message
9
+ // waited 9 s for the network): the push handler asks the room's COUNT, then the last PREFETCH_TAIL entries, and keeps
10
+ // them as a TAIL under a hash of the room (prefetchHashKey — nothing kept under the room's name). The first poll
11
+ // takes the part from ITS position on, when the tail reaches back that far.
12
+ export const PREFETCH_MAX_AGE_MS = 15 * 60 * 1000
13
+ export const PREFETCH_TAIL = 30
14
+
15
+ /** Where a TAIL prefetch is kept: a hash of the room, the same in the service worker (sw-notif-core.js wbxPrefetchHashKey). */
16
+ export async function prefetchHashKey (room) {
17
+ const d = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode('wb-prefetch\n' + String(room || ''))))
18
+ return 'prefetch:h:' + Array.from(d.slice(0, 16), (b) => b.toString(16).padStart(2, '0')).join('')
19
+ }
20
+
21
+ /** Is this prefetched answer usable for a poll asking from `sinceCount`? A reason string when not. */
22
+ export function prefetchUsable(pf, sinceCount, now = Date.now()) {
23
+ if (!pf || typeof pf !== 'object' || !pf.r || typeof pf.r !== 'object') return 'none'
24
+ if (!Number.isFinite(pf.at) || now - pf.at > PREFETCH_MAX_AGE_MS) return 'stale'
25
+ if (pf.tail) { // a tail covers any position from where it starts to the count it saw
26
+ if (!Number.isInteger(pf.sinceCount) || pf.sinceCount > (sinceCount | 0) || !Number.isInteger(pf.r.count) || (sinceCount | 0) > pf.r.count) return 'position moved'
27
+ } else if (!Number.isInteger(pf.sinceCount) || pf.sinceCount !== (sinceCount | 0)) return 'position moved'
28
+ if (!pf.r.changed || typeof pf.r.sealed !== 'string') return 'nothing new in it'
29
+ return ''
30
+ }
31
+
32
+ /** The position record to keep after a poll answered: null when the answer carries none. */
33
+ export function positionOf(result) {
34
+ if (!result || result.status !== 200 || !Number.isInteger(result.version)) return null
35
+ return { etag: typeof result.etag === 'string' ? result.etag : '', count: result.version, at: Date.now() }
36
+ }
37
+
38
+ /** What the push handler stores — or null when the server's answer has nothing worth keeping (bounded in size). */
39
+ export function prefetchRecord(j, sinceCount, { maxBytes = 400000, now = Date.now() } = {}) {
40
+ if (!j || !j.changed || typeof j.sealed !== 'string' || j.sealed.length > maxBytes || !Number.isInteger(sinceCount)) return null
41
+ const { notif, ...r } = j // the preview envelope is the notification's business, not the ledger's
42
+ return { at: now, sinceCount, r }
43
+ }
44
+
45
+ /** The stored answer as the client's decoder expects it: the service worker kept the response BODY, and the client's own
46
+ * fetch path adds `status` from the response — without it `decodeSealed` sees "not 200" and hands the body back undecoded
47
+ * (the owner's trail, 2026-10-02 19:24: "prefetch: decoded to status undefined"). */
48
+ export function prefetchAnswer(pf, sinceCount) {
49
+ let r0 = pf && pf.r && typeof pf.r === 'object' ? pf.r : null
50
+ if (!r0) return null
51
+ if (pf.tail && Number.isInteger(sinceCount) && sinceCount > pf.sinceCount) { // a TAIL: only the entries after the page's position
52
+ let sl = null; try { sl = JSON.parse(r0.sealed) } catch { return null }
53
+ if (!sl || !Array.isArray(sl.boxes) || sl.from !== pf.sinceCount || sinceCount > sl.from + sl.boxes.length) return null
54
+ r0 = { ...r0, sealed: JSON.stringify({ ...sl, boxes: sl.boxes.slice(sinceCount - sl.from), from: sinceCount }), from: sinceCount }
55
+ }
56
+ // A turn's progress is LIVE — never replayed from storage (2026-10-03: a push mid-turn stored "working", and the first
57
+ // poll on return showed "Working on it… 104s" under the finished reply). The entries are what a stored answer is for.
58
+ const { partialStatus, partial, partialSeq, ...r } = r0
59
+ return Number.isInteger(r.status) ? r : { status: 200, ...r }
60
+ }
@@ -0,0 +1,426 @@
1
+ // protectedLocal.js — DEVICE STORAGE PROTECTION for the PAGE's own secrets (docs/device-storage-protection.md, slice 2).
2
+ // The key worker seals ITS store (l1-worker.js §PROTECT); this seals what the main thread keeps in localStorage: the
3
+ // backup master, the room signing identities, split shares and commitments, sign-in tokens, the account/invite keys, the
4
+ // Connections / Siri / outside-agent keys, the Code pairing, contacts and the recents list (room titles).
5
+ //
6
+ // HOW, without touching the dozen modules that read them: every protected entry stays IN localStorage UNDER ITS OWN KEY,
7
+ // but as a sealed blob ({ v: 1, s }) — so the code that enumerates localStorage (`key(i)` / `length`) still sees it — and
8
+ // `Storage.prototype.getItem/setItem/removeItem` are wrapped so a protected key reads from an in-memory OVERLAY (filled at
9
+ // unlock, cleared at relock) and writes to the overlay + a fresh sealed blob. Readers are synchronous, WebCrypto is not:
10
+ // the overlay is what makes a synchronous read possible, and `ready()` is what boot awaits so no reader runs before it.
11
+ //
12
+ // INACTIVE (the switch off, or a framed app that does not own the lock): the wrappers pass straight through — every
13
+ // store byte-identical to today. Turning the switch on migrates the existing clear entries in place; turning it off
14
+ // writes them back in the clear.
15
+ //
16
+ // Limit, stated: while LOCKED the overlay is empty, so a protected key reads as absent (the app looks signed out under
17
+ // the lock screen) and a write made while locked lives only in the overlay until the next unlock persists it — a tab
18
+ // closed while locked loses that write. Boot waits for the unlock, so in practice nothing reads or writes before it.
19
+ import { importRaw, seal, open, isSealed } from './deviceSeal.js'
20
+ import { makeNamer, isOpaqueName } from './sealedNames.js'
21
+
22
+ export const PROTECTED_PREFIXES = Object.freeze([
23
+ 'space:vault', // the backup master
24
+ 'space:id:', // room signing identities (private keys)
25
+ 'space:sign:', // room signing keypairs carried for the backup
26
+ 'space:myphoto', 'space:myphoto:safe', 'space:mykey:', // your profile picture and its safe copy (profilePhoto.js)
27
+ 'space:faces', // pictures of people seen in verified Spaces, by email (profilePhoto.js)
28
+ 'space:us:', 'space:spc:', // split-key shares + commitments
29
+ 'space:mk:', // room keys (the worker is the store when protected; any leftover is sealed too)
30
+ 'space:installHelp', // the retired built-in install help's room + its key — an older device may still hold one (docs/install-help.md)
31
+ 'space:compsec', // each paired computer's security check: its weak spots (codeSecurity.js)
32
+ 'space:tok:', 'space:esession', 'space:google-pending', // sign-in tokens, the email-session anchor, a browser sign-in waiting across a restart (its key)
33
+ 'space:acctv2', // account recovery v2's state (acctV2App.js): the account id and its email (exact — `space:acctv2:base` stays clear)
34
+ 'space:acctv2:reset', // an email move this device started (acctV2App.js RESET_KEY, § 11.5): its id and the address
35
+ 'space:acctv2:erase', // "Delete my account"'s request while its answer is unknown (acctV2App.js ERASE_KEY, 10·Q#3): a device signature and a used email ticket
36
+ 'space:awshandle', // THIS device's own AWS key (a handle on the person's AWS budget — acctV2Wiring.js awsHandleStore): its PRIVATE half
37
+ 'space:invitekey', 'space:acctkey', // the invite key, the account-store key
38
+ 'space:attestedBox:', // an attested kind's invite box — its PRIVATE half (attestedBox.js), like the invite key above
39
+ 'space:connectionKeys', 'space:siri', 'space:siri-pending-edit', 'space:a2a', 'space:a2a-pending-edit', 'space:a2a-pending-removals', 'space:a2a-delivered', 'space:code', 'space:clouddevice', // Connections call keys, the Siri inbox key, outside-agent keys, the Code pairing
40
+ 'space:connPending', 'space:androidConsent', // pending grants and the short-lived key for an Android connector return
41
+ 'space:contacts', 'space:agentlinks', 'space:recents', // content: people, agent links, the room list with its titles
42
+ 'space:blocks', // the people you blocked (blocks.js) — names and @usernames
43
+ 'space:chat-locks', // THE CHAT LOCK (chatLockStore.js): which chats are locked, and the wrong-PIN count
44
+ 'space:blocks:keys', // the keys seen writing for a blocked email (blocksPush.js) — emails
45
+ 'space:share-in', 'space:share-last', // shareIn.js: words shared from another app (sessionStorage), the Space last shared into
46
+ 'space:moved-unsent:', // space.js keepUnsentForMove: words you wrote that a moved room refused, carried to the new room's box (sessionStorage)
47
+ 'space:away-unsent:', // space.js keepUnsentAway: words a Space refused after you had left it, kept for your return (sessionStorage; sync sweep 11-21 #7)
48
+ 'space:crossed:', // content: the lines you authored that crossed into a shared room
49
+ 'space:inviteowed:', // rekeyMembers.js: the people a member change added whose invites are still to go (their emails)
50
+ // The 2026-10-10 audit (the owner: "Make sure that everything is encrypted when the lock is on") — every remaining store
51
+ // that holds a key or content: computers' pairing secrets + cloud computers' provider keys, the account index / pipes /
52
+ // temp-index pointers (each carries a room key), lane links (shared + lane keys), forked rooms' ancestor keys, the usage-
53
+ // receipt keys, the agenda, outside-agent tasks, your name / @username / email, contacts' reach, pinned file names, view
54
+ // labels — and the Code frame's own copies (it installs this module too: the computers, the direct-server password, the
55
+ // session list). Left clear: room ids, flags, settings, diagnostics, public keys.
56
+ 'space:computers', 'space:cloud-computers', 'space:index-room', 'space:pipes-room', 'space:msgs-room', 'space:mail-handled', 'space:pipes', 'space:tempidx',
57
+ 'space:epoch:', 'space:usagekey', 'space:usagekey:old', 'space:todos', 'space:events', 'space:a2a-pending',
58
+ 'space:myname', 'space:username', 'space:myusers', 'space:acct-owner', 'space:recovery:owner-mismatch', 'space:reach', 'pinnedfiles:', 'viewmeta:',
59
+ 'oc.computers', 'oc.pass', 'oc.list',
60
+ 'space:negotiations', 'space:vaultprofile:', // legacy lane links (with their keys, migrated away) and the retired vault page's free-text profile
61
+ // THE VAULT's own stores (slice 4 — the hosted app's top-level origin, vault-loader.js): the derived keyring with the
62
+ // index/pipes pointers, the per-room email signing keypairs, the framed app's durable keys/tokens mirrored up, and the
63
+ // mirrored content (contacts, the room list with titles, the temp-room pointers, your name). `space:vault` above is the
64
+ // master there too. Left clear on purpose: `vault:lock` (the config), `vault:place`, the flags and the boot/tap trails.
65
+ 'vault:acct', 'vault:esign:', 'vault:appkv', 'vault:contacts', 'vault:roomlist', 'vault:tempidx', 'vault:myname', 'vault:pending-cloud-signout' /* an email while the cloud device's sign-out is unconfirmed */,
66
+ 'vault:acctsecrets', // the Siri / A2A inbox private keys and the Siri Shortcut key the vault holds for the app (vaultAcctSecrets.js)
67
+ ])
68
+ export const isProtectedKey = (k) => { const s = String(k); return PROTECTED_PREFIXES.some((p) => (p.endsWith(':') ? s.startsWith(p) : s === p)) }
69
+ /** A FRAMED app's marker (clear, non-secret): "my framer protects this device" — set when our vault first hands the key over,
70
+ * cleared when protection is switched off. The framed app has no lock config of its own to read. */
71
+ export const FRAMED_MARK = 'space:protected'
72
+ /** Does a lock config (space:lock / vault:lock) say the device is protected? */
73
+ export const cfgSaysProtected = (c) => !!(c && c.on && c.protect && c.protect.on)
74
+
75
+ // PHASE 2 (docs/desktop-protection.md § Names; the owner, 2026-10-11: "Some metadata stays readable — why?"): on a protected
76
+ // device EVERY entry is sealed, not only the secrets above — room ids in `space:last`, the confidential-room list, the
77
+ // places trail, the flags — and stored under an OPAQUE name (sealedNames.js: `p:` + the encrypted real name), so a disk
78
+ // copy learns neither what is kept nor about which rooms. Only these stay readable: what the lock screen needs before the
79
+ // passkey (the lock configs) and the framed app's marker.
80
+ // And a reviewed handful of SETTINGS that name no room, no person and no activity, which modules read ONCE at load — before
81
+ // the unlock — so sealing them would reset them on every launch: feature flags, the side panel's width, the map language,
82
+ // the diagnostics switches, the boot counter and the PUBLIC app catalog. Anything naming a room or a person is sealed.
83
+ // ⚑ THE SIGN-OUT MARKERS STAY CLEAR (second review, 2026-11-27): "a wipe is still to finish" must outlive the wipe itself. Sealed, the
84
+ // marker went with forgetProtectedLocal() in the same wipe (and read as absent while locked, and to the loader, which reads before
85
+ // this wrapper exists) — so on a protected device a wipe whose key clean-up failed was reported clean and never retried, and the
86
+ // previous account's keys could meet the next one. They name no room and no person ('1', 'reset', or the database names to drop).
87
+ export const STAYS_CLEAR = Object.freeze(['witbitz-builder-reset-pending', 'witbitz-spaces-signout-pending', 'witbitz-device-signout-pending', 'witbitz-device-reset-confirmed', 'space:lock', 'vault:lock', FRAMED_MARK,
88
+ 'space:maplang', 'space:maplang.eff', 'space:mapsapp', 'space:settings:open', 'space:side', 'space:side-hidden', 'space:side-w', 'space:assistw',
89
+ 'space:ohttp', 'space:caretdbg', 'space:rotlab', 'space:diag', 'space:notifPreview', 'space:boots', 'space:apps',
90
+ 'space:channel', 'space:runAt', // Official / Beta / Pinned + the newest build time run (channelChoice.js): read before the unlock, or a locked device would fall back to Official
91
+ 'space:strictfiles', // Strict file viewing (strictFiles.js): sealed, a locked device would read it as off and draw others' files behind the lock screen
92
+ 'space:autoupdate', // "Update automatically" (updateState.js): sealed, a locked device read it as On and updated behind the lock screen (sync sweep, 10-16)
93
+ 'space:atrest', // the regular app's storage is sealed by its DEVICE key (spaceAtRest.js SPACE_AT_REST_MARK): read at load, so its reads wait for the boot's unlock
94
+ 'vault:atrest', // the hosted vault's storage is sealed by its DEVICE key (vaultDeviceKey.js AT_REST_MARK): read at load, so its reads wait for the boot's unlock
95
+ 'vault:repairAt']) // a time only: when the vault's boot guard last repaired (vault-boot-guard.js) — read before any unlock (sync sweep 10-21 #9)
96
+ // + the sign-in callbacks' hand-back: written by a page that holds no key (github-callback.html, mcp-callback.html) and
97
+ // removed once read (connections.js) — sealed, a protected device never finished that path (sync sweep 10-20 #8)
98
+ export const STAYS_CLEAR_PREFIXES = Object.freeze(['space:flag:', 'space:ghcb:', 'space:mcpcb:'])
99
+ // Logs every writer APPENDS to (a JSON array of lines, capped like the writers cap it): unlocking joins their copies.
100
+ const APPEND_LOGS = Object.freeze(['space:bootlog', 'vault:bootlog']), LOG_CAP = 1000
101
+ const staysClear = (k) => { const s = String(k); return STAYS_CLEAR.includes(s) || STAYS_CLEAR_PREFIXES.some((p) => s.startsWith(p)) }
102
+ const sealsHere = (k) => !staysClear(k) && !isOpaqueName(String(k)) // on a protected device: everything else
103
+
104
+ const overlay = new Map() // real name → clear string, while unlocked (or memory-only)
105
+ const lockedWrites = new Map() // real name → value | null (a removal): written while LOCKED, applied over the disk at unlock
106
+ let active = false // the switch is on for THIS surface
107
+ let key = null // the device's AES key (values) while unlocked
108
+ // ⛔ A RELOCK IS NOT A NEW KEY (2026-11-08, docs/state-machines.md I16 / A#11): a sealed write still on its way when the lock engaged
109
+ // was dropped (`key !== k`) — the value was gone at the next unlock. Made under that key, it is still that key's: only a change of
110
+ // the protection itself (switched on or off, released, memory-only) retires writes in flight. `sealGen` counts those.
111
+ let sealGen = 0
112
+ let namer = null // the device's name keys (sealedNames.makeNamer) while unlocked
113
+ let raw = null // the original Storage.prototype methods
114
+ let names = null // the enumeration cache: the real names key(i)/length answer while active
115
+ let readyResolve = null, readyPromise = Promise.resolve()
116
+ // A pending promise is KEPT: a relock while someone already waits (the vault's boot awaits this, and the launch lock's onLock
117
+ // relocks after it started waiting) must not orphan them — the unlock settles the promise they hold (2026-10-13: the hosted
118
+ // app unlocked into an empty window on every protected launch).
119
+ const armReady = () => { if (readyResolve) return; readyPromise = new Promise((r) => { readyResolve = r }) }
120
+ const settleReady = () => { if (readyResolve) { readyResolve(); readyResolve = null } }
121
+
122
+ /** True while a protected key must be answered from the overlay. */
123
+ export const protectedLocalActive = () => active
124
+ /** Boot awaits this: resolved at once when inactive; after the unlock has filled the overlay when active. */
125
+ export const protectedLocalReady = () => readyPromise
126
+ /** A protected key can be read AND written truly now (inactive, unlocked, or memory-only) — while locked a read answers absent
127
+ * and a write would replace the sealed value at the unlock (vaultConnKeys.js asks before it merges). */
128
+ export const protectedLocalOpen = () => !active || !!key || memoryOnly
129
+ /** The stored bytes under a key, unwrapped by nothing — what a disk copy would see. */
130
+ export const rawGet = (k) => (raw ? raw.getItem.call(localStorage, k) : localStorage.getItem(k))
131
+ /** Every key as stored on disk (opaque names included) — what a disk copy would list. */
132
+ export const rawKeys = () => { const out = []; const n = raw ? rawLength() : localStorage.length; for (let i = 0; i < n; i++) { const k = raw ? raw.key.call(localStorage, i) : localStorage.key(i); if (k != null) out.push(k) } return out }
133
+ // On a fresh reset boot the overlay is still locked. Remove the actual stored names, including opaque ones.
134
+ export function clearLocalForBuilderReset(marker) {
135
+ for (const name of rawKeys()) if (name !== marker) {
136
+ if (raw) raw.removeItem.call(localStorage, name)
137
+ else localStorage.removeItem(name)
138
+ }
139
+ }
140
+ let lengthDesc = null
141
+ const rawLength = () => (lengthDesc ? lengthDesc.get.call(localStorage) : localStorage.length)
142
+
143
+ // Disk writes are async (WebCrypto) and must land in the order they were made: one chain.
144
+ let chain = Promise.resolve()
145
+ const onDisk = (fn) => { chain = chain.then(fn).catch(() => {}); return chain }
146
+ const writeSealed = (name, v) => { const k = key, nm = namer, g = sealGen; if (!k || !nm) return; onDisk(async () => { const o = await nm.opaque(name); const blob = await seal(k, v); if (sealGen !== g) return; try { raw.setItem.call(localStorage, o, JSON.stringify(blob)) } catch { /* private mode / full */ } try { raw.removeItem.call(localStorage, name) } catch { /* */ } }) }
147
+ const removeSealed = (name) => { const nm = namer; if (!nm) return; onDisk(async () => { try { raw.removeItem.call(localStorage, await nm.opaque(name)) } catch { /* */ } }) }
148
+ /** Resolves once every queued disk write has landed (tests, and the switch-off). */
149
+ export const protectedLocalFlushed = () => chain
150
+ /** What is ON DISK for `name` once the queued writes have landed — opened as a protected read would open it; null when
151
+ * nothing is there or it cannot be kept (locked, memory-only). Writes swallow their errors (a full or private store), so a
152
+ * caller that must know a value is durable reads it back here (account recovery v2: a new recovery code is kept BEFORE
153
+ * its activation is sent — implementation review R2-03). */
154
+ export async function durableRead (name) {
155
+ await chain
156
+ if (!active || !raw) return rawGet(name)
157
+ if (memoryOnly || !key || !namer) return null
158
+ try {
159
+ const v = raw.getItem.call(localStorage, await namer.opaque(name))
160
+ const blob = v && parseSealed(v)
161
+ return blob ? String(await open(key, blob)) : null
162
+ } catch { return null }
163
+ }
164
+
165
+ // LOCKED or MEMORY-ONLY, an entry still CLEAR on disk (never migrated: an unsecured computer, or a flag an older build wrote)
166
+ // reads through — unless it is a secret: those are only ever answered by the overlay.
167
+ /** Return the exact disk entry that still opens to the pending operation. Hosted storage mirrors this entry. */
168
+ export async function durableEntry(name, value) {
169
+ await chain
170
+ if (!active || !raw) return rawGet(name) === value ? [name, value] : null
171
+ if (memoryOnly || !key || !namer) return null
172
+ try {
173
+ const opaque = await namer.opaque(name), stored = raw.getItem.call(localStorage, opaque)
174
+ const blob = stored && parseSealed(stored)
175
+ return blob && String(await open(key, blob)) === value ? [opaque, stored] : null
176
+ } catch { return null }
177
+ }
178
+
179
+ const readThrough = (n) => { if (isProtectedKey(n)) return null; const v = raw.getItem.call(localStorage, n); return v != null && !parseSealed(v) ? v : null }
180
+ const enumerate = () => {
181
+ if (names) return names
182
+ const set = new Set(overlay.keys())
183
+ for (const [n, v] of lockedWrites) if (v != null) set.add(n)
184
+ for (const k of rawKeys()) if (!isOpaqueName(k) && (staysClear(k) || (!key && readThrough(k) != null))) set.add(k)
185
+ names = [...set]; return names
186
+ }
187
+
188
+ /** Wrap Storage.prototype once (idempotent). `proto` is injectable for tests. */
189
+ export function installProtectedLocal (proto = (typeof Storage !== 'undefined' ? Storage.prototype : null), { on = false } = {}) {
190
+ if (!proto || raw) { if (on && !active) { active = true; names = null; armReady() } return }
191
+ raw = { getItem: proto.getItem, setItem: proto.setItem, removeItem: proto.removeItem, clear: proto.clear, key: proto.key }
192
+ lengthDesc = Object.getOwnPropertyDescriptor(proto, 'length') || null
193
+ const mine = (t) => active && t === localStorage
194
+ proto.getItem = function (k) {
195
+ if (!mine(this) || !sealsHere(k)) return raw.getItem.call(this, k)
196
+ const n = String(k); if (overlay.has(n)) return overlay.get(n)
197
+ if (lockedWrites.has(n)) return lockedWrites.get(n)
198
+ if (!key && !memoryOnly && lockedReads.size < 200) lockedReads.add(n) // a read made before the unlock answers absent: kept so it can be seen (protectedLocalLockedReads)
199
+ return key ? null : readThrough(n)
200
+ }
201
+ proto.setItem = function (k, v) {
202
+ if (!mine(this) || !sealsHere(k)) return raw.setItem.call(this, k, v)
203
+ const n = String(k), s = String(v); names = null
204
+ if (key) { overlay.set(n, s); writeSealed(n, s) } else if (memoryOnly) overlay.set(n, s); else lockedWrites.set(n, s)
205
+ }
206
+ proto.removeItem = function (k) {
207
+ if (!mine(this) || !sealsHere(k)) return raw.removeItem.call(this, k)
208
+ const n = String(k); names = null; overlay.delete(n)
209
+ if (key) { removeSealed(n); try { raw.removeItem.call(this, n) } catch { /* */ } } else if (!memoryOnly) lockedWrites.set(n, null)
210
+ }
211
+ proto.clear = function () { if (this === localStorage) { overlay.clear(); lockedWrites.clear(); names = null; if (memoryOnly) return } return raw.clear.call(this) } // memory-only: the disk (an account, sealed entries) is never touched
212
+ proto.key = function (i) { if (!mine(this)) return raw.key.call(this, i); const a = enumerate(); return i >= 0 && i < a.length ? a[i] : null }
213
+ if (lengthDesc && lengthDesc.get) Object.defineProperty(proto, 'length', { configurable: true, enumerable: lengthDesc.enumerable, get () { return mine(this) ? enumerate().length : lengthDesc.get.call(this) } })
214
+ if (on) { active = true; armReady() }
215
+ }
216
+ let memoryOnly = false
217
+ const lockedReads = new Set()
218
+ /** The names read while LOCKED (answered absent) — a module that read a setting at load, before the unlock, shows up here. */
219
+ export const protectedLocalLockedReads = () => [...lockedReads]
220
+
221
+ const parseSealed = (s) => { try { const o = JSON.parse(s); return isSealed(o) ? o : null } catch { return null } }
222
+
223
+ /** Switch ON / unlock: import the device key, fill the overlay from disk — opaque entries opened; phase-1 entries (sealed
224
+ * under their own names) and clear entries MOVED under opaque names — apply what was written while locked, then answer
225
+ * `ready()`. A wrong key throws on the first sealed entry and changes nothing. */
226
+ //
227
+ // `switchOn`: protection is being TURNED ON with a new passkey (spaceLock.enableProtection). Protection was off, so no lock
228
+ // names a passkey for whatever sealed entries are still here — an earlier setup's leftovers (a reset, site data cleared in
229
+ // part): nothing can ever open them. They are dropped rather than refused — refusing failed every "Secure this computer"
230
+ // for good, each retry a new passkey that opened none of them (the owner's second desktop, 2026-10-29: protect_failed).
231
+ // A GUEST'S VISIT STAYS MEMORY-ONLY (sync sweep 11-04 #1, #5): an unlock would turn memory-only off and write the visit into the
232
+ // account's storage; a "forget" would delete this device's sealed entries. During the demo's temporary room neither happens.
233
+ const guestVisit = () => { try { return memoryOnly && typeof location !== 'undefined' && isGuestTempRoom(location) } catch { return false } }
234
+ export async function unlockProtectedLocal (rawKey, { switchOn = false, also = [] } = {}) {
235
+ if (guestVisit()) return
236
+ if (!raw) installProtectedLocal()
237
+ await chain // a second unlock (the frame takes the key at its store's hand-over, then again from framedProtect): writes still on their way land first, or the disk read below would put an older value back
238
+ const k = await importRaw(rawKey), nm = await makeNamer(rawKey)
239
+ // ⛔ 10·V#1 (pass 10): THE OTHER KEY THIS DEVICE KNOWS (`also` — the device storage key, while a passkey protects it). A switch between
240
+ // them killed half-way left entries under BOTH keys' names: a resumed switch-on removed every name the passkey could not read (the
241
+ // entries not yet re-keyed — the account master among them), and a switch-off that finished its re-key before the lock's config
242
+ // said so left a passkey that "opens nothing here" for good. A name another known key opens is CARRIED: re-sealed under this key,
243
+ // then its old name goes. Nothing a known key can open is ever removed.
244
+ const others = []
245
+ for (const r of (Array.isArray(also) ? also : [also])) { if (!r) continue; try { others.push({ k: await importRaw(r), nm: await makeNamer(r) }) } catch { /* not a key */ } }
246
+ const next = new Map(), move = [], stale = []
247
+ let opaque = 0, ours = 0
248
+ // ALL AT ONCE (2026-11-17, the owner's iPhone: "storage opened with the device key in 223 ms"): WebKit answers each WebCrypto call
249
+ // on another thread, so ~1200 entries × 3 calls awaited one by one cost 127 ms in WebKit here, issued together 4 ms (Chromium: 11 / 9).
250
+ // Every entry is opened first, then taken in the disk's order below — the same outcome, the same throws.
251
+ const entries = []
252
+ for (const stored of rawKeys()) {
253
+ if (staysClear(stored)) continue
254
+ const v = raw.getItem.call(localStorage, stored); if (v == null) continue
255
+ entries.push([stored, v])
256
+ }
257
+ const opened = await Promise.all(entries.map(async ([stored, v]) => {
258
+ if (isOpaqueName(stored)) {
259
+ const name = await nm.real(stored)
260
+ if (name == null) { // not this key's name: another key this device knows (10·V#1), else another key's leftover
261
+ for (const o of others) {
262
+ const n2 = await o.nm.real(stored); if (n2 == null) continue
263
+ const blob = parseSealed(v); if (!blob) return { stale: true }
264
+ try { return { name: n2, clear: String(await open(o.k, blob)), carried: true } } catch { return { stale: true } }
265
+ }
266
+ return { stale: true }
267
+ }
268
+ const blob = parseSealed(v); if (!blob) return { name, skip: true }
269
+ return { name, clear: String(await open(k, blob)) }
270
+ }
271
+ const blob = parseSealed(v)
272
+ if (blob && isProtectedKey(stored)) { // phase 1: sealed under its own name
273
+ try { return { clear: String(await open(k, blob)) } } catch (e) { if (!switchOn) throw e; return { stale: true } }
274
+ }
275
+ return { clear: v } // clear: never protected before, or written by an older build
276
+ }))
277
+ const logCopies = new Map() // an APPEND LOG's every copy, merged below — never one copy replacing another
278
+ const carried = [], carriedNames = new Set() // 10·V#1: entries another known key opened — re-sealed under this one, then their old names go
279
+ entries.forEach(([stored], i) => {
280
+ const r = opened[i]
281
+ if (isOpaqueName(stored)) {
282
+ opaque++
283
+ if (r.stale) { stale.push(stored); return }
284
+ if (r.carried) { ours++; carried.push(stored); if (!next.has(r.name)) { next.set(r.name, r.clear); carriedNames.add(r.name) } return } // this key's own copy, where there is one, is the newer
285
+ ours++
286
+ if (!r.skip) { next.set(r.name, r.clear); if (APPEND_LOGS.includes(r.name)) logCopies.set(r.name, [r.clear, ...(logCopies.get(r.name) || [])]) } // the sealed copy is the older history: first
287
+ } else {
288
+ if (r.stale) { stale.push(stored); return }
289
+ next.set(stored, r.clear)
290
+ if (APPEND_LOGS.includes(stored)) logCopies.set(stored, [...(logCopies.get(stored) || []), r.clear])
291
+ move.push(stored)
292
+ }
293
+ })
294
+ // THE BOOT LOG KEEPS EVERY LINE (2026-11-17, the owner's iPhone sealed by the device key: each Diagnostics showed ONE launch, and one
295
+ // lost every line after the unlock). The loader writes its lines to a CLEAR `space:bootlog` before this module runs, the sealed copy
296
+ // holds the history, and a line written while locked waits in lockedWrites — whichever the disk listed last replaced the others,
297
+ // and a locked write was dropped because the disk had the name. Now the copies are joined (history first, each line once, the cap kept).
298
+ const logWritten = []
299
+ for (const n of APPEND_LOGS) {
300
+ const parts = [...(logCopies.get(n) || []), lockedWrites.get(n)].filter((v) => v != null)
301
+ if (parts.length < 2) continue
302
+ const seen = new Set(), lines = []
303
+ for (const v of parts) { let a = null; try { a = JSON.parse(v) } catch { a = null } if (!Array.isArray(a)) continue; for (const l of a) { const t = String(l); if (!seen.has(t)) { seen.add(t); lines.push(t) } } }
304
+ while (lines.length > LOG_CAP) lines.shift()
305
+ next.set(n, JSON.stringify(lines)); lockedWrites.delete(n); logWritten.push(n)
306
+ }
307
+ if (opaque && !ours && !switchOn) throw new Error('this key opens nothing here') // a wrong key: every name fails to open, change nothing
308
+ if (switchOn) for (const n of stale) { try { raw.removeItem.call(localStorage, n) } catch { /* */ } }
309
+ // A write made while locked is kept only where the disk has NOTHING under that name: a module that found a value "missing"
310
+ // at load (it was sealed) and wrote a default — a fresh device id, an empty list — must never replace the real one.
311
+ const written = []
312
+ for (const [n, v] of lockedWrites) if (v != null && !next.has(n)) { next.set(n, v); written.push(n) }
313
+ const removed = []
314
+ if (switchOn) sealGen++ // a new protection: writes made under another one are not this one's
315
+ key = k; namer = nm; active = true; memoryOnly = false; names = null
316
+ overlay.clear(); for (const [n, v] of next) overlay.set(n, v)
317
+ lockedWrites.clear()
318
+ for (const n of new Set([...move, ...written, ...logWritten, ...carriedNames])) if (overlay.has(n)) writeSealed(n, overlay.get(n))
319
+ if (carried.length) { await chain; for (const o of carried) { try { raw.removeItem.call(localStorage, o) } catch { /* */ } } } // written under this key first (10·V#1)
320
+ settleReady()
321
+ // Modules that cached a value at load (read while locked → absent) re-read it now: enclave.js (the confidential rooms),
322
+ // trustedBuilds.js, unread.js. An event, not an import — the SDK shares those modules and must not install this one.
323
+ try { if (typeof dispatchEvent === 'function' && typeof Event === 'function') dispatchEvent(new Event('wb-protected-unlocked')) } catch { /* */ }
324
+ return { entries: next.size, migrated: move.length }
325
+ }
326
+ /** RE-KEY (docs/vault-at-rest-and-invites-plan.md § 1): the storage, sealed and open under one key, is written again under another —
327
+ * the hosted vault's device key ↔ a passkey's. Every entry in the overlay is sealed under the new key's opaque name FIRST, then the
328
+ * old key's opaque names go: never a clear moment on disk. Unlocked only; throws when locked (nothing would be carried). */
329
+ export async function rekeyProtectedLocal (newRaw) {
330
+ if (!raw || !active || !key || !namer) throw new Error('rekey: not unlocked')
331
+ await chain
332
+ const oldNm = namer, k = await importRaw(newRaw), nm = await makeNamer(newRaw)
333
+ const old = []
334
+ for (const stored of rawKeys()) if (isOpaqueName(stored) && (await oldNm.real(stored)) != null) old.push(stored)
335
+ sealGen++; key = k; namer = nm; names = null
336
+ for (const [n, v] of overlay) writeSealed(n, v)
337
+ await chain
338
+ for (const o of old) { try { raw.removeItem.call(localStorage, o) } catch { /* */ } }
339
+ return { entries: overlay.size, moved: old.length }
340
+ }
341
+ /** Relock: nothing readable stays in memory; the sealed blobs stay on disk. */
342
+ export function relockProtectedLocal () { overlay.clear(); lockedWrites.clear(); key = null; namer = null; names = null; memoryOnly = false; if (active) armReady() }
343
+ /** MEMORY ONLY (docs/desktop-protection.md, a room link on an unsecured computer): every entry but the lock config is
344
+ * answered from and written to the overlay alone — nothing reaches the disk — and boot is not held. */
345
+ export function memoryOnlyProtectedLocal () { sealGen++; if (!raw) installProtectedLocal(); overlay.clear(); lockedWrites.clear(); key = null; namer = null; names = null; memoryOnly = true; active = true; settleReady() }
346
+ /** Switch OFF: every entry back in the clear under its real name; the opaque entries go; the wrappers pass through again. */
347
+ export async function unprotectProtectedLocal (rawKey) {
348
+ if (!raw) installProtectedLocal()
349
+ await chain
350
+ const k = await importRaw(rawKey), nm = await makeNamer(rawKey)
351
+ for (const stored of rawKeys()) {
352
+ const v = raw.getItem.call(localStorage, stored); if (v == null) continue
353
+ if (isOpaqueName(stored)) {
354
+ const name = await nm.real(stored); const blob = parseSealed(v)
355
+ if (name != null && blob) raw.setItem.call(localStorage, name, String(await open(k, blob)))
356
+ if (name != null) raw.removeItem.call(localStorage, stored)
357
+ } else if (isProtectedKey(stored)) { const blob = parseSealed(v); if (blob) raw.setItem.call(localStorage, stored, String(await open(k, blob))) } // phase 1
358
+ }
359
+ sealGen++; overlay.clear(); lockedWrites.clear(); key = null; namer = null; names = null; memoryOnly = false; active = false; settleReady()
360
+ }
361
+ /** A FRAMED app whose framer no longer protects the device (the marker is stale, or the vault never answered): the sealed
362
+ * entries cannot be opened without a key that is gone — drop them (they are mirrors the vault seeds back) and pass through. */
363
+ export function forgetProtectedLocal () { if (guestVisit()) return;
364
+ if (!raw) installProtectedLocal()
365
+ for (const stored of rawKeys()) { const v = raw.getItem.call(localStorage, stored); if (isOpaqueName(stored) || (v != null && parseSealed(v))) { try { raw.removeItem.call(localStorage, stored) } catch { /* */ } } }
366
+ try { raw.removeItem.call(localStorage, FRAMED_MARK) } catch { /* */ }
367
+ sealGen++; overlay.clear(); lockedWrites.clear(); key = null; namer = null; names = null; memoryOnly = false; active = false; settleReady()
368
+ }
369
+ /** A FRAME whose parent switched protection off: the parent wrote every entry back in the clear — just pass through. */
370
+ export function releaseProtectedLocal () { sealGen++; overlay.clear(); lockedWrites.clear(); key = null; namer = null; names = null; memoryOnly = false; active = false; settleReady() }
371
+ // ANOTHER DOCUMENT of this origin wrote an entry (the app and its Code frame share localStorage, each with its own overlay):
372
+ // take the new value into this overlay, so neither reads a stale copy until it reloads.
373
+ try {
374
+ if (typeof window !== 'undefined') addEventListener('storage', (e) => {
375
+ if (!active || !key || !namer || !e.key || e.storageArea !== localStorage || !isOpaqueName(e.key)) return
376
+ const k = key, nm = namer
377
+ nm.real(e.key).then((name) => {
378
+ if (name == null || key !== k) return
379
+ names = null
380
+ if (e.newValue == null) { overlay.delete(name); return }
381
+ const blob = parseSealed(e.newValue); if (blob) open(k, blob).then((v) => { if (key === k) overlay.set(name, String(v)) }).catch(() => {})
382
+ }).catch(() => {})
383
+ })
384
+ } catch { /* no window */ }
385
+ // SELF-INSTALL at import. This module is the FIRST import of space.js (and of vault-loader.js), so it evaluates before any
386
+ // module that reads a protected key; it wraps the prototype once and switches on when the device is protected (active ⇒
387
+ // reads answer null until the unlock fills the overlay). A TOP-LEVEL page owns a lock: the standalone app's `space:lock`
388
+ // or the vault's `vault:lock`. A FRAMED app owns none — its framer (our vault, slice 4) hands it the key, and the marker it
389
+ // leaves says to start sealed; framed by anyone else, or unmarked, nothing happens.
390
+ try {
391
+ if (typeof window !== 'undefined' && typeof Storage !== 'undefined') {
392
+ const rawGet0 = (k) => { try { return Storage.prototype.getItem.call(localStorage, k) } catch { return null } }
393
+ const cfgOn = (k) => { try { return cfgSaysProtected(JSON.parse(rawGet0(k) || 'null')) } catch { return false } }
394
+ // a SAME-ORIGIN frame of the app (the Code section, codeView.js) shares its localStorage: it reads the app's own lock
395
+ // config, and the app hands it the key ({ch:'codeProtect'}), exactly as idbSeal.js does for the idb
396
+ let sameOriginFramed = false; try { sameOriginFramed = window.top !== window && window.parent.location.origin === location.origin } catch { sameOriginFramed = false }
397
+ // A same-origin frame shares only the APP's lock (space:lock — the Code frame inside the app). The vault's vault:lock is
398
+ // the vault's own: an app the vault frames on its origin (dev, a test fixture) waits for the vault's hand-off marker,
399
+ // never reads that config as its own and sits sealed waiting for a key (2026-10-13, vaultProtect).
400
+ const on = window.top === window ? (cfgOn('space:lock') || cfgOn('vault:lock') || rawGet0(FRAMED_MARK) === '1' || rawGet0('vault:atrest') === '1' || rawGet0('space:atrest') === '1')
401
+ : sameOriginFramed ? (cfgOn('space:lock') || rawGet0(FRAMED_MARK) === '1' || rawGet0('space:atrest') === '1') : rawGet0(FRAMED_MARK) === '1' // space:atrest: the app's device key (spaceAtRest.js) — a same-origin frame (Code, the lane panel) waits for its parent's hand-off
402
+ installProtectedLocal(Storage.prototype, { on })
403
+ // A GUEST'S TEMPORARY ROOM (the HN demo's link: ?room=tmp-…, #…guest=1 — the app's address, regular or framed by the vault):
404
+ // the visitor came to look, so NOTHING of the visit reaches the disk — memory-only from this module's first line, before
405
+ // any module writes a device id, a boot log or the room's settings (the owner, 2026-11-04: "Fix Secure this computer"; the
406
+ // hosted frame kept space:model:<room>, space:tempidx, space:usagekey … in its own storage). On a PROTECTED device too: the
407
+ // visit reads nothing sealed and writes nothing, so it needs no unlock (the owner's computer: the demo met "Spaces is locked").
408
+ if (isGuestTempRoom(location)) memoryOnlyProtectedLocal()
409
+ }
410
+ } catch { /* no storage (a worker, a sandbox): nothing to protect here */ }
411
+
412
+ /** The demo's guest link for a temporary room: ?room=tmp-… with guest=1 — after the # (the app's address, the frame's) or in
413
+ * the query (the vault's own link, hnPage.js vaultLinkOf). THE one test: nameGate.js, encHint.js and space.js ask it too — a
414
+ * guest=1 on any other room changes nothing (sync sweep 11-04 #7, #12). */
415
+ export function isGuestTempRoom (loc) {
416
+ try {
417
+ const q = new URLSearchParams(loc.search || '')
418
+ return (/[#&]guest=1(?:&|$)/.test(String(loc.hash || '')) || q.get('guest') === '1') && String(q.get('room') || '').startsWith('tmp-')
419
+ } catch { return false }
420
+ }
421
+
422
+ /** For tests: forget the wrapping (restores the prototype). */
423
+ export function _uninstallProtectedLocal (proto = (typeof Storage !== 'undefined' ? Storage.prototype : null)) {
424
+ if (!raw || !proto) return
425
+ Object.assign(proto, raw); if (lengthDesc) Object.defineProperty(proto, 'length', lengthDesc); raw = null; lengthDesc = null; overlay.clear(); lockedWrites.clear(); key = null; namer = null; names = null; memoryOnly = false; active = false; readyPromise = Promise.resolve(); readyResolve = null
426
+ }
package/pushCore.js ADDED
@@ -0,0 +1,42 @@
1
+ // pushCore.js — THE PUSH SUBSCRIPTION, ONE IMPLEMENTATION FOR BOTH APPS (docs/convergence-review-2026-10-17.md, step 2). The
2
+ // regular app (notifications.js) and the tenant vault (vault-loader.js — it owns push for the framed app) each had their
3
+ // own; the vault's subscribe had none of the iOS lessons the regular one learned. Leaf module: no DOM beyond what is passed.
4
+ import { nativeRegistration } from './nativePush.js' // the Android / Windows app's registration (no service worker needed)
5
+
6
+ /** A base64URL VAPID public key → the bytes pushManager.subscribe wants. */
7
+ export function vapidBytes (s) {
8
+ const t = (String(s) + '='.repeat((4 - (String(s).length % 4)) % 4)).replace(/-/g, '+').replace(/_/g, '/')
9
+ const b = atob(t); const u = new Uint8Array(b.length)
10
+ for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i)
11
+ return u
12
+ }
13
+
14
+ /** The page's service-worker registration, ACTIVE — bounded. `navigator.serviceWorker.ready` waits for ever when the
15
+ * registration is gone (the update fail-safe unregisters it), and every push path then hangs with no error: re-register a
16
+ * missing one, and give up with a readable error after `ms`. */
17
+ export async function swRegBounded ({ ms = 8000, sw = (typeof navigator !== 'undefined' ? navigator.serviceWorker : null), path = '/sw.js', sleep = (r) => setTimeout(r, 250), native = nativeRegistration } = {}) {
18
+ if (!sw) { const nr = native(); if (nr) return nr; throw new Error('no service worker support') }
19
+ let reg = null
20
+ try { reg = await sw.getRegistration() } catch { /* */ }
21
+ // inside the Windows app no service worker may register (bridge.go): its push runs through the app's bridge (nativePush.js)
22
+ if (!reg) { const nr = native(); if (nr) return nr }
23
+ if (!reg) { try { reg = await sw.register(path) } catch (e) { throw new Error('service worker gone and re-register failed (' + ((e && e.message) || e) + ') — close and reopen the app') } }
24
+ const t0 = Date.now()
25
+ while (!reg.active) { if (Date.now() - t0 > ms) throw new Error('service worker not active after ' + (ms / 1000) + 's — close and reopen the app'); await new Promise(sleep) }
26
+ return reg
27
+ }
28
+
29
+ /** This registration's push subscription, made if there is none — the iOS lessons (2026-09): subscribe() can STALL for ever
30
+ * when the push service does not answer (raced against `timeoutMs`), and THROWS for a wedged registration or one minted
31
+ * under an older VAPID key (drop the stale subscription, try once more). Permission is the caller's: this assumes it is
32
+ * granted. → { sub, err } — never throws, never hangs. */
33
+ export async function subscribeRobust (reg, vapidKey, { timeoutMs = 10000 } = {}) {
34
+ let sub = null
35
+ try { sub = await reg.pushManager.getSubscription() } catch { /* treat as none */ }
36
+ if (sub) return { sub, err: '' }
37
+ const withTimeout = (pr) => Promise.race([pr, new Promise((_, rej) => setTimeout(() => rej(new Error('timed out after ' + (timeoutMs / 1000) + 's — push service unreachable')), timeoutMs))])
38
+ const mk = () => withTimeout(reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: vapidBytes(vapidKey) }))
39
+ try { return { sub: await mk(), err: '' } } catch { /* a stale or wedged subscription: drop it and try once more */ }
40
+ try { const old = await reg.pushManager.getSubscription(); if (old) await old.unsubscribe() } catch { /* */ }
41
+ try { return { sub: await mk(), err: '' } } catch (e) { return { sub: null, err: e && e.name ? e.name + ': ' + e.message : String(e) } }
42
+ }