@witbitz/sdk 0.0.0-stage → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +200 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +223 -0
  6. package/accountIndexDoc.js +122 -0
  7. package/accountOwner.js +59 -0
  8. package/accountRecord.js +90 -0
  9. package/accountScope.js +114 -0
  10. package/accountSeal.js +42 -0
  11. package/accountStores.js +173 -0
  12. package/acctV2App.js +619 -0
  13. package/acctV2Check.js +29 -0
  14. package/acctV2Client.js +382 -0
  15. package/acctV2Keys.js +43 -0
  16. package/acctV2Legacy.js +14 -0
  17. package/acctV2Switch.js +80 -0
  18. package/acctV2UiCore.js +857 -0
  19. package/acctV2WebAuthn.js +61 -0
  20. package/acctV2Wire.js +59 -0
  21. package/address.js +42 -0
  22. package/attestedBox.js +30 -0
  23. package/attestedRooms.js +78 -0
  24. package/awsKey.js +98 -0
  25. package/backupRecord.js +106 -0
  26. package/backupVault.js +97 -0
  27. package/blocks.js +115 -0
  28. package/blocksPush.js +64 -0
  29. package/browseSeal.js +103 -0
  30. package/cbor.js +225 -0
  31. package/changePush.js +75 -0
  32. package/chatLock.js +149 -0
  33. package/chatLockSw.js +13 -0
  34. package/cloudDeviceBuilds.js +11 -0
  35. package/cloudDevicePins.js +33 -0
  36. package/cloudDeviceSeal.js +53 -0
  37. package/codeBrowse.js +224 -0
  38. package/codeCloud.js +652 -0
  39. package/codeCloudKeys.js +112 -0
  40. package/codeCommands.js +167 -0
  41. package/codeComputers.js +388 -0
  42. package/codeEgress.js +123 -0
  43. package/codeFilesRoutes.js +17 -0
  44. package/codeMkdir.js +8 -0
  45. package/codeModes.js +57 -0
  46. package/codeOrphanKeys.js +42 -0
  47. package/codeOutputs.js +141 -0
  48. package/codeRelay.js +505 -0
  49. package/codeSentinel.js +86 -0
  50. package/codeTransport.js +295 -0
  51. package/codeUndo.js +48 -0
  52. package/compress.js +24 -0
  53. package/config.js +11 -0
  54. package/connCatalog.js +164 -0
  55. package/connDisp.js +76 -0
  56. package/connOtherWays.js +74 -0
  57. package/connPending.js +16 -0
  58. package/connWrap.js +53 -0
  59. package/connectionEntry.js +89 -0
  60. package/connections.js +562 -0
  61. package/credits.js +30 -0
  62. package/csAttest.js +112 -0
  63. package/decrypt.html +384 -0
  64. package/deviceAttest.js +521 -0
  65. package/deviceCall.js +54 -0
  66. package/deviceKeyCore.js +41 -0
  67. package/deviceSeal.js +59 -0
  68. package/e2ee.js +323 -0
  69. package/eat.js +103 -0
  70. package/emailFork.js +275 -0
  71. package/emailSignIn.js +81 -0
  72. package/emptySpaces.js +111 -0
  73. package/encSource.js +55 -0
  74. package/enclaveAccept.js +214 -0
  75. package/enclaveClaim.js +241 -0
  76. package/enclaveRoute.js +102 -0
  77. package/enclaveSnapshotMerge.js +44 -0
  78. package/entrySig.js +165 -0
  79. package/env.js +73 -0
  80. package/eraseFile.js +58 -0
  81. package/followImage.js +86 -0
  82. package/healNames.js +45 -0
  83. package/idb.js +97 -0
  84. package/idbSeal.js +119 -0
  85. package/indexGone.js +12 -0
  86. package/invite.js +51 -0
  87. package/inviteEnroll.js +67 -0
  88. package/inviteSend.js +68 -0
  89. package/jobAgents.js +87 -0
  90. package/keptMerge.js +84 -0
  91. package/l1-worker-src.js +2 -0
  92. package/l1-worker.js +831 -0
  93. package/laneConfig.js +57 -0
  94. package/laneLinkCore.js +177 -0
  95. package/ledgerView.js +64 -0
  96. package/manifest.json +220 -0
  97. package/mcpRecommended.js +25 -0
  98. package/memberChange.js +123 -0
  99. package/mkseal.js +101 -0
  100. package/nativePush.js +153 -0
  101. package/nitroVerify.js +220 -0
  102. package/noble-p256.js +27 -0
  103. package/notice.js +116 -0
  104. package/notifKey.js +58 -0
  105. package/offlineBundle.js +62 -0
  106. package/ohttp.js +177 -0
  107. package/opencodeWire.js +282 -0
  108. package/oprf.js +70 -0
  109. package/ownAgentLink.js +96 -0
  110. package/ownerPolicy.js +117 -0
  111. package/package.json +254 -4
  112. package/pollVerdict.js +33 -0
  113. package/prefetchPoll.js +60 -0
  114. package/protectedLocal.js +410 -0
  115. package/pushCore.js +42 -0
  116. package/recovery.js +107 -0
  117. package/regions.js +42 -0
  118. package/removedMessage.js +11 -0
  119. package/renameRefusal.js +9 -0
  120. package/replyQuote.js +34 -0
  121. package/reqEnvelope.js +126 -0
  122. package/roomDefaultPrefs.js +76 -0
  123. package/roomDelete.js +109 -0
  124. package/roomName.js +177 -0
  125. package/roomPass.js +256 -0
  126. package/roomRoster.js +289 -0
  127. package/roomSettings.js +61 -0
  128. package/roomState.js +58 -0
  129. package/roomStreamClient.js +115 -0
  130. package/rosterCount.js +49 -0
  131. package/rosterHash.js +13 -0
  132. package/rowSchema.js +113 -0
  133. package/safeMedia.js +116 -0
  134. package/safeMediaPins.js +17 -0
  135. package/schedulesDoc.js +78 -0
  136. package/sdkA2A.js +404 -0
  137. package/sdkAccount.js +470 -0
  138. package/sdkAccountDoc.js +81 -0
  139. package/sdkAccountSections.js +223 -0
  140. package/sdkAgui.js +141 -0
  141. package/sdkAttest.js +34 -0
  142. package/sdkBackup.js +480 -0
  143. package/sdkBackupV2.js +630 -0
  144. package/sdkBrowserPrivate.js +28 -0
  145. package/sdkBuilds.js +208 -0
  146. package/sdkCloudDevice.js +215 -0
  147. package/sdkComputers.js +480 -0
  148. package/sdkDictation.js +142 -0
  149. package/sdkErase.js +283 -0
  150. package/sdkExports.js +69 -0
  151. package/sdkInvitations.js +34 -0
  152. package/sdkKeptAgent.js +188 -0
  153. package/sdkLaneLink.js +205 -0
  154. package/sdkPlan.js +94 -0
  155. package/sdkProtect.js +228 -0
  156. package/sdkRedact.js +36 -0
  157. package/sdkRekey.js +307 -0
  158. package/sdkReport.js +68 -0
  159. package/sdkSafeMedia.js +255 -0
  160. package/sdkSchedules.js +39 -0
  161. package/sdkSpeech.js +54 -0
  162. package/sdkTurn.js +117 -0
  163. package/sdkVault.js +124 -0
  164. package/sealShare.js +18 -0
  165. package/sealedNames.js +64 -0
  166. package/sealedReceipt.js +17 -0
  167. package/sentinelRelease.js +154 -0
  168. package/shamir.js +85 -0
  169. package/sharedViews.js +38 -0
  170. package/sheetChrome.js +450 -0
  171. package/siri.js +171 -0
  172. package/spaceClient.js +1418 -0
  173. package/spaceConfig.js +81 -0
  174. package/spaceEmailGate.js +813 -0
  175. package/spaceExport.js +125 -0
  176. package/spaceFork.js +216 -0
  177. package/spaceLock.js +358 -0
  178. package/spacePasskey.js +180 -0
  179. package/speechOut.js +100 -0
  180. package/splitKeyClient.js +90 -0
  181. package/store.js +587 -0
  182. package/streamHint.js +36 -0
  183. package/sttCloud.js +220 -0
  184. package/sttWorklet.js +38 -0
  185. package/sw-notif-core.js +538 -0
  186. package/tempList.js +48 -0
  187. package/tinfoilVerifier.js +78 -0
  188. package/toolBooks.js +31 -0
  189. package/toolRules.js +52 -0
  190. package/turnCerts.js +254 -0
  191. package/turnFeed.js +58 -0
  192. package/turnVerdict.js +36 -0
  193. package/usageReceipts.js +176 -0
  194. package/usageSummary.js +90 -0
  195. package/util.js +181 -0
  196. package/vault-core.js +1958 -0
  197. package/vault-kit.mjs +354 -0
  198. package/vault-screens.js +263 -0
  199. package/vaultAtRest.js +177 -0
  200. package/vaultCoreLock.js +111 -0
  201. package/vaultCorePush.js +140 -0
  202. package/vaultDeviceKey.js +95 -0
  203. package/vaultEnclaveHandoff.js +114 -0
  204. package/vaultKeep.js +281 -0
  205. package/vaultSealedStore.js +77 -0
  206. package/vaultWorkerHost.js +98 -0
  207. package/vcWorker.js +34 -0
  208. package/voiceAttest.js +50 -0
  209. package/voiceCert.js +51 -0
  210. package/witbitz-admin.d.ts +135 -0
  211. package/witbitz-admin.js +529 -0
  212. package/witbitz-admin.mjs +1459 -0
  213. package/witbitz-sdk.d.ts +1106 -0
  214. package/witbitz-sdk.js +3835 -0
  215. package/workerClient.js +16 -0
  216. package/workerLiveness.js +21 -0
  217. package/x509.js +218 -0
package/emailFork.js ADDED
@@ -0,0 +1,275 @@
1
+ // spaces/public/emailFork.js — THE MOVE OF A VERIFIED (EMAIL-GATED) ROOM, one set of rules for the SDK and the app
2
+ // (https://witbitz.chat/docs/sdk-people.md#fork). Membership in a verified room is its sealed allow-list, and changing who is in mints a
3
+ // NEW room with a fresh key (a removed member still holds the old one). These are the rules both callers apply: the gate,
4
+ // the owners/admins rule (the same one the server applies — agent/spaceService.mjs forkGovernanceRefusal), the new room's
5
+ // config, which devices receive the new key (the room's guest book, as the email gate verified it), the notice, and what a
6
+ // member's device checks before it follows. Moved verbatim out of witbitz-sdk.js (Space#fork, _maybeMoved,
7
+ // _newRoomKeepsGov, 2026-10-05); the MINT and the transport stay with the caller (the SDK's client, the app's split-,
8
+ // tenant- and enclave-aware path).
9
+ import { memberHash } from './rosterHash.js'
10
+ import { boxesHash, bareEC, jkey } from './spaceFork.js'
11
+ import { sealTo, openBox } from './e2ee.js'
12
+ import { roomRegion } from './regions.js' // a room's home region is in its id (docs/multi-region.md)
13
+ import { accountEmail } from './accountScope.js'
14
+
15
+ export const GATE_EMAIL = /^[^\s@]{1,200}@[^\s@]{1,63}\.[a-z]{2,63}$/i
16
+ export const GATE_DOMAIN = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\.[a-z]{2,63}$/
17
+ /** Does a normAdmission() gate admit this address (shown, hidden or by domain)? */
18
+ export function admittedBy(gate, email) {
19
+ const e = String(email || '').toLowerCase(), al = (gate && gate.allow) || {}
20
+ return [...(al.emails || []), ...(al.hidden || [])].includes(e) || (al.domains || []).includes(e.slice(e.indexOf('@') + 1))
21
+ }
22
+ /** OWNERS — the move rule, the same one the server applies (agent/spaceService.mjs forkGovernanceRefusal). → null when a
23
+ * move to `gov` = { owners, admins } is allowed, else why. An owner may move it any way; anyone else keeps the owners
24
+ * exactly and keeps every admin an admin (raising members to admin is fine). */
25
+ export function govRefusal(owners, admins, gov, byOwner) {
26
+ const l = (v) => (Array.isArray(v) ? v.map((x) => String(x).trim().toLowerCase()).filter(Boolean) : null)
27
+ const nO = l(gov && gov.owners), nA = l(gov && gov.admins)
28
+ if (!nO || !nA) return "a move in a room with owners must declare the new room's owners and admins"
29
+ if (byOwner) return null
30
+ const o = [...new Set(owners)], n = [...new Set(nO)]
31
+ if (o.length !== n.length || !o.every((x) => n.includes(x))) return 'only an owner can change the owners'
32
+ const lost = admins.filter((x) => !nA.includes(x) && !nO.includes(x))
33
+ return lost.length ? `only an owner can lower or remove an admin (${lost.join(', ')})` : null
34
+ }
35
+
36
+ // A gate that cannot be used: one code for all, so fork() and plan() can say why (sync sweep, 2026-10-12).
37
+ const badAdmission = (m) => Object.assign(new Error(m), { code: 'invalid_admission' })
38
+ export function normAdmission(a) {
39
+ if (a === undefined || a === null) return null
40
+ if (typeof a !== 'object' || Array.isArray(a)) throw badAdmission('witbitz: admission takes { emails?, domains? }')
41
+ const clean = (v) => (Array.isArray(v) ? v : []).map((x) => String(x || '').trim().toLowerCase()).filter(Boolean)
42
+ const emails = clean(a.emails), domains = clean(a.domains)
43
+ for (const e of emails) if (!GATE_EMAIL.test(e)) throw badAdmission(`witbitz: "${e}" is not an email address`)
44
+ for (const d of domains) if (!GATE_DOMAIN.test(d)) throw badAdmission(`witbitz: "${d}" is not a domain name, like keepwarden.com`)
45
+ if (!emails.length && !domains.length) throw badAdmission('witbitz: admission needs at least one address or domain — a gate that admits nobody locks you out of your own room, and a room cannot be converted afterwards')
46
+ // ADVERTISE (2026-10-02): addresses are stored HASHED by default, so a member can check one (space.admits) but not
47
+ // read the list. `advertise: true` stores every address readable to members; an array advertises just those.
48
+ const adv = a.advertise === true ? emails : (Array.isArray(a.advertise) ? clean(a.advertise) : [])
49
+ for (const x of adv) if (!emails.includes(x)) throw badAdmission(`witbitz: advertise names "${x}", which is not in emails`)
50
+ if (a.advertise !== undefined && a.advertise !== true && a.advertise !== false && !Array.isArray(a.advertise)) throw badAdmission('witbitz: admission.advertise is true, false, or an array of addresses from emails')
51
+ // ADMINS (2026-10-02): enforced by the room, not the app — see Space#isAdmin. Each must be admitted by this gate.
52
+ // Stored as plain addresses inside the sealed config, so members can see who the admins are; the platform cannot.
53
+ const admins = clean(a.admins)
54
+ for (const x of admins) {
55
+ if (!GATE_EMAIL.test(x)) throw badAdmission(`witbitz: admin "${x}" is not an email address`)
56
+ if (!emails.includes(x) && !domains.includes(x.slice(x.indexOf('@') + 1))) throw badAdmission(`witbitz: admin "${x}" is not admitted by this room — add it to emails (or its domain to domains)`)
57
+ }
58
+ // OWNERS (2026-10-03): a level above admins, enforced by the room — an owner is an admin, and only an owner changes the
59
+ // owners or lowers / removes an admin (Space#fork). Each must be admitted by this gate, like an admin.
60
+ const owners = clean(a.owners)
61
+ for (const x of owners) {
62
+ if (!GATE_EMAIL.test(x)) throw badAdmission(`witbitz: owner "${x}" is not an email address`)
63
+ if (!emails.includes(x) && !domains.includes(x.slice(x.indexOf('@') + 1))) throw badAdmission(`witbitz: owner "${x}" is not admitted by this room — add it to emails (or its domain to domains)`)
64
+ }
65
+ // `approve: 'admins'` (every card admin-only) is REMOVED (the owner, 2026-10-11: "Too complicated") — refused, never
66
+ // dropped in silence: a builder who asked for it must learn the room will not enforce it.
67
+ if (a.removeUsers !== undefined) throw Object.assign(new Error("witbitz: admission.removeUsers was removed — an @username is not stored in a room (only a hash of the account's email), so nobody is moved or removed by it"), { code: 'removed' })
68
+ if (a.approve === 'admins') throw Object.assign(new Error("witbitz: admission.approve 'admins' was removed — admins still decide the cards that change admin-only collections or call a connection"), { code: 'removed' })
69
+ if (a.approve !== undefined && a.approve !== 'members') throw badAdmission("witbitz: admission.approve is no longer an option")
70
+ const adm = { ...(admins.length ? { admins: { emails: admins } } : {}), ...(owners.length ? { owners: { emails: owners } } : {}) }
71
+ if (!adv.length) return { admission: 'email', allow: { ...(emails.length ? { emails } : {}), ...(domains.length ? { domains } : {}) }, ...adm } // all hashed (spaceClient), byte-identical to before when no admins
72
+ const shown = emails.filter((x) => adv.includes(x)), hidden = emails.filter((x) => !adv.includes(x))
73
+ return { admission: 'email', allow: { emails: shown, hidden, ...(domains.length ? { domains } : {}) }, ...adm } // spaceClient: `emails` stay readable, `hidden` are hashed
74
+ }
75
+
76
+ const lower = (v) => (Array.isArray(v) ? v.map((x) => String(x).trim().toLowerCase()).filter(Boolean) : [])
77
+ /** The owners and admins of a room's sealed config, lower-cased. */
78
+ export const govOf = (cfg) => ({ owners: lower(cfg && cfg.owners && cfg.owners.emails), admins: lower(cfg && cfg.admins && cfg.admins.emails) })
79
+
80
+ /** May `email` move this room at all? In a room with admins or owners only they may; otherwise any verified member
81
+ * (the server's rule — spaceService refuses a fork notice from a non-admin where there are admins). */
82
+ export function mayMove(cfg, email) {
83
+ const { owners, admins } = govOf(cfg), me = String(email || '').toLowerCase()
84
+ return !(admins.length || owners.length) || admins.includes(me) || owners.includes(me)
85
+ }
86
+
87
+ /** The OWNERS step of a move, before anything is minted: fills the new gate's owners (and, unless stated, the admins it
88
+ * still admits) from the old room, and refuses a move the server would refuse. → { gate, gov } (gov null in a room
89
+ * without owners). `statedAdmins` = whether the caller stated the new admins itself. */
90
+ export function planGovernance(old, gate, email, statedAdmins) {
91
+ const { owners: oldOwners, admins: oldAdmins } = govOf(old)
92
+ const me = String(email || '').toLowerCase()
93
+ if (!oldOwners.length) return { gate, gov: null }
94
+ gate.owners = gate.owners || { emails: oldOwners }
95
+ if (!statedAdmins && oldAdmins.length) gate.admins = { emails: oldAdmins.filter((e) => admittedBy(gate, e)) }
96
+ const gov = { owners: (gate.owners && gate.owners.emails) || [], admins: (gate.admins && gate.admins.emails) || [] }
97
+ const why = govRefusal(oldOwners, oldAdmins, gov, oldOwners.includes(me))
98
+ if (why) throw Object.assign(new Error('witbitz: ' + why), { code: 'not_owner' })
99
+ const out = [...gov.owners, ...gov.admins].find((x) => !admittedBy(gate, x))
100
+ if (out) throw new Error(`witbitz: "${out}" is an owner or admin of the new room but its gate does not admit them — add them to emails`)
101
+ return { gate, gov }
102
+ }
103
+
104
+ /** The NEW room's config: the same assistant, store and settings under the new gate. Governance from the old gate does
105
+ * not carry (allow, admins, owners, approve, revoked, the key roster), and a connection carries only when the account
106
+ * that granted it is still admitted. `forkedFrom` records where it came from, inside the sealed config. */
107
+ /** A LEGACY room's advertised @username entries (`allow.users: [{ handle, username }]`, written before 2026-10-11) as the
108
+ * handles to carry into the room it moves to — where they are stored HASHED like any hidden entry (spaceClient
109
+ * `handles`). The username label does not carry: an @username is only a redirect, resolved once at invite (the owner,
110
+ * 2026-10-11). One rule for the app's Change members and the SDK's fork. */
111
+ export function carriedHandles(old) {
112
+ return [...new Set((old && old.allow && Array.isArray(old.allow.users) ? old.allow.users : [])
113
+ .filter((u) => u && typeof u === 'object' && typeof u.handle === 'string' && u.handle).map((u) => u.handle))]
114
+ }
115
+
116
+ /** Throws `admins_required` for a collection declared `write: 'admins'` in a room with no admins or owners: the server
117
+ * enforces it only where there are some, so every member would write it (sync sweep, 2026-10-10). `cfg` carries
118
+ * `admins` / `owners` as the sealed config does — a create's gate, a fork's new config. */
119
+ export function checkAdminCollections(data, cfg) {
120
+ const adminOnly = data && typeof data === 'object' ? Object.entries(data).find(([, v]) => v && typeof v === 'object' && v.write === 'admins') : null
121
+ const g = cfg || {}
122
+ if (adminOnly && !(g.admins && Array.isArray(g.admins.emails) && g.admins.emails.length) && !(g.owners && Array.isArray(g.owners.emails) && g.owners.emails.length)) {
123
+ throw Object.assign(new Error(`witbitz: collection "${adminOnly[0]}" is write: 'admins', but the room has no admins or owners — give admission.admins (or owners), or drop write: 'admins'`), { code: 'admins_required' })
124
+ }
125
+ }
126
+
127
+ export function forkConfig(old, gate, fromRoom) {
128
+ // `funding` stays behind: a grant is bound to ITS room (roomFunding: other_room), so the new room would say it is funded and pay nothing (sync sweep, 2026-10-10)
129
+ const { admission: _a, allow: _al, admins: _ad, owners: _ow, approve: _ap, revoked: _r, roster: _ro, parent: _p, forkAuthority: _f, enclave: _e, funding: _fu, ...keep } = old || {}
130
+ if (Array.isArray(keep.connections)) {
131
+ const kept = keep.connections.filter((c) => c && admittedBy(gate, accountEmail(c.account))) // the person, not the app's account (accountScope.js)
132
+ if (kept.length) keep.connections = kept; else delete keep.connections
133
+ }
134
+ return { ...keep, ...gate, forkedFrom: fromRoom, region: roomRegion(fromRoom) } // the new room stays in the old one's region
135
+ }
136
+
137
+ /** The devices that receive the new key: every device that announced itself in the room's guest book AND that the gate
138
+ * verified under an address the new gate admits — plus this one (`selfPub`). → Map(jkey → EC public JWK). */
139
+ export function forkTargets({ book, gate, selfPub }) {
140
+ const admits = (email) => {
141
+ const e = String(email || '').toLowerCase(), a = gate.allow || {}
142
+ return [...(a.emails || []), ...(a.hidden || [])].includes(e) || (a.domains || []).includes(e.slice(e.indexOf('@') + 1))
143
+ }
144
+ const targets = new Map([[jkey(selfPub), bareEC(selfPub)]])
145
+ const seen = (book && book.seen) || {}
146
+ // The guest book's rows: the SDK writes them as the doc itself (an array); the app as { people: [...] } (space.js
147
+ // announceSelf). Both name a member's row by its signing key (x.y) and the server's `seen` vouches for it the same way.
148
+ const st = book && book.state
149
+ const rows = Array.isArray(st) ? st : (st && Array.isArray(st.people) ? st.people : [])
150
+ for (const row of rows) {
151
+ const m = /^([A-Za-z0-9_-]{43})\.([A-Za-z0-9_-]{43})$/.exec((row && row.id) || '')
152
+ if (m && seen[row.id] && admits(seen[row.id].email)) targets.set(row.id, { kty: 'EC', crv: 'P-256', x: m[1], y: m[2] })
153
+ }
154
+ return targets
155
+ }
156
+
157
+ /** The fork NOTICE posted into the old room: the new room's pointer sealed to each target device, the boxes bound by
158
+ * their hash in the signed text, and the declared governance. */
159
+ export async function forkNotice({ from, room, mk, link, targets, gov = null, ts = Date.now() }) {
160
+ const pointer = JSON.stringify({ v: 1, kind: 'space-fork', from, room, mk, link })
161
+ const boxes = await Promise.all([...targets.values()].map((j) => sealTo(pointer, j)))
162
+ return { kind: 'fork', id: 'fork:' + ts, ts, name: 'fork', from: 'fork', text: 'fork:' + (await boxesHash(boxes)), boxes, ...(gov ? { gov } : {}) }
163
+ }
164
+
165
+ // THE CREATOR'S SIGNATURE (a room with no owners/admins). The server's stamp names the key the email gate verified — the
166
+ // device's EMAIL signing key — while the room's `forkAuthority` is the creator key minted at creation, a different key. So
167
+ // in such a room the creator's device also signs the notice with the creator key (`sig`, a field the server keeps) and
168
+ // members verify it against `forkAuthority`. Bound to the room and the notice text (which binds the boxes).
169
+ const ECDSA = { name: 'ECDSA', namedCurve: 'P-256' }
170
+ const SIG_ALG = { name: 'ECDSA', hash: 'SHA-256' }
171
+ const moveMessage = (room, text) => new TextEncoder().encode('witbitz-email-move|' + room + '|' + text)
172
+ const b64u = (u8) => btoa(String.fromCharCode(...u8)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
173
+ const unb64u = (s) => Uint8Array.from(atob(String(s).replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0))
174
+ const ecJwk = (j, priv) => ({ kty: 'EC', crv: 'P-256', x: j.x, y: j.y, ...(priv ? { d: j.d } : {}) })
175
+ /** The creator signs a notice (a room with no owners/admins). → the notice with `sig`. */
176
+ export async function signMove(notice, room, creatorPriv) {
177
+ const k = await crypto.subtle.importKey('jwk', ecJwk(creatorPriv, true), ECDSA, false, ['sign'])
178
+ return { ...notice, sig: b64u(new Uint8Array(await crypto.subtle.sign(SIG_ALG, k, moveMessage(room, notice.text)))) }
179
+ }
180
+ /** Was this notice signed by `pub` for this room? Anything malformed is a no. */
181
+ export async function moveSignedBy(e, room, pub) {
182
+ try {
183
+ if (!e || typeof e.sig !== 'string' || !pub || !pub.x) return false
184
+ const k = await crypto.subtle.importKey('jwk', ecJwk(pub, false), ECDSA, false, ['verify'])
185
+ return await crypto.subtle.verify(SIG_ALG, k, unb64u(e.sig), moveMessage(room, String(e.text || '')))
186
+ } catch { return false }
187
+ }
188
+
189
+ /** A member's device decides about a fork notice in an email room. `cfg` = the room's sealed config as this device reads
190
+ * it, `signPriv` = this device's signing key, `forkAuthority` = the room's creator key when it has no owners/admins (the
191
+ * app's rule: there, only a notice the creator key SIGNED is followed — signMove; the SDK passes none). → { follow: pointer } | { refuse: reason } | null
192
+ * (not for this device / not a valid notice — ignore it). The caller still checks the NEW room (newRoomKeepsGov). */
193
+ export async function judgeMove(e, { cfg, signPriv, room, forkAuthority = null }) {
194
+ if (!signPriv) return null
195
+ const auth = await moveAuthority(e, { cfg, room, forkAuthority })
196
+ if (auth !== 'ok') return auth === 'refuse' ? { refuse: 'the move does not keep this room\'s owners and admins' } : null
197
+ const { owners } = govOf(cfg)
198
+ for (const b of e.boxes) {
199
+ let o = null
200
+ try { const pt = await openBox(b, bareEC(signPriv)); o = pt ? JSON.parse(pt) : null } catch { o = null }
201
+ if (o && o.kind === 'space-fork' && o.from === room && o.room && o.mk && typeof o.link === 'string') return { follow: o, needsGovCheck: owners.length > 0 }
202
+ }
203
+ return null
204
+ }
205
+
206
+ /** IS THIS A REAL MOVE OF THIS ROOM — whoever it is addressed to? The checks judgeMove makes before opening a box: the
207
+ * server's stamp, an admin's notice where the room has owners/admins (else the creator's signature), the owners kept,
208
+ * the boxes bound by the text. → 'ok' | 'refuse' | null. A device the notice does NOT address (a member removed by it)
209
+ * uses it to know the room is over (space.js noteMovedRoom). */
210
+ export async function moveAuthority(e, { cfg, room, forkAuthority = null }) {
211
+ if (!e || e.kind !== 'fork' || e.verified !== true || !Array.isArray(e.boxes)) return null
212
+ const { owners, admins } = govOf(cfg)
213
+ if ((admins.length || owners.length) && e.admin !== true) return null
214
+ if (!admins.length && !owners.length && forkAuthority && !(await moveSignedBy(e, room, forkAuthority))) return null
215
+ if (owners.length && (!e.gov || govRefusal(owners, admins, e.gov, e.owner === true))) return 'refuse'
216
+ if (String(e.text || '') !== 'fork:' + (await boxesHash(e.boxes))) return null
217
+ return 'ok'
218
+ }
219
+
220
+ /** OWNERS: does the NEW room's sealed config (read with the new room's key) name exactly the owners and admins the move
221
+ * declared, and admit each of them? Anything unreadable is a no. */
222
+ export async function newRoomKeepsGov(cfg, gov, room) {
223
+ try {
224
+ if (!cfg || cfg.admission !== 'email') return false
225
+ const set = (o) => [...new Set((o && Array.isArray(o.emails) ? o.emails : []).map((x) => String(x).trim().toLowerCase()))].sort().join('\n')
226
+ const want = (v) => [...new Set((Array.isArray(v) ? v : []).map((x) => String(x).trim().toLowerCase()))].sort().join('\n')
227
+ if (set(cfg.owners) !== want(gov.owners) || set(cfg.admins) !== want(gov.admins)) return false
228
+ const a = cfg.allow || {}
229
+ for (const e of [...gov.owners, ...gov.admins]) {
230
+ const x = String(e).toLowerCase()
231
+ const ok = (Array.isArray(a.emails) && a.emails.map((y) => String(y).toLowerCase()).includes(x)) ||
232
+ (Array.isArray(a.mh) && a.mh.includes(await memberHash(x, room))) ||
233
+ (Array.isArray(a.domains) && a.domains.map((d) => String(d).toLowerCase().replace(/^@/, '')).includes(x.slice(x.indexOf('@') + 1)))
234
+ if (!ok) return false
235
+ }
236
+ return true
237
+ } catch { return false }
238
+ }
239
+
240
+ /** THE NEW ROOM'S OWNERS, READ AS A DEVICE CAN (the owner, 2026-10-21: a remaining member's Android refused a move as "owners
241
+ * or admins don't match" and stayed behind with the removed member; reopening followed at once). `read()` → the new room's
242
+ * sealed config; right after a move it can fail or come back empty (a confidential, verified room is still waking or
243
+ * signing this device in). Tried a few times over ~40 s. → 'keeps' | 'differs' (it read, and names other owners/admins —
244
+ * final) | 'unreadable' (never read — not a verdict on the move). `pause(ms)` is for tests. */
245
+ export const NEW_ROOM_READ_WAITS = [2000, 4000, 8000, 12000, 15000]
246
+ export async function checkNewRoomGov(read, gov, room, { pause = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {
247
+ for (let i = 0; ; i++) {
248
+ let cfg = null
249
+ try { cfg = await read() } catch { cfg = null }
250
+ if (cfg && typeof cfg === 'object') return (await newRoomKeepsGov(cfg, gov, room)) ? 'keeps' : 'differs'
251
+ if (i >= NEW_ROOM_READ_WAITS.length) return 'unreadable'
252
+ await pause(NEW_ROOM_READ_WAITS[i])
253
+ }
254
+ }
255
+
256
+ /** CARRY THE HISTORY (2026-10-07). The SERVER copies it (op 'carry'): it reads the old room under its key and keeps each
257
+ * entry's verified mark as `carried` — which a device carrying the entries itself could never vouch for. `page(cursor)`
258
+ * → the op's answer for one page; the loop follows `next`. A server without the op (a confidential room until its
259
+ * enclave learns it) or a path that cannot send the old key answers 400 on the first page — and a room worker of an older
260
+ * build (the hosted app's vault) THROWS there, not knowing the op — and `viaDevice()` carries the history the old way (the
261
+ * marks are then not kept). → { carried, server } or { refused: <the answer> }. */
262
+ export async function carryHistory(page, viaDevice) {
263
+ if (typeof page !== 'function') return { carried: await viaDevice(), server: false }
264
+ let cursor = 0, carried = 0
265
+ for (let n = 0; n < 10000; n++) {
266
+ let r
267
+ try { r = await page(cursor) } catch (e) { if (n === 0) return { carried: await viaDevice(), server: false }; throw e }
268
+ if (n === 0 && r && r.status === 400) return { carried: await viaDevice(), server: false }
269
+ if (!r || r.status !== 200) return { refused: r || { status: 0 } }
270
+ carried += Number(r.carried) || 0
271
+ if (!Number.isInteger(r.next) || r.next <= cursor) return { carried, server: true }
272
+ cursor = r.next
273
+ }
274
+ return { refused: { status: 0, error: 'carry_runaway' } }
275
+ }
package/emailSignIn.js ADDED
@@ -0,0 +1,81 @@
1
+ // emailSignIn.js — signing in with an emailed code, one protocol for the vault, the Spaces app and the SDK
2
+ // (docs/sdk-convergence.md, phase 5). Each side keeps its own SCREENS (the vault's sheet, the app's overlay, a builder's
3
+ // form); the wire and its rules live here:
4
+ // start — mail a code, bound to this device's signing key through `nonce` → { ticket }
5
+ // verify — the code → an RS256 token for the verified email (the server accepts it like a Google token)
6
+ // refresh — the same session onto a NEW key, without a new code: the OLD key signs the new nonce (proof it is the
7
+ // device that verified). The app has always renewed this way; the SDK now can too (wb.refreshSession()).
8
+ // `post` is a function (path, body) → parsed JSON | null. makeEmailPost tries the local origin first and, when it has no
9
+ // email stack, the auth broker's relay — the vault's behaviour.
10
+ import { signAssertion } from './entrySig.js'
11
+
12
+ const RELAY_MAP = { '/api/email/start': '/api/relay/start', '/api/email/verify': '/api/relay/verify', '/api/email/refresh': '/api/relay/refresh', '/api/email/adopt': '/api/relay/adopt' }
13
+ export function makeEmailPost (base, { broker = '', fetchImpl = (...a) => fetch(...a) } = {}) {
14
+ const call = async (url, body) => {
15
+ try {
16
+ const response = await fetchImpl(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
17
+ const data = await response.json().catch(() => null)
18
+ if (response.status === 401 || response.status === 403) return { ...data, ok: false, status: response.status }
19
+ return data
20
+ } catch { return null }
21
+ }
22
+ return async (path, body) => {
23
+ const local = await call(String(base || '').replace(/\/$/, '') + path, body)
24
+ if (local && local.configured !== false) return local
25
+ const rp = RELAY_MAP[path]
26
+ if (!broker || !rp) return local
27
+ return (await call(String(broker).replace(/\/$/, '') + rp, body)) || local
28
+ }
29
+ }
30
+
31
+ export function jwtPayload (jwt) {
32
+ try { const b = String(jwt).split('.')[1].replace(/-/g, '+').replace(/_/g, '/'); return JSON.parse(decodeURIComponent(escape(atob(b)))) } catch { return {} }
33
+ }
34
+
35
+ // Friendly copy for the backend's machine reasons (never a provider's raw body).
36
+ export function startError (reason) {
37
+ if (reason === 'invalid email') return 'Enter a valid email address.'
38
+ if (reason === 'too many requests') return 'Too many requests — wait a minute and try again.'
39
+ if (reason === 'invalid room') return 'Something went wrong — reopen the Space and try again.'
40
+ if (typeof reason === 'string' && reason.includes('capacity')) return reason
41
+ return 'Couldn’t send the code — try again.'
42
+ }
43
+ export function verifyError (reason) {
44
+ if (reason === 'mismatch') return 'That code didn’t match — check it and try again.'
45
+ if (reason === 'expired') return 'That code expired — go back and request a new one.'
46
+ if (reason === 'too many attempts' || reason === 'locked') return 'Too many tries — request a new code.'
47
+ return 'Couldn’t verify that code — try again.'
48
+ }
49
+ const fail = (code, reason, message) => Object.assign(new Error(message), { code, reason: reason || '' })
50
+ export const isEmail = (s) => /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(String(s || ''))
51
+
52
+ /** → { ticket }. Throws { code: 'not_configured' | 'start_failed', reason, message (friendly) }. */
53
+ export async function emailStart (post, { email, room = '', nonce, tenant = '' }) {
54
+ // `tenant` (the SDK's): lets the mail carry the app's name when this page is on an origin that tenant declared
55
+ const r = await post('/api/email/start', { email: String(email).trim().toLowerCase(), room: String(room || '').slice(0, 200), nonce, ...(tenant ? { tenant: String(tenant).slice(0, 64) } : {}) })
56
+ if (r && r.configured === false) throw fail('not_configured', '', 'Email codes aren’t available right now.')
57
+ if (!r || !r.ok || !r.ticket) throw fail('start_failed', r && r.reason, startError(r && r.reason))
58
+ return { ticket: r.ticket }
59
+ }
60
+ /** → { jwt, email, exp (ms) }. Throws { code: 'verify_failed', reason, message (friendly) }. */
61
+ export async function emailVerify (post, { ticket, code }) {
62
+ const r = await post('/api/email/verify', { ticket, code: String(code).trim() })
63
+ if (!r || !r.ok || !r.jwt) throw fail('verify_failed', r && r.reason, verifyError(r && r.reason))
64
+ const p = jwtPayload(r.jwt)
65
+ return { jwt: r.jwt, email: String(p.email || '').toLowerCase(), exp: (Number(p.exp) || 0) * 1000 }
66
+ }
67
+ /** The session onto a new key. `kpOld` = { priv, pub } the token is bound to; `newNonce` = the new key's nonce.
68
+ * → { jwt, email, exp } | null (the caller falls back to a new code). */
69
+ export async function emailRefresh (post, { token, kpOld, newNonce, tenant, throwOnRefusal = false }) { // tenant: a builder's app — its scope rides the renewed token when the registry holds this origin as the tenant's proven one (docs/device-gate-design.md § 12.1)
70
+ try {
71
+ const ts = Date.now()
72
+ const sig = await signAssertion(kpOld.priv, { act: 'email-refresh', to: String(newNonce), ts })
73
+ const r = await post('/api/email/refresh', { token, spkOld: kpOld.pub, newNonce, ts, sig, ...(tenant ? { tenant: String(tenant).slice(0, 64) } : {}) })
74
+ if (throwOnRefusal && !r?.ok && (r?.status === 401 || r?.status === 403)) {
75
+ throw Object.assign(new Error('Sign in again to renew this session'), { code: 'refresh_failed', status: r.status })
76
+ }
77
+ if (!r || !r.ok || !r.jwt) return null
78
+ const p = jwtPayload(r.jwt)
79
+ return { jwt: r.jwt, email: String(p.email || '').toLowerCase(), exp: (Number(p.exp) || 0) * 1000 }
80
+ } catch (err) { if (throwOnRefusal && err?.code === 'refresh_failed') throw err; return null }
81
+ }
package/emptySpaces.js ADDED
@@ -0,0 +1,111 @@
1
+ // spaces/public/emptySpaces.js — Settings → "Remove empty Spaces" (spaces/test/emptySpaces.test.mjs). The owner,
2
+ // 2026-10-10, after a day of Help attempts left a run of unnamed, empty Spaces in the list: "Build it that way" — check
3
+ // each Space with the server, list what qualifies, ask once, delete them on the server and from every device.
4
+ //
5
+ // ★ WHAT QUALIFIES — all of it, or the Space is kept:
6
+ // - the server answers for it, and it holds NO message (a name entry is not a message);
7
+ // - nobody else was invited into it (its sealed config names no other email);
8
+ // - it is not pinned, not the Help Space, not a private lane or one with a lane, not temporary.
9
+ // ★ HOW IT GOES: the server delete first (roomDelete.deleteOwnRoom — the account's delete commitment; the server itself
10
+ // refuses a Space someone else has used, 409), then the device forgets it exactly as a delete by hand does (tombstone
11
+ // → every device). A Space this account did not create carries no commitment (404): it holds nothing, so it is only
12
+ // forgotten. Anything the server refuses or fails is kept and said.
13
+
14
+ let _h = {
15
+ rooms: () => [], // → [{ room, title, pinned, archived }] — this device's list (recents)
16
+ read: async () => null, // (room) → { entries, config } | null (the server's answer; null = could not read)
17
+ me: () => '', // → this account's email
18
+ keep: () => false, // (room) → true for the Help Space, lanes, anything never to touch
19
+ deleteOnServer: async () => ({ ok: false, status: 0 }), // (room) → roomDelete.deleteOwnRoom
20
+ forget: async () => {}, // (room) → the device's delete (forgetSpace + afterItemGone)
21
+ gone: async () => false, // (room) → true when the Space answers 'deleted' (410): the server finished after the call gave up
22
+ }
23
+ export const setEmptySpacesHooks = (h) => { _h = { ..._h, ...h } }
24
+
25
+ /** A message is anything a person or the assistant put in the room — not its name (title entries) or a system line. */
26
+ export const hasMessages = (entries) => (Array.isArray(entries) ? entries : []).some((e) => e && e.kind !== 'title' && !e.sys)
27
+ /** Other people named in its sealed config (invited by email, admins, owners) — then it is not only yours. */
28
+ export async function ownAdmissionEntries(config, email, readRoster) {
29
+ const mine = String(email || '').trim().toLowerCase()
30
+ if (!mine || ![config?.allow, config?.admins, config?.owners].some(p => p?.users?.length || p?.mh?.length)) return []
31
+ const book = await Promise.resolve().then(readRoster).catch(() => null)
32
+ if (book?.status !== 200) return []
33
+ return Object.values(book.seen || {}).filter(row => String(row?.email || '').trim().toLowerCase() === mine)
34
+ .flatMap(row => Array.isArray(row.entries) ? row.entries : [])
35
+ }
36
+ export function othersIn(config, me, selfHash = '', selfEntries = []) {
37
+ if (!config || typeof config !== 'object' || config.gated || config.error) return true
38
+ for (const policy of [config.allow, config.admins, config.owners]) {
39
+ if (policy?.mh && (!Array.isArray(policy.mh) || policy.mh.some(hash => hash !== selfHash && !selfEntries.includes('mh:' + hash)))) return true
40
+ if (policy?.domains?.length) return true
41
+ if (policy?.users?.some(user => !user?.handle || !selfEntries.includes('u:' + String(user.handle).toLowerCase()))) return true
42
+ }
43
+ const mine = String(me || '').trim().toLowerCase()
44
+ const lists = [config && config.allow && config.allow.emails, config && config.admins && config.admins.emails, config && config.owners && config.owners.emails]
45
+ return lists.flat().filter(Boolean).map((x) => String(x).trim().toLowerCase()).some((x) => x && x !== mine)
46
+ }
47
+
48
+ /** → [{ room, title }] of the Spaces that qualify. Reads up to 4 at a time; a Space it cannot read is kept. */
49
+ export async function findEmptySpaces({ onProgress, onUnreadable } = {}, hooks = _h) {
50
+ const me = hooks.me()
51
+ const list = (hooks.rooms() || []).filter((r) => r && r.room && !String(r.room).startsWith('tmp-') && !r.pinned && !hooks.keep(r.room))
52
+ const out = []
53
+ let i = 0, done = 0
54
+ const worker = async () => {
55
+ while (i < list.length) {
56
+ const r = list[i++]
57
+ let v = null
58
+ try { v = await hooks.read(r.room) } catch { v = null }
59
+ done++; try { onProgress && onProgress(done, list.length) } catch { /* */ }
60
+ if (v?.excluded) continue
61
+ if (!v || !Array.isArray(v.entries) || !v.config || v.config.gated || v.config.error) { onUnreadable?.(r.room); continue } // unknown → kept
62
+ if (hasMessages(v.entries) || othersIn(v.config, me, v.selfHash, v.selfEntries)) continue
63
+ out.push({ room: r.room, title: (r.title && r.title !== r.room) ? r.title : 'Space' })
64
+ }
65
+ }
66
+ await Promise.all([worker(), worker(), worker(), worker()])
67
+ return out
68
+ }
69
+
70
+ /** Why a Space stayed, in words — the owner saw "the server did not answer" for a delete that never left the phone. */
71
+ export function whyKept (r) {
72
+ const st = (r && r.status) || 0, err = (r && r.body && r.body.error) || ''
73
+ if (err === 'room_changed' || err === 'cleanup_unconfirmed') return 'the final check could not confirm the room was unchanged'
74
+ if (st === 200 && r?.body?.deleted === false) return 'deletion has not been confirmed'
75
+ if (st === 409) return 'someone else has used it'
76
+ if (err === 'no_account_key') return 'this device has no key for deleting your Spaces — open the app on the device you made it on'
77
+ if (!st) return 'the server could not be reached'
78
+ return `the server refused it (${st}${err ? ' ' + err : ''})`
79
+ }
80
+
81
+ /** Delete each on the server, then forget it on every device. → { removed, forgottenOnly, kept: [{ title, why }] } */
82
+ export async function removeEmptySpaces(found, hooks = _h) {
83
+ const rep = { removed: 0, forgottenOnly: 0, kept: [] }
84
+ for (const s of found) {
85
+ const listed = (hooks.rooms() || []).find(item => item.room === s.room)
86
+ const policy = listed && hooks.prepare ? await hooks.prepare(s.room).catch(() => null) : null
87
+ const latest = listed && !listed.pinned && !s.room.startsWith('tmp-') && !hooks.keep(s.room)
88
+ ? await hooks.read(s.room).catch(() => null) : null
89
+ if (!latest || !Array.isArray(latest.entries) || hasMessages(latest.entries) || othersIn(latest.config, hooks.me(), latest.selfHash, latest.selfEntries)) {
90
+ rep.kept.push({ title: s.title, why: 'could not confirm it is still empty and only yours' })
91
+ continue
92
+ }
93
+ let r = { ok: false, status: 0 }
94
+ for (let n = 0; n < 5; n++) { r = await hooks.deleteOnServer(s.room, latest.etag || 'absent', policy?.body?.policyVersion).catch(() => ({ ok: false, status: 0 })); if (r.status !== 207) break } // 207: partly done, call again
95
+ if (r.status === 200 && r.body?.deleted === false && hooks.checkDeletion) {
96
+ const until = Date.now() + 120000
97
+ do {
98
+ await new Promise(resolve => setTimeout(resolve, 2000))
99
+ const checked = await hooks.checkDeletion(s.room).catch(() => null)
100
+ if (!checked || checked.status !== 200 || checked.body?.deleted === true) { if (checked?.body?.deleted === true) r = checked; break }
101
+ } while (Date.now() < until)
102
+ }
103
+ if ((r.ok || r.status === 200) && r.body?.deleted === true) { await hooks.forget(s.room); rep.removed++ }
104
+ else if (r.status === 404) { await hooks.forget(s.room); rep.forgottenOnly++ } // not created by this account: nothing on it to delete
105
+ // the delete marks the Space deleted FIRST and then sweeps its data — a sweep longer than the gateway's 30 s answers 503 (or
106
+ // nothing) to a delete that went through (the owner, 2026-10-16: 'Try' kept with 503; the server logged it done, 75–98 s)
107
+ else if (r.status !== 409 && await hooks.gone(s.room).catch(() => false)) { await hooks.forget(s.room); rep.removed++ }
108
+ else rep.kept.push({ title: s.title, why: whyKept(r) })
109
+ }
110
+ return rep
111
+ }
package/encSource.js ADDED
@@ -0,0 +1,55 @@
1
+ // encSource.js — "REBUILT FROM SOURCE" in a confidential room's sheet (the Hacker News demo's verify step). The build this room's
2
+ // enclave attests (its PCR16, verified on this device) is looked up in the build enclave's published releases
3
+ // (/audit/releases/turn-enclave.jsonl, docs/build-enclave.md): a passing entry says the attested build enclave rebuilt that
4
+ // measurement from a named commit's source, and the entry is in Rekor, the public transparency log, at its logIndex. The row
5
+ // links that entry, so anyone can check it without trusting this page.
6
+ export const RELEASES_LOG = '/audit/releases/turn-enclave.jsonl'
7
+ export const rekorUrl = (logIndex) => `https://search.sigstore.dev/?logIndex=${encodeURIComponent(String(logIndex))}`
8
+
9
+ /** The newest PASSING release whose claim names `pcr16`, from the log's text → { commit, logIndex, at } | null. */
10
+ export function releaseFor (text, pcr16) {
11
+ const want = String(pcr16 || '').toLowerCase()
12
+ if (!/^[0-9a-f]{96}$/.test(want)) return null
13
+ let hit = null
14
+ for (const line of String(text || '').split('\n')) {
15
+ if (!line.trim()) continue
16
+ let e; try { e = JSON.parse(line) } catch { continue }
17
+ const c = e && e.claim, s = e && e.source, r = e && e.rekor
18
+ if (!e || e.verdict !== 'pass' || !c || String(c.pcr16 || '').toLowerCase() !== want) continue
19
+ if (!s || !/^[0-9a-f]{40}$/.test(String(s.commit || '')) || !r || !Number.isInteger(r.logIndex)) continue
20
+ if (!hit || Number(e.at) >= hit.at) hit = { commit: s.commit, logIndex: r.logIndex, at: Number(e.at) || 0 }
21
+ }
22
+ return hit
23
+ }
24
+
25
+ let _log = null // the log's text for this page's life: it changes only with a release
26
+ /** Look `pcr16` up in the published log → the release, null (not in it), or undefined (the log could not be read). */
27
+ export async function loadReleaseFor (pcr16, fetchImpl = (u, o) => fetch(u, o)) {
28
+ try {
29
+ if (_log === null) { const r = await fetchImpl(RELEASES_LOG, { cache: 'no-cache' }); if (!r || !r.ok) return undefined; _log = await r.text() }
30
+ return releaseFor(_log, pcr16)
31
+ } catch { return undefined }
32
+ }
33
+ export const _resetLog = () => { _log = null } // tests
34
+
35
+ /** Fill the sheet's row (label + value span) for the attested build `att`. */
36
+ export async function renderEncSource (valueEl, att, deps = {}) {
37
+ if (!valueEl) return
38
+ const pcr16 = att && att.pcrs && att.pcrs[16]
39
+ valueEl.textContent = 'Checking…'
40
+ const rel = pcr16 ? await loadReleaseFor(pcr16, deps.fetch) : null
41
+ if (rel === undefined) { valueEl.textContent = 'Couldn’t read the log'; return }
42
+ if (!rel) { valueEl.textContent = 'Not in the published log'; valueEl.classList.add('enc-bad'); return }
43
+ const a = document.createElement('a')
44
+ a.href = rekorUrl(rel.logIndex); a.target = '_blank'; a.rel = 'noopener noreferrer'
45
+ a.textContent = `Yes · commit ${rel.commit.slice(0, 8)} ↗`
46
+ a.title = `The build enclave rebuilt this measurement from commit ${rel.commit}; Rekor entry ${rel.logIndex}`
47
+ // OUR COPY OF THE RECORD beside the public log's (2026-11-04: search.sigstore.dev said "Load failed" while Rekor did not
48
+ // answer): the signed entry is in the published release log too, so the proof never rests on one third-party page.
49
+ const rec = document.createElement('a')
50
+ rec.href = RELEASES_LOG; rec.target = '_blank'; rec.rel = 'noopener noreferrer'; rec.className = 'enc-rec'
51
+ rec.textContent = 'record ↗'
52
+ rec.title = 'The build enclave\'s signed release record (the same entry as in Rekor), published with this app'
53
+ valueEl.replaceChildren(a, ' · ', rec); valueEl.classList.add('enc-ok')
54
+ return rel
55
+ }