@witbitz/sdk 0.0.0-stage → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +200 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +223 -0
  6. package/accountIndexDoc.js +122 -0
  7. package/accountOwner.js +59 -0
  8. package/accountRecord.js +90 -0
  9. package/accountScope.js +114 -0
  10. package/accountSeal.js +42 -0
  11. package/accountStores.js +173 -0
  12. package/acctV2App.js +619 -0
  13. package/acctV2Check.js +29 -0
  14. package/acctV2Client.js +382 -0
  15. package/acctV2Keys.js +43 -0
  16. package/acctV2Legacy.js +14 -0
  17. package/acctV2Switch.js +80 -0
  18. package/acctV2UiCore.js +857 -0
  19. package/acctV2WebAuthn.js +61 -0
  20. package/acctV2Wire.js +59 -0
  21. package/address.js +42 -0
  22. package/attestedBox.js +30 -0
  23. package/attestedRooms.js +78 -0
  24. package/awsKey.js +98 -0
  25. package/backupRecord.js +106 -0
  26. package/backupVault.js +97 -0
  27. package/blocks.js +115 -0
  28. package/blocksPush.js +64 -0
  29. package/browseSeal.js +103 -0
  30. package/cbor.js +225 -0
  31. package/changePush.js +75 -0
  32. package/chatLock.js +149 -0
  33. package/chatLockSw.js +13 -0
  34. package/cloudDeviceBuilds.js +11 -0
  35. package/cloudDevicePins.js +33 -0
  36. package/cloudDeviceSeal.js +53 -0
  37. package/codeBrowse.js +224 -0
  38. package/codeCloud.js +652 -0
  39. package/codeCloudKeys.js +112 -0
  40. package/codeCommands.js +167 -0
  41. package/codeComputers.js +388 -0
  42. package/codeEgress.js +123 -0
  43. package/codeFilesRoutes.js +17 -0
  44. package/codeMkdir.js +8 -0
  45. package/codeModes.js +57 -0
  46. package/codeOrphanKeys.js +42 -0
  47. package/codeOutputs.js +141 -0
  48. package/codeRelay.js +505 -0
  49. package/codeSentinel.js +86 -0
  50. package/codeTransport.js +295 -0
  51. package/codeUndo.js +48 -0
  52. package/compress.js +24 -0
  53. package/config.js +11 -0
  54. package/connCatalog.js +164 -0
  55. package/connDisp.js +76 -0
  56. package/connOtherWays.js +74 -0
  57. package/connPending.js +16 -0
  58. package/connWrap.js +53 -0
  59. package/connectionEntry.js +89 -0
  60. package/connections.js +562 -0
  61. package/credits.js +30 -0
  62. package/csAttest.js +112 -0
  63. package/decrypt.html +384 -0
  64. package/deviceAttest.js +521 -0
  65. package/deviceCall.js +54 -0
  66. package/deviceKeyCore.js +41 -0
  67. package/deviceSeal.js +59 -0
  68. package/e2ee.js +323 -0
  69. package/eat.js +103 -0
  70. package/emailFork.js +275 -0
  71. package/emailSignIn.js +81 -0
  72. package/emptySpaces.js +111 -0
  73. package/encSource.js +55 -0
  74. package/enclaveAccept.js +214 -0
  75. package/enclaveClaim.js +241 -0
  76. package/enclaveRoute.js +102 -0
  77. package/enclaveSnapshotMerge.js +44 -0
  78. package/entrySig.js +165 -0
  79. package/env.js +73 -0
  80. package/eraseFile.js +58 -0
  81. package/followImage.js +86 -0
  82. package/healNames.js +45 -0
  83. package/idb.js +97 -0
  84. package/idbSeal.js +119 -0
  85. package/indexGone.js +12 -0
  86. package/invite.js +51 -0
  87. package/inviteEnroll.js +67 -0
  88. package/inviteSend.js +68 -0
  89. package/jobAgents.js +87 -0
  90. package/keptMerge.js +84 -0
  91. package/l1-worker-src.js +2 -0
  92. package/l1-worker.js +831 -0
  93. package/laneConfig.js +57 -0
  94. package/laneLinkCore.js +177 -0
  95. package/ledgerView.js +64 -0
  96. package/manifest.json +220 -0
  97. package/mcpRecommended.js +25 -0
  98. package/memberChange.js +123 -0
  99. package/mkseal.js +101 -0
  100. package/nativePush.js +153 -0
  101. package/nitroVerify.js +220 -0
  102. package/noble-p256.js +27 -0
  103. package/notice.js +116 -0
  104. package/notifKey.js +58 -0
  105. package/offlineBundle.js +62 -0
  106. package/ohttp.js +177 -0
  107. package/opencodeWire.js +282 -0
  108. package/oprf.js +70 -0
  109. package/ownAgentLink.js +96 -0
  110. package/ownerPolicy.js +117 -0
  111. package/package.json +254 -4
  112. package/pollVerdict.js +33 -0
  113. package/prefetchPoll.js +60 -0
  114. package/protectedLocal.js +410 -0
  115. package/pushCore.js +42 -0
  116. package/recovery.js +107 -0
  117. package/regions.js +42 -0
  118. package/removedMessage.js +11 -0
  119. package/renameRefusal.js +9 -0
  120. package/replyQuote.js +34 -0
  121. package/reqEnvelope.js +126 -0
  122. package/roomDefaultPrefs.js +76 -0
  123. package/roomDelete.js +109 -0
  124. package/roomName.js +177 -0
  125. package/roomPass.js +256 -0
  126. package/roomRoster.js +289 -0
  127. package/roomSettings.js +61 -0
  128. package/roomState.js +58 -0
  129. package/roomStreamClient.js +115 -0
  130. package/rosterCount.js +49 -0
  131. package/rosterHash.js +13 -0
  132. package/rowSchema.js +113 -0
  133. package/safeMedia.js +116 -0
  134. package/safeMediaPins.js +17 -0
  135. package/schedulesDoc.js +78 -0
  136. package/sdkA2A.js +404 -0
  137. package/sdkAccount.js +470 -0
  138. package/sdkAccountDoc.js +81 -0
  139. package/sdkAccountSections.js +223 -0
  140. package/sdkAgui.js +141 -0
  141. package/sdkAttest.js +34 -0
  142. package/sdkBackup.js +480 -0
  143. package/sdkBackupV2.js +630 -0
  144. package/sdkBrowserPrivate.js +28 -0
  145. package/sdkBuilds.js +208 -0
  146. package/sdkCloudDevice.js +215 -0
  147. package/sdkComputers.js +480 -0
  148. package/sdkDictation.js +142 -0
  149. package/sdkErase.js +283 -0
  150. package/sdkExports.js +69 -0
  151. package/sdkInvitations.js +34 -0
  152. package/sdkKeptAgent.js +188 -0
  153. package/sdkLaneLink.js +205 -0
  154. package/sdkPlan.js +94 -0
  155. package/sdkProtect.js +228 -0
  156. package/sdkRedact.js +36 -0
  157. package/sdkRekey.js +307 -0
  158. package/sdkReport.js +68 -0
  159. package/sdkSafeMedia.js +255 -0
  160. package/sdkSchedules.js +39 -0
  161. package/sdkSpeech.js +54 -0
  162. package/sdkTurn.js +117 -0
  163. package/sdkVault.js +124 -0
  164. package/sealShare.js +18 -0
  165. package/sealedNames.js +64 -0
  166. package/sealedReceipt.js +17 -0
  167. package/sentinelRelease.js +154 -0
  168. package/shamir.js +85 -0
  169. package/sharedViews.js +38 -0
  170. package/sheetChrome.js +450 -0
  171. package/siri.js +171 -0
  172. package/spaceClient.js +1418 -0
  173. package/spaceConfig.js +81 -0
  174. package/spaceEmailGate.js +813 -0
  175. package/spaceExport.js +125 -0
  176. package/spaceFork.js +216 -0
  177. package/spaceLock.js +358 -0
  178. package/spacePasskey.js +180 -0
  179. package/speechOut.js +100 -0
  180. package/splitKeyClient.js +90 -0
  181. package/store.js +587 -0
  182. package/streamHint.js +36 -0
  183. package/sttCloud.js +220 -0
  184. package/sttWorklet.js +38 -0
  185. package/sw-notif-core.js +538 -0
  186. package/tempList.js +48 -0
  187. package/tinfoilVerifier.js +78 -0
  188. package/toolBooks.js +31 -0
  189. package/toolRules.js +52 -0
  190. package/turnCerts.js +254 -0
  191. package/turnFeed.js +58 -0
  192. package/turnVerdict.js +36 -0
  193. package/usageReceipts.js +176 -0
  194. package/usageSummary.js +90 -0
  195. package/util.js +181 -0
  196. package/vault-core.js +1958 -0
  197. package/vault-kit.mjs +354 -0
  198. package/vault-screens.js +263 -0
  199. package/vaultAtRest.js +177 -0
  200. package/vaultCoreLock.js +111 -0
  201. package/vaultCorePush.js +140 -0
  202. package/vaultDeviceKey.js +95 -0
  203. package/vaultEnclaveHandoff.js +114 -0
  204. package/vaultKeep.js +281 -0
  205. package/vaultSealedStore.js +77 -0
  206. package/vaultWorkerHost.js +98 -0
  207. package/vcWorker.js +34 -0
  208. package/voiceAttest.js +50 -0
  209. package/voiceCert.js +51 -0
  210. package/witbitz-admin.d.ts +135 -0
  211. package/witbitz-admin.js +529 -0
  212. package/witbitz-admin.mjs +1459 -0
  213. package/witbitz-sdk.d.ts +1106 -0
  214. package/witbitz-sdk.js +3835 -0
  215. package/workerClient.js +16 -0
  216. package/workerLiveness.js +21 -0
  217. package/x509.js +218 -0
package/entrySig.js ADDED
@@ -0,0 +1,165 @@
1
+ // Per-member identity for async Spaces — the BROWSER counterpart of agent/spaceEntrySig.mjs, and byte-compatible
2
+ // with it (and with the Kibitz room link's inviteToken). The member holds an ECDSA signing keypair; their GRANT is a
3
+ // Kibitz invite token, payload superset `{name, room, exp, spk}`, signed by the ROOM invite key and verified against
4
+ // the public `gk` in the link. Each async ledger turn is SIGNED with the member key; the server (or any reader)
5
+ // checks `grant → (name, spk)` then `entry → spk`. This file signs turns client-side; agent/spaceEntrySig.mjs verifies
6
+ // them server-side in the decrypt-once render. The two MUST stay in lockstep — the interop test cross-verifies them.
7
+ //
8
+ // Standalone (no dependency on e2ee.js): base64url via btoa/atob, ECDSA-P256-SHA256 via crypto.subtle — identical
9
+ // bytes to the server's Buffer.base64url + crypto.subtle path.
10
+
11
+ const enc = new TextEncoder()
12
+ const dec = new TextDecoder()
13
+ const toB64 = (u8) => btoa(String.fromCharCode(...u8)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
14
+ const fromB64 = (s) => {
15
+ const b = atob(String(s).replace(/-/g, '+').replace(/_/g, '/'))
16
+ const u = new Uint8Array(b.length)
17
+ for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i)
18
+ return u
19
+ }
20
+ const ECDSA = { name: 'ECDSA', namedCurve: 'P-256' }
21
+ const SIGN = { name: 'ECDSA', hash: 'SHA-256' }
22
+ const importPriv = (jwk) => crypto.subtle.importKey('jwk', jwk, ECDSA, false, ['sign'])
23
+ const importPub = (jwk) => crypto.subtle.importKey('jwk', jwk, ECDSA, false, ['verify'])
24
+
25
+ // Canonical (sorted-key) JSON — identical to agent/spaceEntrySig.mjs + bridgeLog so the signed form matches.
26
+ function canon(o) {
27
+ if (o === null || typeof o !== 'object') return JSON.stringify(o)
28
+ if (Array.isArray(o)) return '[' + o.map(canon).join(',') + ']'
29
+ return '{' + Object.keys(o).sort().map((k) => JSON.stringify(k) + ':' + canon(o[k])).join(',') + '}'
30
+ }
31
+
32
+ /** A fresh ECDSA P-256 keypair (JWK). Doubles as the ROOM invite keypair and a MEMBER signing keypair. */
33
+ export async function genKeypair() {
34
+ const kp = await crypto.subtle.generateKey(ECDSA, true, ['sign', 'verify'])
35
+ return { pub: await crypto.subtle.exportKey('jwk', kp.publicKey), priv: await crypto.subtle.exportKey('jwk', kp.privateKey) }
36
+ }
37
+
38
+ /** Mint a member GRANT (Kibitz invite token, payload `{name,room,exp,spk,caps?}`) — signed by the ROOM invite private
39
+ * key. `caps` (spaceCaps.Grant) is OPTIONAL; omit it and the token is byte-identical to the pre-caps grant. `caps`
40
+ * is LAST so the byte order matches the server twin (agent/spaceEntrySig.mjs) — the interop test asserts it. */
41
+ export async function mintGrant(roomInvitePrivJwk, { name, room, exp, spk, caps }) {
42
+ const body = toB64(enc.encode(JSON.stringify({ name, room, exp, spk, caps })))
43
+ const sig = new Uint8Array(await crypto.subtle.sign(SIGN, await importPriv(roomInvitePrivJwk), enc.encode(body)))
44
+ return `${body}.${toB64(sig)}`
45
+ }
46
+
47
+ /** Verify a grant against the room invite PUBLIC key (`gk`) + room + expiry. `now`/`exp` are epoch SECONDS. */
48
+ export async function verifyGrant(token, roomInvitePubJwk, { room, now } = {}) {
49
+ const t = String(token)
50
+ const dot = t.indexOf('.')
51
+ if (dot < 1 || dot === t.length - 1) return { ok: false, reason: 'malformed' }
52
+ let payload
53
+ let sig
54
+ try {
55
+ sig = fromB64(t.slice(dot + 1))
56
+ payload = JSON.parse(dec.decode(fromB64(t.slice(0, dot))))
57
+ } catch {
58
+ return { ok: false, reason: 'malformed' }
59
+ }
60
+ const valid = await crypto.subtle.verify(SIGN, await importPub(roomInvitePubJwk), sig, enc.encode(t.slice(0, dot))).catch(() => false)
61
+ if (!valid) return { ok: false, reason: 'bad signature' }
62
+ if (payload.room !== room) return { ok: false, reason: 'wrong room' }
63
+ if (typeof payload.exp !== 'number' || now >= payload.exp) return { ok: false, reason: 'expired' }
64
+ if (!payload.name || !payload.spk) return { ok: false, reason: 'incomplete' }
65
+ return { ok: true, name: payload.name, spk: payload.spk, ...(payload.caps !== undefined ? { caps: payload.caps } : {}) }
66
+ }
67
+
68
+ // `chal` (a server-issued challenge) is folded in only when present, so the entry signature also commits to the fresh
69
+ // challenge (the async presence proof). Omitted ⇒ byte-identical to a pre-challenge signature. MUST match the server
70
+ // twin (agent/spaceEntrySig.mjs) — the interop test asserts it.
71
+ const entryCore = (e) => ({ room: e.room, author: e.author, ts: e.ts, kind: e.kind, id: e.id, text: e.text, ...(e.chal !== undefined ? { chal: e.chal } : {}) })
72
+
73
+ /** Sign a ledger entry with the member's signing PRIVATE key → the entry with `sig` set. */
74
+ export async function signEntry(memberPrivJwk, entry) {
75
+ const sig = toB64(new Uint8Array(await crypto.subtle.sign(SIGN, await importPriv(memberPrivJwk), enc.encode(canon(entryCore(entry))))))
76
+ return { ...entry, sig }
77
+ }
78
+
79
+ /** Sign an arbitrary canonical assertion with a signing PRIVATE key (ECDSA-P256-SHA256) → base64url signature. Used by
80
+ * the email-code SESSION REFRESH to prove possession of the key a token is bound to (api/email/refresh verifies it). */
81
+ export async function signAssertion(privJwk, obj) {
82
+ return toB64(new Uint8Array(await crypto.subtle.sign(SIGN, await importPriv(privJwk), enc.encode(canon(obj)))))
83
+ }
84
+
85
+ /** Bind this device's sign-in to the account service's recovery challenge. */
86
+ export async function signRestoreChallenge(privJwk, challenge) {
87
+ return toB64(new Uint8Array(await crypto.subtle.sign(SIGN, await importPriv(privJwk), enc.encode('witbitz-acct-signin|' + challenge))))
88
+ }
89
+
90
+ /** Verify an entry's signature against a signing PUBLIC key (`spk`). */
91
+ export async function verifyEntry(entry, signPubJwk) {
92
+ if (!entry || !entry.sig) return false
93
+ return crypto.subtle.verify(SIGN, await importPub(signPubJwk), fromB64(entry.sig), enc.encode(canon(entryCore(entry)))).catch(() => false)
94
+ }
95
+
96
+ /** The OIDC nonce that binds a Google ID token to this member's signing key: base64url(SHA-256(canonical-JWK(spk))).
97
+ * Pass it as the `nonce` to Google Identity Services; the server (agent/spaceOidc.mjs spkNonce) recomputes it from the
98
+ * spk the turn carries and requires equality — so a Google token can't be replayed onto a different key. MUST match
99
+ * the server byte-for-byte (the interop test asserts it). */
100
+ export async function spkNonce(spk) {
101
+ const h = await crypto.subtle.digest('SHA-256', enc.encode(canon(spk)))
102
+ return toB64(new Uint8Array(h))
103
+ }
104
+
105
+ /** The reader/agent check: grant valid → (name, spk); entry claims that name; entry signed by spk. */
106
+ export async function attribute(entry, grant, roomInvitePubJwk, { room, now } = {}) {
107
+ const g = await verifyGrant(grant, roomInvitePubJwk, { room, now })
108
+ if (!g.ok) return { ok: false, reason: `grant: ${g.reason}` }
109
+ if (entry.author !== g.name) return { ok: false, reason: 'author mismatch' }
110
+ if (!(await verifyEntry(entry, g.spk))) return { ok: false, reason: 'bad entry signature' }
111
+ // `spk` rides back so the caller can persist it on the entry → the room ROSTER (name→spk) is derivable from the
112
+ // ledger (needed to seal a membership-fork pointer to each keeper — docs/spaces-membership-fork.md, P0).
113
+ return { ok: true, name: g.name, spk: g.spk, ...(g.caps !== undefined ? { caps: g.caps } : {}) }
114
+ }
115
+
116
+ // ── link carry (Kibitz `g*` grammar) ───────────────────────────────────────────────────────────────
117
+ // A JWK rides the link base64url-json (as Kibitz encodes `gk`). PUBLIC bits (`gk`) and the bearer grant (`gt`) plus
118
+ // the member's PRIVATE signing key (`sk`) ALL ride the FRAGMENT (never sent to the server), appended after the room's
119
+ // existing fragment — so this composes with the spaces link grammar without changing it.
120
+ const encJwk = (jwk) => toB64(enc.encode(JSON.stringify(jwk)))
121
+ const decJwk = (s) => { try { return JSON.parse(dec.decode(fromB64(s))) } catch { return null } }
122
+
123
+ /** Append a member's identity params to a link's FRAGMENT: `gk` (room invite pubkey), `gt` (grant), `sk` (member
124
+ * signing PRIVATE key). Returns the extended link. Fragment-only → the server never sees any of it. */
125
+ export function appendIdentity(link, { gk, gt, sk } = {}) {
126
+ const parts = []
127
+ if (gk) parts.push('gk=' + encJwk(gk))
128
+ if (gt) parts.push('gt=' + encodeURIComponent(gt))
129
+ if (sk) parts.push('sk=' + encJwk(sk))
130
+ if (!parts.length) return link
131
+ const hashAt = link.indexOf('#')
132
+ const sep = hashAt < 0 ? '#' : link.indexOf('?', hashAt) >= 0 ? '&' : '?'
133
+ return link + sep + parts.join('&')
134
+ }
135
+
136
+ /** The `name` a grant CLAIMS, decoded without verifying (for a display label; attribution still verifies in §4). */
137
+ export function grantName(token) {
138
+ try {
139
+ return JSON.parse(dec.decode(fromB64(String(token).split('.')[0]))).name || null
140
+ } catch {
141
+ return null
142
+ }
143
+ }
144
+
145
+ /** The signing key a grant BINDS (`spk`), decoded without verifying — the key the server attributes a grant turn to, so the
146
+ * one an attested room's assertion must be bound to (deviceAttest bindHash). Null for anything unreadable. */
147
+ export function grantSpk(token) {
148
+ try {
149
+ return JSON.parse(dec.decode(fromB64(String(token).split('.')[0]))).spk || null
150
+ } catch {
151
+ return null
152
+ }
153
+ }
154
+
155
+ /** Read `{ gk, gt, sk }` from a link/hash fragment (whatever's present). `gk`/`sk` come back as JWKs. */
156
+ export function readIdentity(hashOrLink = '') {
157
+ const h = String(hashOrLink)
158
+ const frag = h.slice(h.indexOf('#') + 1)
159
+ const q = frag.indexOf('?')
160
+ const params = new URLSearchParams(q >= 0 ? frag.slice(q + 1) : '')
161
+ const gk = params.get('gk')
162
+ const gt = params.get('gt')
163
+ const sk = params.get('sk')
164
+ return { gk: gk ? decJwk(gk) : null, gt: gt || null, sk: sk ? decJwk(sk) : null }
165
+ }
package/env.js ADDED
@@ -0,0 +1,73 @@
1
+ // env.js — facts about WHERE this page is running, shared by every module of the split (space.js and the modules cut
2
+ // out of it). LEAF: no imports. Platform (isIOS / installedPWA), the framing vault's origin (VAULT_ORIGIN), and the one
3
+ // mutable boot flag, `env.crossOrigin` (was space.js's `let CROSS_ORIGIN`): set once during boot when a SEPARATE L1
4
+ // vault framed us, read everywhere room-switching or push registration must go THROUGH the vault. An object rather
5
+ // than an exported `let` because ES-module bindings are read-only from the importer's side.
6
+ export const env = { crossOrigin: false } // CROSS_ORIGIN axis (renamed from IN_VAULT, Phase 0): framed by a SEPARATE L1 vault (vcp handshake) → room-switching goes THROUGH the vault (awaitVaultKey per room), never a #mk= reload
7
+ // The origin of the vault that framed us (it delivers the key over vcHandoff). Exact via ancestorOrigins; referrer's
8
+ // origin is the portable fallback. NOT framed / same-origin (Stage 0 + the extension vault) → location.origin, so the
9
+ // handshake stays byte-identical there. Stage 1 (cross-origin vault): this is the vault's separate origin. STAGE 2
10
+ // hardening = compare against a PINNED allowlist here instead of trusting the actual framer (the app only ever RECEIVES
11
+ // the key, never emits it, so a wrong framer can at worst deliver a key that fails to decrypt).
12
+ export const VAULT_ORIGIN = (() => { try { if (window.top === window) return location.origin; const ao = location.ancestorOrigins; if (ao && ao.length && ao[ao.length - 1]) return ao[ao.length - 1]; if (window.parent === window.top && document.referrer) return new URL(document.referrer).origin } catch { /* */ } try { return location.origin } catch { return '' } })() // (no location in Node: the SDK and its test harness import this through util.js) — the TOP frame = the vault; a nested panel/widget resolves IT, not the app it sits inside
13
+ // On iOS, `standalone` is true only for the installed home-screen app; elsewhere the display-mode query covers it.
14
+ // The TENANT app's frame cannot see it: navigator.standalone is undefined in a cross-origin iframe and display-mode is
15
+ // unreliable there, so the vault — the top-level installed app — passes ?standalone=1 (installedChrome.js already trusts it).
16
+ // Without this the installed tenant app offered "Install" and said "install the app first" (the regular↔tenant sweep, 2026-10-12).
17
+ // THE NATIVE APP (android/attested-client, a WebView shell) is installed too, though its page reports no display-mode: it puts its
18
+ // hardware-key bridge on the page (`WitbitzAttest`, deviceAttest.js) — the test browserGate.js uses. Without it the shell met the
19
+ // in-app-browser warning and the install prompts (first run on a phone, 2026-11-07).
20
+ /** WHICH native app this page runs in: its bridge's platform, else the app's user-agent token (a frame the bridge does not reach) —
21
+ * 'ios' | 'android' | 'macos' | 'windows' | 'linux' | '' (a browser). The Mac app answers 'macos' by its bridge, 'mac' by its token. */
22
+ export const nativePlatform = () => {
23
+ try {
24
+ const b = globalThis.WitbitzAttest
25
+ if (b && typeof b.sign === 'function') { const p = typeof b.platform === 'function' ? String(b.platform()) : 'android'; return p === 'mac' ? 'macos' : p }
26
+ const m = /\bWitbitzApp\/([a-z]+)/.exec(navigator.userAgent || '')
27
+ return m ? (m[1] === 'mac' ? 'macos' : m[1]) : ''
28
+ } catch { return '' }
29
+ }
30
+ const APP_NAMES = { ios: 'the iPhone app', android: 'the Android app', macos: 'the Mac app', windows: 'the Windows app', linux: 'the Linux app' }
31
+ /** "the iPhone app" … — the words for the app this is ('the app' for one this page does not know). */
32
+ /** A native app that CARRIES ITS OWN CODE (Android, Windows, the Mac / Linux desktop app, and the iPhone app since its bundled build:
33
+ * a new version is a new app). An iPhone app from before that loads the LIVE hosted app and must take new builds like a browser does.
34
+ * 2026-11-21: checkVersion returned at once for every nativeApp(), so an iPhone app never left the build it first ran
35
+ * (the simulator still ran 7d98b999 four Official releases later). */
36
+ export const nativeBundled = () => nativeApp() && (nativePlatform() !== 'ios' || /\bWitbitzBundled\//.test((globalThis.navigator && navigator.userAgent) || ''))
37
+ // ↑ the iPhone app CARRIES its code since docs/ios-bundled-plan.md (2026-11-21) and says so (WitbitzBundled/1); an older iPhone app
38
+ // that loads the live site does not, and keeps updating like a browser
39
+ export const nativeAppNamed = () => APP_NAMES[nativePlatform()] || 'the app'
40
+ export const nativeApp = () => { try { const b = globalThis.WitbitzAttest; return !!(b && typeof b.sign === 'function') || /\bWitbitzApp\//.test(navigator.userAgent || '') } catch { return false } } // + the app's user-agent token: a frame the bridge does not reach
41
+ export const installedPWA = () => window.navigator.standalone === true || (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches) || framedStandalone() || nativeApp()
42
+ const framedStandalone = () => { try { const q = new URLSearchParams(location.search); return q.get('fullapp') === '1' && q.get('standalone') === '1' } catch { return false } }
43
+ // iOS reports as iPhone/iPad — or, on iPadOS, as "MacIntel" with a touchscreen. We need this because a `_blank`
44
+ // window.open from a STANDALONE PWA on iOS opens the in-app browser (the "Search or enter website name" chrome) and
45
+ // leaves a blank tab in front of the app when maps redirects out. Instead we hand off with the Apple Maps URL scheme,
46
+ // which the OS routes straight to the Maps app — the PWA itself never navigates, so nothing blanks out.
47
+ export const isIOS = () => /iP(hone|ad|od)/.test(navigator.userAgent || '') || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)
48
+ // iPhone LOCKDOWN MODE (the owner, 2026-10-12): it switches off WebAssembly, IndexedDB and — for web apps — notifications,
49
+ // with no exemption for an installed app. On iOS only Lockdown takes WebAssembly away, so its absence is the signal.
50
+ export const iosLockdownLikely = () => { try { return isIOS() && typeof WebAssembly === 'undefined' } catch { return false } }
51
+ // The install LANDING page — per-browser steps that walk a new person through installing the PWA. When we're framed by an
52
+ // L1 vault (a vaulted/tenant deployment), the ENTRY POINT people should install is the VAULT origin (it signs you in and
53
+ // frames the app, confining keys); sharing this inner app origin would bypass the vault and land on the naked app. The
54
+ // vault serves its own install landing at '/'. Standalone → the app IS the entry point, so its own /install page.
55
+ /** Open the install page. In the tenant app the FRAME must not navigate to the vault (it refuses to be framed — a blank
56
+ * screen): the vault page itself goes there. */
57
+ export function openInstallPage() {
58
+ // A GUEST'S ROOM (the HN demo — its key only in this page): the install page opens in a NEW tab, from this tap, so the room
59
+ // stays open (the owner, 2026-11-04: Install did not lead to spaces.witbitz.chat/install, and replaced the room)
60
+ try { if (document.body.classList.contains('guest-room')) { const w = window.open(installLink(), '_blank'); if (w) { try { w.opener = null } catch { /* */ } return } } } catch { /* fall through */ } // not 'noopener': with it open() answers null even when it opened, and this tab left too
61
+ if (env.crossOrigin && VAULT_ORIGIN && VAULT_ORIGIN !== location.origin) { try { window.top.postMessage({ ch: 'vcHandoff', t: 'openInstall' }, VAULT_ORIGIN); return } catch { /* fall through */ } }
62
+ location.href = installLink()
63
+ }
64
+ export const installLink = () => (env.crossOrigin && VAULT_ORIGIN && VAULT_ORIGIN !== location.origin) ? VAULT_ORIGIN + '/install' : location.origin + '/install' // the hosted app's /install too (the owner, 2026-10-20: "like the regular app"; the vault serves the same Install page there)
65
+ export const isLanePanel = (() => { try { return new URLSearchParams(location.search).get('panel') === '1' } catch { return false } })() // this app instance IS a docked private-lane panel (an iframe of the parent shared-room app)
66
+ export const ATLAS = (() => { try { return new URLSearchParams(location.search).get('atlas') === '1' } catch { return false } })() // opt-in: render the drawer from the Atlas keyless projection instead of reading recents directly. Default OFF → byte-identical.
67
+ // The loader passes ?fullapp=1 when it frames the WHOLE app (not one room) — the app-site pane and the installed-app chrome
68
+ // read it (moved from space.js, verified-client split step 50).
69
+ export const FULLAPP = (() => { try { return new URLSearchParams(location.search).get('fullapp') === '1' } catch { return false } })()
70
+ // External APP handoff (whatsapp:// / mailto:) — a cross-origin iframe can't navigate to a custom scheme (iOS blocks it
71
+ // silently: the invite buttons looked dead), so when framed, hand the URL to the VAULT (top-level) to perform. The vault
72
+ // whitelists the schemes it will follow. Standalone: plain location.href, exactly as before.
73
+ export const extNav = (url) => { if (env.crossOrigin) { try { window.top.postMessage({ ch: 'vcHandoff', t: 'extnav', url }, VAULT_ORIGIN); return } catch { /* fall through */ } } location.href = url }
package/eraseFile.js ADDED
@@ -0,0 +1,58 @@
1
+ // eraseFile.js — FILE THIS ACCOUNT'S DELETE LIST WITH THE SENTINEL, for this app's tenant (docs/user-erasure.md E3).
2
+ // If the person leaves and the app's tenant deletes them, no device of theirs is there to read the account index. So the
3
+ // device keeps, sealed to the attested standing Sentinel and filed under THIS app's tenant only, what the account may
4
+ // delete: per room, the creator's delete secret(s) and the account's drops. A secret deletes only a room this account
5
+ // CREATED (the server checks its commitment) and only if nobody else used it (409 shared) — so listing every room the
6
+ // account knows is safe, and the device need not decide which it made. Tenant apps only; nothing leaves when unchanged.
7
+ import { delSecretFor } from './roomDelete.js'
8
+ import { loadUsageKey, loadOldUsageKeys, dropFor } from './usageReceipts.js'
9
+
10
+ export const FILED = 'space:erasefiled'
11
+ export const CT_BUDGET = 560_000 // the Lambda keeps 600 KB of a sealed field; base64 + GCM ≈ 1.34 × the JSON
12
+ const EVERY_MS = 6 * 3600_000 // refile an unchanged list at most this often (a new Sentinel boot keeps the store; this is belt and braces)
13
+ const ROOM = /^(?:sp|tmp)-[0-9a-z-]{1,48}$/
14
+
15
+ async function fingerprint (s) { const h = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s))); return Array.from(h.slice(0, 12), (b) => b.toString(16).padStart(2, '0')).join('') }
16
+
17
+ /** The record the Sentinel takes (erase.mjs grant). `rooms` newest first; trimmed to fit the sealed-field budget. */
18
+ export async function eraseRecordFor ({ account, tenant, rooms, keys, dropKeys = [] }) { // dropKeys: other keys this account leaves traces with (the SDK's usage receipts — sync sweep 11-08 #3)
19
+ const items = []
20
+ let size = 0
21
+ for (const room of [...new Set(rooms)].filter((r) => ROOM.test(r))) {
22
+ const secrets = [], drops = []
23
+ for (const k of keys) { secrets.push(await delSecretFor(k, room)); drops.push(await dropFor(k, room)) }
24
+ for (const k of dropKeys) { const d = await dropFor(k, room); if (!drops.includes(d)) drops.push(d) }
25
+ const it = { room, secrets: secrets.slice(0, 4), drops: drops.slice(0, 8) }
26
+ size += JSON.stringify(it).length + 1
27
+ if (size * 1.34 > CT_BUDGET) break
28
+ items.push(it)
29
+ }
30
+ return { account, tenant, items }
31
+ }
32
+
33
+ /**
34
+ * deps: { tenant, account, rooms: [room] (newest first), post, auth, attest, seal, ls, now, force }
35
+ * → { filed: bool, rooms, skipped? }
36
+ */
37
+ export async function fileEraseList ({ tenant, account, rooms, post, auth = {}, attest, seal, ls = globalThis.localStorage, now = Date.now(), force = false, keys = [loadUsageKey(), ...loadOldUsageKeys()].filter(Boolean), dropKeys = [], stillOurs = null }) {
38
+ if (!tenant || !account || !keys.length) return { filed: false, skipped: 'not a tenant app, not signed in, or no account key yet' }
39
+ const rec = await eraseRecordFor({ account, tenant, rooms, keys, dropKeys })
40
+ const fp = await fingerprint(JSON.stringify([tenant, account, rec.items.map((i) => [i.room, i.secrets, ...(dropKeys.length ? [i.drops] : [])])]))
41
+ let prev = null; try { prev = JSON.parse(ls.getItem(FILED) || 'null') } catch { /* */ }
42
+ if (!force && prev && prev.fp === fp && now - prev.at < EVERY_MS) return { filed: false, skipped: 'unchanged', rooms: rec.items.length }
43
+ if (!force && prev && prev.failAt && now - prev.failAt < EVERY_MS) return { filed: false, skipped: 'backing off after a failure' } // e.g. a Sentinel that does not know the op yet
44
+ // ⛔ A WITHDRAWN LIST STAYS WITHDRAWN (state machines pass 7, F#10): the account was deleted on another device, which withdrew
45
+ // the list (filed it empty); this device, never wiped, filed its full list again at its next change or refile. `stillOurs()`
46
+ // asks whether the account still stands (the SDK: its backup was not deleted) — asked only when something would be filed.
47
+ if (stillOurs && !(await Promise.resolve().then(stillOurs).catch(() => true))) return { filed: false, skipped: 'the account was deleted' }
48
+ try {
49
+ const { nonce, key } = await attest({ post, auth })
50
+ const r = await post({ op: 'sentinel', sentinel: { mode: 'erasegrant', sealed: await seal(key, nonce, rec) }, ...auth })
51
+ if (!r || r.error || r.ok === false) throw new Error('the Sentinel did not take the list (' + ((r && (r.error || r.reason)) || 'no answer') + ')')
52
+ } catch (e) {
53
+ try { ls.setItem(FILED, JSON.stringify({ ...(prev || {}), failAt: now })) } catch { /* */ }
54
+ throw e
55
+ }
56
+ try { ls.setItem(FILED, JSON.stringify({ fp, at: now })) } catch { /* */ }
57
+ return { filed: true, rooms: rec.items.length }
58
+ }
package/followImage.js ADDED
@@ -0,0 +1,86 @@
1
+ // followImage.js — AN ENCLAVE IMAGE THE APP DOES NOT PIN, ACCEPTED BY ITS RELEASE LOG (docs/release-trust-design.md § 6; the owner,
2
+ // 2026-11-23: "Do the plan as you recommend"). Until now a new cloud-device image needed its PCR0 in cloudDevicePins.js and an
3
+ // Official release BEFORE the switch. Now the app also accepts the newest FOLLOW_WINDOW images of that subject whose release records
4
+ // verify HERE: made by a build enclave this app trusts (its anchors + the whole chain, sentinelRelease.js), for THIS record, signed by
5
+ // the key its attestation names, the image rebuilt from its source. The log comes from Witbitz's server (then this app's own site) —
6
+ // a carrier only: it can withhold a record, never invent one. The window is a policy: an old image is not brought back. A bad image
7
+ // is stopped by IMAGE_DENY (compiled in, held equal to agent/followImage.mjs by a test). The KMS key policy that releases an image's
8
+ // secrets stays an explicit list, moved by hand — following never hands a new image the data by itself.
9
+ import { BUILD_ENCLAVE_PCR0, trustedBuilders, chainFromSite, recordPcrBy } from './sentinelRelease.js'
10
+ import { verifyAttestation } from './nitroVerify.js'
11
+
12
+ export const FOLLOW_WINDOW = 2 // the newest two that verify: a rollover's new image and the one it replaces
13
+ export const FOLLOWED_SUBJECTS = Object.freeze(['cloud-device', 'tools-enclave'])
14
+ export const IMAGE_DENY = Object.freeze({ 'cloud-device': Object.freeze([]), 'tools-enclave': Object.freeze([]) })
15
+ export const TRUST_BASE = 'https://api.witbitz.chat/v1/trust/'
16
+
17
+ /** The passing records of `subject` in a log's text (jsonl), newest first. */
18
+ export function recordsOfLogText (text, subject) {
19
+ const out = []
20
+ for (const l of String(text || '').split('\n')) { try { const r = JSON.parse(l); if (r && typeof r === 'object' && r.subject === subject && r.verdict === 'pass') out.push(r) } catch { /* not a record */ } }
21
+ return out.reverse()
22
+ }
23
+
24
+ const _logs = new Map()
25
+ /** One subject's passing records — the server first, this app's site second; once per page (nothing read: asked again next time). */
26
+ export function subjectLog (subject, { fetchFn = (typeof fetch === 'function' ? fetch : null) } = {}) {
27
+ if (!fetchFn || !FOLLOWED_SUBJECTS.includes(subject)) return Promise.resolve([])
28
+ if (typeof process !== 'undefined' && process.env && process.env.NODE_TEST_CONTEXT && fetchFn === globalThis.fetch) return Promise.resolve([]) // tests read no network
29
+ if (!_logs.has(subject)) {
30
+ _logs.set(subject, (async () => {
31
+ for (const u of [TRUST_BASE + subject + '.jsonl', '/audit/releases/' + subject + '.jsonl']) {
32
+ try {
33
+ const res = await fetchFn(u, { cache: 'no-store' })
34
+ if (!res || res.status !== 200 || /text\/html/.test((res.headers && res.headers.get && res.headers.get('content-type')) || '')) continue
35
+ const l = recordsOfLogText(await res.text(), subject)
36
+ if (l.length) return l
37
+ } catch { /* the next */ }
38
+ }
39
+ return []
40
+ })().then((l) => { if (!l.length) _logs.delete(subject); return l }))
41
+ }
42
+ return _logs.get(subject)
43
+ }
44
+
45
+ /** The newest `window` images of `subject` whose records verify here (never the denied): [{ pcr0, measurement }] — a tools-enclave
46
+ * image's measurement names the tool registers it was released with, so a PCR0 and a register are held to the SAME release. */
47
+ export async function followedImageRecords (subject, { window = FOLLOW_WINDOW, fetchFn, verify = verifyAttestation, builders = null, records = null } = {}) {
48
+ try {
49
+ const recs = records || await subjectLog(subject, fetchFn ? { fetchFn } : {})
50
+ if (!recs.length) return []
51
+ const trusted = builders || await trustedBuilders(await chainFromSite(fetchFn ? { fetchFn } : {}), { anchors: BUILD_ENCLAVE_PCR0, verify, max: Infinity })
52
+ const deny = IMAGE_DENY[subject] || []
53
+ const out = []
54
+ for (const r of recs) {
55
+ if (out.length >= window) break
56
+ try { const { pcr0 } = await recordPcrBy(r, subject, trusted, verify); if (!deny.includes(pcr0) && !out.some((x) => x.pcr0 === pcr0)) out.push({ pcr0, measurement: r.measurement || {} }) } catch { /* not this one */ }
57
+ }
58
+ return out
59
+ } catch { return [] }
60
+ }
61
+
62
+ /** The PCR0s of the newest `window` images of `subject` whose records verify here (never the denied). Never throws. */
63
+ export async function followedImages (subject, opts = {}) { return (await followedImageRecords(subject, opts)).map((x) => x.pcr0) }
64
+
65
+ /** An attestation check for a tools-enclave image + one tool register: the pins first; on "not this build", the followed images, each
66
+ * PCR0 paired with ITS register (never mixed). `check(pcr0List, registerList)` → the verified document (throws as verifyAttestation). */
67
+ export async function checkToolPaired (check, pins, register, { follow = followedImageRecords } = {}) {
68
+ try { return await check(pins.pcr0, pins.register) } catch (e) {
69
+ if (!follow || !/PCR\d+ mismatch/.test(String((e && e.message) || e))) throw e
70
+ const pairs = (await follow('tools-enclave')).map((m) => ({ p0: m.pcr0, reg: String((m.measurement && m.measurement['pcr' + register]) || '').toLowerCase() })).filter((x) => /^[0-9a-f]{96}$/.test(x.reg))
71
+ if (!pairs.length) throw e
72
+ let doc
73
+ try { doc = await check(pairs.map((x) => x.p0), pairs.map((x) => x.reg)) } catch { throw e } // neither: the pins' own reason
74
+ const g0 = String(doc.pcrs[0] || '').toLowerCase(), gR = String(doc.pcrs[register] || '').toLowerCase()
75
+ if (!pairs.some((x) => x.p0 === g0 && x.reg === gR)) throw new Error('attestation: the image and the tool register are from different releases')
76
+ return doc
77
+ }
78
+ }
79
+
80
+ /** The PCR0s an attestation of `subject` may name: this build's pins, then the followed images. */
81
+ export async function acceptedImages (subject, pins, opts = {}) {
82
+ const deny = IMAGE_DENY[subject] || []
83
+ const own = (pins || []).map((x) => String(x).toLowerCase()).filter((x) => !deny.includes(x))
84
+ const more = (await followedImages(subject, opts)).filter((x) => !own.includes(x))
85
+ return [...own, ...more]
86
+ }
package/healNames.js ADDED
@@ -0,0 +1,45 @@
1
+ // spaces/public/healNames.js — a Space listed as "Space" gets its own name back (spaces/test/healNames.test.mjs).
2
+ // The owner, 2026-10-10: "In my account I now have many space rooms" → one of them (sp-2t5k…, Arizona with Liat, 4
3
+ // messages from 1 August) is a real conversation whose ROOM still holds its name ("Interesting Places In Arizona", its
4
+ // title doc) while the account's list row says "Space". Rows reach a list without a name when another device pushes
5
+ // them in (the account-switch merge, 755a57ee) or adopts them from an index entry that carried none (roomSync: no title
6
+ // → 'Space'); nothing ever asked the room again, because a room's name is read only when it is OPENED (readSealedTitle).
7
+ //
8
+ // This asks each such room once per session, in the background (two at a time), the same way the open room is asked:
9
+ // its newest title entry, else its title doc. The name lands in the list (and, through the list, on every device);
10
+ // a name set by hand stays marked as one. Nothing is deleted, and a row someone renamed is never touched.
11
+
12
+ let _h = {
13
+ rows: () => [], // → this device's list (recents): [{ room, title, renamed }]
14
+ read: async () => null, // (room) → { entries, doc } — the room's log and its `title` state doc (either may be null)
15
+ apply: () => {}, // (room, title, manual) → write it to the list
16
+ latestTitle: () => null, // roomName.latestTitle
17
+ titleFromDoc: () => null, // roomName.titleFromDoc
18
+ }
19
+ export const setHealNamesHooks = (h) => { _h = { ..._h, ...h } }
20
+
21
+ const asked = new Set() // once per session per room
22
+ export const isUnnamed = (r) => !!r && !!r.room && !r.renamed && !String(r.room).startsWith('tmp-') && (!r.title || r.title === 'Space' || r.title === r.room)
23
+
24
+ /** → how many rows got their name back. */
25
+ export async function healNames(hooks = _h, visited = asked) {
26
+ const todo = (hooks.rows() || []).filter((r) => isUnnamed(r) && !visited.has(r.room))
27
+ let healed = 0, i = 0
28
+ const worker = async () => {
29
+ while (i < todo.length) {
30
+ const r = todo[i++]
31
+ visited.add(r.room)
32
+ let v = null
33
+ try { v = await hooks.read(r.room) } catch { v = null }
34
+ if (!v) continue
35
+ const t = hooks.latestTitle(v.entries || [])
36
+ const d = !t && v.doc ? hooks.titleFromDoc(v.doc) : null
37
+ const name = (t && t.title) || (d && d.title)
38
+ if (!name || name === 'Space') continue
39
+ try { if (hooks.apply(r.room, name, !!((t && t.manual) || (d && d.manual))) !== false) healed++ } catch { /* the row keeps its name */ }
40
+ }
41
+ }
42
+ await Promise.all([worker(), worker()])
43
+ return healed
44
+ }
45
+ export const _resetHealNames = () => asked.clear() // tests
package/idb.js ADDED
@@ -0,0 +1,97 @@
1
+ // spaces/public/idb.js — tiny IndexedDB key/value wrapper (single 'kv' store in the 'spaces' DB).
2
+ // Shared LEAF: the SW-visible mk mirror, the chat-ledger cache, and blob (image/PDF) caching all use it.
3
+ // Zero deps besides deviceSeal (through idbSeal.js) — only the indexedDB global otherwise.
4
+ //
5
+ // §PROTECT (docs/device-storage-protection.md, slice 3): the content caches (`chat:`, `wstate:`, `blob:`, `code:`) go
6
+ // through idbSeal.js — with device storage protection on they are sealed on write and opened on read; while the device is
7
+ // locked a protected key reads as absent and a write is dropped. Every other key, and every call while protection is off,
8
+ // is exactly what it was. `getRaw/setRaw/entriesRaw` bypass the layer for the migration itself.
9
+ import { wrapForStore, unwrapFromStore, migrateIdbProtection, unprotectIdb, idbNamingState, IDB_SHARED_NAMES } from './idbSeal.js'
10
+ import { seal, open as openSealed } from './deviceSeal.js'
11
+ import { isOpaqueName } from './sealedNames.js'
12
+
13
+ // §NAMES (docs/desktop-protection.md, phase 2): the naming state lives in idbSeal.js (set from the device key there and in the
14
+ // key worker); every get/set/del/entries below asks it.
15
+ const isNamed = (k) => { const n = idbNamingState(); return n.on && !IDB_SHARED_NAMES.includes(String(k)) && !isOpaqueName(String(k)) && !String(k).startsWith('nk:') } // nk: keeps its name: the worker writes it CLEAR (setRaw) only when previews are opted in, sealed under an opaque name otherwise
16
+ // ★ NO INDEXEDDB (the owner, 2026-10-12: an iPhone in Lockdown Mode — since iOS 17 it switches IndexedDB OFF, and an
17
+ // installed web app cannot be exempted): every write here was dropped and every read was empty, so the chat cache and
18
+ // Help's search copy held nothing ("0 messages from 0 of 152 Spaces") while the app itself worked from the network. With
19
+ // no IndexedDB the same store lives in this page's MEMORY for the session — kept as a copy (structuredClone), as
20
+ // IndexedDB keeps one — and is gone at the next launch, which is what Lockdown Mode asks for anyway.
21
+ export const idbMemory = { on: false }
22
+ export const idb = (() => {
23
+ let dbp, mem = null
24
+ const memory = () => { if (!mem) { mem = new Map(); idbMemory.on = true } return mem }
25
+ const copy = (v) => (v == null ? v : typeof structuredClone === 'function' ? structuredClone(v) : v)
26
+ const open = () => dbp || (dbp = new Promise((res, rej) => {
27
+ if (typeof indexedDB === 'undefined' || !indexedDB) { rej(Object.assign(new Error('no IndexedDB'), { noIdb: true })); return }
28
+ let r
29
+ try { r = indexedDB.open('spaces', 1) } catch (e) { rej(Object.assign(e instanceof Error ? e : new Error(String(e)), { noIdb: true })); return }
30
+ r.onupgradeneeded = () => r.result.createObjectStore('kv'); r.onsuccess = () => res(r.result); r.onerror = () => rej(Object.assign(r.error || new Error('open failed'), { noIdb: true }))
31
+ }))
32
+ // `fn` on IndexedDB, or `onMem(map)` when there is none (it never opened — a failed TRANSACTION stays a failure, as before)
33
+ const tx = (mode, fn, onMem) => open().then((db) => new Promise((res, rej) => { const t = db.transaction('kv', mode), rq = fn(t.objectStore('kv')); t.oncomplete = () => res(rq && rq.result); t.onerror = () => rej(t.error) }),
34
+ (e) => { if (e && e.noIdb && onMem) return onMem(memory()); throw e })
35
+ const inRange = (k, pfx) => !pfx || String(k).startsWith(pfx)
36
+ // §APP STORE (appStore.js; docs/hosted-app-design.md §6): in the hosted app every raw call below is the VAULT's — its store
37
+ // under this app's address — and this frame keeps no database of its own. Set by the page's loader before the app runs.
38
+ const vault = () => (typeof globalThis !== 'undefined' && typeof globalThis.__wbAppIdb === 'function' ? globalThis.__wbAppIdb : null)
39
+ const getRaw = (k) => (vault() ? vault()('get', k).then((v) => (v === undefined ? null : v)) : tx('readonly', (s) => s.get(k), (m) => copy(m.get(k)))).catch(() => null)
40
+ const setRaw = (k, v) => (vault() ? vault()('set', k, v) : tx('readwrite', (s) => s.put(v, k), (m) => { m.set(k, copy(v)) })).catch(() => {})
41
+ // ★★ A PREFIX READ LOADS ONLY THAT PREFIX (2026-10-06). Every key here is a string, so the keys under `pfx` are exactly the
42
+ // range [pfx, pfx + '\uffff'): IndexedDB answers it from the index without touching another prefix's VALUES. This used to be
43
+ // getAllKeys() + getAll() over the WHOLE store and a filter in JS — so the worker's `mk:` map at boot, its unseal/relock
44
+ // scans (three prefixes, on every unlock, i.e. on every load of a protected device) and the Code frame's session list each
45
+ // pulled every cached room's chat, widget state and attachment bytes into memory to keep a few hundred bytes of keys. On
46
+ // the owner's iPhone (204 rooms) that was the page's process being killed and restored moments after a Code open — the
47
+ // `back_forward` loads with no `leave` before them (docs/device-storage-protection.md § Memory).
48
+ const range = (pfx) => (pfx ? IDBKeyRange.bound(pfx, pfx + '\uffff', false, true) : undefined)
49
+ const entriesRaw = (pfx) => vault() ? vault()('entries', pfx || '').then((es) => (es || []).map(([k, v]) => [String(k), v])).catch(() => []) : open().then((db) => new Promise((res, rej) => {
50
+ const t = db.transaction('kv', 'readonly'), s = t.objectStore('kv'), ks = s.getAllKeys(range(pfx)), vs = s.getAll(range(pfx))
51
+ t.oncomplete = () => { const keys = ks.result || [], vals = vs.result || [], out = []; for (let i = 0; i < keys.length; i++) if (String(keys[i]).startsWith(pfx)) out.push([String(keys[i]), vals[i]]); res(out) }
52
+ t.onerror = () => rej(t.error)
53
+ }), (e) => { if (e && e.noIdb) return [...memory()].filter(([k]) => inRange(k, pfx)).map(([k, v]) => [String(k), copy(v)]); throw e }).catch(() => [])
54
+ // Keys only — a scan over a prefix that never loads the values (the protection migration walks the content ONE entry at a
55
+ // time with it: a getAll() of the values holds every cached room in memory at once, and that killed the page on an iPhone).
56
+ const keysRaw = (pfx) => (vault() ? vault()('keys', pfx || '') : tx('readonly', (s) => s.getAllKeys(range(pfx)), (m) => [...m.keys()])).then((ks) => (ks || []).map(String).filter((k) => k.startsWith(pfx))).catch(() => [])
57
+ const delRaw = (k) => (vault() ? vault()('del', k) : tx('readwrite', (s) => s.delete(k), (m) => { m.delete(k) })).catch(() => {})
58
+ const delPrefixRaw = (pfx) => (vault() ? vault()('delPrefix', pfx || '') : tx('readwrite', (s) => { const rq = s.getAllKeys(range(pfx)); rq.onsuccess = () => { for (const k of (rq.result || [])) if (String(k).startsWith(pfx)) s.delete(k) } },
59
+ (m) => { for (const k of [...m.keys()]) if (String(k).startsWith(pfx)) m.delete(k) })).catch(() => {})
60
+ // §NAMES: the real names behind every opaque key (keys only — no value is read), [opaque, real] pairs.
61
+ const nameIndex = async () => { const nm = idbNamingState().namer; if (!nm) return []; const out = []; for (const o of await keysRaw('p:')) { const n = await nm.real(o); if (n != null) out.push([o, n]) } return out }
62
+ // a value not yet moved under its opaque name (an unlock's migration runs in the background) still answers from its real name
63
+ const legacyGet = (k) => getRaw(k).then((v) => (v == null ? v : unwrapFromStore(k, v)))
64
+ // ⛔ A READ THAT FAILED IS NOT AN ABSENT VALUE (10·Q#2, pass 10): getRaw's catch answers null on a failed transaction (the iPhone's
65
+ // WebKit does fail one), and a caller that then WRITES a fresh value (the device key) destroys the one kept. getStrict throws
66
+ // instead; no database at all still answers from memory, as before.
67
+ const getRawStrict = (k) => (vault() ? vault()('get', k).then((v) => (v === undefined ? null : v)) : tx('readonly', (s) => s.get(k), (m) => copy(m.get(k))))
68
+ const self = {
69
+ get: (k) => (!isNamed(k) ? legacyGet(k) : !idbNamingState().namer ? Promise.resolve(null)
70
+ : (async () => { const v = await getRaw(await idbNamingState().namer.opaque(k)); return v != null ? openSealed(idbNamingState().key, v) : legacyGet(k) })()).catch(() => null),
71
+ set: (k, v) => (!isNamed(k) ? wrapForStore(k, v).then((stored) => (stored === undefined ? undefined : setRaw(k, stored)))
72
+ : !idbNamingState().namer ? Promise.resolve(undefined) // locked or memory-only: dropped, never a write under a real name
73
+ : (async () => { const nm = idbNamingState().namer, key = idbNamingState().key; const o = await nm.opaque(k); const stored = await seal(key, v); await setRaw(o, stored); await delRaw(k) })()).catch(() => {}),
74
+ del: (k) => (!isNamed(k) || !idbNamingState().namer ? delRaw(k) : idbNamingState().namer.opaque(k).then((o) => Promise.all([delRaw(o), delRaw(k)]))).catch(() => {}),
75
+ delPrefix: (pfx) => (!idbNamingState().on || !idbNamingState().namer ? delPrefixRaw(pfx)
76
+ : nameIndex().then((ix) => Promise.all([...ix.filter(([, n]) => n.startsWith(pfx)).map(([o]) => delRaw(o)), delPrefixRaw(pfx)]))).catch(() => {}),
77
+ // All [key, value] pairs whose key starts with pfx. Used by the L1 worker to load its room→mk map.
78
+ entries: (pfx) => (async () => {
79
+ const legacy = await entriesRaw(pfx).then((es) => Promise.all(es.map(async ([k, v]) => [k, await unwrapFromStore(k, v)])))
80
+ if (!idbNamingState().on || pfx.startsWith('nk:') || IDB_SHARED_NAMES.some((n) => n.startsWith(pfx) || pfx.startsWith(n))) return legacy
81
+ if (!idbNamingState().namer) return [] // locked: nothing readable
82
+ const key = idbNamingState().key, seen = new Set(), out = []
83
+ for (const [o, n] of await nameIndex()) { if (!n.startsWith(pfx)) continue; const v = await getRaw(o); if (v == null) continue; try { out.push([n, await openSealed(key, v)]); seen.add(n) } catch { /* another key's leftover */ } }
84
+ for (const [k, v] of legacy) if (!seen.has(k)) out.push([k, v])
85
+ return out
86
+ })().catch(() => []),
87
+ // §NAMES: the real names under a prefix, values never read (the protection migration and listings).
88
+ names: (pfx) => (idbNamingState().on && idbNamingState().namer ? nameIndex().then(async (ix) => [...ix.map(([, n]) => n).filter((n) => n.startsWith(pfx)), ...await keysRaw(pfx)]) : keysRaw(pfx)).catch(() => []),
89
+ getRaw, setRaw, delRaw, entriesRaw, keysRaw, nameIndex,
90
+ /** A read that THROWS when it failed (never null for an error) — for a value that must not be replaced on a failed read. */
91
+ getStrict: (k) => (!isNamed(k) ? getRawStrict(k).then((v) => (v == null ? v : unwrapFromStore(k, v))) : self.get(k)),
92
+ // §PROTECT: switch on / unlock (seal the clear content in place) and switch off (write it back) — the lock hooks call these.
93
+ protect: (rawKey) => migrateIdbProtection(self, rawKey),
94
+ unprotect: (rawKey) => unprotectIdb(self, rawKey),
95
+ }
96
+ return self
97
+ })()