@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/csAttest.js ADDED
@@ -0,0 +1,112 @@
1
+ // csAttest.js — verify a GCP Confidential Space attestation JWT, isomorphic (browser + Node), zero-dep (WebCrypto).
2
+ //
3
+ // The BROWSER CLIENT uses this to verify the OHTTP RELAY before sending any oblivious request — so "the code that
4
+ // sees your IP is measured, and it doesn't log it" is a property you CHECK, not a promise. A Confidential Space token
5
+ // is a Google-signed JWT: Intel-TDX-rooted, secure-boot, debug-off, the running image digest bound to a published
6
+ // release, and (when requested) a client nonce echoed for liveness / connection binding.
7
+ //
8
+ // This is the deliberate browser TWIN of agent/gatewayAttest.mjs (which verifies TrustedRouter's gateway the same
9
+ // way). They are kept as two files because they deploy to two domains that share NO source: agent/ ships in the
10
+ // Lambda + enclave bundles (which copy only agent/), spaces/public/ ships to Cloudflare Pages. Same check, tested on
11
+ // both sides — merging them would break one bundle's module resolution (the controlplane-closure class of bug).
12
+ const subtle = (globalThis.crypto && globalThis.crypto.subtle)
13
+ const RS256 = { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }
14
+ const _dec = new TextDecoder()
15
+ function b64uToBytes(s) {
16
+ s = String(s).replace(/-/g, '+').replace(/_/g, '/'); while (s.length % 4) s += '='
17
+ if (typeof atob === 'function') { const bin = atob(s); const u = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i); return u }
18
+ return new Uint8Array(Buffer.from(s, 'base64')) // Node fallback
19
+ }
20
+
21
+ let _jwks = null // { at, url, keys: Map(kid→CryptoKey) }
22
+ async function jwksKey(kid, jwksUrl, fetchImpl, now) {
23
+ if (!_jwks || _jwks.url !== jwksUrl || now - _jwks.at > 3600_000 || !_jwks.keys.has(kid)) {
24
+ const r = await fetchImpl(jwksUrl)
25
+ if (!r || !r.ok) throw new Error('jwks_fetch_failed')
26
+ const body = await r.json()
27
+ const keys = new Map()
28
+ for (const k of body.keys || []) {
29
+ if (!k || !k.kid || k.kty !== 'RSA') continue
30
+ try { keys.set(k.kid, await subtle.importKey('jwk', { kty: k.kty, n: k.n, e: k.e }, RS256, false, ['verify'])) } catch { /* skip */ }
31
+ }
32
+ _jwks = { at: now, url: jwksUrl, keys }
33
+ }
34
+ return _jwks.keys.get(kid) || null
35
+ }
36
+ export function _resetCsCache() { _jwks = null; _pinned = null }
37
+
38
+ // PINNED JWKS: pass opts.jwks (a { keys:[…] } object baked into the client at deploy) to verify WITHOUT ever fetching
39
+ // Google — so the party being protected never reveals its IP to googleapis.com just to check a signature. The keys are
40
+ // Google's PUBLIC signing keys, so baking them leaks nothing; they rotate, so re-bake on deploy (a kid miss ⇒ verify
41
+ // fails closed rather than silently fetching). Same "pin the root, don't fetch it" discipline as the Nitro path.
42
+ let _pinned = null // { src, keys: Map(kid→CryptoKey) }
43
+ async function pinnedKey(kid, jwks) {
44
+ if (!_pinned || _pinned.src !== jwks) {
45
+ const keys = new Map()
46
+ for (const k of (jwks && jwks.keys) || []) {
47
+ if (!k || !k.kid || k.kty !== 'RSA') continue
48
+ try { keys.set(k.kid, await subtle.importKey('jwk', { kty: k.kty, n: k.n, e: k.e }, RS256, false, ['verify'])) } catch { /* skip */ }
49
+ }
50
+ _pinned = { src: jwks, keys }
51
+ }
52
+ return _pinned.keys.get(kid) || null
53
+ }
54
+
55
+ export const CS_DEFAULTS = {
56
+ iss: 'https://confidentialcomputing.googleapis.com',
57
+ jwksUrl: 'https://www.googleapis.com/service_accounts/v1/metadata/jwk/signer@confidentialspace-sign.iam.gserviceaccount.com',
58
+ hwmodel: 'GCP_INTEL_TDX',
59
+ swname: 'CONFIDENTIAL_SPACE',
60
+ }
61
+
62
+ /**
63
+ * Verify a Confidential Space JWT string against expected identity.
64
+ * @param token the raw JWT
65
+ * @param expect { aud, subProject, digests?, nonce? } — aud + operator project are REQUIRED; digests pins the image,
66
+ * nonce (if given) must appear in eat_nonce (liveness / connection binding).
67
+ * Returns { ok:true, imageDigest, imageReference, sub, exp } | { ok:false, error }. Never throws.
68
+ */
69
+ export async function verifyCsToken(token, expect = {}, { fetchImpl = (typeof fetch !== 'undefined' ? fetch : null), now = Date.now(), ...cfg } = {}) {
70
+ const c = { ...CS_DEFAULTS, ...cfg }
71
+ try {
72
+ if (!subtle) return { ok: false, error: 'no_webcrypto' }
73
+ const [h64, p64, s64] = String(token).trim().split('.')
74
+ if (!h64 || !p64 || !s64) return { ok: false, error: 'not_jwt' }
75
+ const header = JSON.parse(_dec.decode(b64uToBytes(h64)))
76
+ if (header.alg !== 'RS256' || !header.kid) return { ok: false, error: 'bad_header' }
77
+ // Pinned keys (opts.jwks) verify offline — NO googleapis.com fetch; else fall back to the live JWKS.
78
+ const key = c.jwks ? await pinnedKey(header.kid, c.jwks) : await jwksKey(header.kid, c.jwksUrl, fetchImpl, now)
79
+ if (!key) return { ok: false, error: c.jwks ? 'unknown_kid_pinned' : 'unknown_kid' }
80
+ const okSig = await subtle.verify(RS256, key, b64uToBytes(s64), new TextEncoder().encode(h64 + '.' + p64))
81
+ if (!okSig) return { ok: false, error: 'bad_signature' }
82
+ const p = JSON.parse(_dec.decode(b64uToBytes(p64)))
83
+ const sec = Math.floor(now / 1000)
84
+ if (!(p.iat <= sec + 60 && p.exp >= sec - 60)) return { ok: false, error: 'stale' }
85
+ if (p.iss !== c.iss) return { ok: false, error: 'wrong_iss' }
86
+ if (expect.aud && p.aud !== expect.aud) return { ok: false, error: 'wrong_aud' }
87
+ if (expect.subProject && !String(p.sub || '').includes('/projects/' + expect.subProject + '/')) return { ok: false, error: 'wrong_operator' }
88
+ if (p.hwmodel !== c.hwmodel || p.swname !== c.swname) return { ok: false, error: 'wrong_platform' }
89
+ if (p.secboot !== true) return { ok: false, error: 'no_secboot' }
90
+ if (p.dbgstat !== 'disabled-since-boot') return { ok: false, error: 'debug_enabled' }
91
+ if (expect.nonce) { // liveness / connection binding — the client's fresh nonce must be echoed
92
+ const nonces = Array.isArray(p.eat_nonce) ? p.eat_nonce : (p.eat_nonce ? [p.eat_nonce] : [])
93
+ if (!nonces.includes(expect.nonce)) return { ok: false, error: 'nonce_absent' }
94
+ }
95
+ const cont = (p.submods && p.submods.container) || {}
96
+ const digest = String(cont.image_digest || '')
97
+ if (!/^sha256:[0-9a-f]{64}$/.test(digest)) return { ok: false, error: 'no_image_digest' }
98
+ const pins = Array.isArray(expect.digests) ? expect.digests : []
99
+ if (pins.length && !pins.includes(digest)) return { ok: false, error: 'unpinned_image', imageDigest: digest }
100
+ return { ok: true, imageDigest: digest, imageReference: String(cont.image_reference || ''), sub: String(p.sub || ''), exp: p.exp }
101
+ } catch (e) { return { ok: false, error: 'verify_' + String((e && e.message) || e).slice(0, 80) } }
102
+ }
103
+
104
+ /** Fetch the attestation from a URL, then verify. `attestUrl` may append the nonce as CS requires. */
105
+ export async function fetchAndVerifyCs(attestUrl, expect = {}, opts = {}) {
106
+ const fetchImpl = opts.fetchImpl || (typeof fetch !== 'undefined' ? fetch : null)
107
+ try {
108
+ const r = await fetchImpl(attestUrl)
109
+ if (!r || !r.ok) return { ok: false, error: 'fetch_' + (r && r.status) }
110
+ return verifyCsToken((await r.text()).trim(), expect, opts)
111
+ } catch (e) { return { ok: false, error: 'fetch_' + String((e && e.message) || e).slice(0, 80) } }
112
+ }
package/decrypt.html ADDED
@@ -0,0 +1,384 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
6
+ <title>Witbitz — Offline Space Decryptor</title>
7
+ <style>
8
+ :root {
9
+ --bg:#f7f7f5; --card:#ffffff; --fg:#1a1a1f; --muted:#6b6b73; --line:#e5e5e0;
10
+ --accent:#2f7d5b; --accent-weak:#e7f2ec; --field:#f0f0ec; --warn:#8a5a00; --warn-bg:#fdf3df; --agent:#2f5d7d;
11
+ }
12
+ @media (prefers-color-scheme: dark) {
13
+ :root { --bg:#161618; --card:#1f1f22; --fg:#ececef; --muted:#9a9aa2; --line:#2e2e33; --accent:#4bbd86;
14
+ --accent-weak:#17301f; --field:#2a2a2e; --warn:#e0b054; --warn-bg:#2c2410; --agent:#7db4dc; }
15
+ }
16
+ :root[data-theme="dark"] { --bg:#161618; --card:#1f1f22; --fg:#ececef; --muted:#9a9aa2; --line:#2e2e33; --accent:#4bbd86; --accent-weak:#17301f; --field:#2a2a2e; --warn:#e0b054; --warn-bg:#2c2410; --agent:#7db4dc; }
17
+ :root[data-theme="light"] { --bg:#f7f7f5; --card:#ffffff; --fg:#1a1a1f; --muted:#6b6b73; --line:#e5e5e0; --accent:#2f7d5b; --accent-weak:#e7f2ec; --field:#f0f0ec; --warn:#8a5a00; --warn-bg:#fdf3df; --agent:#2f5d7d; }
18
+ * { box-sizing:border-box; }
19
+ body { margin:0; background:var(--bg); color:var(--fg); font:15px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
20
+ padding:max(20px,env(safe-area-inset-top)) 16px calc(40px + env(safe-area-inset-bottom)); }
21
+ .wrap { max-width:760px; margin:0 auto; }
22
+ .back { display:inline-flex; align-items:center; gap:5px; margin-bottom:16px; padding:7px 12px 7px 9px; border-radius:999px;
23
+ border:1px solid var(--line); background:var(--card); color:var(--fg); text-decoration:none; font-size:13.5px; font-weight:600; cursor:pointer; }
24
+ .back:hover { border-color:var(--accent); color:var(--accent); }
25
+ .back svg { width:16px; height:16px; }
26
+ header { display:flex; align-items:center; gap:12px; margin-bottom:6px; }
27
+ .lock { width:38px; height:38px; flex:0 0 auto; border-radius:10px; background:var(--accent-weak); color:var(--accent); display:flex; align-items:center; justify-content:center; }
28
+ .lock svg { width:20px; height:20px; }
29
+ h1 { font-size:19px; margin:0; font-weight:700; letter-spacing:-.01em; }
30
+ .sub { color:var(--muted); font-size:13px; margin:2px 0 0; }
31
+ .offline-badge { display:inline-flex; align-items:center; gap:6px; margin:14px 0 22px; padding:7px 12px; border-radius:999px; background:var(--accent-weak); color:var(--accent); font-size:12.5px; font-weight:600; }
32
+ .card { background:var(--card); border:1px solid var(--line); border-radius:14px; padding:16px; margin-bottom:14px; }
33
+ .step-h { display:flex; align-items:baseline; gap:9px; font-weight:650; margin:0 0 4px; }
34
+ .step-n { flex:0 0 auto; width:22px; height:22px; border-radius:50%; background:var(--field); color:var(--muted); font-size:12px; font-weight:700; display:inline-flex; align-items:center; justify-content:center; }
35
+ .hint { color:var(--muted); font-size:12.5px; margin:2px 0 12px 31px; }
36
+ textarea, input[type=text], select { width:100%; font:13px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; background:var(--field); color:var(--fg); border:1px solid var(--line); border-radius:9px; padding:10px 12px; }
37
+ textarea { min-height:64px; resize:vertical; }
38
+ select { font-family:inherit; }
39
+ .indent { margin-left:31px; }
40
+ label.filebtn { display:inline-flex; align-items:center; gap:8px; padding:9px 14px; border-radius:9px; border:1px dashed var(--line); background:var(--field); color:var(--fg); font-size:13.5px; font-weight:550; cursor:pointer; }
41
+ label.filebtn:hover { border-color:var(--accent); color:var(--accent); }
42
+ label.filebtn input { display:none; }
43
+ .fname { margin-left:31px; margin-top:8px; font-size:12.5px; color:var(--accent); font-weight:600; min-height:1em; }
44
+ .drop { margin-left:31px; margin-top:8px; border:1.5px dashed var(--line); border-radius:10px; padding:14px; text-align:center; color:var(--muted); font-size:12.5px; transition:.15s; }
45
+ .drop.over { border-color:var(--accent); background:var(--accent-weak); color:var(--accent); }
46
+ button.primary { display:block; width:100%; margin:4px 0 0; padding:14px; border:0; border-radius:11px; background:var(--accent); color:#fff; font-size:15.5px; font-weight:650; cursor:pointer; }
47
+ button.primary:disabled { opacity:.5; cursor:default; }
48
+ button.ghost { padding:9px 14px; border:1px solid var(--line); border-radius:9px; background:transparent; color:var(--fg); font-size:13.5px; font-weight:600; cursor:pointer; }
49
+ .warn { display:flex; gap:9px; background:var(--warn-bg); color:var(--warn); border-radius:10px; padding:10px 12px; font-size:12.5px; margin-top:12px; }
50
+ .warn svg { width:16px; height:16px; flex:0 0 auto; margin-top:1px; }
51
+ .status { margin:6px 0 0; text-align:center; font-size:13px; color:var(--muted); min-height:1.2em; }
52
+ .status.err { color:#c0392b; font-weight:600; }
53
+ @media (prefers-color-scheme: dark) { .status.err { color:#ff6b5b; } }
54
+ #out { margin-top:8px; }
55
+ .tx-head { display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap; margin-bottom:12px; }
56
+ .tx-title { font-weight:700; font-size:16px; }
57
+ .tx-meta { color:var(--muted); font-size:12.5px; }
58
+ .tx-actions { display:flex; gap:8px; }
59
+ .msg { padding:10px 0; border-top:1px solid var(--line); }
60
+ .msg:first-child { border-top:0; }
61
+ .msg .who { font-weight:650; }
62
+ .msg.agent .who { color:var(--agent); }
63
+ .msg .ts { color:var(--muted); font-size:11.5px; font-weight:400; margin-left:8px; }
64
+ .msg .body { margin-top:3px; white-space:pre-wrap; word-wrap:break-word; }
65
+ .msg img { max-width:100%; border-radius:10px; margin-top:8px; display:block; }
66
+ .chip { display:inline-block; margin:6px 6px 0 0; padding:3px 9px; border-radius:7px; background:var(--field); color:var(--muted); font-size:12px; }
67
+ .hidden { display:none; }
68
+ footer { color:var(--muted); font-size:12px; margin-top:26px; line-height:1.6; }
69
+ footer code { background:var(--field); padding:1px 5px; border-radius:4px; font-size:11.5px; }
70
+ a { color:var(--accent); }
71
+ </style>
72
+ </head>
73
+ <body>
74
+ <div class="wrap">
75
+ <button class="back hidden" id="backBtn" aria-label="Back to your Space">
76
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 18l-6-6 6-6"/></svg>
77
+ Back to your Space
78
+ </button>
79
+ <header>
80
+ <span class="lock" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="10" width="16" height="10" rx="2"></rect><path d="M8 10V7a4 4 0 0 1 8 0v3"></path></svg></span>
81
+ <div>
82
+ <h1>Offline Space Decryptor</h1>
83
+ <p class="sub">Read a Witbitz Space backup with your key — entirely on this device.</p>
84
+ </div>
85
+ </header>
86
+
87
+ <span class="offline-badge">
88
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><path d="M5 13l4 4L19 7"></path></svg>
89
+ <span><b>No network.</b> Nothing you load here is ever uploaded — view source to verify.</span>
90
+ </span>
91
+
92
+ <div id="noCrypto" class="warn hidden">
93
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 9v4M12 17h.01M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0Z"/></svg>
94
+ <span>This browser blocked local cryptography for a file opened directly. Open this file in <b>Firefox</b> or <b>Safari</b>, or open it from <code>witbitz-spaces.pages.dev/decrypt.html</code> (that page is egress-locked, so it still can’t send your data anywhere).</span>
95
+ </div>
96
+
97
+ <!-- STEP 1 — key(s) -->
98
+ <div class="card">
99
+ <div class="step-h"><span class="step-n">1</span> Your room key</div>
100
+ <p class="hint">Paste a key, or load a key file. A whole-account <code>witbitz-keys…txt</code> works too — it holds every key, and the right one is matched automatically.</p>
101
+ <div class="indent"><textarea id="mk" spellcheck="false" placeholder="paste the room key (mk) here…" rows="2"></textarea></div>
102
+ <div class="indent" style="margin-top:8px"><label class="filebtn">📄 Load key file<input type="file" id="mkFile" accept=".txt,text/plain"></label></div>
103
+ <div class="fname" id="mkFileName"></div>
104
+ </div>
105
+
106
+ <!-- STEP 2 — sealed ledger / bundle -->
107
+ <div class="card">
108
+ <div class="step-h"><span class="step-n">2</span> Your sealed conversation</div>
109
+ <p class="hint">Load a <code>…-ledger.json</code>, or a whole-account <code>witbitz-spaces…json</code> backup (it holds only ciphertext).</p>
110
+ <div class="indent"><label class="filebtn">🔒 Load sealed backup<input type="file" id="ledFile" accept=".json,application/json"></label></div>
111
+ <div class="drop" id="drop">…or drag the sealed file here</div>
112
+ <div class="fname" id="ledName"></div>
113
+ <div class="indent hidden" id="spaceRow" style="margin-top:10px">
114
+ <label style="font-size:12.5px;color:var(--muted);font-weight:600;display:block;margin-bottom:5px">Which conversation</label>
115
+ <select id="spacePicker"></select>
116
+ </div>
117
+ </div>
118
+
119
+ <button class="primary" id="go" disabled>Decrypt &amp; read</button>
120
+ <div class="status" id="status"></div>
121
+
122
+ <div id="out" class="hidden">
123
+ <div class="card">
124
+ <div class="tx-head">
125
+ <div><div class="tx-title" id="txTitle">Conversation</div><div class="tx-meta" id="txMeta"></div></div>
126
+ <div class="tx-actions">
127
+ <button class="ghost" id="saveTxt">Save .txt</button>
128
+ <button class="ghost" id="saveHtml">Save .html</button>
129
+ </div>
130
+ </div>
131
+ <div id="transcript"></div>
132
+ </div>
133
+ </div>
134
+
135
+ <div class="warn" style="margin-top:14px">
136
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 9v4M12 17h.01M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0Z"/></svg>
137
+ <span>Keep your <b>keys</b> and your <b>sealed backup</b> in separate places. Anyone who has both can read the chats; the sealed files alone are unreadable without the keys.</span>
138
+ </div>
139
+
140
+ <div style="margin-top:16px;text-align:center">
141
+ <button class="ghost" id="saveSelf">⤓ Save this decryptor for offline use</button>
142
+ </div>
143
+
144
+ <footer>
145
+ <p><b>How this works.</b> Witbitz stores your conversations as ciphertext it cannot read. Your keys live in your Space links and on your device. On the Confidential tier they reach our servers only sealed to a verified enclave; on the standard tier they are sent with each agent turn, so the stored record is unreadable from the store but the turn itself is handled in the clear. This page rebuilds the exact decryption the app uses (HKDF-SHA-256 → AES-256-GCM) with your browser’s built-in cryptography, with no network access. Save this file, your keys, and your sealed backup, and you can read your data forever — even if Witbitz is gone.</p>
146
+ </footer>
147
+ </div>
148
+
149
+ <script>
150
+ (function () {
151
+ 'use strict'
152
+ const enc = new TextEncoder(), dec = new TextDecoder()
153
+ const $ = (id) => document.getElementById(id)
154
+ const subtle = window.crypto && window.crypto.subtle
155
+ if (!subtle) $('noCrypto').classList.remove('hidden')
156
+
157
+ // BACK — a standalone PWA has no browser chrome, so a navigation here would strand the reader. Hidden for a local
158
+ // file:// copy (the tool IS the destination — nowhere in the app to return to).
159
+ if (location.protocol !== 'file:') {
160
+ const back = $('backBtn'); back.classList.remove('hidden')
161
+ back.addEventListener('click', () => { if (history.length > 1) history.back(); else location.assign('/space') })
162
+ }
163
+
164
+ // ── crypto: a faithful inline port of spaces/public/e2ee.js open() (the mk / symmetric-envelope path) ──
165
+ function ub64(str) {
166
+ let s = String(str || '').replace(/-/g, '+').replace(/_/g, '/'); s += '='.repeat((4 - (s.length % 4)) % 4)
167
+ const bin = atob(s), out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out
168
+ }
169
+ async function roomWrapKey(mk) {
170
+ const ikm = await subtle.importKey('raw', ub64(mk), 'HKDF', false, ['deriveKey'])
171
+ return subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: enc.encode('memwrap') }, ikm, { name: 'AES-GCM', length: 256 }, false, ['decrypt'])
172
+ }
173
+ function isEnvelope(o) {
174
+ return !!(o && typeof o === 'object' && o.v === 1 && typeof o.iv === 'string' && typeof o.ct === 'string' &&
175
+ o.recipients && typeof o.recipients === 'object' && Object.values(o.recipients).some((r) => r && typeof r.iv === 'string' && typeof r.w === 'string'))
176
+ }
177
+ async function openEnv(env, wk, aad) {
178
+ if (!isEnvelope(env)) return null
179
+ if (env.aad && !aad) return null // a BOUND ledger box (aad:1) opens only with its {room, index} — as e2ee.js open()
180
+ for (const slot of Object.keys(env.recipients)) {
181
+ const r = env.recipients[slot]; if (!r || typeof r.iv !== 'string' || typeof r.w !== 'string') continue
182
+ try {
183
+ const cek = new Uint8Array(await subtle.decrypt({ name: 'AES-GCM', iv: ub64(r.iv) }, wk, ub64(r.w)))
184
+ const cekKey = await subtle.importKey('raw', cek, { name: 'AES-GCM' }, false, ['decrypt'])
185
+ const p = { name: 'AES-GCM', iv: ub64(env.iv) }; if (env.aad) p.additionalData = aad
186
+ return dec.decode(new Uint8Array(await subtle.decrypt(p, cekKey, ub64(env.ct))))
187
+ } catch (e) { /* wrong slot → next, else fail closed */ }
188
+ }
189
+ return null
190
+ }
191
+ // M4 (since 2026-08-29): a v3 box is BOUND to its Space and its absolute position — AES-GCM additional data
192
+ // 'v3<US><room><US><index>', byte-identical to e2ee.js ledgerAad. Without it every bound box fails, so the reader needs the
193
+ // Space's id: from the ledger file (`room`), the bundle's sealed name card, the keys file's rows, or a pasted Space link.
194
+ const ledgerAad = (room, index) => enc.encode('v3\x1f' + String(room) + '\x1f' + String(index))
195
+ // v1 = bare array whole-sealed; v2 = {v,entries} whole-sealed; v3 = { v:3, boxes:[<per-entry sealed string>], from }.
196
+ async function decryptLedger(ledger, mk, rooms, otherKeys = []) {
197
+ const wk = await roomWrapKey(mk)
198
+ if (ledger && Array.isArray(ledger.boxes)) {
199
+ const entries = []; let opened = 0, bound = 0, room = null
200
+ const base = Number(ledger.from) || 0, cands = [...new Set([ledger.room, ...(rooms || [])].filter(Boolean).map(String))]
201
+ const usable = [wk], previous = new Set(otherKeys.filter(k => k !== mk))
202
+ if (ledger.keyHistory) {
203
+ const raw = await openEnv(ledger.keyHistory, wk)
204
+ if (raw) {
205
+ const history = JSON.parse(raw)
206
+ if (typeof history.room === 'string' && (!cands.length || cands.includes(history.room)) && Array.isArray(history.keys)) {
207
+ if (!cands.includes(history.room)) cands.push(history.room)
208
+ for (const key of history.keys) if (typeof key === 'string' && key !== mk) previous.add(key)
209
+ }
210
+ }
211
+ }
212
+ for (const key of previous) { try { usable.push(await roomWrapKey(key)) } catch { /* malformed key */ } }
213
+ for (let j = 0; j < ledger.boxes.length; j++) {
214
+ let env; try { env = typeof ledger.boxes[j] === 'string' ? JSON.parse(ledger.boxes[j]) : ledger.boxes[j] } catch (e) { continue }
215
+ let s = null
216
+ if (env && env.aad) {
217
+ bound++
218
+ for (const r of (room ? [room] : cands)) {
219
+ for (const key of usable) { s = await openEnv(env, key, ledgerAad(r, base + j)); if (s != null) break }
220
+ if (s != null) { room = r; break }
221
+ }
222
+ } else for (const key of usable) { s = await openEnv(env, key); if (s != null) break }
223
+ if (s == null) continue; opened++; try { entries.push(JSON.parse(s)) } catch (e) {}
224
+ }
225
+ return { entries, opened, total: ledger.boxes.length, v3: true, needsRoom: bound > 0 && !room && !cands.length }
226
+ }
227
+ const s = await openEnv(ledger, wk); if (s == null) return { entries: null, v3: false }
228
+ let p; try { p = JSON.parse(s) } catch (e) { return { entries: null, v3: false } }
229
+ return { entries: Array.isArray(p) ? p : (p && Array.isArray(p.entries) ? p.entries : null), v3: false }
230
+ }
231
+
232
+ // ── render ──
233
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]))
234
+ const fmtTs = (ts) => { const n = Number(ts); if (!Number.isFinite(n) || n <= 0) return ''; try { return new Date(n).toLocaleString() } catch (e) { return '' } }
235
+ let lastEntries = null, lastTitle = 'Conversation'
236
+ const looksLikeAgent = (e) => { const n = String((e && e.name) || '').toLowerCase(); return e && (e.agent === true || n === 'assistant' || n === 'agent') }
237
+
238
+ function render(entries, title) {
239
+ lastEntries = entries; lastTitle = title || 'Conversation'
240
+ $('txTitle').textContent = lastTitle
241
+ const times = entries.map((e) => Number(e && e.ts)).filter((n) => Number.isFinite(n) && n > 0)
242
+ const range = times.length ? `${new Date(Math.min(...times)).toLocaleDateString()} – ${new Date(Math.max(...times)).toLocaleDateString()}` : ''
243
+ $('txMeta').textContent = `${entries.length} message${entries.length === 1 ? '' : 's'}${range ? ' · ' + range : ''}`
244
+ const t = $('transcript'); t.innerHTML = ''
245
+ for (const e of entries) {
246
+ if (!e || typeof e !== 'object') continue
247
+ const row = document.createElement('div'); row.className = 'msg' + (looksLikeAgent(e) ? ' agent' : '')
248
+ let html = `<div><span class="who">${esc(e.name || 'Unknown')}</span><span class="ts">${esc(fmtTs(e.ts))}</span></div>`
249
+ if (e.text) html += `<div class="body">${esc(e.text)}</div>`
250
+ row.innerHTML = html
251
+ for (const im of (Array.isArray(e.images) ? e.images : [])) { if (im && im.b64 && im.mime) { const img = document.createElement('img'); img.src = `data:${im.mime};base64,${im.b64}`; img.alt = im.name || 'image'; row.appendChild(img) } }
252
+ for (const f of (Array.isArray(e.files) ? e.files : [])) { const c = document.createElement('span'); c.className = 'chip'; c.textContent = '📎 ' + ((f && f.name) || 'file'); row.appendChild(c) }
253
+ for (const w of (Array.isArray(e.widgets) ? e.widgets : [])) { const c = document.createElement('span'); c.className = 'chip'; c.textContent = '▦ ' + ((w && (w.title || w.kind)) || 'widget'); row.appendChild(c) }
254
+ t.appendChild(row)
255
+ }
256
+ $('out').classList.remove('hidden'); $('out').scrollIntoView({ behavior: 'smooth', block: 'start' })
257
+ }
258
+
259
+ // ── inputs ──
260
+ let ledgerText = '', keyFileText = '', bundle = null, bundleTitles = [], singleLedger = null, singleTitle = 'Conversation'
261
+ // Extract candidate keys from pasted text OR a whole keys.txt (a room key is 32 bytes → 43 base64url chars).
262
+ const keysFrom = (txt) => [...new Set((String(txt || '').match(/[A-Za-z0-9_-]{40,64}/g) || []))]
263
+ const allKeys = () => keysFrom($('mk').value + '\n' + keyFileText)
264
+ // The Space ids the reader was given: a keys file's rows (title<TAB>room<TAB>key), and a pasted Space link's room=.
265
+ function roomsFrom(txt) {
266
+ const out = [], t = String(txt || '')
267
+ for (const line of t.split(/\r?\n/)) { const c = line.split('\t'); if (c.length >= 3 && c[1].trim()) out.push(c[1].trim()) }
268
+ for (const m of t.matchAll(/[?&#]room=([A-Za-z0-9_.~-]+)/g)) out.push(decodeURIComponent(m[1]))
269
+ return [...new Set(out)]
270
+ }
271
+ const allRooms = () => roomsFrom($('mk').value + '\n' + keyFileText)
272
+ // a keys-file row's room for THIS key first, then every other room the reader was given
273
+ const roomsForKey = (key) => { const t = $('mk').value + '\n' + keyFileText, own = []; for (const line of t.split(/\r?\n/)) { const c = line.split('\t'); if (c.length >= 3 && c[2].trim() === key && c[1].trim()) own.push(c[1].trim()) } return [...new Set([...own, ...allRooms()])] }
274
+ const bundleRooms = [] // per bundle entry: the room id its sealed name card holds (opened with a key)
275
+ function refreshGo() { $('go').disabled = !((($('mk').value.trim()) || keyFileText.trim()) && ledgerText.trim()); resolveTitles() }
276
+ $('mk').addEventListener('input', refreshGo)
277
+
278
+ // A v2 whole-account bundle seals its per-Space metadata, so the picker can only show real names once keys are
279
+ // loaded — that is the point: the file alone names nothing. Resolve lazily (trial-open each sealed meta with every
280
+ // key held, same as decryption itself does) and relabel in place; until then the options read "Conversation N".
281
+ // v1 bundles carry plaintext titles and fall straight through labelFor without any of this.
282
+ const labelFor = (s, i) => bundleTitles[i] || (s && (s.title || s.room)) || ('Conversation ' + (i + 1))
283
+ let resolving = false
284
+ async function resolveTitles() {
285
+ if (resolving || !bundle || !Array.isArray(bundle.spaces)) return
286
+ const keys = allKeys(); if (!keys.length) return
287
+ if (bundle.spaces.every((s, i) => (bundleTitles[i] && bundleRooms[i]) || !(s && s.meta))) return // nothing left to open
288
+ resolving = true
289
+ try {
290
+ const wks = []
291
+ for (const k of keys) { try { wks.push(await roomWrapKey(k)) } catch (e) { /* not a usable key → skip */ } }
292
+ let changed = false
293
+ for (let i = 0; i < bundle.spaces.length; i++) {
294
+ const s = bundle.spaces[i]
295
+ if ((bundleTitles[i] && bundleRooms[i]) || !s || !s.meta) continue
296
+ for (const wk of wks) {
297
+ const txt = await openEnv(s.meta, wk)
298
+ if (txt == null) continue // wrong key for this Space → try the next
299
+ try { const m = JSON.parse(txt); if (m && m.room) bundleRooms[i] = m.room; if (m && m.title) { bundleTitles[i] = m.title; changed = true } } catch (e) { /* */ }
300
+ break
301
+ }
302
+ }
303
+ if (changed) { const sel = $('spacePicker'); for (let i = 0; i < sel.options.length; i++) sel.options[i].textContent = labelFor(bundle.spaces[i], i) }
304
+ } finally { resolving = false }
305
+ }
306
+
307
+ const readFile = (file, cb) => { const r = new FileReader(); r.onload = () => cb(String(r.result || '')); r.readAsText(file) }
308
+ $('mkFile').addEventListener('change', (ev) => { const f = ev.target.files && ev.target.files[0]; if (f) readFile(f, (txt) => { keyFileText = txt; const n = keysFrom(txt).length; $('mkFileName').textContent = n ? `✓ ${n} key${n === 1 ? '' : 's'} loaded from ${f.name}` : '✓ loaded (no key found?)'; refreshGo() }) })
309
+
310
+ function setLedger(txt, name) {
311
+ ledgerText = txt; $('ledName').textContent = name ? '✓ ' + name : ''
312
+ bundle = null; bundleTitles = []; bundleRooms.length = 0; singleLedger = null; singleTitle = (name || 'Conversation').replace(/\.(witbitz-)?ledger\.json$/i, '').replace(/\.json$/i, '') || 'Conversation'
313
+ let parsed = null; try { parsed = JSON.parse(txt) } catch (e) {}
314
+ if (parsed && Array.isArray(parsed.spaces)) {
315
+ bundle = parsed
316
+ const sel = $('spacePicker'); sel.innerHTML = ''
317
+ bundle.spaces.forEach((s, i) => { const o = document.createElement('option'); o.value = String(i); o.textContent = labelFor(s, i); sel.appendChild(o) })
318
+ $('spaceRow').classList.remove('hidden')
319
+ $('ledName').textContent = `✓ ${name || 'backup'} — ${bundle.spaces.length} conversation${bundle.spaces.length === 1 ? '' : 's'}`
320
+ } else {
321
+ singleLedger = parsed; $('spaceRow').classList.add('hidden')
322
+ }
323
+ refreshGo()
324
+ }
325
+ $('ledFile').addEventListener('change', (ev) => { const f = ev.target.files && ev.target.files[0]; if (f) readFile(f, (txt) => setLedger(txt, f.name)) })
326
+ const drop = $('drop')
327
+ ;['dragenter', 'dragover'].forEach((t) => drop.addEventListener(t, (e) => { e.preventDefault(); drop.classList.add('over') }))
328
+ ;['dragleave', 'drop'].forEach((t) => drop.addEventListener(t, (e) => { e.preventDefault(); drop.classList.remove('over') }))
329
+ drop.addEventListener('drop', (e) => { const f = e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0]; if (f) readFile(f, (txt) => setLedger(txt, f.name)) })
330
+
331
+ const status = (msg, err) => { const s = $('status'); s.textContent = msg || ''; s.className = 'status' + (err ? ' err' : '') }
332
+
333
+ $('go').addEventListener('click', async () => {
334
+ status('Decrypting…'); $('out').classList.add('hidden')
335
+ const keys = allKeys()
336
+ if (!keys.length) return status('Paste your key, or load a key file.', true)
337
+ let target = null, title = 'Conversation', idx = -1
338
+ if (bundle) { await resolveTitles(); idx = Number($('spacePicker').value) || 0
339
+ const i = Number($('spacePicker').value) || 0, s = bundle.spaces[i]
340
+ if (!s) return status('Pick a conversation.', true)
341
+ title = labelFor(s, i); target = s.ledger
342
+ if (typeof target === 'string') { try { target = JSON.parse(target) } catch (e) { return status('That conversation entry is malformed.', true) } }
343
+ } else { target = singleLedger; title = singleTitle }
344
+ if (!target) return status('Load a sealed conversation first.', true)
345
+ let needsRoom = false
346
+ let best = null
347
+ for (const key of keys) {
348
+ try {
349
+ const rooms = [...(idx >= 0 && bundleRooms[idx] ? [bundleRooms[idx]] : []), ...roomsForKey(key)]
350
+ const { entries, opened, total, v3, needsRoom: nr } = await decryptLedger(target, key, rooms, keys.filter(k => roomsForKey(k).some(r => rooms.includes(r)) || !roomsForKey(k).length))
351
+ if (nr) needsRoom = true
352
+ if (entries != null && (!v3 || opened === total)) { render(entries, title); return status(`Read ${entries.length} message${entries.length === 1 ? '' : 's'}.`) }
353
+ if (opened && (!best || opened > best.opened)) best = { entries, opened, total }
354
+ } catch (e) { /* try the next key */ }
355
+ }
356
+ if (best) { render(best.entries, title); return status(`Read ${best.opened} of ${best.total} messages (${best.total - best.opened} could not be opened).`) }
357
+ if (needsRoom) return status('This conversation is tied to its Space. Load the keys file from the same backup, or paste the Space’s link beside the key, then try again.', true)
358
+ status(keys.length > 1 ? 'Couldn’t decrypt — none of the keys provided match this conversation.' : 'Couldn’t decrypt — the key doesn’t match this conversation (or it isn’t a Witbitz ledger).', true)
359
+ })
360
+
361
+ // ── saving ──
362
+ function download(name, text, mime) {
363
+ const url = URL.createObjectURL(new Blob([text], { type: mime || 'text/plain;charset=utf-8' }))
364
+ const a = document.createElement('a'); a.href = url; a.download = name; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 4000)
365
+ }
366
+ const safeName = (t) => (t || 'conversation').replace(/[^\wÀ-￿.-]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 60) || 'conversation'
367
+ function transcriptText() {
368
+ if (!lastEntries) return ''
369
+ return lastEntries.map((e) => {
370
+ const who = (e && e.name) || 'Unknown', ts = fmtTs(e && e.ts)
371
+ const extra = [].concat((e && e.images || []).map(() => '[image]'), (e && e.files || []).map((f) => '[file: ' + ((f && f.name) || '') + ']')).join(' ')
372
+ return `${ts ? '[' + ts + '] ' : ''}${who}: ${(e && e.text) || ''}${extra ? ' ' + extra : ''}`
373
+ }).join('\n')
374
+ }
375
+ $('saveTxt').addEventListener('click', () => download(safeName(lastTitle) + '.txt', transcriptText(), 'text/plain;charset=utf-8'))
376
+ $('saveHtml').addEventListener('click', () => {
377
+ const body = $('transcript').innerHTML
378
+ download(safeName(lastTitle) + '.html', `<!doctype html><meta charset=utf-8><title>${esc(lastTitle)}</title><style>body{font:15px/1.5 -apple-system,system-ui,sans-serif;max-width:760px;margin:24px auto;padding:0 16px}.msg{padding:10px 0;border-top:1px solid #eee}.who{font-weight:650}.ts{color:#888;font-size:11.5px;margin-left:8px}.body{white-space:pre-wrap;margin-top:3px}img{max-width:100%;border-radius:10px;margin-top:8px;display:block}.chip{display:inline-block;margin:6px 6px 0 0;padding:3px 9px;border-radius:7px;background:#f0f0ec;color:#666;font-size:12px}</style><h2>${esc(lastTitle)}</h2>${body}`, 'text/html;charset=utf-8')
379
+ })
380
+ $('saveSelf').addEventListener('click', () => download('witbitz-offline-decryptor.html', '<!doctype html>\n' + document.documentElement.outerHTML, 'text/html;charset=utf-8'))
381
+ })();
382
+ </script>
383
+ </body>
384
+ </html>