@witbitz/sdk 0.0.0-stage → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +221 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +228 -0
  6. package/accountIndexDoc.js +122 -0
  7. package/accountOwner.js +59 -0
  8. package/accountRecord.js +90 -0
  9. package/accountScope.js +114 -0
  10. package/accountSeal.js +42 -0
  11. package/accountStores.js +173 -0
  12. package/acctV2App.js +619 -0
  13. package/acctV2Check.js +29 -0
  14. package/acctV2Client.js +382 -0
  15. package/acctV2Keys.js +43 -0
  16. package/acctV2Legacy.js +14 -0
  17. package/acctV2Switch.js +80 -0
  18. package/acctV2UiCore.js +857 -0
  19. package/acctV2WebAuthn.js +61 -0
  20. package/acctV2Wire.js +59 -0
  21. package/address.js +42 -0
  22. package/agentDoorTools.js +28 -0
  23. package/attestedBox.js +30 -0
  24. package/attestedRooms.js +78 -0
  25. package/awsKey.js +98 -0
  26. package/backupRecord.js +106 -0
  27. package/backupVault.js +97 -0
  28. package/blocks.js +115 -0
  29. package/blocksPush.js +64 -0
  30. package/browseSeal.js +103 -0
  31. package/cbor.js +225 -0
  32. package/changePush.js +75 -0
  33. package/chatLock.js +165 -0
  34. package/chatLockSw.js +13 -0
  35. package/cloudDeviceBuilds.js +11 -0
  36. package/cloudDevicePins.js +33 -0
  37. package/cloudDeviceSeal.js +53 -0
  38. package/codeAttachments.js +100 -0
  39. package/codeBrowse.js +224 -0
  40. package/codeCache.js +149 -0
  41. package/codeCloud.js +650 -0
  42. package/codeCloudKeys.js +112 -0
  43. package/codeCommands.js +167 -0
  44. package/codeComputers.js +389 -0
  45. package/codeEgress.js +123 -0
  46. package/codeFilesRoutes.js +17 -0
  47. package/codeFolders.js +116 -0
  48. package/codeHistory.js +76 -0
  49. package/codeLanguage.js +54 -0
  50. package/codeMkdir.js +8 -0
  51. package/codeModes.js +59 -0
  52. package/codeOrphanKeys.js +42 -0
  53. package/codeOutputs.js +141 -0
  54. package/codeProgress.js +54 -0
  55. package/codeRelay.js +505 -0
  56. package/codeSent.js +68 -0
  57. package/codeSentinel.js +86 -0
  58. package/codeSubagents.js +107 -0
  59. package/codeTransport.js +317 -0
  60. package/codeUndo.js +48 -0
  61. package/compress.js +24 -0
  62. package/config.js +11 -0
  63. package/connCatalog.js +164 -0
  64. package/connDisp.js +76 -0
  65. package/connOtherWays.js +74 -0
  66. package/connPending.js +16 -0
  67. package/connWrap.js +53 -0
  68. package/connectionEntry.js +89 -0
  69. package/connections.js +561 -0
  70. package/credits.js +30 -0
  71. package/csAttest.js +112 -0
  72. package/decrypt.html +384 -0
  73. package/deviceAttest.js +527 -0
  74. package/deviceCall.js +54 -0
  75. package/deviceKeyCore.js +41 -0
  76. package/deviceSeal.js +59 -0
  77. package/e2ee.js +323 -0
  78. package/eat.js +103 -0
  79. package/emailFork.js +275 -0
  80. package/emailSignIn.js +81 -0
  81. package/emptySpaces.js +111 -0
  82. package/encSource.js +55 -0
  83. package/enclaveAccept.js +214 -0
  84. package/enclaveClaim.js +241 -0
  85. package/enclaveRoute.js +102 -0
  86. package/enclaveSnapshotMerge.js +44 -0
  87. package/entrySig.js +165 -0
  88. package/env.js +73 -0
  89. package/eraseFile.js +58 -0
  90. package/followImage.js +86 -0
  91. package/healNames.js +45 -0
  92. package/idb.js +113 -0
  93. package/idbSeal.js +119 -0
  94. package/indexGone.js +12 -0
  95. package/invite.js +51 -0
  96. package/inviteEnroll.js +67 -0
  97. package/inviteSend.js +68 -0
  98. package/jobAgents.js +87 -0
  99. package/keptMerge.js +91 -0
  100. package/l1-worker-src.js +2 -0
  101. package/l1-worker.js +894 -0
  102. package/laneAssociation.js +68 -0
  103. package/laneConfig.js +58 -0
  104. package/laneLinkCore.js +177 -0
  105. package/ledgerView.js +64 -0
  106. package/manifest.json +239 -0
  107. package/mcpRecommended.js +25 -0
  108. package/memberChange.js +125 -0
  109. package/mirrorBatch.js +47 -0
  110. package/mkseal.js +101 -0
  111. package/nativePush.js +153 -0
  112. package/nitroVerify.js +220 -0
  113. package/noble-p256.js +27 -0
  114. package/notice.js +116 -0
  115. package/notifKey.js +58 -0
  116. package/offlineBundle.js +62 -0
  117. package/ohttp.js +177 -0
  118. package/opRouting.js +10 -0
  119. package/opencodeWire.js +282 -0
  120. package/oprf.js +70 -0
  121. package/ownAgentLink.js +96 -0
  122. package/ownerPolicy.js +117 -0
  123. package/package.json +273 -4
  124. package/pdfOptions.js +13 -0
  125. package/pdfText.js +107 -0
  126. package/pdfjs.mjs +28 -0
  127. package/pdfjs.worker.mjs +28 -0
  128. package/pollVerdict.js +33 -0
  129. package/prefetchPoll.js +60 -0
  130. package/protectedLocal.js +426 -0
  131. package/pushCore.js +42 -0
  132. package/recovery.js +107 -0
  133. package/regions.js +42 -0
  134. package/removedMessage.js +11 -0
  135. package/renameRefusal.js +9 -0
  136. package/replyQuote.js +34 -0
  137. package/reqEnvelope.js +126 -0
  138. package/roomDefaultPrefs.js +76 -0
  139. package/roomDelete.js +109 -0
  140. package/roomEmbed.js +111 -0
  141. package/roomName.js +177 -0
  142. package/roomPass.js +256 -0
  143. package/roomRoster.js +305 -0
  144. package/roomSettings.js +61 -0
  145. package/roomState.js +58 -0
  146. package/roomStreamClient.js +115 -0
  147. package/rosterCount.js +52 -0
  148. package/rosterHash.js +13 -0
  149. package/rowSchema.js +113 -0
  150. package/safeMedia.js +116 -0
  151. package/safeMediaPins.js +17 -0
  152. package/schedulesDoc.js +78 -0
  153. package/sdkA2A.js +524 -0
  154. package/sdkAccount.js +483 -0
  155. package/sdkAccountDoc.js +89 -0
  156. package/sdkAccountSections.js +332 -0
  157. package/sdkAgui.js +141 -0
  158. package/sdkAttest.js +34 -0
  159. package/sdkBackup.js +507 -0
  160. package/sdkBackupV2.js +630 -0
  161. package/sdkBrowserPrivate.js +28 -0
  162. package/sdkBuilds.js +208 -0
  163. package/sdkCloudDevice.js +221 -0
  164. package/sdkComputers.js +1009 -0
  165. package/sdkDictation.js +232 -0
  166. package/sdkErase.js +288 -0
  167. package/sdkExports.js +71 -0
  168. package/sdkInvitations.js +34 -0
  169. package/sdkKeptAgent.js +188 -0
  170. package/sdkLaneLink.js +205 -0
  171. package/sdkPlan.js +96 -0
  172. package/sdkProtect.js +228 -0
  173. package/sdkRedact.js +36 -0
  174. package/sdkRekey.js +340 -0
  175. package/sdkReport.js +68 -0
  176. package/sdkSafeMedia.js +255 -0
  177. package/sdkSchedules.js +39 -0
  178. package/sdkSpeech.js +71 -0
  179. package/sdkTemporaryRooms.js +123 -0
  180. package/sdkTurn.js +117 -0
  181. package/sdkVault.js +180 -0
  182. package/sealShare.js +18 -0
  183. package/sealedNames.js +64 -0
  184. package/sealedReceipt.js +17 -0
  185. package/sentinelRelease.js +155 -0
  186. package/shamir.js +85 -0
  187. package/sharedViews.js +52 -0
  188. package/sheetChrome.js +450 -0
  189. package/siri.js +278 -0
  190. package/spaceClient.js +1429 -0
  191. package/spaceConfig.js +81 -0
  192. package/spaceEmailGate.js +813 -0
  193. package/spaceExport.js +125 -0
  194. package/spaceFork.js +216 -0
  195. package/spaceLock.js +358 -0
  196. package/spacePasskey.js +180 -0
  197. package/spaceTemplates.js +99 -0
  198. package/speechOut.js +102 -0
  199. package/splitKeyClient.js +90 -0
  200. package/store.js +656 -0
  201. package/streamHint.js +36 -0
  202. package/sttCloud.js +220 -0
  203. package/sttWorklet.js +38 -0
  204. package/sw-notif-core.js +540 -0
  205. package/tempList.js +48 -0
  206. package/tinfoilVerifier.js +78 -0
  207. package/toolBooks.js +31 -0
  208. package/toolRules.js +52 -0
  209. package/turnCerts.js +254 -0
  210. package/turnFeed.js +58 -0
  211. package/turnVerdict.js +37 -0
  212. package/usageReceipts.js +176 -0
  213. package/usageSummary.js +90 -0
  214. package/util.js +181 -0
  215. package/vault-core.js +2326 -0
  216. package/vault-kit.mjs +354 -0
  217. package/vault-screens.js +261 -0
  218. package/vaultAtRest.js +208 -0
  219. package/vaultCoreLock.js +111 -0
  220. package/vaultCorePush.js +140 -0
  221. package/vaultDeviceKey.js +95 -0
  222. package/vaultEnclaveHandoff.js +114 -0
  223. package/vaultKeep.js +287 -0
  224. package/vaultSealedStore.js +77 -0
  225. package/vaultWorkerHost.js +117 -0
  226. package/vcWorker.js +34 -0
  227. package/voiceAttest.js +50 -0
  228. package/voiceCert.js +51 -0
  229. package/witbitz-admin.d.ts +135 -0
  230. package/witbitz-admin.js +529 -0
  231. package/witbitz-admin.mjs +1460 -0
  232. package/witbitz-sdk.d.ts +1197 -0
  233. package/witbitz-sdk.js +4258 -0
  234. package/workerClient.js +16 -0
  235. package/workerLiveness.js +21 -0
  236. package/x509.js +218 -0
@@ -0,0 +1,813 @@
1
+ // spaceEmailGate.js — "Sign in with Google" for EMAIL-gated async Spaces (the CLIENT half of the gate).
2
+ //
3
+ // The server half is agent/spaceOidc.mjs (verifyEmailTurn): it checks a Google ID token per turn, requires the token's
4
+ // `nonce` to equal spkNonce(the member's signing key), and checks the email against the Space's sealed allow-list. This
5
+ // module obtains that token. The nonce binds the Google identity to THIS device's signing key — the async stand-in for
6
+ // Kibitz binding the OIDC token to the live DTLS cert — so a leaked token can't be replayed onto another key.
7
+ //
8
+ // Reads gate WRITES only: anyone with the room key (mk, in the link) can READ; only allow-listed Google accounts can
9
+ // POST. The token is cached per-nonce until shortly before it expires, then a fresh one is fetched. The client id is
10
+ // PUBLIC (baked at deploy from ~/.witbitz-google-client-id). Zero deps: pure Google Identity Services.
11
+
12
+ import { makeEmailPost, emailStart, emailVerify, emailRefresh, jwtPayload } from './emailSignIn.js' // the email-code protocol, shared with the SDK (docs/sdk-convergence.md phase 5)
13
+ import { deviceOwner } from './accountOwner.js' // whose Spaces this device holds (one email per device, below)
14
+ import { spkNonce } from './entrySig.js' // a token is bound to its key's nonce: the orphan-token sweep
15
+ import { banner } from './notice.js' // the one place a refused address is SHOWN (refuseOther, below)
16
+
17
+ const GIS_SRC = 'https://accounts.google.com/gsi/client'
18
+ let _gisReady = null
19
+ function loadGis() {
20
+ if (_gisReady) return _gisReady
21
+ _gisReady = new Promise((resolve, reject) => {
22
+ if (window.google && window.google.accounts && window.google.accounts.id) return resolve()
23
+ const s = document.createElement('script')
24
+ s.src = GIS_SRC
25
+ s.async = true
26
+ s.defer = true
27
+ s.onload = () => (window.google && window.google.accounts && window.google.accounts.id ? resolve() : reject(new Error('gis_unavailable')))
28
+ s.onerror = () => reject(new Error('gis_load_failed'))
29
+ document.head.appendChild(s)
30
+ })
31
+ return _gisReady
32
+ }
33
+
34
+ // Read a JWT's payload WITHOUT verifying it — the SERVER verifies (signature + claims); we only read `email`/`exp` here
35
+ // for the UI label and the local expiry cache. Never trust these bytes for anything security-relevant.
36
+ // jwtPayload: emailSignIn.js
37
+
38
+ const _cache = new Map() // nonce → { idToken, email, exp(ms) } — mirrored to localStorage below so a reload / PWA reopen
39
+ const FRESH_MS = 5 * 60 * 1000 // re-prompt when a cached token is within 5 min of expiry
40
+
41
+ // PERSIST the verified token across reloads/reopens (keyed by the device-key nonce) so entering a Space you've already
42
+ // verified doesn't re-prompt while the token is still valid. Device-local + device-bound (unusable without the matching
43
+ // signing key, also in localStorage) — same trust surface as the stored keypair. Expired entries are pruned on read.
44
+ const TOK_KEY = (n) => 'space:tok:' + n
45
+ function tokDel(n) { _cache.delete(n); try { localStorage.removeItem(TOK_KEY(n)) } catch { /* */ } }
46
+ function tokGet(n) {
47
+ let v = _cache.get(n)
48
+ if (!v) { try { const s = localStorage.getItem(TOK_KEY(n)); if (s) { v = JSON.parse(s); _cache.set(n, v) } } catch { /* */ } }
49
+ if (v && (!v.exp || v.exp <= Date.now())) { tokDel(n); return null } // drop expired
50
+ if (v && otherDeviceEmail(v.email)) { tokDel(n); return null } // a token for ANOTHER address answers no one (sync sweep 11-09 #6: the Google callback cached it before its refusal, and the retry posted as it)
51
+ return v || null
52
+ }
53
+ // EXPIRED TOKENS GO (the owner's phone, 2026-10-15: its storage was FULL — 6,930 keys — so every write failed silently and the
54
+ // sign-in "did not survive"). One token per signing key was kept for ever. An expired one can never be used again: it is
55
+ // dropped at start and again when a save is refused for space, and the save is retried once.
56
+ // The APP's mode (Settings → Appearance sets html's color-scheme to one word), else the phone's — the Google button matches the card.
57
+ function appIsDark () {
58
+ const cs = typeof getComputedStyle === 'function' ? String(getComputedStyle(document.documentElement).colorScheme || '').trim() : ''
59
+ if (cs === 'dark' || cs === 'light') return cs === 'dark'
60
+ return typeof matchMedia === 'function' && matchMedia('(prefers-color-scheme: dark)').matches
61
+ }
62
+
63
+ export function pruneExpiredTokens(now = Date.now()) {
64
+ let n = 0
65
+ try {
66
+ const dead = []
67
+ for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); if (!k || k.indexOf('space:tok:') !== 0) continue; let v = null; try { v = JSON.parse(localStorage.getItem(k) || 'null') } catch { v = null } if (!v || !(Number(v.exp) > now)) dead.push(k) }
68
+ for (const k of dead) { try { localStorage.removeItem(k); n++ } catch { /* */ } }
69
+ } catch { /* */ }
70
+ return n
71
+ }
72
+ function tokSet(n, v) {
73
+ _cache.set(n, v)
74
+ try { localStorage.setItem(TOK_KEY(n), JSON.stringify(v)) } catch { try { if (pruneExpiredTokens()) localStorage.setItem(TOK_KEY(n), JSON.stringify(v)) } catch { /* still full / private mode */ } }
75
+ }
76
+ // TOKENS FOR KEYS THAT ARE GONE GO TOO (the owner's phone, 2026-10-15: 5,497 live tokens = 9 MB beside 38 signing keys —
77
+ // each was minted for a key since replaced, and lived its 30 days). A token is only ever used for the key it is bound to
78
+ // (its nonce = spkNonce of that key): keep the ones for this device's signing keys and its saved session's key, and the
79
+ // newest few (a key held elsewhere: the Code page, a vault handoff); drop the rest.
80
+ export async function pruneOrphanTokens({ keepNewest = 40 } = {}) {
81
+ try {
82
+ const live = new Set()
83
+ const pubs = []
84
+ for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); if (k && k.indexOf('space:sign:') === 0) { try { const kp = JSON.parse(localStorage.getItem(k) || 'null'); if (kp && kp.pub) pubs.push(kp.pub) } catch { /* */ } } }
85
+ try { const a = anchorGet(); if (a && a.kp && a.kp.pub) pubs.push(a.kp.pub) } catch { /* */ }
86
+ for (const p of pubs) { try { live.add(await spkNonce(p)) } catch { /* */ } }
87
+ const toks = []
88
+ for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); if (!k || k.indexOf('space:tok:') !== 0) continue; let v = null; try { v = JSON.parse(localStorage.getItem(k) || 'null') } catch { v = null } toks.push({ k, n: k.slice(10), exp: Number(v && v.exp) || 0 }) }
89
+ const newest = new Set(toks.filter((t) => !live.has(t.n)).sort((a, b) => b.exp - a.exp).slice(0, keepNewest).map((t) => t.k))
90
+ let n = 0
91
+ for (const t of toks) if (!live.has(t.n) && !newest.has(t.k)) { try { localStorage.removeItem(t.k); _cache.delete(t.n); n++ } catch { /* */ } }
92
+ return n
93
+ } catch { return 0 }
94
+ }
95
+ try { setTimeout(() => { pruneExpiredTokens(); pruneOrphanTokens().then((n) => { if (n) signinLog('cleared ' + n + ' sign-in tokens for keys this device no longer has') }).catch(() => {}) }, 4000) } catch { /* no window */ }
96
+
97
+ /** Clear a cached token (e.g. after the server rejected it) so the next call re-prompts. */
98
+ export function clearGoogleToken(nonce) { if (nonce) tokDel(nonce) }
99
+
100
+ /** Non-prompting: the cached token for `nonce` if still comfortably valid, else null. For the poll loop + read ops,
101
+ * which must gate on a token but must NOT pop a sign-in card on their own (only a user action prompts). */
102
+ export function cachedGoogleToken(nonce) {
103
+ const hit = tokGet(nonce)
104
+ return hit && hit.exp - Date.now() > FRESH_MS ? { idToken: hit.idToken, email: hit.email } : null
105
+ }
106
+
107
+ /** Obtain a Google ID token whose `nonce` claim is bound to the member's signing key (pass `nonce = spkNonce(spk)`).
108
+ * Reuses a cached, unexpired token for the same nonce; otherwise shows a Google sign-in card (+ One Tap, best-effort)
109
+ * and resolves on sign-in. Rejects `cancelled` if the user dismisses, or `email_gate_unconfigured` if no client id.
110
+ * Returns `{ idToken, email }`. */
111
+ export async function googleIdToken({ clientId, nonce, copy = null, fresh = false, googleOwn = false }) { // googleOwn: Google's OWN token, never the broker's session (the account service checks Google's signature — acct/googleProof.mjs) // fresh: never a kept token (account recovery v2 wants a sign-in made now) // copy: { title, sub } — the card's words for another use (account recovery v2's Google in place of a code)
112
+ const hit = fresh ? null : tokGet(nonce)
113
+ if (hit && hit.exp - Date.now() > FRESH_MS) return { idToken: hit.idToken, email: hit.email }
114
+ // ★ THE HOSTED APP'S VAULT (forceBroker): Google runs ONLY on the auth origin — Google does not know the vault's address, and
115
+ // an in-page sign-in there ends in Google's "Access blocked: origin_mismatch" (the owner's iPhone, 2026-11-15, the new account
116
+ // service's "Continue with Google" on spaces.witbitz.chat). The same token, for the same nonce, through the broker.
117
+ if (forceBroker()) {
118
+ let why = ''
119
+ const t = await brokerGoogleToken({ nonce, onEnd: (w) => { why = w } })
120
+ if (why === 'cancelled') throw new Error('cancelled') // the waiting card's Cancel is a decision, not a failure
121
+ if (!t || !t.idToken) throw new Error('Google sign-in did not finish')
122
+ if (googleOwn) { if (!t.google) throw new Error('Google sign-in did not finish'); return { idToken: t.google, email: t.email } } // an older broker hands no Google token: the card says to use the code
123
+ return t
124
+ }
125
+ if (!clientId || clientId.indexOf('__') === 0) throw new Error('email_gate_unconfigured')
126
+ await loadGis()
127
+
128
+ return new Promise((resolve, reject) => {
129
+ const dark = appIsDark()
130
+ const overlay = document.createElement('div')
131
+ overlay.style.cssText = 'position:fixed;inset:0;z-index:2000;background:rgba(0,0,0,.5);display:flex;align-items:center;justify-content:center;padding:24px'
132
+ overlay.className = 'kbfit' // with the keys up it fits the visible area (space.html), its field above them
133
+ const card = document.createElement('div')
134
+ card.style.cssText = 'background:var(--bg,#fff);color:var(--fg,#111);border:1px solid var(--line,#ddd);border-radius:14px;padding:22px;max-width:340px;width:100%;text-align:center;box-shadow:0 12px 40px rgba(0,0,0,.35)'
135
+ const h = document.createElement('div'); h.textContent = (copy && copy.title) || 'Sign in to post'; h.style.cssText = 'font-weight:600;font-size:16px;margin-bottom:6px'
136
+ const sub = document.createElement('div'); sub.textContent = (copy && copy.sub) || 'Only the people this Space names can read or post here. Sign in with an allowed account.' // reading needs the sign-in too (the email gate covers reads) — the old line said anyone could read (owner, 2026-10-15)
137
+ sub.style.cssText = 'font-size:13px;color:var(--muted,#888);margin-bottom:16px;line-height:1.4'
138
+ const btnHost = document.createElement('div'); btnHost.style.cssText = 'display:flex;justify-content:center;min-height:44px'
139
+ const cancel = document.createElement('button'); cancel.textContent = 'Cancel'
140
+ cancel.style.cssText = 'margin-top:14px;background:none;border:none;color:var(--muted,#888);font-size:13px;cursor:pointer'
141
+ card.appendChild(h); card.appendChild(sub); card.appendChild(btnHost); card.appendChild(cancel)
142
+ overlay.appendChild(card); document.body.appendChild(overlay)
143
+
144
+ let done = false
145
+ const close = () => { try { document.body.removeChild(overlay) } catch { /* already gone */ } }
146
+ const finish = (fn) => { if (done) return; done = true; try { window.google.accounts.id.cancel() } catch { /* */ } close(); fn() }
147
+ cancel.onclick = () => finish(() => reject(new Error('cancelled')))
148
+ overlay.onclick = (e) => { if (e.target === overlay) finish(() => reject(new Error('cancelled'))) }
149
+
150
+ try {
151
+ window.google.accounts.id.initialize({
152
+ client_id: clientId,
153
+ nonce, // Google echoes this verbatim into the token's `nonce` claim; the server requires it == spkNonce(spk)
154
+ callback: (resp) => {
155
+ const p = jwtPayload(resp && resp.credential)
156
+ const email = String(p.email || '').toLowerCase()
157
+ tokSet(nonce, { idToken: resp.credential, email, exp: (Number(p.exp) || 0) * 1000 })
158
+ finish(() => resolve({ idToken: resp.credential, email }))
159
+ },
160
+ })
161
+ window.google.accounts.id.renderButton(btnHost, { theme: dark ? 'filled_black' : 'outline', size: 'large', text: 'signin_with', shape: 'pill' })
162
+ try { if (!forceBroker()) window.google.accounts.id.prompt() } catch { /* One Tap is best-effort; the button is the real path */ } // vault surfaces (forceBroker): NO in-page One-Tap — the bottom FedCM sheet duplicated the card's button and surfaced the browser's session unasked
163
+ } catch (e) {
164
+ finish(() => reject(e instanceof Error ? e : new Error('gis_init_failed')))
165
+ }
166
+ })
167
+ }
168
+
169
+ const EMAIL_API = '' // SAME-ORIGIN: our own /api/email/* on the Spaces Pages project (Witbitz-branded sender). '' → relative
170
+
171
+ // ── CENTRAL AUTH BROKER (witbitz-auth.pages.dev) — the ONE Google-registered origin for the whole ecosystem. ─────────
172
+ // Two jobs for a tenant/branded origin: (a) GOOGLE sign-in without registering the origin with Google — the ceremony
173
+ // runs on the broker in a popup, the session comes back device-bound over a polled one-time handoff; (b) EMAIL-CODE
174
+ // sign-in without any email secrets on the origin — when the local /api/email/* is unconfigured, the same calls fall
175
+ // back to the broker's /api/relay/* (allowlisted per-origin CORS; the session is minted AS this origin either way).
176
+ const AUTH_BROKER = 'https://auth.witbitz.chat' // stamped at deploy (deploy.sh / build-vault.sh); placeholder ⇒ no broker
177
+ const brokerUrl = () => (AUTH_BROKER && AUTH_BROKER.indexOf('__') !== 0 ? AUTH_BROKER.replace(/\/$/, '') : '')
178
+ // TENANT-VAULT POLICY (2026-09-01): on VAULT surfaces every Google sign-in runs on the CENTRAL AUTH ORIGIN — one
179
+ // registered ceremony origin, and no in-page One-Tap that could surface whatever Google session the browser happens
180
+ // to hold (the wrong-account trap). Stamped '1' by build-vault.sh; the main app keeps its in-page GIS ('0').
181
+ const AUTH_FORCE_BROKER = '0'
182
+ const forceBroker = () => AUTH_FORCE_BROKER === '1' && !!brokerUrl()
183
+ export const authViaBroker = forceBroker // public predicate: this surface routes ALL Google through the central auth origin (recoveryGate's factor overlay branches on it)
184
+ // POST an email-ceremony call: LOCAL first; if the local origin has no email stack (unconfigured / no such function —
185
+ // an HTML fallback that fails to parse), transparently retry via the broker relay. Returns the parsed JSON or null.
186
+ const emailPost = (apiBase, path, body) => makeEmailPost(apiBase, { broker: brokerUrl() })(path, body) // emailSignIn.js — the protocol shared with the SDK (docs/sdk-convergence.md phase 5)
187
+ // GOOGLE via the broker: open the ceremony popup, poll for the device-bound session. Resolves { idToken, email } | null.
188
+ const E2E_AT_LOAD = (() => { try { return new URLSearchParams(location.search).get('e2etest') === '1' } catch { return false } })() // captured at MODULE INIT — the vault replaceState-strips its query before any click, so a click-time read misses the flag
189
+ // How long the page waits for the ceremony (the owner's Android app, 2026-11-08: "Chrome opens, then stuck"). The ceremony runs in
190
+ // ANOTHER app there (the system browser): the person signs in, then switches back — often after the old 3 minutes, when the wait had
191
+ // already ended and the finished sign-in sat unused until the broker dropped it (5 min after it finished). A return to this page ends
192
+ // the current pause at once (wakeOnReturn), so coming back finds the answer without a wait.
193
+ export const BROKER_WAIT_MS = 10 * 60 * 1000
194
+ const BROKER_POLL_MS = 1500
195
+ // One poll may take this long: a request in flight when iPhone paused the app under Safari can come back never — the wait must not
196
+ // hang on it past the person's return (the next round asks again).
197
+ export const BROKER_POLL_TIMEOUT_MS = 12000
198
+ // A sign-in window OUTSIDE the app seen closed: a few more rounds, not one — the broker closes its own page right after it parks the
199
+ // sign-in, and the first request after iPhone resumes the app often fails ("the network connection was lost"). The closing ends the
200
+ // wait only after this long AND two more polls.
201
+ export const BROKER_CLOSED_GRACE_MS = 8000
202
+ // A window OUTSIDE the app (the shells' browser, iPhone's Safari sheet) that reads closed this soon after it opened was never ours
203
+ // to watch: its "closed" says nothing about the sign-in. The wait goes on to the deadline; the waiting card's Cancel ends it.
204
+ const OUTSIDE_CLOSED_UNTRUSTED_MS = 5000
205
+ // THE NATIVE SHELLS (windows/attested-client, android/attested-client) name themselves in the user agent ("WitbitzApp/<platform>")
206
+ // and put their hardware-key bridge on the page (a cloud device's bridge is not a shell). In the Windows
207
+ // shell window.open answers null by design: every new window opens in the default browser (main_windows.go keepNavigationOnBundle).
208
+ export const inNativeShell = () => {
209
+ try {
210
+ if (/\bWitbitzApp\//.test((typeof navigator !== 'undefined' && navigator.userAgent) || '')) return true
211
+ const b = globalThis.WitbitzAttest
212
+ return !!(b && typeof b.platform === 'function' && /^(windows|android)$/.test(String(b.platform())))
213
+ } catch { return false }
214
+ }
215
+ // iPhone's installed web app: window.open shows a Safari sheet OVER the app, and iPhone pauses the app under it (codeBrowse.js).
216
+ const iosStandalone = () => { try { return typeof navigator !== 'undefined' && navigator.standalone === true } catch { return false } }
217
+ // A pause that ends early when the person comes back to the page (visible again, shown again, focused) or the wait is cancelled.
218
+ const wakeOnReturn = (ms, ctl = null) => new Promise((resolve) => {
219
+ let t = null
220
+ const onVis = () => { try { if (document.visibilityState === 'visible') done() } catch { /* */ } }
221
+ const evs = [['visibilitychange', onVis, () => document], ['pageshow', () => done(), () => window], ['focus', () => done(), () => window]]
222
+ const done = () => {
223
+ clearTimeout(t)
224
+ for (const [ev, f, at] of evs) { try { at().removeEventListener(ev, f) } catch { /* no document/window */ } }
225
+ if (ctl) ctl.wake = null
226
+ resolve()
227
+ }
228
+ t = setTimeout(done, ms)
229
+ for (const [ev, f, at] of evs) { try { at().addEventListener(ev, f) } catch { /* no document/window: the timer alone */ } }
230
+ if (ctl) ctl.wake = done
231
+ })
232
+ const withTimeout = (p, ms) => new Promise((resolve) => {
233
+ const t = setTimeout(() => resolve(null), ms)
234
+ Promise.resolve(p).then((v) => { clearTimeout(t); resolve(v) }, () => { clearTimeout(t); resolve(null) })
235
+ })
236
+ // The card shown while the sign-in runs OUTSIDE this page (a shell's browser, iPhone's Safari sheet): what to do, and a way out —
237
+ // without it the app showed nothing at all for up to 10 minutes. Best effort: no document, no card.
238
+ function brokerWaitCard ({ shell, onCancel }) {
239
+ try {
240
+ const wrap = document.createElement('div')
241
+ wrap.id = 'brokerWait'
242
+ wrap.style.cssText = 'position:fixed;inset:0;z-index:2147483001;background:rgba(0,0,0,.5);display:flex;align-items:center;justify-content:center;padding:24px'
243
+ const card = document.createElement('div')
244
+ card.style.cssText = 'background:var(--bg,#fff);color:var(--fg,#111);border:1px solid var(--line,#ddd);border-radius:14px;padding:22px;max-width:340px;width:100%;text-align:center;box-shadow:0 12px 40px rgba(0,0,0,.35)'
245
+ const h = document.createElement('div'); h.textContent = 'Waiting for Google…'; h.style.cssText = 'font-weight:600;font-size:16px;margin-bottom:6px'
246
+ const sub = document.createElement('div')
247
+ sub.textContent = shell ? 'Google’s sign-in opened in your browser. Finish it there, then come back to this app.' : 'Finish signing in on the Google page, then come back here.'
248
+ sub.style.cssText = 'font-size:13px;color:var(--muted,#888);line-height:1.4'
249
+ const cancel = document.createElement('button'); cancel.type = 'button'; cancel.id = 'brokerWaitCancel'; cancel.textContent = 'Cancel'
250
+ cancel.style.cssText = 'margin-top:14px;background:none;border:none;color:var(--muted,#888);font-size:14px;cursor:pointer'
251
+ cancel.onclick = () => onCancel()
252
+ card.append(h, sub, cancel); wrap.append(card); document.body.append(wrap)
253
+ return { close: () => { try { wrap.remove() } catch { /* gone */ } } }
254
+ } catch { return { close () {} } }
255
+ }
256
+ // GOOGLE'S OWN SHEET IN THE ANDROID APP (android/attested-client GoogleSignIn.kt; docs/TODO.md, the Android app (1a)): no browser, so
257
+ // nothing is lost when Android stops the app while Chrome is in front. The app answers Google's ID token for THIS nonce (audience =
258
+ // the web client id); the broker turns it into our session exactly as its own page does (/api/handoff/complete, then the poll).
259
+ // → { idToken, email, google } | { cancelled: true } | null (not offered, or it failed: the browser path follows).
260
+ const NATIVE_GOOGLE_WAIT_MS = 5 * 60 * 1000
261
+ const signInSheet = () => { try { const b = globalThis.WitbitzSignIn; return b && typeof b.open === 'function' && typeof b.close === 'function' ? b : null } catch { return null } }
262
+ const nativeGoogleBridge = () => { try { const b = globalThis.WitbitzAttest; return b && typeof b.googleSignInStart === 'function' && typeof b.googleSignInResult === 'function' ? b : null } catch { return null } }
263
+ export async function nativeGoogleToken ({ nonce, broker, bridge = nativeGoogleBridge(), clientId = null, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), now = Date.now }) {
264
+ if (!bridge || !broker) return null
265
+ try {
266
+ const cid = clientId || (await import('./config.js')).GOOGLE_CLIENT_ID
267
+ if (!cid || String(cid).indexOf('__') === 0) return null
268
+ const id = String(bridge.googleSignInStart(cid, nonce) || '')
269
+ if (!id) return null
270
+ let ans = '', until = now() + NATIVE_GOOGLE_WAIT_MS
271
+ while (!ans && now() < until) { await sleep(300); ans = String(bridge.googleSignInResult(id) || '') }
272
+ if (!ans) { signinLog('Google (app): no answer from the sheet — the browser instead'); return null }
273
+ const r = JSON.parse(ans)
274
+ if (r.code === 'cancelled') { signinLog('Google (app): cancelled'); return { cancelled: true } }
275
+ if (!r.idToken) { signinLog('Google (app): ' + (r.code || 'failed') + ' (' + String(r.error || '').slice(0, 80) + ') — the browser instead'); return null }
276
+ const sid = [...crypto.getRandomValues(new Uint8Array(18))].map((b) => 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'[b % 64]).join('')
277
+ const post = (path, body) => withTimeout(fetch(broker + path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }).then((x) => x.json()), BROKER_POLL_TIMEOUT_MS)
278
+ const c = await post('/api/handoff/complete', { sid, origin: location.origin, nonce, googleIdToken: r.idToken })
279
+ if (!c || !c.ok) { signinLog('Google (app): the broker refused the token (' + ((c && c.reason) || 'no answer') + ') — the browser instead'); return null }
280
+ const p = await post('/api/handoff/poll', { sid })
281
+ if (!p || !p.jwt) { signinLog('Google (app): the broker did not hand the session back — the browser instead'); return null }
282
+ tokSet(nonce, { idToken: p.jwt, email: p.email, exp: (Number(jwtPayload(p.jwt).exp) || 0) * 1000 })
283
+ signinLog('Google (app): signed in with the app\'s own sheet')
284
+ return { idToken: p.jwt, email: p.email, ...(typeof p.google === 'string' ? { google: p.google } : {}) }
285
+ } catch (e) { signinLog('Google (app): ' + String((e && e.message) || e).slice(0, 80) + ' — the browser instead'); return null }
286
+ }
287
+
288
+ // A SIGN-IN THAT OUTLIVES THE APP (the owner, 2026-11-23: "lets close this gap anyway"). Where Google's sign-in opens in the browser
289
+ // OUTSIDE the app — the Android app on a phone without Google Play services, the Windows app, iPhone's home-screen app — the system
290
+ // may close the app while the person is in the browser; the sign-in then finished at the broker and was never collected. The wait
291
+ // is kept in stored data (the broker's sid, the nonce, the sign-in key the token is bound to, when it started), its heartbeat
292
+ // refreshed on every round; a restart within BROKER_WAIT_MS of the start picks it up (resumePendingGoogle) and finishes the
293
+ // sign-in — this device's session, as the card would have made it. A heartbeat newer than PENDING_ALIVE_MS = the page that
294
+ // started it is still waiting: it is left alone (two pollers would race for the one answer).
295
+ const PENDING_KEY = 'space:google-pending'
296
+ export const PENDING_ALIVE_MS = 6000
297
+ let _signInKey = null // { nonce, kp } of the sign-in ensureIdentity is prompting for
298
+ const pendingRead = () => { try { const p = JSON.parse(localStorage.getItem(PENDING_KEY) || 'null'); return p && typeof p === 'object' && typeof p.sid === 'string' ? p : null } catch { return null } }
299
+ const pendingWrite = (p) => { try { if (p) localStorage.setItem(PENDING_KEY, JSON.stringify(p)); else localStorage.removeItem(PENDING_KEY) } catch { /* private mode: nothing kept */ } }
300
+ /** → true when the resumed wait finished the sign-in (the device's session is set); false when there was nothing to resume, it was
301
+ * left to its live page, it ended, or it was refused. Polls until the original deadline. */
302
+ export async function resumePendingGoogle ({ poll = null, now = Date.now, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {
303
+ const p = pendingRead()
304
+ if (!p) return false
305
+ if (!(now() - Number(p.started) < BROKER_WAIT_MS) || !p.broker || !p.nonce) { pendingWrite(null); return false }
306
+ // its page may still be waiting (a heartbeat newer than PENDING_ALIVE_MS): wait for it to finish or go quiet — never two pollers
307
+ while (now() - Number((pendingRead() || {}).beat || 0) < PENDING_ALIVE_MS) {
308
+ await sleep(PENDING_ALIVE_MS / 2)
309
+ const cur = pendingRead(); if (!cur || cur.sid !== p.sid) return false // its page finished (or a newer sign-in took over)
310
+ }
311
+ signinLog('Google: picking up the sign-in that was waiting when the app closed (' + Math.round((now() - Number(p.started)) / 1000) + ' s ago)')
312
+ const ask = poll || (() => withTimeout(fetch(p.broker + '/api/handoff/poll', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sid: p.sid }) }).then((x) => x.json()), BROKER_POLL_TIMEOUT_MS))
313
+ while (now() - Number(p.started) < BROKER_WAIT_MS) {
314
+ const cur = pendingRead(); if (!cur || cur.sid !== p.sid) return false // a newer sign-in took over, or it was cleared
315
+ pendingWrite({ ...cur, beat: now() })
316
+ const r = await ask()
317
+ if (r && r.jwt) {
318
+ pendingWrite(null)
319
+ tokSet(p.nonce, { idToken: r.jwt, email: r.email, exp: (Number(jwtPayload(r.jwt).exp) || 0) * 1000 })
320
+ const iss = String(jwtPayload(r.jwt).iss || '')
321
+ const set = p.kp && isOurEmailIss(iss) ? anchorSet({ method: 'email', token: r.jwt, kp: p.kp, email: r.email, exp: Date.now() + 30 * 24 * 3600 * 1000 }) : false
322
+ signinLog('Google: the sign-in from before the restart finished — ' + (set ? 'signed in as ' + r.email : 'kept for its Space (no session key)'))
323
+ return !!set
324
+ }
325
+ if (r && r.ok === false) { pendingWrite(null); signinLog('Google: the resumed sign-in was refused (' + (r.reason || 'no reason') + ')'); return false }
326
+ await sleep(BROKER_POLL_MS)
327
+ }
328
+ pendingWrite(null)
329
+ signinLog('Google: the resumed sign-in never finished (timed out)')
330
+ return false
331
+ }
332
+ // at every start of a page that signs in (the app, the vault), once it has settled; nothing to do in most launches
333
+ try { if (typeof window !== 'undefined' && pendingRead()) setTimeout(() => { resumePendingGoogle().catch(() => {}) }, 1200) } catch { /* no window */ }
334
+
335
+ /** GOOGLE via the broker. → { idToken, email } | null. `onEnd(why)` hears why a wait ended without one: 'blocked' | 'cancelled' |
336
+ * 'closed' | 'refused' | 'timeout'. In the Android app Google's own sheet comes first (nativeGoogleToken, above). */
337
+ export async function brokerGoogleToken({ nonce, broker = brokerUrl(), onEnd = null, watchPopup = true }) {
338
+ if (!broker) return null
339
+ const native = await nativeGoogleToken({ nonce, broker })
340
+ if (native && native.cancelled) { if (onEnd) onEnd('cancelled'); return null }
341
+ if (native) return native
342
+ const sid = [...crypto.getRandomValues(new Uint8Array(18))].map((b) => 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'[b % 64]).join('')
343
+ const e2e = E2E_AT_LOAD
344
+ const url = broker + '/?sid=' + sid + '&origin=' + encodeURIComponent(location.origin) + '&nonce=' + encodeURIComponent(nonce) + (e2e ? '&e2e=1' : '')
345
+ let w = null
346
+ // DESKTOP: open the broker ceremony as a compact CENTERED popup WINDOW that returns focus to the app when it closes
347
+ // (the poll below auto-closes it on success), NOT a full browser tab — a featureless _blank from an installed PWA
348
+ // escapes to the browser's tab strip. MOBILE keeps the EXACT current path ('_blank', no features → a tab, the only
349
+ // option there), so iOS/Android are byte-identical. The handoff is POLLED, so the window kind never affects correctness.
350
+ let target = '_blank', feat = ''
351
+ try {
352
+ if (window.matchMedia && window.matchMedia('(min-width: 700px) and (pointer: fine)').matches) {
353
+ const width = 480, height = 680
354
+ const bx = (window.screenX != null ? window.screenX : window.screenLeft) || 0
355
+ const by = (window.screenY != null ? window.screenY : window.screenTop) || 0
356
+ const bw = window.outerWidth || (window.screen && window.screen.width) || width
357
+ const bh = window.outerHeight || (window.screen && window.screen.height) || height
358
+ const left = Math.max(0, Math.round(bx + (bw - width) / 2))
359
+ const top = Math.max(0, Math.round(by + (bh - height) / 2))
360
+ target = 'witbitzGoogle'; feat = 'popup=yes,width=' + width + ',height=' + height + ',left=' + left + ',top=' + top // named → reuse one window instead of stacking on re-click
361
+ }
362
+ } catch { /* matchMedia/screen probing is best-effort → fall back to the plain tab */ }
363
+ const shell = inNativeShell()
364
+ // THE iPHONE APP: Apple's sign-in sheet over the app (SignInSheet.swift), not Safari — the app keeps running under it, nothing is
365
+ // lost, and no switching back by hand. The poll below collects the sign-in as always; the sheet is closed once it has.
366
+ const sheet = signInSheet(), ctlEarly = { cancelled: false, failed: false, wake: null }
367
+ let inSheet = false
368
+ if (sheet) {
369
+ try {
370
+ Promise.resolve(sheet.open(url)).then((r) => { if (r === 'cancelled') { ctlEarly.cancelled = true; if (ctlEarly.wake) ctlEarly.wake() } }, (e) => { signinLog('Google: the sign-in sheet failed — ' + String((e && e.message) || e).slice(0, 80)); ctlEarly.failed = true; if (ctlEarly.wake) ctlEarly.wake() }) // ⛔ 10·V#2 (pass 10): a sheet that never opened ended the wait at once — it held "Waiting for Google…" for 10 minutes
371
+ inSheet = true; signinLog('Google: the sign-in opened in the app\'s sheet — waiting for it')
372
+ } catch { /* no sheet after all: the browser path below */ }
373
+ }
374
+ if (!inSheet) { try { w = window.open(url, target, feat) } catch { /* popup blocked → the user can retry */ } }
375
+ // ★ THE WINDOWS APP (the owner, 2026-11-16, a new installer): its shell opens every new window in the default browser and answers
376
+ // window.open with null, so "blocked" ended a sign-in that was in fact open in Edge — "Google sign-in didn't work here". In a
377
+ // shell a null window means "opened outside": the wait goes on, as the Android app's always did (its window.open answers).
378
+ if (!inSheet && !w && !shell) { signinLog('Google: the sign-in page could not be opened (popup blocked)'); if (onEnd) onEnd('blocked'); return null }
379
+ if (!inSheet && !w) signinLog('Google: the sign-in page opened in the browser, outside the app — waiting for it')
380
+ const outside = !inSheet && (shell || iosStandalone())
381
+ const ctl = inSheet ? ctlEarly : { wake: null, cancelled: false }
382
+ const card = outside ? brokerWaitCard({ shell, onCancel: () => { ctl.cancelled = true; if (ctl.wake) ctl.wake() } }) : null
383
+ const started = Date.now(), deadline = started + BROKER_WAIT_MS
384
+ // OUTSIDE THE APP the system may close it mid-wait: keep the wait (resumePendingGoogle). A popup or an in-app sheet keeps the page alive.
385
+ const key = _signInKey && _signInKey.nonce === nonce ? _signInKey.kp : null
386
+ const keep = outside ? () => pendingWrite({ sid, nonce, broker, kp: key, started, beat: Date.now() }) : () => {}
387
+ const forget = () => { const cur = pendingRead(); if (cur && cur.sid === sid) pendingWrite(null) }
388
+ keep()
389
+ const closeSheet = () => { if (inSheet) { try { sheet.close() } catch { /* already gone */ } } }
390
+ const ended = (why, code) => { forget(); closeSheet(); if (card) card.close(); signinLog('Google: the wait for the sign-in page ended — ' + why + ' after ' + Math.round((Date.now() - started) / 1000) + ' s'); if (onEnd) onEnd(code); return null }
391
+ const poll = () => withTimeout(fetch(broker + '/api/handoff/poll', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sid }) }).then((x) => x.json()), BROKER_POLL_TIMEOUT_MS)
392
+ let closedAt = 0, pollsSinceClosed = 0, watchClosed = !!w && watchPopup
393
+ while (Date.now() < deadline) {
394
+ await wakeOnReturn(BROKER_POLL_MS, ctl)
395
+ if (ctl.cancelled) return ended('cancelled', 'cancelled')
396
+ if (ctl.failed) return ended('the sign-in sheet did not open', 'blocked')
397
+ keep()
398
+ const r = await poll()
399
+ if (ctl.cancelled) return ended('cancelled', 'cancelled')
400
+ if (r && r.jwt) {
401
+ forget()
402
+ try { if (w && w !== window) w.close() } catch { /* the sheet may already be closed */ }
403
+ closeSheet()
404
+ if (card) card.close()
405
+ const p = jwtPayload(r.jwt)
406
+ tokSet(nonce, { idToken: r.jwt, email: r.email, exp: (Number(p.exp) || 0) * 1000 })
407
+ return { idToken: r.jwt, email: r.email, ...(typeof r.google === 'string' ? { google: r.google } : {}) }
408
+ }
409
+ if (r && r.ok === false) return ended('refused (' + (r.reason || 'no reason') + ')', 'refused') // origin refused / broker error — stop polling
410
+ if (closedAt) pollsSinceClosed++
411
+ else if (watchClosed) {
412
+ let closed = false
413
+ try { closed = w.closed === true } catch { /* cross-origin close probe */ }
414
+ if (closed && outside && Date.now() - started < OUTSIDE_CLOSED_UNTRUSTED_MS) { watchClosed = false; signinLog('Google: the sign-in window reads closed at once — waiting on the sign-in itself') }
415
+ else if (closed) closedAt = Date.now()
416
+ }
417
+ if (closedAt && pollsSinceClosed >= (outside ? 2 : 1) && Date.now() - closedAt >= (outside ? BROKER_CLOSED_GRACE_MS : 3000)) return ended('the sign-in window was closed', 'closed') // a desktop popup: the browser was never paused, 3 s as before
418
+ }
419
+ return ended('no answer (timed out)', 'timeout')
420
+ }
421
+
422
+ // Friendly copy for the backend's machine reasons: startError / verifyError in emailSignIn.js
423
+
424
+ // ── Email-code: OUR OWN OIDC provider (reused from the Kibitz call). A tiny two-step overlay — enter email → enter the
425
+ // 6-digit code we mail — that exchanges the code for an RS256 token carrying the verified email + this device's `nonce`.
426
+ // The server accepts it EXACTLY like a Google token (a second trusted issuer), so ANY email works, not just Google
427
+ // accounts. Caches into the SAME per-nonce store as the Google path → cachedGoogleToken()/the poll loop pick it up
428
+ // unchanged. Returns { idToken, email }; rejects `cancelled` if dismissed.
429
+ // NOT ABOUT A SPACE (no `room`: a restore's "Verify to restore", an account sign-in): the Space-gate sentence ("…on this Space’s
430
+ // list. Anyone with the link can still read.") made no sense there — the iPhone shell's first restore in the simulator, 2026-11-17.
431
+ export const EMAIL_SUB_NO_SPACE = 'We’ll send a 6-digit code to this email to check it’s yours.'
432
+ export async function emailCodeToken({ nonce, room, apiBase = EMAIL_API, copy }) {
433
+ const hit = tokGet(nonce)
434
+ if (hit && hit.exp - Date.now() > FRESH_MS) return { idToken: hit.idToken, email: hit.email }
435
+
436
+ const FIELD = 'box-sizing:border-box;width:100%;padding:12px 13px;border:1px solid var(--line,#ddd);border-radius:11px;background:var(--field,#f4f4f4);color:inherit;font:inherit;font-size:16px;margin:0' // box-sizing INLINE: this dialog also renders in the VAULT document, which has no global border-box reset (the app's `* { box-sizing }` masked the width:100%+padding overflow)
437
+ const PRIMARY = 'box-sizing:border-box;width:100%;border:0;border-radius:13px;padding:13px;background:var(--btn,#111);color:var(--btn-fg,#fff);font:inherit;font-weight:600;font-size:15px;cursor:pointer;margin-top:12px'
438
+ const LINK = 'display:block;margin:12px auto 0;background:none;border:0;color:var(--muted,#888);font-size:13px;cursor:pointer'
439
+
440
+ return new Promise((resolve, reject) => {
441
+ const overlay = document.createElement('div')
442
+ overlay.style.cssText = 'position:fixed;inset:0;z-index:2000;background:rgba(0,0,0,.5);display:flex;align-items:center;justify-content:center;padding:24px'
443
+ overlay.className = 'kbfit' // with the keys up it fits the visible area (space.html), its field above them
444
+ const card = document.createElement('div')
445
+ card.style.cssText = 'background:var(--bg,#fff);color:var(--fg,#111);border:1px solid var(--line,#ddd);border-radius:14px;padding:22px;max-width:340px;width:100%;box-shadow:0 12px 40px rgba(0,0,0,.35)'
446
+ overlay.appendChild(card); document.body.appendChild(overlay)
447
+ let done = false
448
+ const close = () => { try { document.body.removeChild(overlay) } catch { /* gone */ } }
449
+ const finish = (fn) => { if (done) return; done = true; close(); fn() }
450
+ overlay.onclick = (e) => { if (e.target === overlay) finish(() => reject(new Error('cancelled'))) }
451
+
452
+ const stepEmail = () => {
453
+ card.innerHTML =
454
+ '<div style="font-weight:600;font-size:16px;margin-bottom:6px">' + ((copy && copy.title) || 'Email me a code') + '</div>' +
455
+ '<div style="font-size:13px;color:var(--muted,#888);margin-bottom:16px;line-height:1.4">' + ((copy && copy.sub) || (room ? 'We’ll send a 6-digit code to check you’re on this Space’s list. Anyone with the link can still read.' : EMAIL_SUB_NO_SPACE)) + '</div>'
456
+ const inp = document.createElement('input'); inp.type = 'email'; inp.inputMode = 'email'; inp.autocomplete = 'email'; inp.placeholder = 'you@example.com'; inp.style.cssText = FIELD
457
+ inp.setAttribute('data-1p-ignore', ''); inp.setAttribute('data-lpignore', 'true'); inp.setAttribute('data-bwignore', '') // don't let a password manager save this passwordless email step as a (duplicate) login
458
+ try { const known = anchorGet(); if (known && known.email) { inp.value = known.email; inp.select() } } catch { /* */ } // already signed in → pre-fill your own address so opening a verified room is one tap, not a retype (still editable)
459
+ const err = document.createElement('div'); err.style.cssText = 'color:#e5484d;font-size:12.5px;margin-top:8px'
460
+ const send = document.createElement('button'); send.textContent = 'Send code'; send.style.cssText = PRIMARY
461
+ const cancel = document.createElement('button'); cancel.textContent = 'Cancel'; cancel.style.cssText = LINK
462
+ card.appendChild(inp); card.appendChild(err); card.appendChild(send); card.appendChild(cancel)
463
+ inp.focus()
464
+ cancel.onclick = () => finish(() => reject(new Error('cancelled')))
465
+ const submit = async () => {
466
+ const email = String(inp.value || '').trim().toLowerCase()
467
+ if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) { err.textContent = 'Enter a valid email address.'; return }
468
+ { const d = otherDeviceEmail(email); if (d) { err.textContent = refuseOther(d, email, null).message; return } } // one email per device: no code is sent — the banner above the card carries the way out where a screen has one (sync sweep 11-09 #12)
469
+ send.disabled = true; send.textContent = 'Sending…'; err.textContent = ''
470
+ try {
471
+ const { ticket } = await emailStart((path, body) => emailPost(apiBase, path, body), { email, room, nonce })
472
+ stepCode(email, ticket)
473
+ } catch (e) { err.textContent = (e && e.code && e.message) || 'Network error — try again.'; send.disabled = false; send.textContent = 'Send code' }
474
+ }
475
+ send.onclick = submit
476
+ inp.onkeydown = (e) => { if (e.key === 'Enter') { e.preventDefault(); submit() } }
477
+ }
478
+
479
+ const stepCode = (email, ticket) => {
480
+ card.innerHTML =
481
+ '<div style="font-weight:600;font-size:16px;margin-bottom:6px">Enter the code</div>' +
482
+ '<div style="font-size:13px;color:var(--muted,#888);margin-bottom:16px;line-height:1.4">We emailed a 6-digit code to <b></b>. It expires in 10 minutes.</div>'
483
+ card.querySelector('b').textContent = email
484
+ const inp = document.createElement('input'); inp.type = 'text'; inp.inputMode = 'numeric'; inp.autocomplete = 'one-time-code'; inp.maxLength = 6; inp.placeholder = '123456'; inp.style.cssText = FIELD + ';letter-spacing:5px;text-align:center'
485
+ inp.setAttribute('data-1p-ignore', ''); inp.setAttribute('data-lpignore', 'true'); inp.setAttribute('data-bwignore', '') // it's a one-time code, not a login to save
486
+ const err = document.createElement('div'); err.style.cssText = 'color:#e5484d;font-size:12.5px;margin-top:8px'
487
+ const verify = document.createElement('button'); verify.textContent = 'Verify'; verify.style.cssText = PRIMARY
488
+ const back = document.createElement('button'); back.textContent = 'Use a different email'; back.style.cssText = LINK
489
+ card.appendChild(inp); card.appendChild(err); card.appendChild(verify); card.appendChild(back)
490
+ inp.focus()
491
+ back.onclick = () => stepEmail()
492
+ const submit = async () => {
493
+ const code = String(inp.value || '').trim()
494
+ if (!/^\d{4,8}$/.test(code)) { err.textContent = 'Enter the 6-digit code.'; return }
495
+ verify.disabled = true; verify.textContent = 'Verifying…'; err.textContent = ''
496
+ try {
497
+ const v = await emailVerify((path, body) => emailPost(apiBase, path, body), { ticket, code })
498
+ tokSet(nonce, { idToken: v.jwt, email, exp: v.exp })
499
+ finish(() => resolve({ idToken: v.jwt, email }))
500
+ } catch (e) { err.textContent = (e && e.code && e.message) || 'Network error — try again.'; verify.disabled = false; verify.textContent = 'Verify' }
501
+ }
502
+ verify.onclick = submit
503
+ inp.onkeydown = (e) => { if (e.key === 'Enter') { e.preventDefault(); submit() } }
504
+ }
505
+
506
+ stepEmail()
507
+ })
508
+ }
509
+
510
+ /** The Space identity prompt: offers "Sign in with Google" (when a client id is baked) AND "Email me a code", and
511
+ * resolves { idToken, email } from whichever the member completes — so someone WITHOUT a Google account can still be
512
+ * admitted. Both cache per-nonce (→ cachedGoogleToken picks either up). Rejects `cancelled` if dismissed. */
513
+ export async function promptIdentity({ clientId, nonce, room, apiBase = EMAIL_API, titleText, subText }) {
514
+ const hit = tokGet(nonce)
515
+ if (hit && hit.exp - Date.now() > FRESH_MS) return { idToken: hit.idToken, email: hit.email }
516
+ const hasGoogle = !forceBroker() && !!clientId && clientId.indexOf('__') !== 0 // vault surfaces (forceBroker): Google runs ONLY on the auth origin — no in-page GIS
517
+ if (hasGoogle) { try { await loadGis() } catch { /* Google unavailable → email-code only */ } }
518
+ const googleUp = hasGoogle && window.google && window.google.accounts && window.google.accounts.id
519
+
520
+ return new Promise((resolve, reject) => {
521
+ const dark = appIsDark()
522
+ const overlay = document.createElement('div')
523
+ overlay.style.cssText = 'position:fixed;inset:0;z-index:2000;background:rgba(0,0,0,.5);display:flex;align-items:center;justify-content:center;padding:24px'
524
+ overlay.className = 'kbfit' // with the keys up it fits the visible area (space.html), its field above them
525
+ const card = document.createElement('div')
526
+ card.style.cssText = 'background:var(--bg,#fff);color:var(--fg,#111);border:1px solid var(--line,#ddd);border-radius:14px;padding:22px;max-width:340px;width:100%;text-align:center;box-shadow:0 12px 40px rgba(0,0,0,.35)'
527
+ const h = document.createElement('div'); h.textContent = titleText || 'Sign in to this Space'; h.style.cssText = 'font-weight:600;font-size:16px;margin-bottom:6px'
528
+ const sub = document.createElement('div'); sub.textContent = subText || 'Only the people this Space names can read or post here. Sign in with your email to continue.' // reading needs the sign-in too — the old line said anyone with the link could read (owner, 2026-10-15)
529
+ sub.style.cssText = 'font-size:13px;color:var(--muted,#888);margin-bottom:16px;line-height:1.4'
530
+ card.appendChild(h); card.appendChild(sub)
531
+ const brokered = !googleUp && !!brokerUrl() // no in-page GIS on this origin, but the CENTRAL broker can run the ceremony — Google works with ZERO Google-console registration for this origin
532
+ const googleAny = googleUp || brokered
533
+ const btnHost = document.createElement('div'); btnHost.style.cssText = 'display:flex;justify-content:center'
534
+ if (googleAny) { btnHost.style.minHeight = '44px'; card.appendChild(btnHost) }
535
+ const emailBtn = document.createElement('button'); emailBtn.textContent = googleAny ? '✉️ Email me a code instead' : '✉️ Email me a code'
536
+ emailBtn.style.cssText = googleAny
537
+ ? 'margin-top:14px;width:100%;background:none;border:1px solid var(--line,#ddd);color:var(--fg,#111);border-radius:22px;padding:10px 16px;font:inherit;font-size:14px;font-weight:600;cursor:pointer'
538
+ : 'margin-top:2px;width:100%;background:var(--btn,#111);border:0;color:var(--btn-fg,#fff);border-radius:22px;padding:12px 16px;font:inherit;font-size:15px;font-weight:600;cursor:pointer'
539
+ const cancel = document.createElement('button'); cancel.textContent = 'Cancel'; cancel.style.cssText = 'display:block;margin:14px auto 0;background:none;border:none;color:var(--muted,#888);font-size:13px;cursor:pointer'
540
+ card.appendChild(emailBtn); card.appendChild(cancel)
541
+ overlay.appendChild(card); document.body.appendChild(overlay)
542
+
543
+ let done = false
544
+ const close = () => { try { document.body.removeChild(overlay) } catch { /* gone */ } }
545
+ const finish = (fn) => { if (done) return; done = true; try { if (googleUp) window.google.accounts.id.cancel() } catch { /* */ } close(); fn() }
546
+ cancel.onclick = () => finish(() => reject(new Error('cancelled')))
547
+ overlay.onclick = (e) => { if (e.target === overlay) finish(() => reject(new Error('cancelled'))) }
548
+ emailBtn.onclick = () => finish(() => emailCodeToken({ nonce, room, apiBase }).then(resolve, reject))
549
+
550
+ if (googleUp) {
551
+ try {
552
+ window.google.accounts.id.initialize({
553
+ client_id: clientId,
554
+ nonce, // Google echoes this into the token's `nonce`; the server requires it == spkNonce(spk)
555
+ callback: (resp) => {
556
+ const p = jwtPayload(resp && resp.credential)
557
+ const email = String(p.email || '').toLowerCase()
558
+ tokSet(nonce, { idToken: resp.credential, email, exp: (Number(p.exp) || 0) * 1000 })
559
+ finish(() => resolve({ idToken: resp.credential, email }))
560
+ },
561
+ })
562
+ window.google.accounts.id.renderButton(btnHost, { theme: dark ? 'filled_black' : 'outline', size: 'large', text: 'signin_with', shape: 'pill' })
563
+ try { window.google.accounts.id.prompt() } catch { /* One Tap best-effort */ }
564
+ } catch { /* Google init failed → the email-code button still works */ }
565
+ } else if (brokered) {
566
+ // The BROKER Google button: the ceremony runs on the central Google-registered origin in a popup/sheet; the
567
+ // session comes back device-bound via the polled handoff. Styled to read as the primary option, like the GIS pill.
568
+ const gb = document.createElement('button'); gb.id = 'egBrokerGoogle'
569
+ gb.textContent = 'Continue with Google'
570
+ gb.style.cssText = 'width:100%;background:var(--btn,#111);border:0;color:var(--btn-fg,#fff);border-radius:22px;padding:12px 16px;font:inherit;font-size:15px;font-weight:600;cursor:pointer'
571
+ btnHost.appendChild(gb)
572
+ gb.onclick = async () => {
573
+ gb.disabled = true; gb.textContent = 'Waiting for Google…'
574
+ const t = await brokerGoogleToken({ nonce }).catch(() => null)
575
+ if (t) { finish(() => resolve(t)); return }
576
+ gb.disabled = false; gb.textContent = 'Continue with Google' // popup blocked / cancelled / timed out — let them retry or use email
577
+ }
578
+ }
579
+ })
580
+ }
581
+
582
+ // ── ONE login covers ALL your Spaces ─────────────────────────────────────────────────────────────────────────────────
583
+ // Each Space has its own signing key, so it needs its own token. Rather than re-verify per Space, one verification sets
584
+ // a DEVICE SESSION anchor; every other Space's token is then minted SILENTLY: email-code → api/email/refresh (device-key
585
+ // assertion, no new code); Google → One-Tap auto-select. Per-room keys are preserved (the sealed ledger stays
586
+ // unlinkable); only the EMAIL is verified once (~monthly).
587
+ const ANCHOR_KEY = 'space:esession'
588
+ function anchorGet() {
589
+ try { const a = JSON.parse(localStorage.getItem(ANCHOR_KEY) || 'null'); return a && (!a.exp || a.exp > Date.now()) ? a : null } catch { return null }
590
+ }
591
+ // ⛔ ONE EMAIL PER DEVICE (the owner, 2026-11-08: "C" — docs/state-machines.md D1). A device signs in as ONE address. A sign-in made for
592
+ // one verified Space wrote whatever address it verified into this device-wide slot: the next Spaces renewed silently as that
593
+ // address, Settings said "Signed in as" it, and the account guard (accountOwner.js) stopped every backup and index push because the
594
+ // email no longer matched the device's owner. Now a different address is refused — at the email card before any code is sent,
595
+ // for a Google sign-in, and here — with how to change it: sign out first. The device's email = the slot's, else its owner mark.
596
+ export function deviceEmail () {
597
+ try { const a = JSON.parse(localStorage.getItem(ANCHOR_KEY) || 'null'); const e = a && typeof a.email === 'string' ? a.email.trim().toLowerCase() : ''; if (e) return e } catch { /* */ }
598
+ try { return deviceOwner() || '' } catch { return '' }
599
+ }
600
+ /** The device's email when `email` is ANOTHER one (refused), else ''. */
601
+ export function otherDeviceEmail (email) { const d = deviceEmail(), e = String(email || '').trim().toLowerCase(); return d && e && d !== e ? d : '' }
602
+ // WHERE TO CHANGE IT (sync sweep 11-09 #6, #12): the regular app's row is "Log out", not "Sign out"; a screen with no Settings (the
603
+ // vault's first screens) registers its own way out — setOtherAccountAction({ label, onClick }) — and the words name that instead.
604
+ // `when` (optional): the action holds only while it says so (the vault: while no account is held).
605
+ let _otherAction = null
606
+ export function setOtherAccountAction (a) { _otherAction = a && a.label && typeof a.onClick === 'function' ? { label: String(a.label), onClick: a.onClick, when: typeof a.when === 'function' ? a.when : null } : null }
607
+ const otherAction = () => { try { return _otherAction && (!_otherAction.when || _otherAction.when()) ? _otherAction : null } catch { return null } }
608
+ export const otherEmailText = (d, e, how = (otherAction() || {}).label) => how
609
+ ? `This device is signed in as ${d}. To use ${e}, tap “${how}” first — one email per device.`
610
+ : `This device is signed in as ${d}. To use ${e}, log out first (Settings → Log out) — one email per device.`
611
+ // ⛔ A REFUSED ADDRESS, ONE WAY (sync sweep 11-09 #6). Its token was cached under this key's nonce BEFORE the refusal (the Google
612
+ // callback keeps what it gets — tokGet now drops such a token), and every caller swallowed the refusal (Settings, restore,
613
+ // @username, the vault's Create), so the person saw nothing, or "Sign-in didn't work". Now Google stops picking that account by
614
+ // itself, and the reason is shown HERE, once, for every caller.
615
+ function refuseOther (d, email, nonce) {
616
+ if (nonce) tokDel(nonce)
617
+ try { window.google.accounts.id.disableAutoSelect() } catch { /* no Google on this page */ }
618
+ const e = new Error(otherEmailText(d, email)); e.code = 'other_account'
619
+ try { signinLog('refused ' + email + ' — this device is signed in as ' + d) } catch { /* */ }
620
+ try { banner(e.message, { id: 'other-account', kind: 'error', action: otherAction() }) } catch { /* no page to show it on */ }
621
+ return e
622
+ }
623
+ /** → true when the device's sign-in now holds `a`; false when it was refused (another address) or could not be written. */
624
+ function anchorSet(a) {
625
+ if (a && a.email && otherDeviceEmail(a.email)) return false // never another address over the device's (the cards below refuse first; this is the last word)
626
+ try { localStorage.setItem(ANCHOR_KEY, JSON.stringify(a)) } catch { return false /* private mode */ } try { if (a && a.token && typeof dispatchEvent === 'function') dispatchEvent(new CustomEvent('wb-identity')) } catch { /* */ } return true } // a new sign-in: its hints are fetched in the background (identityPrefetch.js)
627
+
628
+ // Refresh an email-code session to a NEW key WITHOUT re-emailing: sign a fresh challenge with the OLD key (proof of the
629
+ // verifying device) and present the still-valid token. Returns { idToken, email } or null (→ caller falls back).
630
+ // WHY THE SIGN-IN CARD CAME BACK (the owner, 2026-10-15: "I keep getting this. It looks like the token doesn't survive"):
631
+ // the boot log (Settings → 5 taps on the build line) says, each time the card is about to show, what the silent path had.
632
+ let _refreshWhy = ''
633
+ // its OWN log ('space:signinlog', 30 lines), shown first in the crash-trail viewer — the shared boot log turns over in seconds
634
+ export function signinLog (m) { try { const k = 'space:signinlog', a = JSON.parse(localStorage.getItem(k) || '[]'); a.push(new Date().toLocaleString() + ' ' + m); while (a.length > 30) a.shift(); localStorage.setItem(k, JSON.stringify(a)) } catch { /* */ } }
635
+ async function refreshEmailToken({ apiBase, token, kpOld, newNonce, throwOnRefusal }) { // emailSignIn.js — the SDK renews the same way
636
+ _refreshWhy = ''
637
+ const r = await emailRefresh(async (path, body) => { const out = await emailPost(apiBase, path, body); if (!out || !out.ok) _refreshWhy = String((out && (out.reason || out.error)) || 'no answer').slice(0, 60); return out }, { token, kpOld, newNonce, throwOnRefusal })
638
+ if (!r) { if (!_refreshWhy) _refreshWhy = 'failed before asking'; return null }
639
+ tokSet(newNonce, { idToken: r.jwt, email: r.email, exp: r.exp })
640
+ return { idToken: r.jwt, email: r.email }
641
+ }
642
+
643
+ // Google One-Tap auto-select — re-issue a token for `nonce` WITHOUT a full sign-in card, for a returning signed-in user.
644
+ // Resolves { idToken, email } on a silent success, or null (not signed in / cooldown / dismissed) → caller prompts.
645
+ async function silentGoogleToken({ clientId, nonce }) {
646
+ if (!clientId || clientId.indexOf('__') === 0) return null
647
+ try { await loadGis() } catch { return null }
648
+ return new Promise((resolve) => {
649
+ let done = false; const fin = (v) => { if (!done) { done = true; resolve(v) } }
650
+ try {
651
+ window.google.accounts.id.initialize({
652
+ client_id: clientId, nonce, auto_select: true, cancel_on_tap_outside: false,
653
+ callback: (resp) => {
654
+ const p = jwtPayload(resp && resp.credential); const email = String(p.email || '').toLowerCase()
655
+ tokSet(nonce, { idToken: resp.credential, email, exp: (Number(p.exp) || 0) * 1000 })
656
+ fin({ idToken: resp.credential, email })
657
+ },
658
+ })
659
+ window.google.accounts.id.prompt((n) => { try { if ((n.isNotDisplayed && n.isNotDisplayed()) || (n.isSkippedMoment && n.isSkippedMoment())) fin(null) } catch { /* */ } })
660
+ setTimeout(() => fin(null), 3500) // no callback in time → give up silently
661
+ } catch { fin(null) }
662
+ })
663
+ }
664
+
665
+ // Exchange a freshly-verified GOOGLE token for OUR OWN 30-day refreshable session (POST /api/email/adopt). This is what
666
+ // gives Google the SAME "one login covers all Spaces" smoothness the email-code path has: afterwards, every other Space
667
+ // re-mints SILENTLY via /api/email/refresh (a device-key proof) instead of leaning on Google's 1-hour tokens + flaky
668
+ // One-Tap. Sets an EMAIL anchor + caches the token for `nonce`, and returns { idToken, email } — OUR token, bound to
669
+ // THIS key. Returns null on any failure → the caller keeps the Google token + a Google anchor (graceful, no regression).
670
+ async function adoptGoogleSession({ apiBase, googleIdToken, nonce, kp, email }) {
671
+ try {
672
+ const r = await emailPost(apiBase, '/api/email/adopt', { googleIdToken, nonce }) // an origin with no email stack (app.witbitz.chat) → the broker's /api/relay/adopt
673
+ if (!r || !r.ok || !r.jwt) return null
674
+ const p = jwtPayload(r.jwt); const em = String(p.email || email || '').toLowerCase()
675
+ if (otherDeviceEmail(em)) return null // never a session for another address (its callers refuse first)
676
+ tokSet(nonce, { idToken: r.jwt, email: em, exp: (Number(p.exp) || 0) * 1000 })
677
+ anchorSet({ method: 'email', token: r.jwt, kp, email: em, exp: Date.now() + 30 * 24 * 3600 * 1000 })
678
+ return { idToken: r.jwt, email: em }
679
+ } catch { return null }
680
+ }
681
+
682
+ const OUR_EMAIL_ISS = 'https://witbitz-spaces.pages.dev' // our own email-code issuer (refreshable); Google/kibitz are not
683
+ // A vault reached by its CUSTOM domain mints under its Pages project's name (spaces.witbitz.chat → https://witbitz-vault-prod
684
+ // .pages.dev, measured 2026-10-03; a tenant vault → witbitz-vault-<tenant>.pages.dev): neither OUR_EMAIL_ISS nor
685
+ // location.origin, so the anchor was never kept and every sign-in-token action on the vault app asked for the code again.
686
+ // Bookkeeping, not trust — this only decides whether THIS device keeps its own token for silent refresh.
687
+ const VAULT_ISS = /^https:\/\/witbitz-vault-[a-z0-9][a-z0-9-]{0,40}\.pages\.dev$/
688
+ export const isOurEmailIss = (iss, origin = (typeof location !== 'undefined' ? location.origin : '')) => !!iss && (iss === OUR_EMAIL_ISS || iss === origin || VAULT_ISS.test(iss))
689
+
690
+ /** Get a token for THIS device key (nonce = spkNonce(kp.pub)) with the LEAST friction: cached → silent (refresh the
691
+ * email session, or Google One-Tap) → full prompt. Records/reuses a device session anchor so opening the NEXT Space
692
+ * doesn't re-verify. `kp` is this Space's signing keypair. Returns { idToken, email }; rejects `cancelled` if dismissed. */
693
+ export async function ensureIdentity({ clientId, nonce, kp, room, apiBase = EMAIL_API, silentOnly = false, promptCopy, forcePrompt = false, throwOnRefusal = false }) {
694
+ // ★ forcePrompt ALSO skips the cached token (the owner, 2026-10-22: signed in to a verified Space with the wrong Gmail,
695
+ // then "Use another email" signed them in as that same Gmail again — the card was never shown: the cached token, then
696
+ // the saved session's silent renewal, answered first). A person asking for the card gets the card.
697
+ if (forcePrompt) { clearGoogleToken(nonce); try { window.google.accounts.id.disableAutoSelect() } catch { /* no Google on this page */ } }
698
+ const hit = tokGet(nonce)
699
+ if (hit && hit.exp - Date.now() > FRESH_MS) return { idToken: hit.idToken, email: hit.email }
700
+
701
+ // SILENT — one prior verification covers every Space. `forcePrompt` SKIPS both silent paths (anchor refresh + Google
702
+ // auto-select): a CREATE-account flow must always SHOW the identity step (email in the flow) — silently reusing an
703
+ // existing session would mint the wrong account (esp. a per-tenant account, which must be a deliberate act).
704
+ const anchor = anchorGet()
705
+ if (!forcePrompt && anchor && anchor.method === 'email' && anchor.token && anchor.kp) {
706
+ const r = await refreshEmailToken({ apiBase, token: anchor.token, kpOld: anchor.kp, newNonce: nonce, throwOnRefusal })
707
+ // SLIDING session: re-anchor on every successful refresh (fresh token + this Space's key + a new 30-day window), so
708
+ // an active user — opening any Space within 30 days — never does a full login again; only 30 days IDLE lapses it.
709
+ if (r) { anchorSet({ method: 'email', token: r.idToken, kp, email: r.email, exp: Date.now() + 30 * 24 * 3600 * 1000 }); return r }
710
+ }
711
+ // Google One-Tap is NOT a truly-silent path: `auto_select` can't complete without UI on iOS Safari (and when the
712
+ // Google login was never adopted into our own refreshable session, it recurs). So a boot/background caller (silentOnly)
713
+ // must SKIP it — otherwise "enroll silently on boot" pops the Google nudge on every launch. Only the email-refresh
714
+ // above is genuinely silent (no Google contact); a Google-anchored device simply enrolls on its next real gated auth.
715
+ if (!forcePrompt && !silentOnly && !forceBroker() && clientId && clientId.indexOf('__') !== 0) { // vault surfaces (forceBroker): no in-page One-Tap either — all Google runs on the auth origin
716
+ const g = await silentGoogleToken({ clientId, nonce })
717
+ { const d = g && otherDeviceEmail(g.email); if (d) throw refuseOther(d, g.email, nonce) } // One-Tap picked another address: refused like the card (sync sweep 11-09 #6 — it was adopted and its token returned)
718
+ if (g) {
719
+ const adopted = await adoptGoogleSession({ apiBase, googleIdToken: g.idToken, nonce, kp, email: g.email })
720
+ if (adopted) return adopted // Google → our refreshable session; the NEXT Space slides silently via /refresh
721
+ anchorSet({ method: 'google', email: g.email, exp: Date.now() + 30 * 24 * 3600 * 1000 }); return g // adopt unavailable → keep Google (no regression)
722
+ }
723
+ }
724
+
725
+ try {
726
+ const why = forcePrompt ? 'asked for' : !anchor ? 'no saved session on this device' : anchor.method !== 'email' ? 'the saved session is ' + anchor.method + ' (no silent renewal)'
727
+ : !anchor.token ? 'the saved session has no token' : !anchor.kp ? 'the saved session has no key' : 'the renewal was refused: ' + (_refreshWhy || '?')
728
+ signinLog((silentOnly ? 'quiet renewal failed' : 'sign-in card') + ' for ' + String(room || '').slice(-6) + ' — ' + why + (anchor && anchor.exp ? ' · session until ' + new Date(anchor.exp).toISOString().slice(0, 10) : '') + (anchor && anchor.email ? ' · ' + anchor.email : ''))
729
+ } catch { /* */ }
730
+ if (silentOnly) return null // boot/background: no full card AND (per above) no Google One-Tap — never phone Google to enroll
731
+ _signInKey = { nonce, kp } // a browser sign-in outside the app keeps this key with its pending wait (rememberPending, below)
732
+
733
+ // Full prompt — first login on this device, or the session lapsed. Record the anchor for next time.
734
+ // With a Google client id → the choice card (Google + email). Email-ONLY (onboarding register, no clientId) → straight
735
+ // to the email field, no intermediate "Email me a code" tap, with the caller's onboarding copy.
736
+ const t = (clientId || brokerUrl())
737
+ ? await promptIdentity({ clientId, nonce, room, apiBase, titleText: promptCopy && promptCopy.title, subText: promptCopy && promptCopy.sub }) // brokerUrl(): even with NO client id on this origin, the choice card offers Google via the central broker
738
+ : await emailCodeToken({ nonce, room, apiBase, copy: promptCopy })
739
+ { const d = otherDeviceEmail(t && t.email); if (d) throw refuseOther(d, t.email, nonce) } // a Google sign-in as another address: refused, nothing kept — not even its cached token
740
+ try {
741
+ const iss = String(jwtPayload(t.idToken).iss || '')
742
+ // "Ours" = the refreshable email-code token. The legacy/default issuer is the main-app origin (OUR_EMAIL_ISS), but a
743
+ // branded/vaulted deployment mints its OWN issuer = ITS origin (EMAIL_ISSUER env; how SPACE_OIDC_ISSUERS trusts it).
744
+ // Only matching the hardcoded main origin silently DROPPED the anchor on such deployments — the account was created
745
+ // but currentAnchor() stayed null, so the framed app's identityGet got nothing and Settings showed "Login".
746
+ if (isOurEmailIss(iss)) {
747
+ anchorSet({ method: 'email', token: t.idToken, kp, email: t.email, exp: Date.now() + 30 * 24 * 3600 * 1000 })
748
+ } else if (iss.indexOf('accounts.google') >= 0) {
749
+ // Adopt the Google login into OUR refreshable session so it, too, is one-login-covers-all. Fall back to a Google
750
+ // anchor (today's behavior) if /adopt is unavailable — no regression.
751
+ const adopted = await adoptGoogleSession({ apiBase, googleIdToken: t.idToken, nonce, kp, email: t.email })
752
+ if (adopted) return adopted
753
+ anchorSet({ method: 'google', email: t.email, exp: Date.now() + 30 * 24 * 3600 * 1000 })
754
+ }
755
+ } catch { /* anchor is best-effort */ }
756
+ return t
757
+ }
758
+
759
+ /** RENEW THIS KEY'S SIGN-IN SO IT NAMES ITS APP (docs/device-gate-design.md § 12.1): a Space refused the token as naming no app
760
+ * (`pass: app_unnamed` — one minted before `asc`, or a raw Google token kept when /adopt was unavailable). Quietly, never a card:
761
+ * a raw Google token is adopted into our session now; ours is renewed through the saved session (/refresh adds `asc`). On
762
+ * nothing better, the token it had is kept. → { idToken, email } | null */
763
+ export async function renewIdentity({ clientId, nonce, kp, room, apiBase = EMAIL_API }) {
764
+ const hit = tokGet(nonce)
765
+ clearGoogleToken(nonce)
766
+ let t = null
767
+ try {
768
+ if (hit && hit.idToken && String(jwtPayload(hit.idToken).iss || '').indexOf('accounts.google') >= 0) t = await adoptGoogleSession({ apiBase, googleIdToken: hit.idToken, nonce, kp, email: hit.email })
769
+ if (!t) t = await ensureIdentity({ clientId, nonce, kp, room, apiBase, silentOnly: true, throwOnRefusal: true })
770
+ } catch (err) { if (err?.status === 401 || err?.status === 403) throw err; t = null }
771
+ if (!t && hit) tokSet(nonce, hit)
772
+ return t || null
773
+ }
774
+
775
+ /** Sign out THIS device: drop every cached/persisted identity TOKEN + the device session anchor, and stop Google
776
+ * One-Tap auto-select (so it won't silently sign you back in). The signing keys, your name, and your Spaces list are
777
+ * the app's to clear (space.html) — this handles only the auth identity. After this, the next gated op re-verifies. */
778
+ export function signOut() {
779
+ _cache.clear()
780
+ try { for (let i = localStorage.length - 1; i >= 0; i--) { const k = localStorage.key(i); if (k && (k.indexOf('space:tok:') === 0 || k === ANCHOR_KEY)) localStorage.removeItem(k) } } catch { /* */ }
781
+ try { if (window.google && window.google.accounts && window.google.accounts.id) window.google.accounts.id.disableAutoSelect() } catch { /* */ }
782
+ try { localStorage.removeItem('space:myusers'); localStorage.removeItem('space:username') } catch { /* */ } // ownIdentity.js: another account must not inherit this one's side of the transcript
783
+ }
784
+
785
+ /** The current device identity from the session anchor, or null — so the UI can show "Signed in as …" and choose
786
+ * between Sign in / Sign out. A verified email/Google identity exists on this device iff this returns non-null. */
787
+ export function identity() { const a = anchorGet(); return a ? { email: a.email || '', method: a.method } : null }
788
+ // The FULL device anchor (token + device kp + email) — so a TOP-LEVEL sign-in (the vault) can hand the identity down to a
789
+ // framed app that can't run Google/FedCM/email-overlay itself. currentAnchor() reads it; adoptAnchor() records one received.
790
+ export function currentAnchor() { return anchorGet() }
791
+ export function adoptAnchor(a) {
792
+ try {
793
+ if (!(a && a.method && a.email)) return false
794
+ if (a.token || a.method === 'google') return anchorSet(a) // full session (or Google) — adopt as-is; false when refused (another address — sync sweep 11-09 #13: "Linked" under another sign-in)
795
+ // TOKEN-LESS email anchor: a VERIFIED ADDRESS recorded without a session (noteVerifiedEmail — e.g. a gate-factor
796
+ // restore leg that couldn't mint the jwt). Adopt it for IDENTITY/display + prefill — without this, the vault knew
797
+ // the email but the framed app rejected the handed-down anchor and Settings showed "Login" as if signed out.
798
+ // Never DOWNGRADE: an existing token-ful anchor (silent refresh works) must not be replaced by a token-less one.
799
+ if (a.method === 'email') { const cur = anchorGet(); if (cur && cur.token) return false; return anchorSet({ method: 'email', email: a.email, exp: a.exp || (Date.now() + 30 * 24 * 3600 * 1000) }) }
800
+ } catch (e) { /* */ }
801
+ return false
802
+ }
803
+
804
+ /** Record a verified email as this device's identity WITHOUT a fresh login round-trip. Used after the recovery EMAIL
805
+ * factor (code + email restore), which already proved control of this email via a mailed 6-digit code — so the user IS
806
+ * logged in and shouldn't be asked to "verify email" again. There's no idToken/kp here, so the first time an
807
+ * email-GATED Space needs a cryptographic proof, ensureIdentity() falls through to a normal (silent Google / email-code)
808
+ * verification and upgrades the anchor. For the UI + Sign-in/Sign-out state, this is the identity. */
809
+ export function noteVerifiedEmail(email) {
810
+ const e = String(email || '').trim().toLowerCase()
811
+ if (!e) return
812
+ anchorSet({ method: 'email', email: e, exp: Date.now() + 30 * 24 * 3600 * 1000 })
813
+ }