@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
@@ -0,0 +1,521 @@
1
+ // deviceAttest.js — THE DEVICE HALF of the attested client (docs/the-attested-client.md § The wire). A native shell
2
+ // (android/attested-client) exposes ONE small bridge, `window.WitbitzAttest`, and this module turns it into what a turn
3
+ // needs: a fresh room challenge + a platform assertion bound to it and to the member's signing key.
4
+ //
5
+ // bridge.platform() → 'android' | 'ios' | 'macos' | 'windows' | 'clouddevice' (the cloud device's enclave, cloud-device/attestBridge.mjs) bridge.keyId() → the enrolled hardware key's id, or ''
6
+ // ('macos': the Mac app's App Attest, macOS 27+ — the iPhone's shapes, its own platform name)
7
+ // bridge.activate(credential, secret) → JSON { secret } (Windows only: enrolment's second step, docs/windows-attestation.md)
8
+ // bridge.enroll(bound) → JSON { keyId, chain } (Android: a NEW Keystore key attested to `bound`; its X.509 chain)
9
+ // bridge.sign(bound) → base64 signature (ECDSA by that key over the UTF-8 bytes of `bound`)
10
+ //
11
+ // `bound` = bindHash(spk, chal) — the SAME value agent/attestation.mjs recomputes (canon JSON, SHA-256, base64url), so the
12
+ // hardware signature covers exactly what the server checks. Enrollment happens ONCE per device key (op 'attest-enroll',
13
+ // clientAttestVerifiers.mjs) and is remembered; a server answer of `device_not_enrolled` forgets it, so the next send
14
+ // enrolls a fresh key. Without a bridge, or before the first poll has brought a challenge, a turn goes out unattested —
15
+ // the server decides whether the room requires more (rooms without `requireAttestation` never notice this module).
16
+ //
17
+ // This is NOT the client-release attestation (`clientAttestation` on reads, spaceClient.setAttestProvider): that one says
18
+ // "this page is a known build"; this one says "this signing key lives in this genuine device's hardware".
19
+ const BRIDGE = 'WitbitzAttest'
20
+ const RETRY_MS = 10 * 60_000 // after a failed enrollment, do not try again on every send
21
+ // A "NO" TO THE ADMINISTRATOR PROMPT (or the device's own refusal) holds for a DAY against every automatic proof (state machines
22
+ // pass 9, X#5): it lapsed with RETRY_MS, and the next automatic read of an attested Windows room put the prompt up again every ten
23
+ // minutes. Not every surface that shows this refusal has a Retry — a refused read is a toast, the attested-backup pull and the key
24
+ // backup show nothing, an SDK app's are its builder's — so it is not final; the person's own Retry (retryNow({ person: true }))
25
+ // still asks at once.
26
+ const DECLINED_MS = 24 * 3600_000
27
+ const MEMO_KEY = 'attest:device'
28
+
29
+ /** The native bridge, when the page runs inside the attested shell; null in a browser. */
30
+ export function deviceBridge (w = globalThis) {
31
+ const b = w && w[BRIDGE]
32
+ return b && typeof b.sign === 'function' && typeof b.enroll === 'function' ? b : null
33
+ }
34
+
35
+ // canon + bindHash: byte-for-byte the agent's (agent/attestation.mjs) — held equal by spaces/test/deviceAttest.test.mjs.
36
+ function canon (o) {
37
+ if (o === null || typeof o !== 'object') return JSON.stringify(o)
38
+ if (Array.isArray(o)) return '[' + o.map(canon).join(',') + ']'
39
+ return '{' + Object.keys(o).sort().map((k) => JSON.stringify(k) + ':' + canon(o[k])).join(',') + '}'
40
+ }
41
+ const b64url = (u8) => { let s = ''; for (const b of u8) s += String.fromCharCode(b); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
42
+ export async function bindHash (spk, challenge) {
43
+ const bytes = new TextEncoder().encode(canon({ spk: spk || null, challenge: String(challenge || '') }))
44
+ return b64url(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)))
45
+ }
46
+
47
+ // The latest server challenge per room, as the polls bring it (spaceClient poll/pollSealed answer `challenge`), WITH when it came:
48
+ // the server takes a challenge for 120 s, so one older than CHAL_FRESH_MS is not offered — a held send, or a continuation for a room
49
+ // no longer polled, would bind a stale one and be refused "challenge stale" (state machines E#3). The callers fetch a fresh one when
50
+ // challengeFor answers null (space.js: a pollSealed before the turn).
51
+ export const CHAL_FRESH_MS = 90_000
52
+ const challenges = new Map()
53
+ export function noteChallenge (room, r) { const c = r && r.challenge; if (room && typeof c === 'string' && c) challenges.set(room, { chal: c, at: Date.now() }) }
54
+ export const challengeFor = (room, t = Date.now()) => { const e = challenges.get(room); return e && t - e.at <= CHAL_FRESH_MS ? e.chal : null }
55
+ // A K_att step's challenge is the SENTINEL's, not a room's: the enrol op (spaceHandler attest-enroll) checks a ROOM challenge, so an
56
+ // enrolment started from one is refused, and its pause held every waiting caller (E#4). A device enrols from a Space or a backup.
57
+ const enrollableScope = (room) => enclaveOfScope(room) !== 'sentinel'
58
+
59
+ const memoryStorage = () => { const m = new Map(); return { getItem: (k) => (m.has(k) ? m.get(k) : null), setItem: (k, v) => { m.set(k, String(v)) }, removeItem: (k) => { m.delete(k) } } }
60
+
61
+ /** makeDeviceAttest({ bridge, client, storage, now, log }) → { attestFor({ room, spk }), noteAnswer(r), enrolledKeyId() }.
62
+ * `client.attestEnroll({ room, chal, spk, enroll })` is spaceClient's op 'attest-enroll'. */
63
+ // enclaveFor(room) → 'turn' | 'sentinel' | null: which ENCLAVE will check this proof — a Windows key is activated by each enclave itself
64
+ // (agent/winActivation.mjs; docs/windows-attestation.md § Enclaves), once, before its first proof there. Default: from the scope alone.
65
+ export const enclaveOfScope = (room) => (/^attkey:/.test(String(room)) ? 'sentinel' : /^confidential-[a-z-]*backup:/.test(String(room)) ? 'turn' : null)
66
+ // locks: navigator.locks — the room page and a warmed lane panel are two documents with one memo and one TPM key (E#1)
67
+ // sleep: the wait between step-2 retries (a test passes an instant one)
68
+ const isRefusal = (r) => !!r && r.status >= 400 && r.status < 500 && r.status !== 408 && r.status !== 429 // the server SAID no; else the answer was lost
69
+ // build: this app build's id (space.js APP_BUILD) — AN ANDROID KEY IS MADE AGAIN AFTER AN UPDATE. Android writes the app's versionCode
70
+ // into a key's attestation when the key is MADE and never again, so a phone updated since kept proving the version it had then (the
71
+ // owner's phone, 2026-11-19: on 0.1.3, its key from version 2 — the device check said "version 2 is not an approved release").
72
+ // The memo names the build that made the key; another build enrols a new one (silent on Android). '' / the unstamped placeholder
73
+ // (dev, tests, the SDK) → never. enrolFrom(): → { room, spk } | null — a Space this page is in, for "Verify this device" to enrol from.
74
+ export const PI_EVERY_MS = 29 * 60_000 // a check every 29 minutes (the owner, 2026-11-22), under the server's 30-minute verdict (agent/playIntegrity.mjs VERDICT_MS)
75
+ const PI_BACKOFF_MIN_MS = 60_000, PI_BACKOFF_MAX_MS = 10 * 60_000
76
+ // the longest the shell's ask can take (PlayIntegrity.kt: a request 30 s, a fresh provider 60 s, the request again 30 s) and a margin
77
+ export const PI_ASK_STALE_MS = 150_000
78
+ export function makeDeviceAttest ({ bridge: bridgeOpt = deviceBridge(), client, storage = null, now = () => Date.now(), log = () => {}, enclaveFor = enclaveOfScope, locks = undefined, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), build = '', enrolFrom = null, freshChallenge = null } = {}) { // freshChallenge(room) → a fresh challenge from that Space (a poll), for the verify step
79
+ const BUILD = typeof build === 'string' && build && !/^__/.test(build) ? build : ''
80
+ // ONE ENROLMENT / ACTIVATION PER DEVICE, across documents (E#1): each document's bridge knows only the key IT enrolled, and each
81
+ // TPM Enroll replaces the one key — two documents enrolling in turn re-enrolled each other on every attested send (an
82
+ // administrator prompt each). Held under a lock, the memo re-read once it is held: what another document did meanwhile counts.
83
+ const withLock = (name, fn) => {
84
+ const l = locks !== undefined ? locks : (globalThis.navigator && globalThis.navigator.locks)
85
+ return l && typeof l.request === 'function' ? l.request(name, fn) : fn()
86
+ }
87
+ // `bridge` may be a FUNCTION, asked at each use (a native shell's bridge may appear after this was made).
88
+ const getBridge = () => { try { return typeof bridgeOpt === 'function' ? bridgeOpt() : bridgeOpt } catch { return null } }
89
+ const store = storage || (() => { try { return globalThis.localStorage || memoryStorage() } catch { return memoryStorage() } })()
90
+ const readMemo = () => { try { return JSON.parse(store.getItem(MEMO_KEY) || 'null') || {} } catch { return {} } }
91
+ const writeMemo = (m) => { try { store.setItem(MEMO_KEY, JSON.stringify(m)) } catch { /* private mode: enrollment is simply re-done next launch */ } }
92
+ const platform = () => { try { return String(getBridge().platform ? getBridge().platform() : 'android') } catch { return 'android' } }
93
+ /** An Android key another build of the app made (or one from before the memo named its build): its attestation names an older version. */
94
+ const outdated = (m) => !!BUILD && platform() === 'android' && !!(m && m.keyId) && m.build !== BUILD
95
+ let lastWhy = ''
96
+ // Play Integrity's pace (integrityDueFor): when a token last went, Google's back-off, the server's ask, one ask at a time
97
+ const isHidden = () => { try { return typeof document !== 'undefined' && document.visibilityState === 'hidden' } catch { return false } }
98
+ const pi = { askedHidden: false, lastAt: -Infinity, force: false, inflight: false, inflightAt: 0, lastBefore: -Infinity, gen: 0, skipSaidAt: -Infinity, backoffUntil: 0, backoffMs: PI_BACKOFF_MIN_MS }
99
+
100
+ /** Google Play's integrity token for a request bound to `bound` (requestHash = base64url SHA-256 of its UTF-8 bytes — the server's
101
+ * playIntegrity.requestHashOf), or '' (no such bridge, or Play said no — the reason goes to the log). */
102
+ async function integrityFor (bound) {
103
+ const b = getBridge()
104
+ if (!b || typeof b.integrity !== 'function') return '' // (called as getBridge().integrity: spaces/test/androidShell.test.mjs pins every bridge call to the Kotlin)
105
+ if (now() < pi.backoffUntil) { log('attest: not asked — Play said too many requests; ' + Math.round((pi.backoffUntil - now()) / 1000) + ' s of the back-off left'); return '' } // Google said "too many requests": wait it out (below)
106
+ try {
107
+ const d = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(String(bound))))
108
+ const h = btoa(String.fromCharCode(...d)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
109
+ let r = {}; try { r = JSON.parse(String((await getBridge().integrity(h)) || '{}')) } catch { r = {} }
110
+ if (r && typeof r.token === 'string' && r.token) { pi.backoffMs = PI_BACKOFF_MIN_MS; return r.token }
111
+ const err = String((r && r.error) || 'no answer')
112
+ // -8 TOO_MANY_REQUESTS (the owner's phone, 2026-11-20 — it asked on every read): back off, doubling to 10 min, never hammer
113
+ if (/^-8\b|TOO_MANY_REQUESTS|too many requests/i.test(err)) { pi.backoffUntil = now() + pi.backoffMs; log('attest: Play Integrity throttled — next try in ' + Math.round(pi.backoffMs / 1000) + ' s'); pi.backoffMs = Math.min(PI_BACKOFF_MAX_MS, pi.backoffMs * 2) }
114
+ else log('attest: no Play Integrity token: ' + err.slice(0, 120))
115
+ } catch (e) { log('attest: Play Integrity failed: ' + String((e && e.message) || e).slice(0, 120)) }
116
+ return ''
117
+ }
118
+ // ONE TOKEN EVERY 29 MINUTES (owner, 2026-11-20: "B"; 2026-11-22: "A check every 29 minutes"; agent/playIntegrity.mjs checkIntegrityKept): the
119
+ // server keeps a passing verdict for this key 30 minutes and a request without a token stands on it. So a token goes with the first attested request once
120
+ // PI_EVERY_MS has passed since the last one (or at once when the server answered integrity_required), and only one is asked at a time.
121
+ // ⛔ THE OWNER'S PHONE, 2026-11-24 07:11 UTC: back after 49 minutes in the background, 118 attested requests in a minute went with
122
+ // NO token and the boot log held no `attest:` line — every failed ask writes one, so Play was never asked, and nothing said why.
123
+ // Now: an ask that has not answered in PI_ASK_STALE_MS no longer holds every later request back (the one-at-a-time flag was the
124
+ // only silent way to skip a due token), and each ask, each token and each due-but-skipped request is in the boot log.
125
+ async function integrityDueFor (bound, requireIntegrity = false) {
126
+ // Another request's token is bound to its challenge. A challenged read waits
127
+ // for that ask to finish, then requests its own token under the normal backoff.
128
+ if (requireIntegrity && pi.inflight && pi.pending) {
129
+ const left = PI_ASK_STALE_MS - (now() - pi.inflightAt)
130
+ if (left > 0) {
131
+ let timer
132
+ try { await Promise.race([pi.pending, new Promise(resolve => { timer = setTimeout(resolve, left) })]) }
133
+ finally { clearTimeout(timer) }
134
+ }
135
+ }
136
+ const t0 = now()
137
+ if (pi.inflight) { // one ask at a time — but an ask the shell never answered must not hold every later request back
138
+ if (t0 - pi.inflightAt < PI_ASK_STALE_MS) { if (pi.force && t0 - pi.skipSaidAt > 60_000) { pi.skipSaidAt = t0; log('attest: a Play Integrity token is due — this request goes without one while the ask started ' + Math.round((t0 - pi.inflightAt) / 1000) + ' s ago answers') } return '' }
139
+ log('attest: the Play Integrity ask started ' + Math.round((t0 - pi.inflightAt) / 1000) + ' s ago never answered — asking again')
140
+ pi.lastAt = pi.lastBefore
141
+ } else if (!requireIntegrity && !pi.force && t0 - pi.lastAt < PI_EVERY_MS) return ''
142
+ const gen = ++pi.gen
143
+ pi.askedHidden = isHidden() // a token asked in the background may ride a request the system never sends (resumed() below)
144
+ pi.inflight = true; pi.inflightAt = t0; const was = pi.lastAt; pi.lastBefore = was; pi.lastAt = t0
145
+ log('attest: asking Play Integrity for a token (' + ((requireIntegrity || pi.force) ? 'the server asked for one' : Number.isFinite(was) ? 'the last was ' + Math.round((t0 - was) / 60_000) + ' min ago' : 'the first in this page') + ')')
146
+ try {
147
+ pi.pending = integrityFor(bound)
148
+ const t = await pi.pending
149
+ if (gen !== pi.gen) return t // a newer ask took over (this one was stale): it decides the pace
150
+ if (t) { pi.force = false; log('attest: Play Integrity token sent with this request') } else pi.lastAt = was
151
+ return t
152
+ } finally { if (gen === pi.gen) { pi.inflight = false; pi.pending = null } }
153
+ }
154
+
155
+ // ⛔ AND A TOKEN ASKED IN THE BACKGROUND (the same morning): Android may never send the request it went with (the network is cut in
156
+ // the background), yet the pace counted it — 29 minutes of requests with no token, and in shadow the server never says so. Back in
157
+ // the foreground, a token asked while hidden does not count: the next request carries one.
158
+ function resumed () {
159
+ if (pi.askedHidden && Number.isFinite(pi.lastAt)) { pi.askedHidden = false; pi.force = true; log('attest: back in the foreground — the Play Integrity token asked in the background may not have reached the server; the next request carries one') }
160
+ }
161
+ try { if (typeof document !== 'undefined' && document.addEventListener) document.addEventListener('visibilitychange', () => { if (!isHidden()) resumed() }) } catch { /* not a page */ }
162
+
163
+ // ── ONE ADMINISTRATOR PROMPT FOR EVERY ACTIVATION (2026-11-18, the owner: "Do it"; docs/windows-attestation.md § Enclaves). Each
164
+ // activation is a TPM2_ActivateCredential, and Windows asks for administrator rights for each run: the Space server's (enrolment)
165
+ // and each enclave's (turn, Sentinel) came at three different moments. A shell with `activateAll` (the Windows app since 2026-11-18)
166
+ // answers every challenge that is due in ONE elevated run; an older shell keeps one prompt per activation.
167
+ const ENCLAVES = ['turn', 'sentinel']
168
+ const canBundle = () => { try { const b = getBridge(); return platform() === 'windows' && !!b && typeof b.activateAll === 'function' && !!client && typeof client.winAct === 'function' } catch { return false } }
169
+ async function bridgeActivateAll (pairs) {
170
+ let r
171
+ try { r = JSON.parse(String((await getBridge().activateAll(pairs.map((p) => ({ credential: p.credential, secret: p.secret })))) || '{}')) } catch (e) { r = { error: 'bridge: ' + ((e && e.message) || e) } }
172
+ if (!r || r.error || !Array.isArray(r.answers) || r.answers.length !== pairs.length) return { error: (r && r.error) || 'no answer' }
173
+ return { answers: r.answers }
174
+ }
175
+ /** The enclaves due an activation of `keyId` (not done, and not declined in the last day — `also` is asked regardless). */
176
+ const enclavesDue = (keyId, also = null) => {
177
+ const m = readMemo()
178
+ return ENCLAVES.filter((to) => (m.act || {})[to] !== keyId && (to === also || !((m.actDeclined || {})[to] && now() - m.actDeclined[to] < DECLINED_MS)))
179
+ }
180
+ /** Each enclave's challenge (in parallel) → { starts: [{ to, s }], why: { to: reason } } for those that gave none. */
181
+ async function enclaveStarts (keyId, tos) {
182
+ const why = {}
183
+ const got = await Promise.all(tos.map(async (to) => {
184
+ const s = await client.winAct({ to, step: 'start', keyId }).catch((e) => ({ status: 0, error: String((e && e.message) || e) }))
185
+ if (s && s.status === 200 && s.activate && s.ticket) return { to, s }
186
+ why[to] = String((s && (s.reason || s.error)) || 'no answer')
187
+ log('attest: activation refused (start, ' + to + '): ' + why[to])
188
+ return null
189
+ }))
190
+ return { starts: got.filter(Boolean), why }
191
+ }
192
+ /** Each enclave's finish with the TPM's answer → { to: reason } for those not activated; the memo records the rest. */
193
+ async function enclaveFinishes (keyId, starts, answers) {
194
+ const why = {}
195
+ for (const [i, { to, s }] of starts.entries()) {
196
+ const a = answers[i] || {}
197
+ if (!a.secret) {
198
+ why[to] = 'activation: ' + (a.error || 'no answer')
199
+ const m = readMemo(); writeMemo({ ...m, actDeclined: { ...(m.actDeclined || {}), [to]: now() } })
200
+ log('attest: activation refused (' + to + '): ' + why[to])
201
+ continue
202
+ }
203
+ const f = await client.winAct({ to, step: 'finish', keyId, activation: a.secret, ticket: s.ticket }).catch((e) => ({ status: 0, error: String((e && e.message) || e) }))
204
+ if (!f || f.status !== 200) { why[to] = String((f && (f.reason || f.error)) || 'no answer'); log('attest: activation refused (finish, ' + to + '): ' + why[to]); continue }
205
+ const m = readMemo(); const ad = { ...(m.actDeclined || {}) }; delete ad[to]
206
+ writeMemo({ ...m, actDeclined: ad, act: { ...(m.act || {}), [to]: keyId } })
207
+ log('attest: activated with the ' + to + ' enclave')
208
+ }
209
+ return why
210
+ }
211
+ /** Activate `keyId` with every enclave in `tos` — one administrator prompt. → { to: reason } for those not activated. */
212
+ async function activateMany (keyId, tos) {
213
+ log('attest: activating (windows) with ' + tos.join(' + ') + ' — one administrator prompt')
214
+ const { starts, why } = await enclaveStarts(keyId, tos)
215
+ if (Object.values(why).some((w) => /windows_reenroll|device_not_enrolled/.test(w))) { const m = readMemo(); writeMemo({ platform: m.platform }); log('attest: the server asks this key to enrol again'); return why } // the next proof enrols afresh
216
+ if (!starts.length) return why
217
+ const all = await bridgeActivateAll(starts.map((x) => x.s.activate))
218
+ if (all.error) {
219
+ const m = readMemo(), ad = { ...(m.actDeclined || {}) }
220
+ for (const { to } of starts) { ad[to] = now(); why[to] = 'activation: ' + all.error }
221
+ writeMemo({ ...m, actDeclined: ad })
222
+ log('attest: activation refused (' + starts.map((x) => x.to).join(' + ') + '): ' + all.error)
223
+ return why
224
+ }
225
+ return { ...why, ...(await enclaveFinishes(keyId, starts, all.answers)) }
226
+ }
227
+
228
+ // ONE ENROLMENT AT A TIME (the Windows app, 2026-11-09: four enrolment requests at once — the first message and the key backup each
229
+ // enrolled, and each bridge.enroll makes a NEW key, replacing the one the other was activating). A second caller waits for the
230
+ // first and then signs with the key it enrolled; it never starts its own.
231
+ let enrolling = null
232
+ // `stale`: the key this caller judged wrong (null when the memo had none) — under the lock, a memo naming any OTHER key means
233
+ // another document enrolled while this one waited, and that key is used.
234
+ function enroll (room, chal, spk, bound, stale = null) {
235
+ if (!enrolling) {
236
+ enrolling = withLock('witbitz-attest-enroll', async () => {
237
+ const m = readMemo()
238
+ if (m.keyId && m.keyId !== stale) return m.keyId
239
+ return enrollOnce(room, chal, spk, bound)
240
+ }).finally(() => { enrolling = null })
241
+ }
242
+ return enrolling
243
+ }
244
+ async function enrollOnce (room, chal, spk, bound) {
245
+ const memo = readMemo()
246
+ let bundled = null // the enclaves' challenges answered in the enrolment's own administrator prompt
247
+ if (memo.failedAt && now() - memo.failedAt < (memo.declined ? DECLINED_MS : RETRY_MS)) return null // a "No": a day (X#5)
248
+ log('attest: enrolling (' + platform() + ') for ' + String(room).slice(0, 40))
249
+ let res
250
+ // await: a bridge may answer a Promise (the cloud device) or a string (a native shell)
251
+ try { res = JSON.parse(String((await getBridge().enroll(bound)) || '{}')) } catch (e) { res = { error: 'bridge: ' + ((e && e.message) || e) } }
252
+ if (!res || res.error || !res.keyId) { writeMemo({ ...memo, failedAt: now(), reason: (res && res.error) || 'no key' }); log('attest: enroll refused by the device: ' + ((res && res.error) || 'no key')); return null }
253
+ const p = platform()
254
+ const enrollBody = p === 'ios' || p === 'macos' ? { platform: p, keyId: res.keyId, app: res.app, attestation: res.attestation }
255
+ : p === 'windows' ? { platform: 'windows', keyId: res.keyId, ekChain: res.ekChain, ak: res.ak, key: res.key }
256
+ : p === 'clouddevice' ? { platform: 'clouddevice', keyId: res.keyId, publicKeyJwk: res.publicKeyJwk, doc: res.doc } // the cloud device: its enclave's document over this key (cloud-device/attestBridge.mjs)
257
+ : { platform: 'android', keyId: res.keyId, chain: res.chain }
258
+ // ONLY A REFUSAL PAUSES (E#2): a lost answer (no network, a 5xx, a timeout) is tried again on the next proof. A 10-minute pause
259
+ // for a blip outlived every retry of the attested-backup pull, and the attested rooms stayed missing until a relaunch.
260
+ const refused = (r, step = '') => {
261
+ const why = (r && (r.reason || r.error)) || 'no answer'
262
+ const pause = r && r.device ? true : isRefusal(r) // r.device: the device or the person said no (the bridge, the admin prompt)
263
+ // `declined`: the DEVICE or the PERSON said no (the administrator prompt) — only the person's own Retry asks again; the
264
+ // automatic retries (the attested-backup pull's, every 30 s) used to clear the pause and prompt — and make a TPM key — each time
265
+ writeMemo(pause ? { ...memo, failedAt: now(), reason: why, ...(r && r.device ? { declined: true } : {}) } : { ...memo, reason: why })
266
+ log('attest: enrollment ' + (pause ? 'refused' : 'not answered') + (step ? ' (' + step + ')' : '') + ': ' + why + (r && r.status ? ' · HTTP ' + r.status : ''))
267
+ return null
268
+ }
269
+ const send = (enroll) => client.attestEnroll({ room, chal, spk, enroll }).catch((e) => ({ status: 0, error: String((e && e.message) || e) }))
270
+ let r = await send(enrollBody)
271
+ if (!r || r.status !== 200) return refused(r, 'step 1')
272
+ // WINDOWS, STEP 2 (docs/windows-attestation.md): the server's challenge, encrypted to the TPM's endorsement key and bound to the
273
+ // attestation key — the shell answers it with TPM2_ActivateCredential (Windows asks for administrator rights for this, once)
274
+ if (p === 'windows' && r.activate) {
275
+ let a
276
+ if (canBundle()) { // the enclaves' challenges now too — the Space server's and theirs in ONE administrator prompt
277
+ const { starts } = await enclaveStarts(res.keyId, enclavesDue(res.keyId))
278
+ const all = await bridgeActivateAll([r.activate, ...starts.map((x) => x.s.activate)])
279
+ a = all.error ? { error: all.error } : all.answers[0]
280
+ if (!all.error && starts.length) bundled = { starts, answers: all.answers.slice(1) }
281
+ log('attest: one administrator prompt for the Space server' + (starts.length ? ' and the ' + starts.map((x) => x.to).join(' + ') + ' enclave' + (starts.length > 1 ? 's' : '') : ''))
282
+ } else {
283
+ try { a = JSON.parse(String((await getBridge().activate(r.activate.credential, r.activate.secret)) || '{}')) } catch (e) { a = { error: 'bridge: ' + ((e && e.message) || e) } }
284
+ }
285
+ if (!a || a.error || !a.secret) return refused({ device: true, reason: 'activation: ' + ((a && a.error) || 'no answer') })
286
+ log('attest: activation answered by the TPM — sending step 2')
287
+ // A LOST STEP-2 ANSWER (E#5): the server may have stored the device before its answer was lost. Sent again (the activation
288
+ // stays good while the enrolment is pending); "no enrolment waiting" after a lost answer means the first one went through.
289
+ // Still unanswered: kept as enrolled, unconfirmed — the next proof's answer says (device_not_enrolled forgets it) — rather
290
+ // than a new key and another administrator prompt.
291
+ const body2 = { platform: 'windows', keyId: res.keyId, activation: a.secret }
292
+ r = await send(body2)
293
+ let lost = false
294
+ for (let i = 0; i < 2 && !(r && r.status === 200) && !isRefusal(r); i++) { lost = true; await sleep(2000 * (i + 1)); r = await send(body2) }
295
+ if (lost && r && r.status === 409 && /no enrolment waiting/.test(String(r.reason || ''))) r = { status: 200 }
296
+ if (!(r && r.status === 200) && !isRefusal(r)) {
297
+ writeMemo({ keyId: res.keyId, platform: p, at: now(), unconfirmed: true })
298
+ log('attest: step 2 not answered — the key is kept; the next proof tells whether the server holds it')
299
+ if (bundled) await enclaveFinishes(res.keyId, bundled.starts, bundled.answers) // kept only if the server holds the key
300
+ return res.keyId
301
+ }
302
+ if (!r || r.status !== 200) return refused(r, 'step 2')
303
+ }
304
+ writeMemo({ keyId: res.keyId, platform: p, at: now(), ...(BUILD ? { build: BUILD } : {}), ...(memo.badSigAt ? { badSigAt: memo.badSigAt } : {}), ...(readMemo().noSigAt ? { noSigAt: readMemo().noSigAt } : {}) }) // badSigAt: the hourly limit on forgetting a key (noteAnswer) outlives the new key
305
+ // A NEW KEY HAS NO PLAY INTEGRITY VERDICT on the server (it keeps one per key): the next request carries a token, not the one
306
+ // due in up to 29 minutes (the owner's phone, 2026-11-23: after the update to versionCode 10 every request of its new key read
307
+ // "would refuse — integrity_required" for 26 minutes in shadow; switched on, they would have been refused)
308
+ pi.force = true
309
+ log('attest: device enrolled (' + p + ')')
310
+ if (bundled) await enclaveFinishes(res.keyId, bundled.starts, bundled.answers) // the enclaves' answers from the same prompt
311
+ return res.keyId
312
+ }
313
+
314
+ // A WINDOWS KEY BEFORE AN ENCLAVE: start (the enclave's TPM challenge + its sealed ticket) → the TPM answers (Windows asks for
315
+ // administrator rights) → finish (the front keeps the record the enclave sealed). Once per enclave per key; one at a time.
316
+ const activating = {}
317
+ function activateFor (to, keyId) {
318
+ if (canBundle()) { // every enclave due, in one prompt; a second caller (the other enclave) waits for the same run
319
+ if (!activating.all) {
320
+ activating.all = withLock('witbitz-attest-activate', async () => {
321
+ const m = readMemo()
322
+ if ((m.act || {})[to] === keyId) return {} // another document activated it meanwhile
323
+ const no = (m.actDeclined || {})[to]
324
+ if (no && now() - no < DECLINED_MS) return { [to]: 'activation declined — tap Retry to be asked again' }
325
+ return activateMany(keyId, enclavesDue(keyId, to))
326
+ }).finally(() => { activating.all = null })
327
+ }
328
+ return activating.all.then((why) => ((readMemo().act || {})[to] === keyId ? '' : String((why && why[to]) || 'not activated')))
329
+ }
330
+ if (!activating[to]) {
331
+ activating[to] = withLock('witbitz-attest-activate', async () => {
332
+ const m = readMemo()
333
+ if ((m.act || {})[to] === keyId) return '' // another document activated it meanwhile
334
+ // a "No" to the administrator prompt holds for the pause, as an enrolment's does (state machines pass 8, W#1)
335
+ const no = (m.actDeclined || {})[to]
336
+ if (no && now() - no < DECLINED_MS) return 'activation declined — tap Retry to be asked again' // a day, as an enrolment's "No" (pass 9, X#5)
337
+ return activateOnce(to, keyId)
338
+ })
339
+ .finally(() => { activating[to] = null })
340
+ }
341
+ return activating[to]
342
+ }
343
+ async function activateOnce (to, keyId) {
344
+ if (!client || typeof client.winAct !== 'function') return 'no activation here'
345
+ log('attest: activating (windows) with the ' + to + ' enclave')
346
+ const s = await client.winAct({ to, step: 'start', keyId }).catch((e) => ({ status: 0, error: String((e && e.message) || e) }))
347
+ if (!s || s.status !== 200 || !s.activate || !s.ticket) {
348
+ const why = String((s && (s.reason || s.error)) || 'no answer')
349
+ if (/windows_reenroll|device_not_enrolled/.test(why)) { const m = readMemo(); writeMemo({ platform: m.platform }); log('attest: the server asks this key to enrol again') } // the next proof enrols afresh
350
+ log('attest: activation refused (start, ' + to + '): ' + why)
351
+ return why
352
+ }
353
+ let a
354
+ try { a = JSON.parse(String((await getBridge().activate(s.activate.credential, s.activate.secret)) || '{}')) } catch (e) { a = { error: 'bridge: ' + ((e && e.message) || e) } }
355
+ if (!a || a.error || !a.secret) {
356
+ const why = 'activation: ' + ((a && a.error) || 'no answer')
357
+ const m = readMemo(); writeMemo({ ...m, actDeclined: { ...(m.actDeclined || {}), [to]: now() } })
358
+ log('attest: activation refused (' + to + '): ' + why)
359
+ return why
360
+ }
361
+ const f = await client.winAct({ to, step: 'finish', keyId, activation: a.secret, ticket: s.ticket }).catch((e) => ({ status: 0, error: String((e && e.message) || e) }))
362
+ if (!f || f.status !== 200) { const why = String((f && (f.reason || f.error)) || 'no answer'); log('attest: activation refused (finish, ' + to + '): ' + why); return why }
363
+ const m = readMemo(); const { actDeclined: _d, ...kept } = m; writeMemo({ ...kept, act: { ...(m.act || {}), [to]: keyId } })
364
+ log('attest: activated with the ' + to + ' enclave')
365
+ return ''
366
+ }
367
+
368
+ return {
369
+ enrolledKeyId: () => readMemo().keyId || null,
370
+ /** The turn fields to add: { chal, attestation } — or null when this turn cannot be attested (no bridge, no challenge yet, enrollment refused). */
371
+ /** Why the last attestFor made no proof — said under a refused post ("attestation: missing"; the first real test on a phone,
372
+ * 2026-11-07, could not tell which). '' when it made one. */
373
+ lastWhy: () => lastWhy,
374
+ /** Forget a refused enrolment's pause (RETRY_MS keeps automatic sends from re-trying each time). `person`: the person tapped
375
+ * Retry — only that also forgets a "No" they gave the administrator prompt; an automatic retry leaves it standing. */
376
+ retryNow: ({ person = false } = {}) => {
377
+ const m = readMemo()
378
+ if (m.declined && !person) return
379
+ if (m.failedAt || m.actDeclined) { const { failedAt: _f, reason: _r, declined: _d, actDeclined: _a, ...rest } = m; writeMemo(person ? rest : { ...rest, ...(m.actDeclined ? { actDeclined: m.actDeclined } : {}) }) }
380
+ },
381
+ async attestFor ({ room, spk = null, requireIntegrity = false } = {}) {
382
+ lastWhy = ''
383
+ if (!getBridge() || !client) { lastWhy = 'no hardware bridge on this page'; return null }
384
+ const chal = challengeFor(room)
385
+ if (!chal) { lastWhy = 'no challenge from the Space yet'; return null }
386
+ const bound = await bindHash(spk, chal)
387
+ const memoKey = readMemo().keyId || null
388
+ let keyId = memoKey
389
+ let deviceKey = ''
390
+ try { deviceKey = String(getBridge().keyId ? getBridge().keyId() : '') } catch { deviceKey = '' }
391
+ // the device's key moved under us (Android: the Keystore's own key). NOT on Windows: its bridge answers the key enrolled in
392
+ // THIS document, so after another document enrolled it names an older key — the shared memo is the device's truth (E#1);
393
+ // a key the server does not hold comes back as device_not_enrolled and is forgotten (noteAnswer).
394
+ // ⛔ NOT ON THE APPLE PLATFORMS EITHER (the owner's iPhone, 2026-11-24 10:39: a new App Attest key every 2 s): the shell's keyId()
395
+ // is what THIS page was handed at load or last enrolled, not the phone's — the Space and the lane panel each held their own, read
396
+ // the other's enrolment as "moved" and enrolled over each other. There the shared memo is the truth; a key that is really gone
397
+ // signs nothing (below), a key the page names wrongly is refused bad_assertion_signature (noteAnswer).
398
+ const shimOnly = platform() === 'ios' || platform() === 'macos'
399
+ const moved = platform() !== 'windows' && !shimOnly && !!deviceKey && deviceKey !== keyId
400
+ // ⛔ THE DEVICE HOLDS NO KEY while the memo names one (the owner's iPhone, 2026-11-24: App Attest's key was gone — the shell drops
401
+ // one Apple calls invalid — and every proof since was "the hardware key did not sign"; the page re-enrols only on the server's
402
+ // device_not_enrolled, which an unsigned request never reaches): enrolled again, as a key that moved. Only a bridge that can say.
403
+ const lost = !moved && !shimOnly && !!keyId && !deviceKey && platform() !== 'windows' && platform() !== 'clouddevice' && (() => { try { return typeof getBridge().keyId === 'function' } catch { return false } })()
404
+ const old = !moved && outdated(readMemo()) // the app was updated since this key was made: a new key, attested as THIS version
405
+ if (!keyId || moved || lost) {
406
+ if (lost) log('attest: the device holds no key, the memo names one — enrolling a new one')
407
+ if (!enrollableScope(room)) { lastWhy = 'this device is not enrolled yet — it enrols from a Space, not from the key step'; return null }
408
+ keyId = await enroll(room, chal, spk, bound, memoKey) // first run, or the device's key moved under us
409
+ } else if (old && enrollableScope(room)) {
410
+ // …and if that enrolment does not go through (offline, refused), the key it has still stands at the server: this turn uses it
411
+ const fresh = await enroll(room, chal, spk, bound, memoKey)
412
+ if (fresh) keyId = fresh
413
+ else {
414
+ // ⛔ 10·P#3 (pass 10): kept only if it is still THE DEVICE'S key. Android's Keystore holds one key under the alias: a
415
+ // re-enrol that made its new key and was then refused by the server has already deleted the old one — signing as the old
416
+ // key id sent the new key's signature, refused with an unclear reason. Not sent; the next try enrols again.
417
+ let nowKey = ''
418
+ try { nowKey = String(getBridge().keyId ? getBridge().keyId() : '') } catch { nowKey = '' }
419
+ if (platform() !== 'windows' && nowKey && nowKey !== keyId) { lastWhy = 'this device\'s key is being renewed after an app update — try again in a moment'; log('attest: the older key is gone and its new one is not enrolled yet — not sent'); return null }
420
+ log('attest: the key from an older build is kept — a new one could not be enrolled now')
421
+ }
422
+ }
423
+ if (!keyId) { const m = readMemo(); lastWhy = 'enrolment refused: ' + String(m.reason || 'unknown').slice(0, 120); return null }
424
+ const to = platform() === 'windows' ? (() => { try { return enclaveFor(room) } catch { return null } })() : null
425
+ if (to && (readMemo().act || {})[to] !== keyId) { const why = await activateFor(to, keyId); if (why) { lastWhy = 'windows activation (' + to + '): ' + String(why).slice(0, 120); return null } }
426
+ let sig
427
+ try { sig = String((await getBridge().sign(bound)) || '') } catch (e) { lastWhy = 'signing failed: ' + String((e && e.message) || e).slice(0, 100); log('attest: sign failed: ' + ((e && e.message) || e)); return null }
428
+ // NO SIGNATURE: the key went while this page was open (iOS answers invalidKey and the shell forgets it) — enrolled once more and
429
+ // signed again, where a Space may enrol; else said, and the next attested send from a Space renews it
430
+ // …AT MOST EVERY 10 MINUTES (2026-11-24: dozens of keys in two minutes): a phone that keeps signing nothing is not helped by more keys
431
+ const why = () => { try { const w = getBridge().why ? String(getBridge().why() || '') : ''; return w ? ' (' + w.slice(0, 120) + ')' : '' } catch { return '' } }
432
+ if (!sig && platform() !== 'windows' && enrollableScope(room)) {
433
+ const m = readMemo()
434
+ if (m.noSigAt && now() - m.noSigAt < 10 * 60_000) log('attest: the device signed nothing' + why() + ' — a new key was made ' + Math.round((now() - m.noSigAt) / 1000) + ' s ago; not another yet')
435
+ else {
436
+ log('attest: the device signed nothing' + why() + ' — its key is gone; enrolling a new one')
437
+ writeMemo({ ...m, noSigAt: now() })
438
+ const fresh = await enroll(room, chal, spk, bound, keyId)
439
+ if (fresh && fresh !== keyId) { keyId = fresh; try { sig = String((await getBridge().sign(bound)) || '') } catch { sig = '' } }
440
+ }
441
+ }
442
+ if (!sig) { lastWhy = 'the device gave no signature' + why(); return null }
443
+ const p = platform()
444
+ // ANDROID'S VERSION PER REQUEST (docs/build-enclave.md § 5.1 step 5; agent/playIntegrity.mjs): Google Play's verdict for THIS
445
+ // request — its requestHash is SHA-256 of the same `bound` the hardware key signed — carries the versionCode of the app actually
446
+ // running; the server holds it to the build enclave's log. A shell without it (older APK) sends none; the server decides.
447
+ if (p === 'clouddevice') return { chal, attestation: { platform: 'clouddevice', keyId, bound, sig } } // its enclave key's signature (clientAttestVerifiers.mjs clouddevice)
448
+ const integrity = p === 'android' ? await integrityDueFor(bound, requireIntegrity) : ''
449
+ return { chal, attestation: p === 'ios' || p === 'macos' ? { platform: p, keyId, bound, assertion: sig } : { platform: p === 'windows' ? 'windows' : 'android', keyId, bound, sig, ...(integrity ? { integrity } : {}) } }
450
+ },
451
+ /** "VERIFY THIS DEVICE" (docs/device-verify.md): sign a checker's nonce with the enrolled hardware key and send it. →
452
+ * { ok, key } where `key` is computed HERE from this device's own key id (the code the checker compares), or
453
+ * { ok: false, reason }. Never a verdict: a page cannot vouch for itself — the checker on the other device decides. */
454
+ async verifyThisDevice (nonce) {
455
+ const n = String(nonce || '').replace(/^witbitz-verify:/, '').trim()
456
+ if (!/^[A-Za-z0-9_-]{22,64}$/.test(n)) return { ok: false, reason: 'that is not a verification code' }
457
+ if (!getBridge() || !client || !client.deviceVerify) return { ok: false, reason: 'this is not the Witbitz app (no hardware key here)' }
458
+ let keyId = readMemo().keyId || ''
459
+ // ENROL HERE, from the Space this page is in (an enrolment needs a Space's fresh challenge, nothing of the Space itself) — so the
460
+ // check names the version running and needs no attested Space first. The challenge is ASKED for when none is fresh (the owner,
461
+ // 2026-11-23: "Not sent: device_not_enrolled" — a challenge came only before a turn that needed one, so after an app update the
462
+ // phone signed with a key the server had never seen).
463
+ const enrolHere = async (stale) => {
464
+ if (typeof enrolFrom !== 'function') return null
465
+ let from = null; try { from = enrolFrom() } catch { from = null }
466
+ if (!from || !from.room || !enrollableScope(from.room)) return null
467
+ let chal = challengeFor(from.room)
468
+ if (!chal && typeof freshChallenge === 'function') { try { chal = (await freshChallenge(from.room)) || challengeFor(from.room) } catch { chal = null } }
469
+ if (!chal) return null
470
+ return enroll(from.room, chal, from.spk || null, await bindHash(from.spk || null, chal), stale).catch(() => null)
471
+ }
472
+ if (!keyId || outdated(readMemo())) { const k = await enrolHere(keyId || null); if (k) keyId = k }
473
+ if (!keyId) { try { keyId = String(getBridge().keyId ? getBridge().keyId() : '') } catch { keyId = '' } }
474
+ if (!keyId) return { ok: false, reason: 'this device has no enrolled key yet — open a Space, then try again' }
475
+ let sig
476
+ try { sig = String((await getBridge().sign('witbitz-device-verify/1:' + n)) || '') } catch (e) { return { ok: false, reason: 'the hardware key did not sign' } }
477
+ // the key is gone (2026-11-24, the owner's iPhone): a new one enrolled from this Space, and signed again
478
+ if (!sig && platform() !== 'windows') {
479
+ const k = await enrolHere(keyId)
480
+ if (k && k !== keyId) { keyId = k; try { sig = String((await getBridge().sign('witbitz-device-verify/1:' + n)) || '') } catch { sig = '' } }
481
+ }
482
+ if (!sig) return { ok: false, reason: 'the hardware key did not sign' + (typeof enrolFrom === 'function' ? ', and a new key could not be enrolled — open a Space, then try again' : '') }
483
+ const p = platform()
484
+ // Android: Google Play's verdict for THIS check too (the version actually running; agent/playIntegrity.mjs) — a turn sends one,
485
+ // and a checker that holds the version to the log must get one here as well, or ANDROID_INTEGRITY=1 refuses every device check
486
+ const integrity = p === 'android' ? await integrityFor('witbitz-device-verify/1:' + n) : ''
487
+ const ask = (k, s) => client.deviceVerify(p === 'ios' || p === 'macos' ? { platform: p, keyId: k, nonce: n, assertion: s } : { platform: 'android', keyId: k, nonce: n, sig: s, ...(integrity ? { integrity } : {}) })
488
+ let r = await ask(keyId, sig)
489
+ // THE SERVER DOES NOT KNOW THIS KEY: enrol it now and ask once more, signed by the key just enrolled
490
+ if (r && /device_not_enrolled/.test(String(r.error || r.reason || ''))) {
491
+ const k = await enrolHere(keyId || null)
492
+ if (k) {
493
+ let s2 = ''; try { s2 = String((await getBridge().sign('witbitz-device-verify/1:' + n)) || '') } catch { s2 = '' }
494
+ if (s2) { keyId = k; r = await ask(keyId, s2) }
495
+ }
496
+ }
497
+ const own = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(keyId))), (b) => b.toString(16).padStart(2, '0')).join('').slice(0, 8)
498
+ if (!r || r.status && r.status !== 200 || r.ok === false) return { ok: false, reason: (r && (r.error || r.reason)) || 'the server did not take it', key: own }
499
+ return { ok: true, key: own } // OUR code, from our own key id — not the server's echo
500
+ },
501
+ /** Read the server's answer to a turn: an unenrolled key is forgotten, so the next send enrolls again. */
502
+ resumed,
503
+ // `sentKeyId` (11·P#3): the key id the refused request NAMED. Pages of one phone share its hardware key and the memo: a refusal of a
504
+ // proof made before another page enrolled a NEW key must not forget that new key (it threw away a good key, then the hourly limit
505
+ // blocked the real repair). Given and not the memo's key → nothing is forgotten.
506
+ noteAnswer (r, sentKeyId = '') {
507
+ const reason = r && r.status === 403 ? String(r.reason || '') : ''
508
+ if (/integrity_required|integrity_missing/.test(reason)) { pi.force = true; log('attest: the server holds no fresh Play Integrity verdict — the next request carries a token') } // integrity_missing: an enclave before 10·P#1 (pass 10), which wanted a token every time
509
+ if (/device_not_enrolled/.test(reason)) { const m = readMemo(); writeMemo({ platform: m.platform }); log('attest: the server does not know this key — will enroll again') }
510
+ // THE PHONE SIGNS WITH ANOTHER KEY than the one this page names (the owner's iPhone, 2026-11-24: the key enrolled at 09:20 never
511
+ // signed once; every attested backup "ios: bad assertion signature"): forgotten, so the next proof enrols the key the phone holds —
512
+ // at most once an hour, so a verifier that refuses every key cannot make a new hardware key per request
513
+ if (/\b(ios|macos): bad assertion signature/.test(reason)) {
514
+ const m = readMemo()
515
+ if (sentKeyId && m.keyId && sentKeyId !== m.keyId) log('attest: a refused signature named an earlier key — the key enrolled since is kept')
516
+ else if (m.keyId && !(m.badSigAt && now() - m.badSigAt < 60 * 60_000)) { writeMemo({ platform: m.platform, badSigAt: now() }); log('attest: the server could not verify this key\'s signature — will enroll again') }
517
+ }
518
+ if (/windows_needs_activation/.test(reason)) { const m = readMemo(); const { act: _a, ...rest } = m; writeMemo(rest); log('attest: an enclave does not know this key\'s activation — will activate again') }
519
+ },
520
+ }
521
+ }
package/deviceCall.js ADDED
@@ -0,0 +1,54 @@
1
+ // deviceCall.js — answering a turn that asked THIS device to run a tool (an `await` action: read the calendar, ask the host
2
+ // page), one way for the Spaces app and the SDK (docs/sdk-convergence.md, phase 4b). Once per call id; the handler is
3
+ // found by the caller (the SDK: its actions; the app: its device tools, the app-site, the embedding page, the parent
4
+ // panel); its answer — or why there is none — goes back to the waiting turn, which otherwise times out gracefully.
5
+ //
6
+ // Executed once, answered once (docs/state-machines.md G-M3):
7
+ // · `claim(name, dc)` (optional) is asked AFTER a handler is found and BEFORE it runs: false → another device of the member
8
+ // took the call (G#3: tell_lane ran on two devices) — this one does nothing; null/throw → not known (the claim did not
9
+ // reach the server) — the call is let go and tried again the next time a poll surfaces it.
10
+ // · the call counts as answered only once `send` succeeded (G#4: a failed send was swallowed and the call marked done, so
11
+ // the turn waited out its 25 s): a failed send keeps the RESULT — the tool never runs twice — and the next surfacing of
12
+ // the same call sends it again.
13
+ export const HANDLED_ELSEWHERE = Symbol('handled elsewhere') // `find` (or its handler) sent the call on (e.g. to a parent page) — that side answers it
14
+
15
+ const _unsent = new WeakMap() // done set → Map(callId → result not yet delivered)
16
+ const _sending = new WeakMap() // done set → Set(callId) a send is in flight for
17
+ const bucket = (wm, done, mk) => { let b = wm.get(done); if (!b) { b = mk(); wm.set(done, b) } return b }
18
+
19
+ const sentOk = (r) => !(r && typeof r === 'object' && (r.ok === false || r.error || (typeof r.status === 'number' && r.status !== 200)))
20
+
21
+ async function deliver (callId, result, done, send) {
22
+ const unsent = bucket(_unsent, done, () => new Map()), sending = bucket(_sending, done, () => new Set())
23
+ if (sending.has(callId)) return
24
+ sending.add(callId)
25
+ try {
26
+ let r
27
+ try { r = await send(result) } catch { r = { ok: false } }
28
+ if (sentOk(r)) unsent.delete(callId); else unsent.set(callId, result) // kept for the next surfacing — never re-run
29
+ } finally { sending.delete(callId) }
30
+ }
31
+
32
+ export async function answerDeviceCall (dc, { done, find, send, claim }) {
33
+ if (!dc || !dc.callId || !dc.name) return
34
+ if (done.has(dc.callId)) { // ran here already — only a result whose send failed is owed
35
+ const unsent = _unsent.get(done)
36
+ if (unsent && unsent.has(dc.callId)) await deliver(dc.callId, unsent.get(dc.callId), done, send)
37
+ return
38
+ }
39
+ done.add(dc.callId)
40
+ let result
41
+ try {
42
+ const fn = await find(String(dc.name), dc)
43
+ if (fn === HANDLED_ELSEWHERE) return
44
+ if (typeof fn === 'function' && typeof claim === 'function') {
45
+ let won = null
46
+ try { won = await claim(String(dc.name), dc) } catch { won = null }
47
+ if (won === false) return // another device of the member runs it: done here, nothing to answer
48
+ if (won !== true) { done.delete(dc.callId); return } // not known: ask again when the call surfaces again
49
+ }
50
+ result = typeof fn === 'function' ? await fn(dc.args || {}) : { error: `No handler for "${String(dc.name).slice(0, 40)}" on this device.` }
51
+ if (result === HANDLED_ELSEWHERE) return
52
+ } catch (e) { result = { error: 'The tool failed on this device' + (e && e.message ? ': ' + String(e.message).slice(0, 200) : '.') } }
53
+ await deliver(dc.callId, result, done, send)
54
+ }