@witbitz/sdk 0.0.0-stage → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +221 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +228 -0
  6. package/accountIndexDoc.js +122 -0
  7. package/accountOwner.js +59 -0
  8. package/accountRecord.js +90 -0
  9. package/accountScope.js +114 -0
  10. package/accountSeal.js +42 -0
  11. package/accountStores.js +173 -0
  12. package/acctV2App.js +619 -0
  13. package/acctV2Check.js +29 -0
  14. package/acctV2Client.js +382 -0
  15. package/acctV2Keys.js +43 -0
  16. package/acctV2Legacy.js +14 -0
  17. package/acctV2Switch.js +80 -0
  18. package/acctV2UiCore.js +857 -0
  19. package/acctV2WebAuthn.js +61 -0
  20. package/acctV2Wire.js +59 -0
  21. package/address.js +42 -0
  22. package/agentDoorTools.js +28 -0
  23. package/attestedBox.js +30 -0
  24. package/attestedRooms.js +78 -0
  25. package/awsKey.js +98 -0
  26. package/backupRecord.js +106 -0
  27. package/backupVault.js +97 -0
  28. package/blocks.js +115 -0
  29. package/blocksPush.js +64 -0
  30. package/browseSeal.js +103 -0
  31. package/cbor.js +225 -0
  32. package/changePush.js +75 -0
  33. package/chatLock.js +165 -0
  34. package/chatLockSw.js +13 -0
  35. package/cloudDeviceBuilds.js +11 -0
  36. package/cloudDevicePins.js +33 -0
  37. package/cloudDeviceSeal.js +53 -0
  38. package/codeAttachments.js +100 -0
  39. package/codeBrowse.js +224 -0
  40. package/codeCache.js +149 -0
  41. package/codeCloud.js +650 -0
  42. package/codeCloudKeys.js +112 -0
  43. package/codeCommands.js +167 -0
  44. package/codeComputers.js +389 -0
  45. package/codeEgress.js +123 -0
  46. package/codeFilesRoutes.js +17 -0
  47. package/codeFolders.js +116 -0
  48. package/codeHistory.js +76 -0
  49. package/codeLanguage.js +54 -0
  50. package/codeMkdir.js +8 -0
  51. package/codeModes.js +59 -0
  52. package/codeOrphanKeys.js +42 -0
  53. package/codeOutputs.js +141 -0
  54. package/codeProgress.js +54 -0
  55. package/codeRelay.js +505 -0
  56. package/codeSent.js +68 -0
  57. package/codeSentinel.js +86 -0
  58. package/codeSubagents.js +107 -0
  59. package/codeTransport.js +317 -0
  60. package/codeUndo.js +48 -0
  61. package/compress.js +24 -0
  62. package/config.js +11 -0
  63. package/connCatalog.js +164 -0
  64. package/connDisp.js +76 -0
  65. package/connOtherWays.js +74 -0
  66. package/connPending.js +16 -0
  67. package/connWrap.js +53 -0
  68. package/connectionEntry.js +89 -0
  69. package/connections.js +561 -0
  70. package/credits.js +30 -0
  71. package/csAttest.js +112 -0
  72. package/decrypt.html +384 -0
  73. package/deviceAttest.js +527 -0
  74. package/deviceCall.js +54 -0
  75. package/deviceKeyCore.js +41 -0
  76. package/deviceSeal.js +59 -0
  77. package/e2ee.js +323 -0
  78. package/eat.js +103 -0
  79. package/emailFork.js +275 -0
  80. package/emailSignIn.js +81 -0
  81. package/emptySpaces.js +111 -0
  82. package/encSource.js +55 -0
  83. package/enclaveAccept.js +214 -0
  84. package/enclaveClaim.js +241 -0
  85. package/enclaveRoute.js +102 -0
  86. package/enclaveSnapshotMerge.js +44 -0
  87. package/entrySig.js +165 -0
  88. package/env.js +73 -0
  89. package/eraseFile.js +58 -0
  90. package/followImage.js +86 -0
  91. package/healNames.js +45 -0
  92. package/idb.js +113 -0
  93. package/idbSeal.js +119 -0
  94. package/indexGone.js +12 -0
  95. package/invite.js +51 -0
  96. package/inviteEnroll.js +67 -0
  97. package/inviteSend.js +68 -0
  98. package/jobAgents.js +87 -0
  99. package/keptMerge.js +91 -0
  100. package/l1-worker-src.js +2 -0
  101. package/l1-worker.js +894 -0
  102. package/laneAssociation.js +68 -0
  103. package/laneConfig.js +58 -0
  104. package/laneLinkCore.js +177 -0
  105. package/ledgerView.js +64 -0
  106. package/manifest.json +239 -0
  107. package/mcpRecommended.js +25 -0
  108. package/memberChange.js +125 -0
  109. package/mirrorBatch.js +47 -0
  110. package/mkseal.js +101 -0
  111. package/nativePush.js +153 -0
  112. package/nitroVerify.js +220 -0
  113. package/noble-p256.js +27 -0
  114. package/notice.js +116 -0
  115. package/notifKey.js +58 -0
  116. package/offlineBundle.js +62 -0
  117. package/ohttp.js +177 -0
  118. package/opRouting.js +10 -0
  119. package/opencodeWire.js +282 -0
  120. package/oprf.js +70 -0
  121. package/ownAgentLink.js +96 -0
  122. package/ownerPolicy.js +117 -0
  123. package/package.json +273 -4
  124. package/pdfOptions.js +13 -0
  125. package/pdfText.js +107 -0
  126. package/pdfjs.mjs +28 -0
  127. package/pdfjs.worker.mjs +28 -0
  128. package/pollVerdict.js +33 -0
  129. package/prefetchPoll.js +60 -0
  130. package/protectedLocal.js +426 -0
  131. package/pushCore.js +42 -0
  132. package/recovery.js +107 -0
  133. package/regions.js +42 -0
  134. package/removedMessage.js +11 -0
  135. package/renameRefusal.js +9 -0
  136. package/replyQuote.js +34 -0
  137. package/reqEnvelope.js +126 -0
  138. package/roomDefaultPrefs.js +76 -0
  139. package/roomDelete.js +109 -0
  140. package/roomEmbed.js +111 -0
  141. package/roomName.js +177 -0
  142. package/roomPass.js +256 -0
  143. package/roomRoster.js +305 -0
  144. package/roomSettings.js +61 -0
  145. package/roomState.js +58 -0
  146. package/roomStreamClient.js +115 -0
  147. package/rosterCount.js +52 -0
  148. package/rosterHash.js +13 -0
  149. package/rowSchema.js +113 -0
  150. package/safeMedia.js +116 -0
  151. package/safeMediaPins.js +17 -0
  152. package/schedulesDoc.js +78 -0
  153. package/sdkA2A.js +524 -0
  154. package/sdkAccount.js +483 -0
  155. package/sdkAccountDoc.js +89 -0
  156. package/sdkAccountSections.js +332 -0
  157. package/sdkAgui.js +141 -0
  158. package/sdkAttest.js +34 -0
  159. package/sdkBackup.js +507 -0
  160. package/sdkBackupV2.js +630 -0
  161. package/sdkBrowserPrivate.js +28 -0
  162. package/sdkBuilds.js +208 -0
  163. package/sdkCloudDevice.js +221 -0
  164. package/sdkComputers.js +1009 -0
  165. package/sdkDictation.js +232 -0
  166. package/sdkErase.js +288 -0
  167. package/sdkExports.js +71 -0
  168. package/sdkInvitations.js +34 -0
  169. package/sdkKeptAgent.js +188 -0
  170. package/sdkLaneLink.js +205 -0
  171. package/sdkPlan.js +96 -0
  172. package/sdkProtect.js +228 -0
  173. package/sdkRedact.js +36 -0
  174. package/sdkRekey.js +340 -0
  175. package/sdkReport.js +68 -0
  176. package/sdkSafeMedia.js +255 -0
  177. package/sdkSchedules.js +39 -0
  178. package/sdkSpeech.js +71 -0
  179. package/sdkTemporaryRooms.js +123 -0
  180. package/sdkTurn.js +117 -0
  181. package/sdkVault.js +180 -0
  182. package/sealShare.js +18 -0
  183. package/sealedNames.js +64 -0
  184. package/sealedReceipt.js +17 -0
  185. package/sentinelRelease.js +155 -0
  186. package/shamir.js +85 -0
  187. package/sharedViews.js +52 -0
  188. package/sheetChrome.js +450 -0
  189. package/siri.js +278 -0
  190. package/spaceClient.js +1429 -0
  191. package/spaceConfig.js +81 -0
  192. package/spaceEmailGate.js +813 -0
  193. package/spaceExport.js +125 -0
  194. package/spaceFork.js +216 -0
  195. package/spaceLock.js +358 -0
  196. package/spacePasskey.js +180 -0
  197. package/spaceTemplates.js +99 -0
  198. package/speechOut.js +102 -0
  199. package/splitKeyClient.js +90 -0
  200. package/store.js +656 -0
  201. package/streamHint.js +36 -0
  202. package/sttCloud.js +220 -0
  203. package/sttWorklet.js +38 -0
  204. package/sw-notif-core.js +540 -0
  205. package/tempList.js +48 -0
  206. package/tinfoilVerifier.js +78 -0
  207. package/toolBooks.js +31 -0
  208. package/toolRules.js +52 -0
  209. package/turnCerts.js +254 -0
  210. package/turnFeed.js +58 -0
  211. package/turnVerdict.js +37 -0
  212. package/usageReceipts.js +176 -0
  213. package/usageSummary.js +90 -0
  214. package/util.js +181 -0
  215. package/vault-core.js +2326 -0
  216. package/vault-kit.mjs +354 -0
  217. package/vault-screens.js +261 -0
  218. package/vaultAtRest.js +208 -0
  219. package/vaultCoreLock.js +111 -0
  220. package/vaultCorePush.js +140 -0
  221. package/vaultDeviceKey.js +95 -0
  222. package/vaultEnclaveHandoff.js +114 -0
  223. package/vaultKeep.js +287 -0
  224. package/vaultSealedStore.js +77 -0
  225. package/vaultWorkerHost.js +117 -0
  226. package/vcWorker.js +34 -0
  227. package/voiceAttest.js +50 -0
  228. package/voiceCert.js +51 -0
  229. package/witbitz-admin.d.ts +135 -0
  230. package/witbitz-admin.js +529 -0
  231. package/witbitz-admin.mjs +1460 -0
  232. package/witbitz-sdk.d.ts +1197 -0
  233. package/witbitz-sdk.js +4258 -0
  234. package/workerClient.js +16 -0
  235. package/workerLiveness.js +21 -0
  236. package/x509.js +218 -0
@@ -0,0 +1,214 @@
1
+ // spaces/public/enclaveAccept.js — does THIS Space accept the enclave that just attested? (docs/enclave-room-acceptance.md)
2
+ //
3
+ // The claim in /enclave-claim.json says what the PLATFORM currently runs. A confidential Space carries its own
4
+ // mk-sealed `enclave` block saying what IT accepts: `follow` (the platform's pins, but never a policy older than
5
+ // the floor) or `pin` (exactly one of the builds its owner verified). This file is the comparison — a pure function
6
+ // over (room block, live attestation, platform claim) with no I/O, so the main thread and the mk-kernel worker run
7
+ // the SAME decision right where mk is sealed, and it is testable in isolation.
8
+ //
9
+ // Rules that are easy to get wrong, stated once:
10
+ // • a build is a TRIPLE {kernel, payload, policy}; the room accepts triples, never a cross product of stages;
11
+ // • an absent stage is never a wildcard, in either direction — a monolith pin does not accept a two-stage kernel
12
+ // (which could load ANY payload), and a two-stage pin does not accept a monolith with the same PCR0;
13
+ // • an UNKNOWN policy version is not above the floor;
14
+ // • no attestation ⇒ refused. Nothing here ever accepts by default.
15
+
16
+ const HEX48 = /^[0-9a-f]{96}$/
17
+ const MODES = new Set(['follow', 'pin'])
18
+ const STAGES = [['kernel', '0'], ['payload', '16'], ['policy', '17']]
19
+
20
+ const hex = (v, what) => {
21
+ const h = String(v).toLowerCase()
22
+ if (!HEX48.test(h)) throw new Error(`enclave acceptance: ${what} is not a SHA-384 hex digest`)
23
+ return h
24
+ }
25
+ const version = (v, what) => {
26
+ if (v === undefined || v === null) return 0
27
+ if (typeof v !== 'number' || !Number.isInteger(v) || v < 0) throw new Error(`enclave acceptance: ${what} must be a non-negative integer`)
28
+ return v
29
+ }
30
+
31
+ /** The {kernel, payload?, policy?} a live attestation (or a claim) measures — only the stages actually present. */
32
+ export function tripleOf(att) {
33
+ const p = (att && att.pcrs) || {}
34
+ const t = {}
35
+ for (const [name, idx] of STAGES) if (p[idx]) t[name] = String(p[idx]).toLowerCase()
36
+ return t
37
+ }
38
+
39
+ export const sameTriple = (a, b) => STAGES.every(([name]) => (a[name] || null) === (b[name] || null))
40
+
41
+ /** Normalise a room's `enclave` block. `null`/`undefined` ⇒ null = a pre-P2 room (follow, no floor). Throws on garbage. */
42
+ export function parseAcceptance(raw) {
43
+ if (raw === undefined || raw === null) return null
44
+ if (typeof raw !== 'object') throw new Error('enclave acceptance: block must be an object')
45
+ if (!MODES.has(raw.mode)) throw new Error(`enclave acceptance: unknown mode ${JSON.stringify(raw.mode)}`)
46
+ const minPolicyVersion = version(raw.minPolicyVersion, 'minPolicyVersion')
47
+ const accepted = Array.isArray(raw.accepted) ? raw.accepted.map((e, i) => {
48
+ if (!e || typeof e !== 'object') throw new Error(`enclave acceptance: accepted[${i}] is not an object`)
49
+ const out = { kernel: hex(e.kernel, `accepted[${i}].kernel`) }
50
+ if (e.payload !== undefined && e.payload !== null) out.payload = hex(e.payload, `accepted[${i}].payload`)
51
+ if (e.policy !== undefined && e.policy !== null) out.policy = hex(e.policy, `accepted[${i}].policy`)
52
+ out.policyVersion = version(e.policyVersion, `accepted[${i}].policyVersion`)
53
+ out.label = String(e.label || '').slice(0, 64)
54
+ out.at = typeof e.at === 'number' ? e.at : 0
55
+ return out
56
+ }) : []
57
+ if (raw.mode === 'pin' && !accepted.length) throw new Error('enclave acceptance: a pinned Space that accepts nothing can never seal its key')
58
+ return { mode: raw.mode, minPolicyVersion, accepted }
59
+ }
60
+
61
+ /**
62
+ * The decision. → { ok:true, matched } or { ok:false, reason, live, floor }
63
+ * reason ∈ no_attestation | no_platform_claim | kernel | payload | policy | floor | not_accepted
64
+ * `cfg` may be null (pre-P2 room ⇒ follow, no floor). `attested` = { pcrs:{0,16?,17?}, policyVersion? } from the LIVE
65
+ * doc; `platform` = the parsed claim { pcrs } (only consulted in follow mode).
66
+ */
67
+ export function acceptsMeasurement(cfg, attested, platform) {
68
+ const c = parseAcceptance(cfg) || { mode: 'follow', minPolicyVersion: 0, accepted: [] }
69
+ const live = tripleOf(attested)
70
+ if (!live.kernel) return { ok: false, reason: 'no_attestation', live }
71
+ const pv = attested && typeof attested.policyVersion === 'number' ? attested.policyVersion : null
72
+ if (c.minPolicyVersion > 0 && !(pv !== null && pv >= c.minPolicyVersion)) return { ok: false, reason: 'floor', live, floor: c.minPolicyVersion, policyVersion: pv }
73
+ if (c.mode === 'pin') {
74
+ const matched = c.accepted.find((e) => sameTriple(e, live))
75
+ return matched ? { ok: true, matched, live } : { ok: false, reason: 'not_accepted', live }
76
+ }
77
+ // follow: the platform's current pins, stage by stage — the first differing stage names the reason.
78
+ // ⛔ A STAGE PIN MAY BE A SET (2026-09-29, a builder: `enclave_not_accepted (payload)`). A repin publishes
79
+ // {outgoing, incoming} so the instance still on the old build keeps working while the new one comes up; this used to
80
+ // run tripleOf() over the claim, whose String() turned the list into ONE string "0ad2…,8721…" that no live build can
81
+ // equal — every follow-mode Space was refused for exactly the window a rollover exists to make safe.
82
+ const want = pinSetsOf(platform)
83
+ if (!want.kernel.length) return { ok: false, reason: 'no_platform_claim', live }
84
+ for (const [name] of STAGES) {
85
+ const ok = want[name].length ? want[name].includes(live[name] || '') : !live[name] // no pin for a stage ⇒ the live build must not have one either, as before
86
+ if (!ok) return { ok: false, reason: name, live, platform: want }
87
+ }
88
+ return { ok: true, matched: { ...live }, live }
89
+ }
90
+
91
+ /** The platform claim's pins as a LIST per stage — a single string or a rollover set, lower-cased. */
92
+ function pinSetsOf(att) {
93
+ const p = (att && att.pcrs) || {}
94
+ const t = {}
95
+ for (const [name, idx] of STAGES) t[name] = (Array.isArray(p[idx]) ? p[idx] : (p[idx] ? [p[idx]] : [])).map((v) => String(v).toLowerCase())
96
+ return t
97
+ }
98
+
99
+ // ── THE USER'S ACCEPTED BUILDS (the owner, 2026-10-11: "Accept this build should be only from the user perspective. It is
100
+ // a per user choice. No fork at all." → "Block until accepted", "Per account (all devices)"). ─────────────────────────
101
+ // Which enclave builds a person trusts is THEIR choice, not the room's: their account keeps a list of accepted builds
102
+ // (trustedBuilds.js syncs it), and their app seals a confidential room's key only to a build that is (1) published by
103
+ // Witbitz (the claim's pins — a build the platform does not publish is never accepted) and (2) on that list. A new
104
+ // build blocks this person until they accept it; nothing about the room changes and no other member is affected.
105
+ // The room's sealed `enclave` block (above) is no longer written and no longer gates anything.
106
+
107
+ /** A list of accepted builds → [{ kernel, payload?, policy?, at }] (garbage dropped, never thrown on). */
108
+ export function parseTrusted(raw) {
109
+ const out = []
110
+ for (const e of Array.isArray(raw) ? raw : []) {
111
+ try {
112
+ if (!e || typeof e !== 'object') continue
113
+ const t = { kernel: hex(e.kernel, 'kernel') }
114
+ if (e.payload) t.payload = hex(e.payload, 'payload')
115
+ if (e.policy) t.policy = hex(e.policy, 'policy')
116
+ t.at = typeof e.at === 'number' && Number.isFinite(e.at) ? e.at : 0
117
+ if (!out.some((x) => sameTriple(x, t))) out.push(t)
118
+ } catch { /* an entry this build cannot read is skipped, never trusted */ }
119
+ }
120
+ return out
121
+ }
122
+
123
+ /** Two lists → their union (a build accepted on any device of the account stays accepted). */
124
+ export const mergeTrusted = (a, b) => parseTrusted([...parseTrusted(a), ...parseTrusted(b)])
125
+
126
+ /** The list with the live build added (accepting it). Throws without a verified attestation. */
127
+ export function trustBuild(list, attested, at = Date.now()) {
128
+ const t = tripleOf(attested)
129
+ if (!t.kernel) throw new Error('enclave acceptance: accepting a build needs a verified attestation')
130
+ const cur = parseTrusted(list)
131
+ return cur.some((e) => sameTriple(e, t)) ? cur : [...cur, { ...t, at }]
132
+ }
133
+
134
+ /**
135
+ * Does THIS USER accept the live build? → { ok:true, matched, live } or { ok:false, reason, live }
136
+ * reason ∈ no_attestation | no_platform_claim | kernel | payload | policy (not published by Witbitz)
137
+ * | unknown (the user's list has not loaded yet) | not_accepted (published, but this user has not accepted it)
138
+ * `trusted` undefined = not loaded yet: refused, never "accepted by default".
139
+ */
140
+ export function userVerdict(trusted, attested, platform) {
141
+ const pub = acceptsMeasurement(null, attested, platform) // published by the platform, stage by stage (a rollover's set counts)
142
+ if (!pub.ok) return pub
143
+ if (trusted === undefined) return { ok: false, reason: 'unknown', live: pub.live }
144
+ return parseTrusted(trusted).some((e) => sameTriple(e, pub.live)) ? { ok: true, matched: pub.live, live: pub.live } : { ok: false, reason: 'not_accepted', live: pub.live }
145
+ }
146
+
147
+ /**
148
+ * The seal-time gate — what `mkPub(room)` calls on the main thread AND in the mk-kernel worker, right where mk is about
149
+ * to be sealed to the enclave key. → `key` iff this user accepts the live build; `null` when there is no key yet (the
150
+ * client's own fail-closed "key unavailable" path); otherwise THROWS `enclave_not_accepted` carrying the verdict, so the
151
+ * caller can say what to do (accept the build) instead of a generic "key unavailable".
152
+ */
153
+ export function gatedKey({ key, trusted, attested, platform, room } = {}) {
154
+ if (!key) return null
155
+ const verdict = userVerdict(trusted, attested, platform)
156
+ if (verdict.ok) return key
157
+ const err = new Error(`enclave_not_accepted: you have not accepted the enclave build this Space runs on (${verdict.reason})`)
158
+ err.code = 'enclave_not_accepted'; err.verdict = verdict; err.room = room || null
159
+ throw err
160
+ }
161
+
162
+ /** The platform-only gate (the SDK's default, builds: 'published' — sdkBuilds.js): the build must be published by Witbitz. */
163
+ export function publishedKey({ key, attested, platform, room } = {}) {
164
+ if (!key) return null
165
+ const verdict = acceptsMeasurement(null, attested, platform)
166
+ if (verdict.ok) return key
167
+ const err = new Error(`enclave_not_accepted: the enclave that attested is not a build Witbitz publishes (${verdict.reason})`)
168
+ err.code = 'enclave_not_accepted'; err.verdict = verdict; err.room = room || null
169
+ throw err
170
+ }
171
+
172
+ // ---- tools OUTSIDE the enclave (P3 phase 2, docs/enclave-two-stage-launch.md) --------------------------------------
173
+ // A tool the turn calls out to (read_file → Tinfoil's document enclave) is DECLARED in the measured policy's env —
174
+ // `TOOL_<NAME>=<root>:<repo>@<host><path>` — so it is under PCR17 like every other statement the enclave is held to:
175
+ // a `pin` Space refuses a build whose declaration changed (different policy digest), a `follow` Space shows it on
176
+ // /trust, and the payload REFUSES to call an endpoint the policy does not name. `root` is the trust anchor the
177
+ // payload verifies the endpoint against before any byte leaves (only `tinfoil` today: AMD SEV-SNP + Sigstore
178
+ // provenance of `repo`). Hosts are lower-case, portless — exactly what the egress allowlist matches on.
179
+ //
180
+ // Two roots: `tinfoil:<owner/repo>@host/path` (AMD SEV-SNP + Sigstore provenance of `repo`) and, for Witbitz's own
181
+ // KEYLESS tools enclave (write_pdf, fetch_url — docs/enclave-two-stage-launch.md), `nitro:<pcr0>/<n>.<pcrN>@host/path`:
182
+ // the AWS Nitro image (PCR0, 96 hex) AND the one tool blob the bytes go to (PCR<n>, locked at boot from the blob's
183
+ // digest — n ≥ 18, one register per tool). The payload fetches a fresh-nonce attestation, checks BOTH registers
184
+ // against the AWS root, and pins the TLS session to the key the document carries. Naming the tool's register rather
185
+ // than the manifest's means a rebuilt write_pdf blob does not change what a fetch_url Space is pinned to.
186
+ const TOOL_ROOTS = new Set(['tinfoil', 'nitro'])
187
+ const TOOL_DECL = /^([a-z][a-z0-9-]*):([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)@([a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+)(\/[A-Za-z0-9_./-]*)$/
188
+ const NITRO_REPO = /^([0-9a-f]{96})\/(1[89]|2[0-9]|3[01])\.([0-9a-f]{96})$/ // <pcr0>/<n>.<pcrN>, n in 18..31 (0-17 are the image's own)
189
+
190
+ /** `tinfoil:owner/repo@host/path` → { root, repo, host, path }; `nitro:<pcr0>/<n>.<pcrN>@host/path` → the same plus
191
+ * { pcr0, pcrIndex, pcrDigest }; null for anything the payload must not act on. */
192
+ /** A TOOLS-ENCLAVE ROLLOVER (docs/reproducible-enclave.md, 2026-11-07): one TOOL_* may name SEVERAL builds of one nitro tool,
193
+ * space-separated — the same host and path, each its own PCR0 + register — so the turn accepts whichever of them serves while
194
+ * the tools box moves to a new image (the old one until it is gone, the new one from its first answer). → [decl, …]: one for
195
+ * an ordinary value; [] when any part does not parse, roots are mixed, or the builds name different hosts or paths.
196
+ * ⚑ An app or SDK released before this reads a several-build value as one it cannot parse (trustRoom: "undeclarable"): a
197
+ * rollover is short and is narrowed back to one build. */
198
+ export function parseToolDecls(s) {
199
+ const parts = String(s || '').trim().split(/\s+/).filter(Boolean)
200
+ if (parts.length <= 1) { const d = parseToolDecl(parts[0] || ''); return d ? [d] : [] }
201
+ const ds = parts.map((p) => parseToolDecl(p))
202
+ if (ds.some((d) => !d || d.root !== 'nitro')) return []
203
+ if (new Set(ds.map((d) => d.host + d.path)).size !== 1) return []
204
+ return ds
205
+ }
206
+ export function parseToolDecl(s) {
207
+ const m = TOOL_DECL.exec(String(s || '').trim())
208
+ if (!m || !TOOL_ROOTS.has(m[1])) return null
209
+ const d = { root: m[1], repo: m[2], host: m[3], path: m[4] }
210
+ if (d.root !== 'nitro') return d
211
+ const n = NITRO_REPO.exec(d.repo)
212
+ if (!n) return null
213
+ return { ...d, pcr0: n[1], pcrIndex: Number(n[2]), pcrDigest: n[3] }
214
+ }
@@ -0,0 +1,241 @@
1
+ // spaces/public/enclaveClaim.js — check a running enclave against what we published about it.
2
+ //
3
+ // The attestation verifier (nitroVerify.js) answers "is this a genuine AWS enclave, and what does it measure?".
4
+ // It cannot answer "is it the enclave Witbitz said it would be" — that needs something published in advance to
5
+ // compare against. That something is the `enclave` block of /cert.json, and this file is the comparison.
6
+ //
7
+ // ★ THE POINT OF PUBLISHING THE SIGNING CERTIFICATE. A cert.json that just asserts `pcr8: "abc…"` is a number you
8
+ // have to take on faith. Publishing the signing CERTIFICATE instead means you derive that number yourself and check
9
+ // ours against it — so a Witbitz that lied about PCR8 is caught by arithmetic rather than by trust. `verifyClaim`
10
+ // recomputes it and refuses a claim whose stated PCR8 doesn't match its own certificate.
11
+ //
12
+ // PCR0/1/2 have no such shortcut: they come from rebuilding the image (see docs/reproducible-enclave.md, and
13
+ // infra/enclave/build-eif.sh which reproduces them). PCR8 is the one measurement checkable from a published artifact
14
+ // alone, which is exactly why it is worth having even once PCR0 is reproducible.
15
+
16
+ import { MAX_PIN_SET, acceptedSet, toHex, verifyAttestation } from './nitroVerify.js'
17
+
18
+ const b64ToBytes = (b64) => {
19
+ const bin = atob(String(b64).replace(/-/g, '+').replace(/_/g, '/').replace(/\s+/g, ''))
20
+ const out = new Uint8Array(bin.length)
21
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
22
+ return out
23
+ }
24
+
25
+ /** Accept a certificate as DER bytes or a PEM string. */
26
+ function certToDer(cert) {
27
+ if (cert instanceof Uint8Array) return cert
28
+ if (cert instanceof ArrayBuffer) return new Uint8Array(cert)
29
+ const s = String(cert || '')
30
+ const m = /-----BEGIN CERTIFICATE-----([\s\S]*?)-----END CERTIFICATE-----/.exec(s)
31
+ const body = m ? m[1] : s
32
+ const der = b64ToBytes(body)
33
+ if (der.length < 64) throw new Error('enclave: certificate is too short to be real')
34
+ return der
35
+ }
36
+
37
+ /**
38
+ * A PCR is a TPM-style register: it starts at zero and is "extended" with a measurement. nitro-cli builds each one
39
+ * with a single extend of a single blob, which reduces to this:
40
+ *
41
+ * PCR = SHA384( 48 zero bytes ‖ SHA384(measured bytes) )
42
+ *
43
+ * (from aws-nitro-enclaves-image-format, `EifHasher::tpm_extend_finalize_reset`: hash the accumulated data, then
44
+ * hash `initial_digest ‖ that`.)
45
+ */
46
+ export async function tpmExtendOnce(bytes) {
47
+ const inner = new Uint8Array(await crypto.subtle.digest('SHA-384', bytes))
48
+ const buf = new Uint8Array(48 + inner.length) // initial digest is 48 zero bytes for SHA-384
49
+ buf.set(inner, 48)
50
+ return toHex(new Uint8Array(await crypto.subtle.digest('SHA-384', buf)))
51
+ }
52
+
53
+ /**
54
+ * The PCR8 an enclave signed with this certificate must report.
55
+ *
56
+ * ⚠ DERIVED FROM AWS'S SOURCE, NOT YET CONFIRMED AGAINST REAL HARDWARE. `nitro-cli build-enclave --signing-certificate`
57
+ * measures the DER of that certificate; AWS's own documentation instead calls PCR8 "the SHA384 hash of the signing
58
+ * certificate's fingerprint", which does NOT match the code and has confused others (aws-nitro-enclaves-cli#446).
59
+ * We follow the code. Until an EIF is actually signed, treat this as unverified: `infra/enclave/build-eif.sh`
60
+ * compares this function's output to what nitro-cli reports and FAILS the build on a mismatch, so the first real
61
+ * signed build is the thing that confirms it — loudly, rather than by a wrong constant sitting in cert.json.
62
+ */
63
+ export async function expectedPcr8(cert) {
64
+ return tpmExtendOnce(certToDer(cert))
65
+ }
66
+
67
+ const HEX48 = /^[0-9a-f]{96}$/
68
+
69
+ /** Pull the `enclave` block out of a parsed cert.json payload, rejecting anything malformed. Returns null when the
70
+ * deployment simply has no attested tier — which is not an error, and must never be reported as a failed check. */
71
+ export function enclaveClaim(payload) {
72
+ const e = payload && typeof payload === 'object' ? payload.enclave : null
73
+ if (!e || typeof e !== 'object') return null
74
+ const pcrs = {}
75
+ for (const k of ['0', '1', '2', '8', '16', '17']) {
76
+ const v = e.pcrs && e.pcrs[k]
77
+ if (v === undefined) continue
78
+ // §ROLLOVER-SET: a claim may pin {outgoing, incoming} so the PUBLISHED claim keeps verifying both images while a
79
+ // new payload rolls out. Same capped grammar as the verifier; every member is still a real digest.
80
+ const list = acceptedSet(v, `PCR${k}`)
81
+ for (const h of list) if (!HEX48.test(h)) throw new Error(`enclave: PCR${k} in cert.json is not a SHA-384 hex digest`)
82
+ pcrs[k] = Array.isArray(v) ? list : list[0]
83
+ }
84
+ if (!Object.keys(pcrs).length) throw new Error('enclave: the claim names no PCRs, so it constrains nothing')
85
+ if (!pcrs['0']) throw new Error('enclave: a claim without PCR0 does not pin the image')
86
+ const stages = enclaveStages(e.stages, pcrs)
87
+ return { pcrs, stages, signingCert: e.signingCert || null, recipe: e.recipe || '', moduleId: e.moduleId || '', payload: artifactBlock(e.payload, 'payload'), policy: artifactBlock(e.policy, 'policy') }
88
+ }
89
+
90
+ /**
91
+ * P2 (docs/enclave-room-acceptance.md): the claim may also NAME the two loaded artifacts — `payload: {sha384, source}`
92
+ * and `policy: {sha384, version, url}` — so a reader can fetch the turn code / the policy text and check them against
93
+ * the PCR16/PCR17 the live enclave reports (checkPolicyText). Optional; validated when present. `version` is the
94
+ * policy's monotonic release number, the thing a Space's floor is compared to.
95
+ */
96
+ function artifactBlock(b, name) {
97
+ if (b === undefined || b === null) return null
98
+ // A SET, for the same reason `pcrs` takes one: across a repin the live enclave may be running EITHER artifact, and
99
+ // each entry carries its OWN url so both policy texts can be served at once. An array in ⇒ an array out; a bare
100
+ // object still reads back as an object, so every claim written before this keeps its exact shape.
101
+ if (Array.isArray(b)) {
102
+ if (!b.length) throw new Error(`enclave: ${name} names an empty set — that is not a check`)
103
+ if (b.length > MAX_PIN_SET) throw new Error(`enclave: ${name} names ${b.length} artifacts; at most ${MAX_PIN_SET} (a rollover is {outgoing, incoming})`)
104
+ return b.map((one) => oneArtifact(one, name))
105
+ }
106
+ return oneArtifact(b, name)
107
+ }
108
+
109
+ /** Validate ONE artifact entry — the shape this file has always required. */
110
+ function oneArtifact(b, name) {
111
+ if (!b || typeof b !== 'object') throw new Error(`enclave: ${name} must be an object`)
112
+ const sha384 = String(b.sha384 || '').toLowerCase()
113
+ if (!HEX48.test(sha384)) throw new Error(`enclave: ${name}.sha384 is not a SHA-384 hex digest`)
114
+ const out = { sha384 }
115
+ if (name === 'payload') {
116
+ if (b.source !== undefined && typeof b.source !== 'string') throw new Error('enclave: payload.source must be a URL string')
117
+ out.source = b.source || ''
118
+ } else {
119
+ if (!Number.isInteger(b.version) || b.version < 0) throw new Error('enclave: policy.version must be a non-negative integer')
120
+ if (b.url !== undefined && typeof b.url !== 'string') throw new Error('enclave: policy.url must be a URL string')
121
+ out.version = b.version
122
+ out.url = b.url || ''
123
+ }
124
+ return out
125
+ }
126
+
127
+ /** The artifact block as a LIST, whichever shape the claim used. One place decides that, so no caller has to. */
128
+ export function artifactList(a) {
129
+ return a == null ? [] : (Array.isArray(a) ? a : [a])
130
+ }
131
+
132
+ /** Pick the artifact the HARDWARE says is loaded: the entry whose sha384 extends to the LIVE PCR. Returns null when
133
+ * none matches — which is the honest answer, not a reason to fall back to entry 0.
134
+ *
135
+ * ★ THIS IS THE POINT OF THE SET. Before it, the reader fetched `policy.url` — the single declared URL — and then
136
+ * checked the text against the live PCR17. Across a repin that check could only ever pass for ONE of the two live
137
+ * payloads, so the policy could not roll over and the flip needed a window in which the served text was wrong for
138
+ * whatever was actually running. Selecting by the live PCR first inverts it: the hardware names the artifact, and
139
+ * only then do we go and fetch it. */
140
+ export async function pickArtifact(a, livePcrHex) {
141
+ const want = String(livePcrHex || '').toLowerCase()
142
+ if (!want) return null
143
+ for (const one of artifactList(a)) {
144
+ if (one && one.sha384 && (await extendOfDigest(one.sha384)) === want) return one
145
+ }
146
+ return null
147
+ }
148
+
149
+ const hexToBytes = (hex) => new Uint8Array(hex.match(/../g).map((h) => parseInt(h, 16)))
150
+
151
+ /** The PCR a single extend of a blob with THIS sha384 yields — the same arithmetic as tpmExtendOnce, from the digest. */
152
+ async function extendOfDigest(sha384hex) {
153
+ const buf = new Uint8Array(96)
154
+ buf.set(hexToBytes(sha384hex), 48)
155
+ return toHex(new Uint8Array(await crypto.subtle.digest('SHA-384', buf)))
156
+ }
157
+
158
+ /**
159
+ * Believe a fetched policy.json ONLY if it measures to the PCR17 the LIVE enclave reported. This is how the client
160
+ * renders "policy v3, egress: …" from text served by the origin without trusting the origin's prose: the number the
161
+ * hardware signed decides which text is real. → the parsed policy { version, egress, … }.
162
+ */
163
+ export async function checkPolicyText(bytes, livePcr17) {
164
+ const u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
165
+ const got = await tpmExtendOnce(u8)
166
+ if (!livePcr17 || got !== String(livePcr17).toLowerCase()) throw new Error(`enclave: the policy text does not measure to the live PCR17 (${got.slice(0, 12)}… vs ${String(livePcr17 || '').slice(0, 12)}…)`)
167
+ let p
168
+ try { p = JSON.parse(new TextDecoder().decode(u8)) } catch { throw new Error('enclave: policy text is not JSON') }
169
+ if (!p || typeof p !== 'object' || !Number.isInteger(p.version) || p.version < 0) throw new Error('enclave: policy.version must be a non-negative integer')
170
+ return { ...p, egress: Array.isArray(p.egress) ? p.egress.map(String) : [] }
171
+ }
172
+
173
+ /**
174
+ * Two-stage measured launch (docs/enclave-two-stage-launch.md): PCR0 pins only the KERNEL image; the turn code the
175
+ * kernel loads at boot is measured into PCR16 and its policy.json into PCR17. A claim that DECLARES `stages` promises
176
+ * the reader that both were checked — so declaring it without pinning both is refused, otherwise a kernel-only pin
177
+ * would read as a full check. The indices are fixed (16/17 are what the loader extends) and stated in the claim only
178
+ * so a reader can see them without reading the loader.
179
+ */
180
+ function enclaveStages(st, pcrs) {
181
+ if (st === undefined || st === null) return null
182
+ if (typeof st !== 'object') throw new Error('enclave: stages must be an object')
183
+ if (st.payload !== 16) throw new Error('enclave: stages.payload must be 16 (the PCR the loader extends with the turn payload)')
184
+ if (st.policy !== 17) throw new Error('enclave: stages.policy must be 17 (the PCR the loader extends with policy.json)')
185
+ if (!pcrs['16']) throw new Error('enclave: the claim declares a payload stage but pins no PCR16 — the turn code would go unchecked')
186
+ if (!pcrs['17']) throw new Error('enclave: the claim declares a policy stage but pins no PCR17 — the policy would go unchecked')
187
+ return { payload: 16, policy: 17 }
188
+ }
189
+
190
+ /**
191
+ * Verify an attestation document against a published claim.
192
+ * → { ok, doc, checked: {...} } or throws with the reason.
193
+ *
194
+ * `nonce` is strongly recommended: without it this proves the enclave we described existed, not that it is the one
195
+ * on the other end of this connection. The caller decides, but the honest panel should never present a nonce-less
196
+ * result as "you are talking to the attested enclave".
197
+ */
198
+ export async function verifyClaim(cose, payload, { now = Date.now(), nonce = null, maxAgeMs = 0, root, atDocTime = false, clockBoundMs = 0 } = {}) {
199
+ const claim = enclaveClaim(payload)
200
+ if (!claim) throw new Error('enclave: cert.json makes no enclave claim')
201
+
202
+ // Recompute PCR8 from the published certificate BEFORE trusting the number next to it. If they disagree, the
203
+ // published document is internally inconsistent and nothing downstream of it means anything.
204
+ let derived = null
205
+ if (claim.signingCert) {
206
+ derived = await expectedPcr8(claim.signingCert)
207
+ if (claim.pcrs['8'] && !acceptedSet(claim.pcrs['8'], 'PCR8').includes(derived)) {
208
+ throw new Error(`enclave: cert.json states PCR8 ${[claim.pcrs['8']].flat().join(' or ')} but its own signing certificate yields ${derived}`)
209
+ }
210
+ }
211
+ // Prefer the DERIVED value: it is the one the reader can reproduce.
212
+ const expectedPCRs = { ...claim.pcrs, ...(derived ? { 8: derived } : {}) }
213
+ // Same discipline for the named artifacts: a policy/payload digest that does not extend to the PCR pinned next to
214
+ // it makes the claim internally inconsistent — refuse before the wire is consulted.
215
+ for (const [name, idx] of [['policy', '17'], ['payload', '16']]) {
216
+ const a = claim[name]
217
+ if (!a || !claim.pcrs[idx]) continue
218
+ const pinned = acceptedSet(claim.pcrs[idx], `PCR${idx}`)
219
+ // EVERY entry, not just the first: a rollover that names an artifact nothing pins is a claim nobody can satisfy.
220
+ for (const one of artifactList(a)) {
221
+ const ext = await extendOfDigest(one.sha384)
222
+ if (!pinned.includes(ext)) throw new Error(`enclave: the claim's ${name} sha384 ${one.sha384.slice(0, 12)}… yields PCR${idx} ${ext.slice(0, 12)}…, not the ${pinned.map((h) => h.slice(0, 12) + '…').join(' or ')} it pins`)
223
+ }
224
+ }
225
+
226
+ const doc = await verifyAttestation(cose, { now, nonce, maxAgeMs, expectedPCRs, ...(root ? { root } : {}), ...(atDocTime ? { atDocTime, clockBoundMs } : {}) })
227
+ if (claim.moduleId && doc.moduleId !== claim.moduleId) {
228
+ throw new Error(`enclave: module ${doc.moduleId} is not the ${claim.moduleId} named in cert.json`)
229
+ }
230
+ return {
231
+ ok: true,
232
+ doc,
233
+ checked: {
234
+ pcrs: Object.keys(expectedPCRs).map(Number).sort((a, b) => a - b),
235
+ pcr8Derived: !!derived,
236
+ stages: claim.stages,
237
+ fresh: !!nonce,
238
+ policyDigest: !!(claim.policy && claim.pcrs['17']),
239
+ },
240
+ }
241
+ }
@@ -0,0 +1,102 @@
1
+ // spaces/public/enclaveRoute.js — the CLIENT half of the enclave tier.
2
+ //
3
+ // For an enclave-tier Space, the turn runs inside a Nitro enclave, reached via the relaying Lambda. To make that
4
+ // operator-blind at INGRESS (the Lambda must never see mk), the client:
5
+ // 1. fetches the enclave's hardware attestation (op:'enclaveattest', relayed to the enclave),
6
+ // 2. VERIFIES + PINS it against the published measurement (verifyClaim: genuine AWS enclave, expected PCR0/PCR8, a
7
+ // fresh nonce so it's THIS enclave now — not a replay), and
8
+ // 3. seals mk to the recipient key carried INSIDE the verified attestation, so only the measured image can open it.
9
+ // The Lambda then relays opaque bytes. Fail-closed: any verification failure throws and no mk is sent.
10
+ import { verifyClaim, checkPolicyText, enclaveClaim, pickArtifact } from './enclaveClaim.js'
11
+ import { sealMk, sealIdentity, mkAad, newNonce, sealNow, clockOffset, noteServerClock, MAX_CLOCK_OFFSET_MS } from './mkseal.js'
12
+
13
+ const b64uToBytes = (s) => {
14
+ const bin = atob(String(s).replace(/-/g, '+').replace(/_/g, '/').replace(/\s+/g, ''))
15
+ const u = new Uint8Array(bin.length)
16
+ for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i)
17
+ return u
18
+ }
19
+
20
+ // The enclave attests its recipient public key as an SPKI (the P-256 ECDH key mk is sealed to). Import it as the JWK
21
+ // sealMk wants. Comes from the VERIFIED attestation doc, never a side channel.
22
+ async function spkiToJwk(spki) {
23
+ const der = spki instanceof Uint8Array ? spki : b64uToBytes(spki)
24
+ const key = await crypto.subtle.importKey('spki', der, { name: 'ECDH', namedCurve: 'P-256' }, true, [])
25
+ return crypto.subtle.exportKey('jwk', key)
26
+ }
27
+
28
+ /**
29
+ * Verify a running enclave and return its attested recipient key (as a JWK) to seal mk to.
30
+ * @param send a function that POSTs a Space op and resolves the JSON — the SAME transport the ops use, so
31
+ * op:'enclaveattest' is relayed to the enclave. Must carry `enclave:true`.
32
+ * @param claim the published enclave claim to pin against — a cert.json payload with an `.enclave` block
33
+ * ({ enclave: { pcrs:{0,…}, signingCert } }). Throws if the live enclave doesn't match.
34
+ * @param root optional pinned AWS Nitro root override (tests).
35
+ * @param fetchPolicy (url) → policy.json bytes; defaults to fetch(). Only consulted when the claim names a policy
36
+ * URL and the live doc reports PCR17. The text is believed ONLY if it measures to the LIVE PCR17.
37
+ * → { recipientJwk, doc, attested } where attested = { pcrs:{0,16?,17?}, policyVersion|null, policy|null, at } —
38
+ * the facts the Space's own acceptance check (enclaveAccept.js) decides on. A fetch that fails leaves the version
39
+ * UNKNOWN (a Space with a floor then refuses); a text that measures wrong REFUSES the whole attest.
40
+ */
41
+ export async function attestEnclave({ send, claim, root, now, fetchPolicy, room } = {}) {
42
+ // The enclave supervisor decodes the challenge with STANDARD base64 (infra/enclave/app/main.go base64.StdEncoding), so
43
+ // the nonce MUST be standard base64 — a base64URL nonce whose random bytes happen to contain '-' or '_' mis-decodes
44
+ // there, the NSM binds a different challenge, and the freshness check fails ~half the time. Send raw bytes as standard
45
+ // base64; verify against those same bytes.
46
+ const nonceBytes = crypto.getRandomValues(new Uint8Array(16))
47
+ const nonce = btoa(String.fromCharCode(...nonceBytes)) // standard base64 (may contain '+', '/', '=')
48
+ // `room`: the room this key will seal for. A room lives in ONE region (regions.js) and its enclave is that region's, so
49
+ // the request names it and api.witbitz.chat forwards it there (agent/regionForward.mjs). Without it the answer is the
50
+ // enclave of whichever region was asked — whose key the room's own enclave cannot open (docs/multi-region.md).
51
+ const r = await send({ op: 'enclaveattest', enclave: true, nonce, ...(room ? { room } : {}) })
52
+ const cose = r && r.doc
53
+ if (!cose) throw new Error('enclave: no attestation document returned')
54
+ // op:'enclaveattest' returns the COSE doc base64-encoded; verifyClaim/verifyAttestation want raw bytes.
55
+ // T#2b (state machines pass 7): the chain is checked at the document's own time — it is fresh, it carries our nonce — so a
56
+ // device clock that is off no longer refuses a genuine enclave; the device clock (with the offset already learned) must be
57
+ // within a day of the enclave's, else the check fails naming the clock. The document's time then sets the seal clock
58
+ // (mkseal.js): signed by the Nitro hardware and bound to our nonce, it is the enclave's own clock, not the relay's word.
59
+ const { doc } = await verifyClaim(b64uToBytes(cose), claim, { nonce: nonceBytes, ...(root ? { root } : {}), now: now || (Date.now() + clockOffset()), atDocTime: true, clockBoundMs: MAX_CLOCK_OFFSET_MS })
60
+ if (!now && Number.isFinite(doc.timestamp)) noteServerClock(doc.timestamp)
61
+ if (!doc.publicKey) throw new Error('enclave: attestation carries no recipient key')
62
+ const attested = await attestedFacts(doc, claim, fetchPolicy)
63
+ return { recipientJwk: await spkiToJwk(doc.publicKey), doc, attested }
64
+ }
65
+
66
+ const defaultFetchPolicy = async (url) => {
67
+ const r = await fetch(url, { cache: 'no-store', ...(typeof AbortSignal !== 'undefined' && AbortSignal.timeout ? { signal: AbortSignal.timeout(10000) } : {}) }) // network-only, like the claim: a cached policy text is a stale one; BOUNDED — a server that holds the request open must not hang the attestation (2026-09-29)
68
+ if (!r.ok) throw new Error(`enclave: policy text ${r.status}`)
69
+ return new Uint8Array(await r.arrayBuffer())
70
+ }
71
+
72
+ /** The live triple + the policy version proven by the policy text (docs/enclave-room-acceptance.md §5). */
73
+ async function attestedFacts(doc, claim, fetchPolicy) {
74
+ const pcrs = {}
75
+ for (const k of ['0', '16', '17']) if (doc.pcrs && doc.pcrs[k]) pcrs[k] = String(doc.pcrs[k]).toLowerCase()
76
+ const out = { pcrs, policyVersion: null, policy: null, at: Date.now() }
77
+ let named = null
78
+ try { named = enclaveClaim(claim) } catch { named = null }
79
+ if (!named || !named.policy || !pcrs['17']) return out
80
+ // Let the HARDWARE name the artifact before we go and fetch one. The claim may declare two policies across a repin
81
+ // ({outgoing, incoming}), each at its own url; the entry whose digest extends to the LIVE PCR17 is the one actually
82
+ // loaded. Selecting first is what lets the policy roll over — fetching a single declared url could only ever match
83
+ // one side of the flip. No entry matches ⇒ version stays unknown, which is the honest answer, not entry 0.
84
+ const chosen = await pickArtifact(named.policy, pcrs['17'])
85
+ if (!chosen || !chosen.url) return out
86
+ let bytes = null
87
+ try { bytes = await (fetchPolicy || defaultFetchPolicy)(chosen.url) } catch { bytes = null } // unreachable ⇒ version unknown
88
+ if (!bytes) return out
89
+ const policy = await checkPolicyText(bytes, pcrs['17']) // wrong text ⇒ throws ⇒ no key returned
90
+ return { ...out, policyVersion: policy.version, policy }
91
+ }
92
+
93
+ /** Seal mk (and optionally the sign-in identity) to the attested enclave key for ONE op, bound to room|op|ts|nonce.
94
+ * → the fields to send INSTEAD OF raw mk: { mkSealed, mkTs, mkNonce, enclave, [idSealed] }. */
95
+ export async function sealForEnclave(mk, recipientJwk, { room, op, idToken, from } = {}) {
96
+ const ts = sealNow() // the enclave's clock, as far as this device knows it (mkseal.js, T#2)
97
+ const nonce = newNonce()
98
+ const aad = mkAad({ room, op, ts, nonce })
99
+ const out = { enclave: true, mkSealed: await sealMk(mk, recipientJwk, aad), mkTs: ts, mkNonce: nonce }
100
+ if (idToken || from) out.idSealed = await sealIdentity({ idToken, from }, recipientJwk, aad)
101
+ return out
102
+ }
@@ -0,0 +1,44 @@
1
+ // enclaveSnapshotMerge.js — what the VAULT's one key worker is told about the enclave when several app frames speak (the main app,
2
+ // a lane panel, the Code page inside it): each sends its own `{ t:'enclave', key, attested, keys, acceptance, rooms }` and the worker
3
+ // REPLACES its state on every message (l1-worker.js case 'enclave').
4
+ // ⛔ STATE MACHINES PASS 8, R#1: the vault relayed the LAST frame's key, attestation and acceptance whole — a panel holding an older
5
+ // enclave key (the enclave re-attested since it opened) put that key back over the main app's newer one. The main app's key and
6
+ // attestation win; a panel only fills what is missing. Per-region keys merge the same way; accepted builds and confidential rooms are
7
+ // the UNION (a room wrongly listed costs a read, one missing sends its key unsealed — sync sweep 2026-11-09 #1).
8
+ const union = (a, b) => [...new Set([...(Array.isArray(a) ? a : []), ...(Array.isArray(b) ? b : [])])]
9
+ const obj = (o) => (o && typeof o === 'object' && !Array.isArray(o) ? o : {})
10
+
11
+ // ⛔ PASS 9, X#1 — AND THE NEWER ATTESTATION WINS, WHOEVER SENT IT. "The main app's wins" alone froze the first key: the enclave is
12
+ // restarted (a wake, a repin), the person wakes it from the lane panel, the panel attests the NEW key — and the vault handed the
13
+ // worker the main app's old one again; every turn from the panel was sealed to a dead key until the main frame happened to
14
+ // attest. Every snapshot carries when its key was attested (`attested.at`, enclaveRoute.js): the later one is the enclave's key
15
+ // now. Equal or unknown times → the main app's, as pass 8 left it.
16
+ const at = (a) => (a && Number.isFinite(a.at) && a.at > 0 ? a.at : 0)
17
+
18
+ /** prev: the last merged snapshot (or null); msg: a frame's; fromMain: it came from the main app's window. → the merged message. */
19
+ export function mergeEnclaveSnapshot (prev, msg, fromMain) {
20
+ const p = prev || {}
21
+ // which of two attested keys stands: 'm' (this message's) or 'p' (what the worker holds)
22
+ const side = (mKey, mAtt, pKey, pAtt) => {
23
+ if (mKey == null) return 'p'
24
+ if (pKey == null) return 'm'
25
+ const a = at(mAtt), b = at(pAtt)
26
+ if (a && b && a !== b) return a > b ? 'm' : 'p'
27
+ return fromMain ? 'm' : 'p'
28
+ }
29
+ const top = side(msg.key, msg.attested, p.key, p.attested)
30
+ const keys = { ...obj(p.keys) }
31
+ for (const [region, e] of Object.entries(obj(msg.keys))) {
32
+ const was = keys[region]
33
+ if (side(e && e.key, e && e.attested, was && was.key, was && was.attested) === 'm') keys[region] = e
34
+ }
35
+ const pt = p.acceptance && p.acceptance.trusted, mt = msg.acceptance && msg.acceptance.trusted
36
+ return {
37
+ ...msg,
38
+ key: (top === 'm' ? msg.key : p.key) ?? null,
39
+ attested: (top === 'm' ? (msg.attested ?? p.attested) : (p.attested ?? msg.attested)) ?? null,
40
+ keys,
41
+ acceptance: Array.isArray(pt) || Array.isArray(mt) ? { ...obj(p.acceptance), ...obj(msg.acceptance), trusted: union(pt, mt) } : { ...obj(p.acceptance), ...obj(msg.acceptance) },
42
+ rooms: union(p.rooms, msg.rooms),
43
+ }
44
+ }