@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,123 @@
1
+ // memberChange.js — THE PURE HALF OF A MEMBER CHANGE IN PLACE (docs/key-rotation-design.md § (b)), one rule for the Spaces app
2
+ // (rekeyMembers.js, through its key worker) and the SDK (sdkRekey.js, which holds the key itself): who the room ends with, in
3
+ // the config's own shape, and each remaining member's grant address and invite key. Nothing here holds a key.
4
+ import { memberHash } from './rosterHash.js'
5
+ import { govOf } from './emailFork.js'
6
+ import { resolveHandle } from './inviteEnroll.js'
7
+ import { findInvitee } from './inviteSend.js'
8
+
9
+ export const lc = (e) => String(e || '').trim().toLowerCase()
10
+ export const EMAIL = /^[^\s@]{1,200}@[^\s@]{1,63}\.[a-z]{2,63}$/i
11
+
12
+ /** Each email's grant address in this room (memberHash) and its account invite key (the directory). Someone with no invite key
13
+ * is named, and their grant address holds 'pending' (their device asks for a fresh link). `app`: another slot of the account
14
+ * (an attested room's box for its kind); `scope`: the directory namespace (the SDK: its app's own, 'app:<origin>').
15
+ * → { recipients:[{ email, mh, boxPub }], unreachable:[email], pending:[mh] } */
16
+ export async function recipientsFor (room, emails, client, { app = '', scope, allow, people = [] } = {}) {
17
+ const recipients = [], unreachable = [], pending = []
18
+ // A roster email is not an email admission. Resolve a public username only after its CURRENT room tag matches
19
+ // the retained allow-list. Never seal a grant to a roster-supplied key, or redirect one to a renamed/reclaimed username.
20
+ const tagOnly = new Set(), allowed = new Set(allow && allow.mh || [])
21
+ for (const p of people) {
22
+ if (!p || p.left || !p.user || !Array.isArray(p.entries) || typeof client.userTag !== 'function') continue
23
+ const candidates = p.entries.filter((x) => typeof x === 'string' && x.startsWith('mh:') && allowed.has(x.slice(3))).map((x) => x.slice(3))
24
+ if (!candidates.length) continue
25
+ const email = lc(p.email), emailHash = email ? await memberHash(email, room) : ''
26
+ const t = await client.userTag(p.user, room).catch(() => null)
27
+ if (!t || t.status !== 200 || !candidates.includes(t.tag)) continue
28
+ if (!(allow.emails || []).map(lc).includes(email) && !allowed.has(emailHash) && !(allow.domains || []).some((d) => email.endsWith('@' + lc(d)))) tagOnly.add(email)
29
+ let f = await findInvitee({ username: p.user, app, scope }, client).catch(() => null)
30
+ // Builders may have an email slot without a username slot. Only an existing, discoverable slot counts:
31
+ // keep the verified room tag, never manufacture an email pending grant when this door is closed.
32
+ if ((!f || !f.ok) && email) f = await findInvitee({ email, app, scope }, client).catch(() => null)
33
+ if (f && f.ok && !recipients.some((r) => r.mh === t.tag)) recipients.push({ email, mh: t.tag, boxPub: f.entry.boxPub })
34
+ else if (!f || !f.ok) unreachable.push(email || '@' + p.user)
35
+ }
36
+ await Promise.all([...new Set(emails.map(lc).filter((e) => EMAIL.test(e)))].map(async (email) => {
37
+ if (tagOnly.has(email)) return
38
+ try {
39
+ const mh = await memberHash(email, room)
40
+ const handle = await (scope === undefined ? resolveHandle(email, client) : resolveHandle(email, client, scope))
41
+ const g = handle ? await client.dirGet(handle, app ? { app } : {}) : null
42
+ if (g && g.status === 200 && g.entry && g.entry.boxPub) recipients.push({ email, mh, boxPub: g.entry.boxPub })
43
+ else { unreachable.push(email); pending.push(mh) }
44
+ } catch { unreachable.push(email) }
45
+ }))
46
+ return { recipients, unreachable, pending }
47
+ }
48
+
49
+ /** A REMOVED PERSON'S @USERNAME ENTRIES (sync sweep 2026-10-22): the list may hold them by @username too — a tag for this room
50
+ * (new rooms), the hash of their handle or an advertised { handle, username } (older rooms). `tagOf(u)` → tag, `handleOf(u)` →
51
+ * handle; a lookup that fails drops what it can. → { mh, users } for membersAfter's `want.drop`. */
52
+ export async function dropsForUsers (room, users, { tagOf, handleOf } = {}) {
53
+ const names = [...new Set((users || []).map((u) => lc(u).replace(/^@/, '')).filter(Boolean))]
54
+ const mh = []
55
+ await Promise.all(names.map(async (u) => {
56
+ try { const t = tagOf ? await tagOf(u) : ''; if (typeof t === 'string' && t) mh.push(t) } catch { /* no tag known */ }
57
+ try { const h = handleOf ? await handleOf(u) : ''; if (typeof h === 'string' && h) mh.push(await memberHash(h, room)) } catch { /* no handle */ }
58
+ }))
59
+ return { mh: [...new Set(mh)], users: names }
60
+ }
61
+
62
+ /** The members a change ends with, in the config's OWN shape: advertised addresses stay in `emails`, hidden ones stay as
63
+ * their hashes (`mh`) unless the change removes them, domains as they are. */
64
+ export async function membersAfter (cfg, want, room) {
65
+ const al = (cfg && cfg.allow) || {}
66
+ const keepAll = new Set((want.emails || []).map(lc))
67
+ const before = [...new Set([...(Array.isArray(al.emails) ? al.emails : []), ...(want.known || [])].map(lc))]
68
+ const removed = before.filter((e) => EMAIL.test(e) && !keepAll.has(e))
69
+ const removedMh = new Set(await Promise.all(removed.map((e) => memberHash(e, room))))
70
+ const shown = [...new Set((want.shown || []).map(lc).filter((e) => keepAll.has(e)))]
71
+ const allow = { ...al, emails: shown }
72
+ // the same people's @username entries (dropsForUsers): a tag or a handle's hash in `mh`, an older room's advertised `users`
73
+ const drop = want.drop || {}
74
+ for (const h of (Array.isArray(drop.mh) ? drop.mh : [])) removedMh.add(h)
75
+ const dropUsers = new Set((Array.isArray(drop.users) ? drop.users : []).map((u) => lc(u).replace(/^@/, '')))
76
+ if (Array.isArray(al.mh)) allow.mh = al.mh.filter((h) => !removedMh.has(h))
77
+ if (Array.isArray(al.users) && dropUsers.size) allow.users = al.users.filter((u) => !(u && typeof u === 'object' && dropUsers.has(lc(u.username))))
78
+ if (Array.isArray(want.domains)) allow.domains = want.domains.map(lc)
79
+ for (const k of Object.keys(allow)) if (allow[k] === undefined || (Array.isArray(allow[k]) && !allow[k].length && k !== 'emails')) delete allow[k]
80
+ const set = (xs) => ({ emails: [...new Set((xs || []).map(lc))] })
81
+ return { allow, owners: set(want.owners), admins: set((want.admins || []).filter((e) => !(want.owners || []).map(lc).includes(lc(e)))), removed }
82
+ }
83
+
84
+ // HIDDEN MEMBERS NOBODY HAS SEEN: an address the list keeps only as its hash (allow.mh — a private invite not opened yet) has no
85
+ // email to look up an invite key by, so no grant can be sealed to it. Each gets the `pending` marker at its own hash: their
86
+ // device, with the link it was sent, is told to ask for a fresh one — never that the room went on without them.
87
+ export const unseenHidden = (allow, recipients, pending) => {
88
+ const covered = new Set([...recipients.map((x) => x.mh), ...pending])
89
+ return (Array.isArray(allow && allow.mh) ? allow.mh : []).filter((h) => typeof h === 'string' && h && !covered.has(h))
90
+ }
91
+
92
+ /** STILL ON THE LIST? A room re-keyed in place (option (b): its config carries `keyChain`) keeps its guest book — so the
93
+ * devices of someone REMOVED are still in it, and their posts are still in the history. Before, a member change made a
94
+ * new room with a fresh guest book; now the book must be checked against the list (the owner, 2026-10-22: "After removing
95
+ * from the group I see alice as a member"). → a predicate (email, user) → bool, or null when the room was never
96
+ * re-keyed (the guest book is the list, as before). On the list: an advertised email, an owner or admin, a domain, a
97
+ * hidden entry (memberHash). Someone known only by @username where the list has @username entries cannot be decided
98
+ * here and is kept. */
99
+ export async function stillOnList (cfg, room, people = []) {
100
+ if (!cfg || !Array.isArray(cfg.keyChain) || !cfg.keyChain.length) return null
101
+ const al = cfg.allow || {}, g = govOf(cfg)
102
+ const ok = new Set([...(Array.isArray(al.emails) ? al.emails : []), ...g.owners, ...g.admins].map(lc))
103
+ const domains = (Array.isArray(al.domains) ? al.domains : []).map(lc)
104
+ const mh = new Set(Array.isArray(al.mh) ? al.mh : [])
105
+ const byUser = (Array.isArray(al.users) && al.users.length) || (Array.isArray(al.tagUsers) && al.tagUsers.length)
106
+ // `people`: addresses, or the guest book's records ({ email, entries }). A person added by @USERNAME is on the list by an `mh:` entry
107
+ // that is NOT the hash of their email (a tag or a handle's hash — memberTag.mjs): the guest book recorded which entry let them in,
108
+ // and that entry still on the list keeps them (sync sweep 2026-11-23 #2 — they vanished from Members after any re-key)
109
+ const byEntry = new Map()
110
+ for (const p of people || []) {
111
+ if (!p || typeof p !== 'object') continue
112
+ const e = lc(p.email), ents = Array.isArray(p.entries) ? p.entries : []
113
+ if (e && EMAIL.test(e) && ents.some((x) => typeof x === 'string' && ((x.startsWith('mh:') && mh.has(x.slice(3))) || (x.startsWith('u:') && (Array.isArray(al.users) ? al.users : []).some((u) => u && lc(u.handle) === lc(x.slice(2))))))) byEntry.set(e, true)
114
+ }
115
+ const emailsOf = (people || []).map((p) => (p && typeof p === 'object' ? p.email : p))
116
+ const hashed = new Map()
117
+ if (mh.size) for (const e of new Set(emailsOf.map(lc).filter((x) => EMAIL.test(x) && !ok.has(x) && !byEntry.has(x)))) { try { hashed.set(e, mh.has(await memberHash(e, room))) } catch { hashed.set(e, false) } }
118
+ return (email, user) => {
119
+ const e = lc(email)
120
+ if (e && EMAIL.test(e)) return ok.has(e) || domains.some((d) => e.endsWith('@' + d)) || hashed.get(e) === true || byEntry.get(e) === true
121
+ return !!(user && byUser) // no email to decide by: kept only where the list names people by @username
122
+ }
123
+ }
package/mkseal.js ADDED
@@ -0,0 +1,101 @@
1
+ // spaces/public/mkseal.js — seal the room key TO THE SERVICE'S PUBLIC KEY before it goes on the wire.
2
+ //
3
+ // WHAT THIS DOES: removes `mk` from every surface that captures request bodies without meaning to — API Gateway's
4
+ // "log full requests/responses", WAF body logging to Firehose/S3, a `console.log(event)` added while debugging, an
5
+ // exception handler that serialises the event, an intercepting proxy. Each of those archives ciphertext to a key that
6
+ // is not in the archive. That is the common way keys actually leak, and this closes all of it at once.
7
+ //
8
+ // WHAT THIS DOES NOT DO — say it plainly, because overclaiming here would be worse than not shipping it: the Lambda
9
+ // unwraps `mk` and holds it in memory for the turn, exactly as before. This is NOT protection against the operator.
10
+ // The honest sentence is "your key is never transmitted in a form logging can capture", never "we can't read it".
11
+ //
12
+ // WHY IT'S WORTH BUILDING ANYWAY: it is the migration path. Today the private half lives in the service; tomorrow it
13
+ // can live only inside an attested enclave with key release gated on the measured image, and NOTHING on this side
14
+ // changes — same wire format, same client, same receipts. Protocol changes are expensive to coordinate; key-custody
15
+ // changes are not. Ship the protocol now, upgrade the trust property later.
16
+ //
17
+ // CONSTRUCTION: ephemeral-static ECDH (P-256) → HKDF-SHA256 → AES-256-GCM. That is HPKE base mode in shape, hand-rolled
18
+ // on the same WebCrypto primitives e2ee.js already uses so a certified, egress-locked, reproducible build gains no new
19
+ // dependency. It is NOT an RFC 9180 implementation and must not be described as one.
20
+ //
21
+ // The AAD is what makes this more than a wrapper. Sealed to a static public key with no binding, the ciphertext is
22
+ // itself a bearer token: capture it from a log, replay it, and you have the same power as holding mk. Binding
23
+ // room|op|ts|nonce means a captured blob only works for that exact operation, inside the freshness window, once.
24
+ const VERSION = 1
25
+ const enc = new TextEncoder()
26
+
27
+ // ── THE SEAL CLOCK (state machines pass 7, T#2). A seal's `ts` must be within 60 s of the ENCLAVE's clock (agent/mkUnseal.mjs
28
+ // DEFAULT_SKEW_MS), so a device whose clock was off had every confidential request refused, with no way back. Every seal's
29
+ // `ts` reads sealNow(): the device clock plus an offset learned from the enclave — from a refused envelope's `now`
30
+ // (agent/reqEnvelope.mjs) or a fresh attestation's own timestamp (enclaveRoute.js). Clamped to ±1 day: a front that lies
31
+ // can make requests fail (it can anyway), never move this clock further.
32
+ export const MAX_CLOCK_OFFSET_MS = 86_400_000
33
+ // Kept on the realm, not the module: this file is imported under more than one URL (with and without ?v=), and each would
34
+ // otherwise hold its own offset.
35
+ const CLOCK = (globalThis.__wbSealClock = globalThis.__wbSealClock || { offset: 0 })
36
+ export const sealNow = () => Date.now() + CLOCK.offset
37
+ export const clockOffset = () => CLOCK.offset
38
+ /** Learn the offset from a server time taken just now. → true when it moved by more than a second (a retry is worth it). */
39
+ export function noteServerClock (serverNow, localNow = Date.now()) {
40
+ const t = Number(serverNow)
41
+ if (!Number.isFinite(t) || t <= 0) return false
42
+ const d = Math.max(-MAX_CLOCK_OFFSET_MS, Math.min(MAX_CLOCK_OFFSET_MS, Math.round(t - localNow)))
43
+ const moved = Math.abs(d - CLOCK.offset) > 1000
44
+ CLOCK.offset = d
45
+ return moved
46
+ }
47
+ export const _resetSealClock = () => { CLOCK.offset = 0 } // test hook
48
+
49
+ function b64(bytes) {
50
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
51
+ let s = ''
52
+ for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i])
53
+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
54
+ }
55
+
56
+ /** The canonical bound context. MUST match agent/mkUnseal.mjs byte for byte — the cross-module test pins it.
57
+ * `|` is safe as a separator: room ids are slugs, op is from a fixed set, ts is a number, nonce is base64url. */
58
+ export function mkAad({ room, op, ts, nonce } = {}) {
59
+ return `mkseal-v1|${room || ''}|${op || ''}|${ts || 0}|${nonce || ''}`
60
+ }
61
+
62
+ /** A single-use request nonce (base64url, 96 bits). Paired with `ts` it makes a captured blob replayable at most once,
63
+ * inside the skew window, for the one operation it was sealed for. */
64
+ export function newNonce() {
65
+ return b64(crypto.getRandomValues(new Uint8Array(12)))
66
+ }
67
+
68
+ /** Seal `mk` to the service's public key (JWK, P-256), bound to `aad`. → { v, epk, iv, ct }, all base64url.
69
+ * A fresh ephemeral keypair per call, so two seals of the same key share no bytes and a captured blob is never a
70
+ * stable fingerprint of the room. */
71
+ export async function sealMk(mk, publicJwk, aad) {
72
+ const pub = await crypto.subtle.importKey('jwk', publicJwk, { name: 'ECDH', namedCurve: 'P-256' }, false, [])
73
+ const eph = await crypto.subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, false, ['deriveBits'])
74
+ const epk = new Uint8Array(await crypto.subtle.exportKey('raw', eph.publicKey))
75
+ const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: 'ECDH', public: pub }, eph.privateKey, 256))
76
+ const key = await deriveKey(shared, epk)
77
+ const iv = crypto.getRandomValues(new Uint8Array(12))
78
+ const ct = new Uint8Array(await crypto.subtle.encrypt(
79
+ { name: 'AES-GCM', iv, additionalData: enc.encode(String(aad || '')) }, key, enc.encode(String(mk)),
80
+ ))
81
+ return { v: VERSION, epk: b64(epk), iv: b64(iv), ct: b64(ct) }
82
+ }
83
+
84
+ /** Seal the sign-in identity — `{ idToken, from }` — to the service's public key, bound to `aad`, in the SAME envelope
85
+ * as `sealMk`. Rides alongside `mkSealed` on a turn; the enclave unwraps it inside the measured image, so the email
86
+ * never reaches the operator. Same limits as sealMk: out of body-logging today, out of the operator's view only once
87
+ * the private half lives enclave-only. Ship the protocol now, upgrade the trust property later. */
88
+ export async function sealIdentity(fields, publicJwk, aad) {
89
+ return sealMk(JSON.stringify(fields || {}), publicJwk, aad)
90
+ }
91
+
92
+ // HKDF over the ECDH shared secret, with the ephemeral public key folded into `info` so the derived key is bound to
93
+ // this exact encapsulation (HPKE binds its KEM context the same way). Salt empty — the shared secret is already
94
+ // uniformly random. Must stay identical to the server's deriveKey.
95
+ async function deriveKey(shared, epk) {
96
+ const ikm = await crypto.subtle.importKey('raw', shared, 'HKDF', false, ['deriveKey'])
97
+ const info = new Uint8Array([...enc.encode('mkseal-v1'), ...epk])
98
+ return crypto.subtle.deriveKey(
99
+ { name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info }, ikm, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'],
100
+ )
101
+ }
package/nativePush.js ADDED
@@ -0,0 +1,153 @@
1
+ // nativePush.js — NOTIFICATIONS INSIDE THE ANDROID APP (docs/android-notifications.md). Its WebView has no Notification, no
2
+ // PushManager and no push on a service worker registration. The app's shell exposes `window.WitbitzPush` (PushBridge.kt): FCM
3
+ // for delivery, and the app's OWN Web Push keys (p256dh, auth), so the server encrypts exactly as for a browser. Here the three
4
+ // missing pieces are supplied from it, so every existing path — the permission check, subscribeRobust (pushCore.js), the
5
+ // subscription's toJSON to the app frame, unsubscribe — runs unchanged. Outside the app (no bridge) this does nothing.
6
+ // The bridge's calls are synchronous (a @JavascriptInterface); the permission prompt and the token fetch block this page for
7
+ // the moment they take — the prompt covers the page anyway. The bridge is visible to EVERY frame of the WebView, so each call
8
+ // but permission() carries this launch's key, which the shell serves on the vault's own origin only (KEY_PATH, no CORS): the
9
+ // app this page frames, or any widget, cannot read it.
10
+ const b64 = (s) => { const t = String(s).replace(/-/g, '+').replace(/_/g, '/'); const bin = atob(t + '='.repeat((4 - (t.length % 4)) % 4)); const u = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i); return u.buffer }
11
+ const parse = (s) => { try { return JSON.parse(s || 'null') } catch { return null } }
12
+
13
+ /** Install the shims on `w` (the window) when the app's bridge is there. → whether it did. */
14
+ export const KEY_PATH = '/__witbitz/push-key'
15
+ export function installNativePush (w = globalThis, { fetch: f = w && w.fetch ? w.fetch.bind(w) : null } = {}) {
16
+ const B = w && w.WitbitzPush
17
+ if (!B || typeof B.subscribe !== 'function') return false
18
+ let _key = null
19
+ const key = () => (_key = _key || Promise.resolve().then(async () => { const r = f && await f(KEY_PATH, { cache: 'no-store' }); return r && r.ok ? (await r.text()).trim() : '' }).catch(() => ''))
20
+ const perm = () => { try { const p = String(B.permission()); return p === 'granted' || p === 'denied' ? p : 'default' } catch { return 'default' } }
21
+ const subOf = (j) => {
22
+ if (!j || typeof j.endpoint !== 'string' || !j.keys) return null
23
+ const keys = { p256dh: String(j.keys.p256dh), auth: String(j.keys.auth) }
24
+ return {
25
+ endpoint: j.endpoint, expirationTime: null, options: { userVisibleOnly: true, applicationServerKey: null },
26
+ toJSON: () => ({ endpoint: j.endpoint, expirationTime: null, keys: { ...keys } }),
27
+ getKey: (name) => (keys[name] ? b64(keys[name]) : null),
28
+ unsubscribe: async () => { try { const ok = String(B.unsubscribe(await key())) === 'ok'; if (ok && _native) _native.sent.clear(); return ok } catch { return false } }, // the app forgot the Space keys too: send them again next time (the review)
29
+ }
30
+ }
31
+ const pushManager = Object.freeze({
32
+ getSubscription: async () => { const k = await key(); raiseRotated(k); return subOf(parse(B.subscription(k))) },
33
+ subscribe: async () => {
34
+ const j = parse(B.subscribe(await key()))
35
+ if (!j || j.error) { const e = new Error('notifications: ' + ((j && j.error) || 'unavailable')); e.name = j && j.error === 'permission' ? 'NotAllowedError' : 'AbortError'; throw e }
36
+ return subOf(j)
37
+ },
38
+ permissionState: async () => (perm() === 'default' ? 'prompt' : perm()),
39
+ })
40
+ // ALWAYS replaced inside the app: a WebView may expose its own Notification / PushManager that can never be granted or
41
+ // subscribe (APK 29: the vault saw "denied" and never subscribed — the shim had kept the WebView's)
42
+ const def = (name, value) => { try { Object.defineProperty(w, name, { configurable: true, writable: true, value }) } catch { w[name] = value } }
43
+ def('PushManager', function PushManager () {})
44
+ {
45
+ def('Notification', class Notification {
46
+ static get permission () { return perm() }
47
+ static async requestPermission () { try { const p = String(B.requestPermission(await key())); return p === 'granted' || p === 'denied' ? p : 'default' } catch { return 'default' } }
48
+ })
49
+ }
50
+ if (w.ServiceWorkerRegistration && w.ServiceWorkerRegistration.prototype) {
51
+ const proto = w.ServiceWorkerRegistration.prototype
52
+ Object.defineProperty(proto, 'pushManager', { configurable: true, get () { return pushManager } })
53
+ // ── THE APP'S NOTIFICATIONS IN THE TRAY (docs/state-machines.md C#17 b): the app shows them itself (nm.notify), so every page
54
+ // path that reads reg.getNotifications() — the vault's trayQuery / trayClose, the close when a Space is opened — never saw
55
+ // them. They are merged in here, shaped like the worker's ({ tag, data: { room }, close() }), so those paths run unchanged.
56
+ const orig = typeof proto.getNotifications === 'function' ? proto.getNotifications : null
57
+ Object.defineProperty(proto, 'getNotifications', { configurable: true, writable: true, value: async function (opts) {
58
+ let web = []
59
+ try { web = orig ? (await orig.call(this, opts)) || [] : [] } catch { web = [] }
60
+ let mine = []
61
+ try { const k = await key(); const a = parse(B.shown(k)); mine = Array.isArray(a) ? a.filter((x) => x && typeof x.room === 'string' && x.room) : [] } catch { mine = [] }
62
+ const tagOf = (room) => 'native-' + room
63
+ const want = opts && typeof opts.tag === 'string' ? opts.tag : null
64
+ return [...web, ...mine.filter((x) => !want || want === tagOf(x.room)).map((x) => ({
65
+ tag: tagOf(x.room), data: { room: x.room, native: true },
66
+ close: () => { key().then((k) => { try { B.close(k, x.room) } catch { /* */ } }).catch(() => {}) },
67
+ }))]
68
+ } })
69
+ }
70
+ // ── A TOKEN FCM REPLACED (S#16): its endpoint stays in every Space's subscriber list until FCM calls it dead — two notifications,
71
+ // the author's own phone tickled. Each look at the subscription raises the replaced endpoints (once while their drop runs);
72
+ // the vault files op pushdrop for them (dropRotatedEndpoints) and only then are they forgotten here.
73
+ const raiseRotated = (k) => {
74
+ try {
75
+ if (typeof B.rotated !== 'function' || typeof w.dispatchEvent !== 'function') return
76
+ const a = parse(B.rotated(k)); const fresh = Array.isArray(a) ? a.filter((e) => typeof e === 'string' && e && !_rotBusy.has(e)) : []
77
+ if (!fresh.length) return
78
+ for (const e of fresh) _rotBusy.add(e)
79
+ const Ev = w.CustomEvent || (typeof CustomEvent !== 'undefined' ? CustomEvent : null)
80
+ if (Ev) w.dispatchEvent(new Ev('wb-native-push-rotated', { detail: { endpoints: fresh } }))
81
+ } catch { /* the next look raises them again */ }
82
+ }
83
+ // ── A REGISTRATION WITHOUT A SERVICE WORKER (the Windows app refuses them — windows/attested-client/bridge.go): the page's push
84
+ // paths ask for a registration first (pushCore.js swRegBounded) and only then for its pushManager. Inside an app this one
85
+ // answers: the bridge's pushManager and getNotifications, active from the start, nothing to update or show.
86
+ const getN = w.ServiceWorkerRegistration && w.ServiceWorkerRegistration.prototype && w.ServiceWorkerRegistration.prototype.getNotifications
87
+ const reg = Object.freeze({
88
+ active: Object.freeze({ state: 'activated', postMessage () {} }), installing: null, waiting: null,
89
+ scope: (w.location && w.location.origin ? w.location.origin : '') + '/', pushManager,
90
+ getNotifications: async (opts) => { try { return getN ? await getN.call(reg, opts) : [] } catch { return [] } },
91
+ showNotification: async () => {}, update: async () => {}, unregister: async () => false,
92
+ })
93
+ _native = { B, key, sent: new Map(), reg }
94
+ return true
95
+ }
96
+
97
+ /** Inside the Android or Windows app: a registration for the push paths when no service worker is registered; null elsewhere. */
98
+ export function nativeRegistration () { return _native ? _native.reg : null }
99
+
100
+ // ── PREVIEWS (phase 3): the vault hands the app each Space's notification key (NK — opens a preview and nothing else) exactly
101
+ // when it keeps that key in the clear itself, and the "Show message preview" switch. Write-only bridge calls; no-ops
102
+ // outside the app. Repeats of the same key are not sent again.
103
+ let _native = null
104
+ const _rotBusy = new Set() // replaced endpoints whose drop is under way (raiseRotated)
105
+ export function nativeNotifKey (room, nk) {
106
+ const n = _native; if (!n || !room || !nk || n.sent.get(room) === nk) return
107
+ n.sent.set(room, nk)
108
+ n.key().then((k) => { try { if (String(n.B.setNotifKey(k, String(room), String(nk))) !== 'ok') n.sent.delete(room) } catch { n.sent.delete(room) } }).catch(() => n.sent.delete(room))
109
+ }
110
+ /** room null = every Space's key. */
111
+ export function nativeForgetNotifKey (room = null) {
112
+ const n = _native; if (!n) return
113
+ if (room) n.sent.delete(room); else n.sent.clear()
114
+ n.key().then((k) => { try { n.B.forgetNotifKey(k, room ? String(room) : '') } catch { /* */ } }).catch(() => {})
115
+ }
116
+ export function nativePreviews (on) {
117
+ const n = _native; if (!n) return
118
+ n.key().then((k) => { try { n.B.setPreviews(k, !!on) } catch { /* */ } }).catch(() => {})
119
+ }
120
+ /** Sender-proof hashes only, shared with the web notification worker. Older shells safely ignore this. */
121
+ export function nativeBlockTokens (tokens) {
122
+ const n = _native; if (!n || typeof n.B.setBlocks !== 'function') return
123
+ const list = Array.isArray(tokens) ? tokens.filter((x) => typeof x === 'string' && /^[0-9a-f]{32}$/.test(x)).slice(0, 5000) : []
124
+ n.key().then((k) => { try { n.B.setBlocks(k, JSON.stringify(list)) } catch { /* next sync retries */ } }).catch(() => {})
125
+ }
126
+
127
+ if (typeof window !== 'undefined') installNativePush(window)
128
+
129
+ /** The page's viewing record { room, at } (viewingBeacon.js): the app shows nothing for the Space on screen (C#17 b). */
130
+ export function nativeViewing (room, at) {
131
+ const n = _native; if (!n || typeof n.B.setViewing !== 'function') return
132
+ n.key().then((k) => { try { n.B.setViewing(k, String(room || ''), Number(at) || Date.now()) } catch { /* */ } }).catch(() => {})
133
+ }
134
+ /** Take a replaced token's endpoints off every Space this account holds (op pushdrop — keyless; the room's next turn removes a
135
+ * subscription whose address hashes the same, agent/pushDrop.mjs). `post(body)` → { status }. The app forgets an endpoint only when
136
+ * every drop for it was filed; else the next look raises it again. → how many drops were filed. */
137
+ export async function dropRotatedEndpoints (endpoints, rooms, post) {
138
+ const n = _native
139
+ const eps = (Array.isArray(endpoints) ? endpoints : []).filter((e) => typeof e === 'string' && e)
140
+ const rs = [...new Set((Array.isArray(rooms) ? rooms : []).filter((r) => typeof r === 'string' && r))]
141
+ let filed = 0; const done = []
142
+ for (const e of eps) {
143
+ let all = true
144
+ for (const room of rs) {
145
+ let r = null; try { r = await post({ op: 'pushdrop', room, subscription: { endpoint: e } }) } catch { r = null }
146
+ if (r && r.status === 200) filed++; else all = false
147
+ }
148
+ if (all) done.push(e)
149
+ _rotBusy.delete(e)
150
+ }
151
+ if (n && done.length && typeof n.B.rotatedDone === 'function') { try { const k = await n.key(); n.B.rotatedDone(k, JSON.stringify(done)) } catch { /* */ } }
152
+ return filed
153
+ }
package/nitroVerify.js ADDED
@@ -0,0 +1,220 @@
1
+ // spaces/public/nitroVerify.js — verify an AWS Nitro Enclaves attestation document, in the browser.
2
+ //
3
+ // ★ WHAT THIS BUYS. The rest of the trust ladder (D1 egress-lock CSP, D2 content-blind proof, D3 signed build cert,
4
+ // D4 reproducible build) proves things about code we PUBLISH. It cannot prove what the machine actually loaded.
5
+ // A Nitro attestation document is signed by a key that lives in hardware the operator cannot reach, and it states:
6
+ // "the enclave running right now measures to these PCRs, and it holds the private half of this public key".
7
+ // Verify it, and sealing a room key to that public key means the plaintext is reachable only by the measured image.
8
+ //
9
+ // ★★ WHAT IT DOES NOT BUY — and the copy must say so, because the whole point of this programme is not overclaiming:
10
+ // 1. It proves the MEASUREMENT, not the BEHAVIOUR. PCR0 is a hash. If you cannot rebuild that hash from published
11
+ // source (D4), "measured" tells you the image didn't change, not that it does what the docs say.
12
+ // 2. A document with no nonce proves an enclave EXISTED, not that it is the one answering you now. Freshness comes
13
+ // from a challenge (`nonce`), not from a timestamp the same party chose.
14
+ // 3. Model egress is untouched. Attestation protects the key and the code. It does not stop plaintext going to a
15
+ // model vendor, because that is what the room is FOR.
16
+ //
17
+ // Everything here runs on WebCrypto and nothing else, so the same file serves the Lambda and the page.
18
+
19
+ import { decode, encodeArray, encodeBytes, encodeText } from './cbor.js'
20
+ import { bytesEqual, importSpki, verifyChain } from './x509.js'
21
+
22
+ /** The AWS Nitro Enclaves root, G1 — https://aws-nitro-enclaves.amazonaws.com/AWS_NitroEnclaves_Root-G1.zip
23
+ * SHA-256 of this DER: 641a0321a3e244efe456463195d606317ed7cdcc3c1756e09893f3c68f79bb5b (AWS publishes the same).
24
+ * ★ PINNED ON PURPOSE. The document carries its own root in `cabundle[0]`; we ignore that copy and start from this
25
+ * one. A verifier that trusts the anchor its input supplied is not verifying anything. */
26
+ export const NITRO_ROOT_G1_B64 =
27
+ 'MIICETCCAZagAwIBAgIRAPkxdWgbkK/hHUbMtOTn+FYwCgYIKoZIzj0EAwMwSTELMAkGA1UEBhMCVVMxDzANBgNVBAoMBkFtYXpvbjEMMAoG' +
28
+ 'A1UECwwDQVdTMRswGQYDVQQDDBJhd3Mubml0cm8tZW5jbGF2ZXMwHhcNMTkxMDI4MTMyODA1WhcNNDkxMDI4MTQyODA1WjBJMQswCQYDVQQG' +
29
+ 'EwJVUzEPMA0GA1UECgwGQW1hem9uMQwwCgYDVQQLDANBV1MxGzAZBgNVBAMMEmF3cy5uaXRyby1lbmNsYXZlczB2MBAGByqGSM49AgEGBSuB' +
30
+ 'BAAiA2IABPwCVOumCMHzaHDimtqQvkY4MpJzbolL//Zy2YlES1BR5TSksfbb48C8WBoyt7F2Bw7eEtaaP+ohG2bnUs990d0JX28TcPQXCEPZ' +
31
+ '3BABIeTPYwEoCWZEh8l5YoQwTcU/9KNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUkCW1DdkFR+eWw5b6cp3PmanfS5YwDgYDVR0P' +
32
+ 'AQH/BAQDAgGGMAoGCCqGSM49BAMDA2kAMGYCMQCjfy+Rocm9Xue4YnwWmNJVA44fA0P5W2OpYow9OYCVRaEevL8uO1XYru5xtMPWrfMCMQCi' +
33
+ '85sWBbJwKKXdS6BptQFuZbT73o/gBh1qUxl/nNr12UO8Yfwr6wPLb+6NIwLz3/Y='
34
+
35
+ const COSE_ALG_ES384 = -35 // COSE header label 1 (alg); ES384 is the only algorithm Nitro emits
36
+ const MAX_DOC = 1 << 20
37
+ const MAX_FIELD = 1024
38
+ const MAX_CABUNDLE = 8
39
+
40
+ export function b64ToBytes(b64) {
41
+ const s = String(b64).replace(/-/g, '+').replace(/_/g, '/').replace(/\s+/g, '')
42
+ const bin = atob(s)
43
+ const out = new Uint8Array(bin.length)
44
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
45
+ return out
46
+ }
47
+
48
+ export const toHex = (u8) => Array.from(u8, (b) => b.toString(16).padStart(2, '0')).join('')
49
+
50
+ const isBytes = (x) => x instanceof Uint8Array
51
+ const optBytes = (m, k) => {
52
+ const v = m.get(k)
53
+ if (v === null || v === undefined) return null
54
+ if (!isBytes(v) || v.length > MAX_FIELD) throw new Error(`attestation: bad ${k}`)
55
+ return v.length ? v : null
56
+ }
57
+
58
+ /** Rebuild the exact bytes COSE_Sign1 signs: ["Signature1", protected, external_aad, payload]. */
59
+ function sigStructure(protectedBytes, payloadBytes) {
60
+ return encodeArray([
61
+ encodeText('Signature1'),
62
+ encodeBytes(protectedBytes),
63
+ encodeBytes(new Uint8Array(0)), // external_aad — always empty for Nitro
64
+ encodeBytes(payloadBytes),
65
+ ])
66
+ }
67
+
68
+ function parseDocument(payloadBytes) {
69
+ const m = decode(payloadBytes)
70
+ if (!(m instanceof Map)) throw new Error('attestation: payload is not a map')
71
+
72
+ const moduleId = m.get('module_id')
73
+ if (typeof moduleId !== 'string' || !moduleId || moduleId.length > MAX_FIELD) throw new Error('attestation: bad module_id')
74
+
75
+ const digest = m.get('digest')
76
+ if (digest !== 'SHA384') throw new Error(`attestation: unexpected digest ${digest}`)
77
+
78
+ const timestamp = m.get('timestamp')
79
+ if (typeof timestamp !== 'number' || !(timestamp > 0)) throw new Error('attestation: bad timestamp')
80
+
81
+ const pcrsMap = m.get('pcrs')
82
+ if (!(pcrsMap instanceof Map) || pcrsMap.size < 1 || pcrsMap.size > 32) throw new Error('attestation: bad pcrs')
83
+ const pcrs = {}
84
+ for (const [k, v] of pcrsMap) {
85
+ if (!Number.isInteger(k) || k < 0 || k > 31) throw new Error('attestation: bad PCR index')
86
+ if (!isBytes(v) || (v.length !== 32 && v.length !== 48 && v.length !== 64)) throw new Error(`attestation: bad PCR${k}`)
87
+ pcrs[k] = toHex(v)
88
+ }
89
+
90
+ const certificate = m.get('certificate')
91
+ if (!isBytes(certificate) || !certificate.length) throw new Error('attestation: missing certificate')
92
+
93
+ const cabundle = m.get('cabundle')
94
+ if (!Array.isArray(cabundle) || !cabundle.length || cabundle.length > MAX_CABUNDLE) throw new Error('attestation: bad cabundle')
95
+ for (const c of cabundle) if (!isBytes(c) || !c.length) throw new Error('attestation: bad cabundle entry')
96
+
97
+ return {
98
+ moduleId,
99
+ timestamp,
100
+ digest,
101
+ pcrs,
102
+ certificate,
103
+ cabundle,
104
+ publicKey: optBytes(m, 'public_key'),
105
+ userData: optBytes(m, 'user_data'),
106
+ nonce: optBytes(m, 'nonce'),
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Verify a Nitro attestation document. Throws with a specific reason on any failure; never returns a partial result.
112
+ *
113
+ * @param cose raw COSE_Sign1 bytes (as returned by the NSM)
114
+ * @param root trust anchor DER; defaults to the pinned AWS Nitro root G1
115
+ * @param now verification time, ms
116
+ * @param maxAgeMs reject a document older than this. A WEAK freshness check — see the header note; prefer `nonce`.
117
+ * @param expectedPCRs { [index]: hex } that must match exactly. Omit and you have verified genuine AWS hardware
118
+ * but NOT which image it is running — which is almost never what you want.
119
+ * @param nonce the challenge you sent; must come back byte-identical. The only real proof of liveness.
120
+ */
121
+ // §ROLLOVER-SET. A pin is one hex digest, or a SET of them. The set exists for exactly one purpose: while a new image
122
+ // rolls out, {outgoing, incoming} must BOTH verify, or whichever side has not moved yet is refused — which is what
123
+ // turns an update into a synchronized cutover. It is CAPPED because a pin's whole value is that it is narrow; an
124
+ // unbounded list stops being a pin and becomes a standing menu of accepted images.
125
+ export const MAX_PIN_SET = 2
126
+ export function acceptedSet(pin, label = 'pin') {
127
+ const list = (Array.isArray(pin) ? pin : [pin]).map((h) => String(h).toLowerCase())
128
+ if (!list.length) throw new Error(`attestation: ${label} pins an empty set — that is not a check`)
129
+ if (list.length > MAX_PIN_SET) throw new Error(`attestation: ${label} pins ${list.length} values; at most ${MAX_PIN_SET} (a rollover is {outgoing, incoming})`)
130
+ return list
131
+ }
132
+
133
+ // `atDocTime`: check the certificate chain as of the document's OWN timestamp — for an ARCHIVED attestation (a turn
134
+ // certificate's certDoc, docs/turn-certificates.md), whose ~3-hour Nitro leaf has long expired by the time a member
135
+ // re-checks it. Off by default: a LIVE attestation is checked against now.
136
+ // `clockBoundMs` (with atDocTime; state machines pass 7, T#2b): a LIVE check made at the document's time — fresh by its nonce —
137
+ // so a device clock that is off does not refuse a genuine enclave as "not yet valid"/"expired". The device's clock (`now`)
138
+ // must still be within this bound of the document's, or it fails with a reason that names the clock.
139
+ export async function verifyAttestation(cose, { root, now = Date.now(), maxAgeMs = 0, expectedPCRs = null, nonce = null, atDocTime = false, clockBoundMs = 0 } = {}) {
140
+ const raw = cose instanceof Uint8Array ? cose : new Uint8Array(cose)
141
+ if (!raw.length || raw.length > MAX_DOC) throw new Error('attestation: implausible document size')
142
+
143
+ const cs = decode(raw)
144
+ if (!Array.isArray(cs) || cs.length !== 4) throw new Error('attestation: not a COSE_Sign1 structure')
145
+ const [protectedBytes, unprotected, payloadBytes, signature] = cs
146
+ if (!isBytes(protectedBytes) || !isBytes(payloadBytes) || !isBytes(signature)) throw new Error('attestation: malformed COSE_Sign1')
147
+ if (!(unprotected instanceof Map)) throw new Error('attestation: malformed COSE header')
148
+
149
+ // The algorithm must come from the PROTECTED header — an unprotected one is attacker-editable without breaking
150
+ // the signature, so reading `alg` from there is how "verified with the algorithm of the attacker's choice" happens.
151
+ // RFC 8152 encodes an EMPTY protected bucket as a zero-length byte string, not as an encoded empty map — so this
152
+ // must be handled as "no algorithm stated" and rejected on its merits, not as a CBOR parse error.
153
+ const ph = protectedBytes.length ? decode(protectedBytes) : new Map()
154
+ if (!(ph instanceof Map) || ph.get(1) !== COSE_ALG_ES384) throw new Error('attestation: protected header must specify ES384')
155
+ if (signature.length !== 96) throw new Error('attestation: ES384 signature must be 96 bytes')
156
+
157
+ const doc = parseDocument(payloadBytes)
158
+
159
+ // Chain from OUR anchor, not the document's. cabundle[0] is the document's copy of the root and is discarded.
160
+ const anchor = root ? (root instanceof Uint8Array ? root : new Uint8Array(root)) : b64ToBytes(NITRO_ROOT_G1_B64)
161
+ const leaf = await verifyChain([anchor, ...doc.cabundle.slice(1), doc.certificate], { now: atDocTime && Number.isFinite(doc.timestamp) ? doc.timestamp : now })
162
+
163
+ const ok = await crypto.subtle.verify(
164
+ { name: 'ECDSA', hash: 'SHA-384' },
165
+ await importSpki(leaf),
166
+ signature,
167
+ sigStructure(protectedBytes, payloadBytes),
168
+ )
169
+ if (!ok) throw new Error('attestation: COSE signature does not verify under the leaf certificate')
170
+
171
+ if (atDocTime && clockBoundMs > 0 && Number.isFinite(doc.timestamp) && Math.abs(now - doc.timestamp) > clockBoundMs) {
172
+ const h = Math.round(Math.abs(now - doc.timestamp) / 3_600_000)
173
+ const e = new Error(`attestation: this device's clock is about ${h} hour${h === 1 ? '' : 's'} off the enclave's — check the date and time settings`)
174
+ e.code = 'clock_off'
175
+ throw e
176
+ }
177
+
178
+ if (maxAgeMs > 0 && now - doc.timestamp > maxAgeMs) {
179
+ throw new Error(`attestation: document is ${Math.round((now - doc.timestamp) / 1000)}s old`)
180
+ }
181
+
182
+ if (nonce) {
183
+ const want = typeof nonce === 'string' ? new TextEncoder().encode(nonce) : new Uint8Array(nonce)
184
+ if (!doc.nonce || !bytesEqual(doc.nonce, want)) throw new Error('attestation: nonce does not match the challenge')
185
+ }
186
+
187
+ if (expectedPCRs) {
188
+ const wanted = Object.entries(expectedPCRs)
189
+ if (!wanted.length) throw new Error('attestation: expectedPCRs was empty — that is not a check')
190
+ for (const [idx, pin] of wanted) {
191
+ // A key that isn't a register index means the caller pinned nothing at all. This already failed closed, but
192
+ // with "PCRPCR0 is absent" — say what actually went wrong instead of letting a typo look like a hardware fault.
193
+ const n = Number(idx)
194
+ if (!Number.isInteger(n) || n < 0 || n > 31) {
195
+ throw new Error(`attestation: expectedPCRs key ${JSON.stringify(idx)} is not a PCR index (0-31)`)
196
+ }
197
+ const accepted = acceptedSet(pin, `PCR${idx}`)
198
+ const got = doc.pcrs[n]
199
+ if (!got) throw new Error(`attestation: PCR${idx} is absent from the document`)
200
+ if (!accepted.includes(got)) throw new Error(`attestation: PCR${idx} mismatch\n expected ${accepted.join(' or ')}\n got ${got}`)
201
+ }
202
+ }
203
+
204
+ return { ok: true, ...doc, leaf }
205
+ }
206
+
207
+ /** Same check, shaped for a UI: `{ ok, reason, doc }` rather than an exception. */
208
+ export async function tryVerifyAttestation(cose, opts) {
209
+ try {
210
+ return { ok: true, reason: '', doc: await verifyAttestation(cose, opts) }
211
+ } catch (e) {
212
+ return { ok: false, reason: (e && e.message) || 'attestation: failed', doc: null }
213
+ }
214
+ }
215
+
216
+ /** Import the enclave's attested public key (DER SubjectPublicKeyInfo) for sealing to it. */
217
+ export async function importAttestedKey(doc, usages = []) {
218
+ if (!doc || !doc.publicKey) throw new Error('attestation: document carries no public key')
219
+ return crypto.subtle.importKey('spki', doc.publicKey, { name: 'ECDH', namedCurve: 'P-384' }, false, usages)
220
+ }