@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.
- package/LICENSE +21 -0
- package/README.md +20 -2
- package/a2aCore.js +221 -0
- package/a2aShared.js +27 -0
- package/accountErase.js +228 -0
- package/accountIndexDoc.js +122 -0
- package/accountOwner.js +59 -0
- package/accountRecord.js +90 -0
- package/accountScope.js +114 -0
- package/accountSeal.js +42 -0
- package/accountStores.js +173 -0
- package/acctV2App.js +619 -0
- package/acctV2Check.js +29 -0
- package/acctV2Client.js +382 -0
- package/acctV2Keys.js +43 -0
- package/acctV2Legacy.js +14 -0
- package/acctV2Switch.js +80 -0
- package/acctV2UiCore.js +857 -0
- package/acctV2WebAuthn.js +61 -0
- package/acctV2Wire.js +59 -0
- package/address.js +42 -0
- package/agentDoorTools.js +28 -0
- package/attestedBox.js +30 -0
- package/attestedRooms.js +78 -0
- package/awsKey.js +98 -0
- package/backupRecord.js +106 -0
- package/backupVault.js +97 -0
- package/blocks.js +115 -0
- package/blocksPush.js +64 -0
- package/browseSeal.js +103 -0
- package/cbor.js +225 -0
- package/changePush.js +75 -0
- package/chatLock.js +165 -0
- package/chatLockSw.js +13 -0
- package/cloudDeviceBuilds.js +11 -0
- package/cloudDevicePins.js +33 -0
- package/cloudDeviceSeal.js +53 -0
- package/codeAttachments.js +100 -0
- package/codeBrowse.js +224 -0
- package/codeCache.js +149 -0
- package/codeCloud.js +650 -0
- package/codeCloudKeys.js +112 -0
- package/codeCommands.js +167 -0
- package/codeComputers.js +389 -0
- package/codeEgress.js +123 -0
- package/codeFilesRoutes.js +17 -0
- package/codeFolders.js +116 -0
- package/codeHistory.js +76 -0
- package/codeLanguage.js +54 -0
- package/codeMkdir.js +8 -0
- package/codeModes.js +59 -0
- package/codeOrphanKeys.js +42 -0
- package/codeOutputs.js +141 -0
- package/codeProgress.js +54 -0
- package/codeRelay.js +505 -0
- package/codeSent.js +68 -0
- package/codeSentinel.js +86 -0
- package/codeSubagents.js +107 -0
- package/codeTransport.js +317 -0
- package/codeUndo.js +48 -0
- package/compress.js +24 -0
- package/config.js +11 -0
- package/connCatalog.js +164 -0
- package/connDisp.js +76 -0
- package/connOtherWays.js +74 -0
- package/connPending.js +16 -0
- package/connWrap.js +53 -0
- package/connectionEntry.js +89 -0
- package/connections.js +561 -0
- package/credits.js +30 -0
- package/csAttest.js +112 -0
- package/decrypt.html +384 -0
- package/deviceAttest.js +527 -0
- package/deviceCall.js +54 -0
- package/deviceKeyCore.js +41 -0
- package/deviceSeal.js +59 -0
- package/e2ee.js +323 -0
- package/eat.js +103 -0
- package/emailFork.js +275 -0
- package/emailSignIn.js +81 -0
- package/emptySpaces.js +111 -0
- package/encSource.js +55 -0
- package/enclaveAccept.js +214 -0
- package/enclaveClaim.js +241 -0
- package/enclaveRoute.js +102 -0
- package/enclaveSnapshotMerge.js +44 -0
- package/entrySig.js +165 -0
- package/env.js +73 -0
- package/eraseFile.js +58 -0
- package/followImage.js +86 -0
- package/healNames.js +45 -0
- package/idb.js +113 -0
- package/idbSeal.js +119 -0
- package/indexGone.js +12 -0
- package/invite.js +51 -0
- package/inviteEnroll.js +67 -0
- package/inviteSend.js +68 -0
- package/jobAgents.js +87 -0
- package/keptMerge.js +91 -0
- package/l1-worker-src.js +2 -0
- package/l1-worker.js +894 -0
- package/laneAssociation.js +68 -0
- package/laneConfig.js +58 -0
- package/laneLinkCore.js +177 -0
- package/ledgerView.js +64 -0
- package/manifest.json +239 -0
- package/mcpRecommended.js +25 -0
- package/memberChange.js +125 -0
- package/mirrorBatch.js +47 -0
- package/mkseal.js +101 -0
- package/nativePush.js +153 -0
- package/nitroVerify.js +220 -0
- package/noble-p256.js +27 -0
- package/notice.js +116 -0
- package/notifKey.js +58 -0
- package/offlineBundle.js +62 -0
- package/ohttp.js +177 -0
- package/opRouting.js +10 -0
- package/opencodeWire.js +282 -0
- package/oprf.js +70 -0
- package/ownAgentLink.js +96 -0
- package/ownerPolicy.js +117 -0
- package/package.json +273 -4
- package/pdfOptions.js +13 -0
- package/pdfText.js +107 -0
- package/pdfjs.mjs +28 -0
- package/pdfjs.worker.mjs +28 -0
- package/pollVerdict.js +33 -0
- package/prefetchPoll.js +60 -0
- package/protectedLocal.js +426 -0
- package/pushCore.js +42 -0
- package/recovery.js +107 -0
- package/regions.js +42 -0
- package/removedMessage.js +11 -0
- package/renameRefusal.js +9 -0
- package/replyQuote.js +34 -0
- package/reqEnvelope.js +126 -0
- package/roomDefaultPrefs.js +76 -0
- package/roomDelete.js +109 -0
- package/roomEmbed.js +111 -0
- package/roomName.js +177 -0
- package/roomPass.js +256 -0
- package/roomRoster.js +305 -0
- package/roomSettings.js +61 -0
- package/roomState.js +58 -0
- package/roomStreamClient.js +115 -0
- package/rosterCount.js +52 -0
- package/rosterHash.js +13 -0
- package/rowSchema.js +113 -0
- package/safeMedia.js +116 -0
- package/safeMediaPins.js +17 -0
- package/schedulesDoc.js +78 -0
- package/sdkA2A.js +524 -0
- package/sdkAccount.js +483 -0
- package/sdkAccountDoc.js +89 -0
- package/sdkAccountSections.js +332 -0
- package/sdkAgui.js +141 -0
- package/sdkAttest.js +34 -0
- package/sdkBackup.js +507 -0
- package/sdkBackupV2.js +630 -0
- package/sdkBrowserPrivate.js +28 -0
- package/sdkBuilds.js +208 -0
- package/sdkCloudDevice.js +221 -0
- package/sdkComputers.js +1009 -0
- package/sdkDictation.js +232 -0
- package/sdkErase.js +288 -0
- package/sdkExports.js +71 -0
- package/sdkInvitations.js +34 -0
- package/sdkKeptAgent.js +188 -0
- package/sdkLaneLink.js +205 -0
- package/sdkPlan.js +96 -0
- package/sdkProtect.js +228 -0
- package/sdkRedact.js +36 -0
- package/sdkRekey.js +340 -0
- package/sdkReport.js +68 -0
- package/sdkSafeMedia.js +255 -0
- package/sdkSchedules.js +39 -0
- package/sdkSpeech.js +71 -0
- package/sdkTemporaryRooms.js +123 -0
- package/sdkTurn.js +117 -0
- package/sdkVault.js +180 -0
- package/sealShare.js +18 -0
- package/sealedNames.js +64 -0
- package/sealedReceipt.js +17 -0
- package/sentinelRelease.js +155 -0
- package/shamir.js +85 -0
- package/sharedViews.js +52 -0
- package/sheetChrome.js +450 -0
- package/siri.js +278 -0
- package/spaceClient.js +1429 -0
- package/spaceConfig.js +81 -0
- package/spaceEmailGate.js +813 -0
- package/spaceExport.js +125 -0
- package/spaceFork.js +216 -0
- package/spaceLock.js +358 -0
- package/spacePasskey.js +180 -0
- package/spaceTemplates.js +99 -0
- package/speechOut.js +102 -0
- package/splitKeyClient.js +90 -0
- package/store.js +656 -0
- package/streamHint.js +36 -0
- package/sttCloud.js +220 -0
- package/sttWorklet.js +38 -0
- package/sw-notif-core.js +540 -0
- package/tempList.js +48 -0
- package/tinfoilVerifier.js +78 -0
- package/toolBooks.js +31 -0
- package/toolRules.js +52 -0
- package/turnCerts.js +254 -0
- package/turnFeed.js +58 -0
- package/turnVerdict.js +37 -0
- package/usageReceipts.js +176 -0
- package/usageSummary.js +90 -0
- package/util.js +181 -0
- package/vault-core.js +2326 -0
- package/vault-kit.mjs +354 -0
- package/vault-screens.js +261 -0
- package/vaultAtRest.js +208 -0
- package/vaultCoreLock.js +111 -0
- package/vaultCorePush.js +140 -0
- package/vaultDeviceKey.js +95 -0
- package/vaultEnclaveHandoff.js +114 -0
- package/vaultKeep.js +287 -0
- package/vaultSealedStore.js +77 -0
- package/vaultWorkerHost.js +117 -0
- package/vcWorker.js +34 -0
- package/voiceAttest.js +50 -0
- package/voiceCert.js +51 -0
- package/witbitz-admin.d.ts +135 -0
- package/witbitz-admin.js +529 -0
- package/witbitz-admin.mjs +1460 -0
- package/witbitz-sdk.d.ts +1197 -0
- package/witbitz-sdk.js +4258 -0
- package/workerClient.js +16 -0
- package/workerLiveness.js +21 -0
- package/x509.js +218 -0
package/sdkTurn.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// sdkTurn.js — a turn you can hold (https://witbitz.chat/docs/sdk-roadmap.md, item 6, 2026-10-05).
|
|
2
|
+
//
|
|
3
|
+
// `space.send()` keeps the room's semantics: it posts a message, and whatever the room does next (the assistant replies,
|
|
4
|
+
// stays quiet, someone else speaks) arrives on `on('message')`. Builders asked for the other shape too — "I sent this,
|
|
5
|
+
// tell me when ITS answer is done" — and wired it by hand from three events. `space.turn(text)` is that shape:
|
|
6
|
+
//
|
|
7
|
+
// const t = space.turn('Plan the trip', { timeoutMs: 120_000 })
|
|
8
|
+
// t.on('partial', ({ text }) => draw(text)) // the reply as it streams (this turn only)
|
|
9
|
+
// const { status, reply } = await t.finished // 'done' | 'silent' | 'failed' | 'aborted' | 'timeout'
|
|
10
|
+
// t.abort() // stop it: the text streamed so far is kept as the reply
|
|
11
|
+
//
|
|
12
|
+
// HOW THE REPLY IS FOUND. The turn request returns when the server has finished the turn (with the reply's text), or is
|
|
13
|
+
// cut at ~30 s by the API front door while the server goes on (`pending`). The reply MESSAGE arrives through the poll. A
|
|
14
|
+
// room runs one reply at a time (the server answers `busy` and the SDK resends), so the first assistant message that
|
|
15
|
+
// lands after the attempt that actually ran is this turn's — matched by its text when the server gave it, else by order.
|
|
16
|
+
// `finished` never rejects: the status says what happened, and `error` carries the server's code when there is one.
|
|
17
|
+
import { turnVerdict, QUEUE_MAX_TRIES, QUEUE_RETRY_MS } from './turnVerdict.js'
|
|
18
|
+
|
|
19
|
+
/** A turn's usage as a builder reads it (Tomer, 2026-10-10: "tokens in/out/cached and the cost, so we can measure a turn
|
|
20
|
+
* without waiting for daily billing"), from the record the server keeps on the reply (agent/turnUsage.mjs). `costMicros`
|
|
21
|
+
* is the PROVIDER's figure in millionths of a dollar; `source` 'provider-partial'/'none' = some calls reported no cost
|
|
22
|
+
* (the total then counts only the priced ones). null when the turn made no model call. */
|
|
23
|
+
export function turnUsage (rec) {
|
|
24
|
+
if (!rec || typeof rec !== 'object' || !Number.isFinite(rec.in)) return null
|
|
25
|
+
const n = (v) => (Number.isFinite(v) ? v : 0)
|
|
26
|
+
return {
|
|
27
|
+
tokensIn: n(rec.in), tokensOut: n(rec.out), tokensCached: n(rec.cached),
|
|
28
|
+
costMicros: n(rec.costMicros), costUsd: n(rec.costMicros) / 1e6,
|
|
29
|
+
calls: n(rec.calls), models: Array.isArray(rec.models) ? rec.models.slice() : [],
|
|
30
|
+
source: typeof rec.source === 'string' ? rec.source : 'none',
|
|
31
|
+
...(rec.estimated ? { estimated: true } : {}), ...(rec.funded ? { funded: true } : {}),
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// THE APP'S WAIT (docs sync, 2026-11-22): the Spaces app holds a send for QUEUE_MAX_TRIES × QUEUE_RETRY_MS (~16 min, turnVerdict.js),
|
|
36
|
+
// longer than the longest turn the server runs (13 min, under the 900 s Lambda, since 2026-11-18). This was 180 s — the old hold —
|
|
37
|
+
// so a long, healthy turn timed out here and was STOPPED (`_stop`). One constant now; spaces/test/sdkTurnWait.test.mjs holds it.
|
|
38
|
+
export const TURN_TIMEOUT_MS = QUEUE_MAX_TRIES * QUEUE_RETRY_MS
|
|
39
|
+
|
|
40
|
+
const randStopKey = () => {
|
|
41
|
+
const a = new Uint8Array(18); crypto.getRandomValues(a)
|
|
42
|
+
return btoa(String.fromCharCode(...a)).replace(/[^A-Za-z0-9]/g, '').slice(0, 24)
|
|
43
|
+
}
|
|
44
|
+
const isReply = (m) => !!(m && m.self && !m.sys)
|
|
45
|
+
|
|
46
|
+
export class Turn {
|
|
47
|
+
/** Use `space.turn(text, opts)`. */
|
|
48
|
+
constructor(space, text, { timeoutMs = TURN_TIMEOUT_MS, ...sendOpts } = {}) {
|
|
49
|
+
this._space = space
|
|
50
|
+
this._subs = {}
|
|
51
|
+
this._stopKey = randStopKey()
|
|
52
|
+
this._mark = null // messages.length when the attempt that RAN was posted
|
|
53
|
+
this._replyText = null // the server's word on the reply, when it gave one
|
|
54
|
+
/** 'running' until it settles; then 'done' | 'silent' | 'failed' | 'aborted' | 'timeout'. */
|
|
55
|
+
this.status = 'running'
|
|
56
|
+
/** The reply as it has streamed so far ('' before the first token). */
|
|
57
|
+
this.text = ''
|
|
58
|
+
/** The send() result, once the server answered. */
|
|
59
|
+
this.result = null
|
|
60
|
+
this.finished = new Promise((res) => { this._resolve = res })
|
|
61
|
+
this._onPartial = (p) => { if (this.status !== 'running' || p.text == null) return; this.text = p.text; this._emit('partial', p) }
|
|
62
|
+
this._onMessage = () => this._look()
|
|
63
|
+
space.on('partial', this._onPartial)
|
|
64
|
+
space.on('message', this._onMessage)
|
|
65
|
+
this._timer = timeoutMs > 0 ? setTimeout(() => { this._settle('timeout'); this._stop() }, timeoutMs) : null
|
|
66
|
+
space.send(text, { ...sendOpts, stopKey: this._stopKey, _onAttempt: () => { this._mark = space.messages.length }, _aborted: () => this.status !== 'running' }) // aborted OR timed out: a held message is never resent after the turn settled
|
|
67
|
+
.then((r) => this._answered(r), (e) => this._settle('failed', { error: (e && e.code) || String((e && e.message) || e) }))
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Listen: 'partial' ({ text, step }) while it streams, 'done' (the settled result). Returns an unsubscribe function. */
|
|
71
|
+
on(event, cb) { (this._subs[event] ||= []).push(cb); return () => { this._subs[event] = (this._subs[event] || []).filter((x) => x !== cb) } }
|
|
72
|
+
_emit(event, arg) { for (const cb of (this._subs[event] || [])) { try { cb(arg) } catch { /* a listener must not break the turn */ } } }
|
|
73
|
+
|
|
74
|
+
/** Stop the reply. The server keeps what streamed so far as the reply; `finished` settles as 'aborted'. */
|
|
75
|
+
async abort() {
|
|
76
|
+
if (this.status !== 'running') return false
|
|
77
|
+
this._settle('aborted')
|
|
78
|
+
await this._stop()
|
|
79
|
+
return true
|
|
80
|
+
}
|
|
81
|
+
async _stop() { try { await this._space._client.stop(this._space.room, this._stopKey) } catch { /* a stop that cannot be sent leaves the turn to finish */ } }
|
|
82
|
+
|
|
83
|
+
_answered(r) {
|
|
84
|
+
this.result = r
|
|
85
|
+
const v = turnVerdict(r)
|
|
86
|
+
if (v.kind === 'silent') return this._settle('silent')
|
|
87
|
+
if (v.kind === 'ok') { this._replyText = typeof r.reply === 'string' ? r.reply : null; if (this._replyText === '') return this._settle('silent'); return this._look() }
|
|
88
|
+
if (r && r.pending) return this._look() // cut at the front door; the reply still comes on the poll
|
|
89
|
+
// NO ANSWER at all (status 0) settles as failed with its code — it MAY have posted (sdk.md): read the room before resending
|
|
90
|
+
this._settle('failed', { error: (r && r.error) || v.code || v.kind, reason: (r && r.reason) || v.reason }) // the server's sentence too (sweep 11-04 P3: TurnResult had no reason)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Is this turn's reply in `messages` yet?
|
|
94
|
+
_look() {
|
|
95
|
+
if (this.status !== 'running' || this._mark === null) return
|
|
96
|
+
if (this.result === null) return // the request is still out: a reply that lands now may be a previous turn's
|
|
97
|
+
const list = this._space.messages
|
|
98
|
+
const after = list.slice(this._mark).filter(isReply)
|
|
99
|
+
const m = (this._replyText ? after.find((x) => String(x.text || '') === this._replyText) : null) || after[0]
|
|
100
|
+
if (m) this._settle(m.stopped ? 'aborted' : 'done', { reply: m })
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
_settle(status, extra = {}) {
|
|
104
|
+
if (this.status !== 'running') return
|
|
105
|
+
this.status = status
|
|
106
|
+
clearTimeout(this._timer)
|
|
107
|
+
this._space.off('partial', this._onPartial)
|
|
108
|
+
this._space.off('message', this._onMessage)
|
|
109
|
+
const reply = extra.reply || null
|
|
110
|
+
if (reply && typeof reply.text === 'string') this.text = reply.text
|
|
111
|
+
// usage: from the turn's answer, else (a turn cut at the 30 s front door) from the stored reply, which carries it too
|
|
112
|
+
const usage = (this.result && this.result.usage) || turnUsage(reply && reply.usage)
|
|
113
|
+
const out = { status, reply, text: this.text, proposed: (this.result && Array.isArray(this.result.proposed)) ? this.result.proposed : [], ...(usage ? { usage } : {}), ...(extra.error ? { error: String(extra.error) } : {}), ...(extra.reason ? { reason: String(extra.reason).slice(0, 500) } : {}) }
|
|
114
|
+
this._emit('done', out)
|
|
115
|
+
this._resolve(out)
|
|
116
|
+
}
|
|
117
|
+
}
|
package/sdkVault.js
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// sdkVault.js — the SDK's side of a BUILDER-HOSTED VAULT (docs/sdk-vault-mode.md).
|
|
2
|
+
//
|
|
3
|
+
// A builder's page runs framed by a vault on another origin the builder also serves. The vault (vault-core.js) holds the
|
|
4
|
+
// room keys in its own worker; this page never does. Every room operation goes up as a message and its answer comes
|
|
5
|
+
// back — the page sends the room id and the operation, never a key, and gets back what the operation returns.
|
|
6
|
+
//
|
|
7
|
+
// The wire, on the `wbvault` channel, origin-pinned BOTH ways:
|
|
8
|
+
// page → vault { ch:'wbvault', t:'hello', v } the handshake; the vault answers { t:'welcome', v, tenant, endpoint, signedIn, email, rooms }
|
|
9
|
+
// page → vault { ch:'wbvault', t:'call', id, op, args } one request; the vault answers { t:'res', id, result } or { t:'res', id, error, code }
|
|
10
|
+
// vault → page { ch:'wbvault', t:'event', ev, ... } rooms changed / joined / signed in or out / a room's stream
|
|
11
|
+
// vault → page { ch:'wbvault', t:'ask', id, kind, ... } the vault needs the page's answer (a Siri drop for its deliver);
|
|
12
|
+
// the page replies with the call `answer(id, { result } | { error })`
|
|
13
|
+
// The page posts ONLY to the pinned vault origin (never '*') and accepts ONLY messages from that origin AND from the
|
|
14
|
+
// window that frames it — a page we did not write must not broadcast, and nothing else on the page may answer for the vault.
|
|
15
|
+
import { TURN_TIMEOUT_MS } from './sdkTurn.js'
|
|
16
|
+
import { WORKER_OPS } from './workerClient.js'
|
|
17
|
+
|
|
18
|
+
export const VAULT_PROTOCOL = 1
|
|
19
|
+
const HELLO_MS = 8000 // the vault's welcome; past it the page is not in a vault (or the vault is not answering)
|
|
20
|
+
const CALL_MS = 120_000 // one operation; a turn can run a while — the vault answers when the server does
|
|
21
|
+
// …but a call that HOLDS A SCREEN for the person (a code from their mail, writing the recovery code down, a confirm) waits for
|
|
22
|
+
// them: at 120 s the page gave up with vault_timeout while the vault went on — a retried fork made a second room (sync sweep 10-22 #8)
|
|
23
|
+
const PERSON_MS = 15 * 60_000
|
|
24
|
+
const PERSON_OPS = new Set(['signIn', 'signOut', 'fork', 'follow', 'share', 'forget', 'changeMembers', 'rotateKey', 'account', 'roomAccount', 'lockSettings', 'notifications'])
|
|
25
|
+
// …and a call that may WAKE a confidential Space's enclave: a confidential create waits up to 45 × 8 s for it, a lane's create may
|
|
26
|
+
// wake it twice — past 120 s the page gave up while the vault went on, and a retry made a second room (sync sweep 11-04 P7)
|
|
27
|
+
const WAKE_MS = 15 * 60_000
|
|
28
|
+
const WAKE_OPS = new Set(['create', 'createLane'])
|
|
29
|
+
|
|
30
|
+
const isOrigin = (s) => typeof s === 'string' && /^https?:\/\/[^/?#]+$/.test(s)
|
|
31
|
+
|
|
32
|
+
/** Connect to the vault that frames this page. Resolves to a KEYLESS client the SDK's Space runs on, plus the vault's own
|
|
33
|
+
* calls (create, rooms, share, signIn, signOut). Rejects with `not_in_vault` when the page is not framed by that origin. */
|
|
34
|
+
export function connectVault({ vault, win = (typeof window !== 'undefined' ? window : null), helloMs = HELLO_MS } = {}) {
|
|
35
|
+
const origin = String(vault || '').replace(/\/+$/, '')
|
|
36
|
+
if (!isOrigin(origin)) return Promise.reject(Object.assign(new Error('witbitz: `vault` must be the vault\'s origin, e.g. https://vault.example.com'), { code: 'invalid_argument' }))
|
|
37
|
+
if (!win || win.top === win) return Promise.reject(Object.assign(new Error('witbitz: this page is not framed by a vault — open the vault (' + origin + '), which opens this page inside it'), { code: 'not_in_vault' }))
|
|
38
|
+
const cacheKey = Symbol.for('witbitz.vault.transports.v1')
|
|
39
|
+
const transports = win[cacheKey] ||= new Map()
|
|
40
|
+
if (transports.has(origin)) return transports.get(origin)
|
|
41
|
+
const connection = openTransport(win, origin, helloMs)
|
|
42
|
+
transports.set(origin, connection)
|
|
43
|
+
connection.catch(() => { if (transports.get(origin) === connection) transports.delete(origin) })
|
|
44
|
+
return connection
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function openTransport(win, origin, helloMs) {
|
|
48
|
+
const top = win.top
|
|
49
|
+
const waiting = new Map()
|
|
50
|
+
const listeners = new Set()
|
|
51
|
+
const askers = new Map() // kind → room → the page's handler for the vault's question
|
|
52
|
+
const streams = new Map() // room → the handlers of every Space on this page showing it (the vault holds one socket per room)
|
|
53
|
+
const sequenceKey = Symbol.for('witbitz.vault.requestSequence')
|
|
54
|
+
if (!Number.isSafeInteger(win[sequenceKey])) win[sequenceKey] = 0
|
|
55
|
+
let welcome = null
|
|
56
|
+
let onWelcome = null
|
|
57
|
+
const receive = (e) => {
|
|
58
|
+
if (e.origin !== origin || e.source !== top) return // only the vault that frames us
|
|
59
|
+
const d = e.data
|
|
60
|
+
if (!d || d.ch !== 'wbvault') return
|
|
61
|
+
if (d.t === 'welcome') { welcome = Object.assign(welcome || {}, d); if (onWelcome) onWelcome(welcome); return }
|
|
62
|
+
if (d.t === 'res') {
|
|
63
|
+
const w = waiting.get(d.id); if (!w) return
|
|
64
|
+
waiting.delete(d.id); clearTimeout(w.timer)
|
|
65
|
+
if (d.error) w.rej(Object.assign(new Error(String(d.error)), { code: d.code || 'vault_refused', status: d.status, ...(d.code === 'wrong_pin' && Number.isSafeInteger(d.next) && d.next >= 0 ? { next: d.next } : {}), ...(d.code === 'partial_revoke' ? { removedFrom: d.removedFrom || [], unchecked: d.unchecked || [] } : {}), ...(Array.isArray(d.unavailable) ? { unavailable: d.unavailable } : {}), ...(typeof d.reason === 'string' ? { reason: d.reason } : {}), ...(d.verdict && typeof d.verdict === 'object' ? { verdict: d.verdict } : {}) })); else w.res(d.result)
|
|
66
|
+
return
|
|
67
|
+
}
|
|
68
|
+
if (d.t === 'ask' && typeof d.id === 'number') {
|
|
69
|
+
const fn = (askers.get(d.kind) || new Map()).get(d.room)
|
|
70
|
+
Promise.resolve().then(() => { if (!fn) throw new Error('nothing on this page takes ' + String(d.kind).slice(0, 30)); return fn(d) })
|
|
71
|
+
.then((result) => call('answer', d.id, { result: result === undefined ? null : result }), (err) => call('answer', d.id, { error: String((err && err.message) || err || 'refused').slice(0, 200) })).catch(() => {})
|
|
72
|
+
return
|
|
73
|
+
}
|
|
74
|
+
if (d.t === 'event' && welcome) {
|
|
75
|
+
if (d.ev === 'signedOut' || d.ev === 'accountSignedOut') {
|
|
76
|
+
Object.assign(welcome, { signedIn: false, email: '', keyId: '', siri: null })
|
|
77
|
+
if (d.reason !== 'expired') {
|
|
78
|
+
streams.clear(); welcome.rooms = []; welcome.keyStates = []; welcome.account = null
|
|
79
|
+
}
|
|
80
|
+
delete welcome.notifOpen
|
|
81
|
+
}
|
|
82
|
+
if (d.ev === 'signedIn') {
|
|
83
|
+
Object.assign(welcome, { signedIn: true, email: d.email || '', keyId: d.keyId || '' })
|
|
84
|
+
post({ t: 'hello', v: VAULT_PROTOCOL })
|
|
85
|
+
}
|
|
86
|
+
if (d.ev === 'siri' && d.siri) welcome.siri = d.siri
|
|
87
|
+
if (d.ev === 'rooms' && Array.isArray(d.rooms)) {
|
|
88
|
+
welcome.rooms = d.rooms
|
|
89
|
+
const held = new Set(d.rooms.map(r => r.room))
|
|
90
|
+
for (const room of streams.keys()) if (!held.has(room)) streams.delete(room)
|
|
91
|
+
}
|
|
92
|
+
if (d.ev === 'session' || d.ev === 'signedIn') welcome.keyId = d.keyId || ''
|
|
93
|
+
if (d.ev === 'account') welcome.account = d.view
|
|
94
|
+
if (d.ev === 'lock') welcome.lock = d.lock
|
|
95
|
+
if (d.ev === 'push') welcome.push = d.push
|
|
96
|
+
if (d.ev === 'key' && d.room) {
|
|
97
|
+
const prior = (Array.isArray(welcome.keyStates) ? welcome.keyStates : []).filter(k => k.room !== d.room)
|
|
98
|
+
if (d.kind === 'pending' || d.kind === 'removed') prior.push({ room: d.room, kind: d.kind, reason: d.reason || '' })
|
|
99
|
+
welcome.keyStates = prior.slice(-200)
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (d.t === 'event' && d.ev === 'stream') { for (const fn of streams.get(d.room) || []) { try { fn(d) } catch { /* */ } } return }
|
|
103
|
+
if (d.t === 'event') { for (const fn of listeners) { try { fn(d) } catch { /* a listener's error is its own */ } } }
|
|
104
|
+
}
|
|
105
|
+
win.addEventListener('message', receive)
|
|
106
|
+
const post = (msg) => top.postMessage({ ch: 'wbvault', ...msg }, origin)
|
|
107
|
+
const call = (op, ...args) => new Promise((res, rej) => {
|
|
108
|
+
const id = ++win[sequenceKey]
|
|
109
|
+
const timer = setTimeout(() => { if (waiting.delete(id)) rej(Object.assign(new Error('witbitz: the vault did not answer (' + op + ')'), { code: 'vault_timeout' })) }, PERSON_OPS.has(op) ? PERSON_MS : WAKE_OPS.has(op) ? WAKE_MS : op === 'op' && args[0] === 'turn' ? TURN_TIMEOUT_MS : CALL_MS)
|
|
110
|
+
waiting.set(id, { res, rej, timer })
|
|
111
|
+
try { post({ t: 'call', id, op, args }) } catch (err) { waiting.delete(id); clearTimeout(timer); rej(err) }
|
|
112
|
+
})
|
|
113
|
+
return new Promise((resolve, reject) => {
|
|
114
|
+
const done = (w) => {
|
|
115
|
+
clearTimeout(timer)
|
|
116
|
+
// THE KEYLESS CLIENT: the same shape workerClient gives the Spaces app — each op takes (room, mk, …rest) and drops mk.
|
|
117
|
+
const client = { keyless: true, vault: origin }
|
|
118
|
+
for (const op of [...WORKER_OPS, 'sealed', 'exportSealed']) client[op] = (room, _mk, ...rest) => call('op', op, room, ...rest) // sealed/exportSealed: the stored ciphertext, for sealedProof
|
|
119
|
+
client.stop = (room, key) => call('op', 'stop', room, key) // turn.abort(): stop the turn on the server — it needs no key, the vault sends it (sync sweep 10-15 #3)
|
|
120
|
+
// SPEECH KEYS (dictation, reading aloud): minted by the vault with ITS sign-in; the idToken argument is the page's (none)
|
|
121
|
+
client.stt = (_idToken, userToken) => call('speechKey', 'stt', userToken || '')
|
|
122
|
+
client.tts = (_idToken, userToken) => call('speechKey', 'tts', userToken || '')
|
|
123
|
+
// ROOM STREAMS: the socket lives in the vault's worker (it needs the key); the page gets its events. The worker
|
|
124
|
+
// keeps the stream in step from the polls it runs, so the page's handle has nothing to sync.
|
|
125
|
+
client.streamOpen = (room, onEvent, onState) => {
|
|
126
|
+
const fn = (d) => { if (d.event) onEvent(d.event); else if ('up' in d && onState) onState(!!d.up) }
|
|
127
|
+
let set = streams.get(room)
|
|
128
|
+
if (!set) {
|
|
129
|
+
set = new Set(); streams.set(room, set)
|
|
130
|
+
let delay = 1000
|
|
131
|
+
const subscribe = () => {
|
|
132
|
+
if (streams.get(room) !== set) return
|
|
133
|
+
call('stream', room, true).catch(err => {
|
|
134
|
+
if (streams.get(room) !== set) return
|
|
135
|
+
for (const notify of set) { try { notify({ up: false }) } catch {} }
|
|
136
|
+
if (['not_in_vault', 'bad_room', 'vault_refused'].includes(err?.code)) return
|
|
137
|
+
setTimeout(subscribe, delay)
|
|
138
|
+
delay = Math.min(30000, delay * 2)
|
|
139
|
+
})
|
|
140
|
+
}
|
|
141
|
+
subscribe()
|
|
142
|
+
}
|
|
143
|
+
set.add(fn)
|
|
144
|
+
return { stop: () => { if (set.delete(fn) && !set.size && streams.get(room) === set) { streams.delete(room); call('stream', room, false).catch(() => {}) } }, setGrants: () => {}, sync: () => {} }
|
|
145
|
+
}
|
|
146
|
+
const v = {
|
|
147
|
+
origin, client, info: w,
|
|
148
|
+
create: (cfg, opts) => call('create', cfg, ...(opts ? [opts] : [])), // opts { enclave }: dropping it would make a STANDARD Space where a confidential one was asked
|
|
149
|
+
rooms: () => call('rooms'),
|
|
150
|
+
share: (room, opts) => call('share', room, opts || {}),
|
|
151
|
+
signIn: () => call('signIn'),
|
|
152
|
+
signOut: () => call('signOut'),
|
|
153
|
+
userToken: (t) => call('userToken', t), // per-user billing: the page's current token, handed over before an op that can spend
|
|
154
|
+
enclaveAvailable: () => call('enclaveAvailable'),
|
|
155
|
+
whoami: () => call('whoami'),
|
|
156
|
+
lockSettings: () => call('lockSettings'), // the vault's lock sheet (a vault started with `lock: true`): the person decides there; the page learns { available, on, protect }
|
|
157
|
+
notifications: () => call('notifications'), // the vault's notifications card (`push: true`): the person decides; the page learns { available, on }
|
|
158
|
+
forget: (room) => call('forget', room),
|
|
159
|
+
createLane: (shared, cfg, o) => (o ? call('createLane', shared, cfg, o) : call('createLane', shared, cfg)), // o { open }: the page asked for an admission that is not a sign-in (refused in a verified Space)
|
|
160
|
+
fork: (room, opts) => call('fork', room, opts),
|
|
161
|
+
changeMembers: (room, admission) => call('changeMembers', room, admission), // a member change in place: the vault makes and keeps the new key (sdkRekey.js)
|
|
162
|
+
rotateKey: (room) => call('rotateKey', room),
|
|
163
|
+
follow: (room, id) => call('follow', room, id),
|
|
164
|
+
announce: (room) => call('announce', room),
|
|
165
|
+
account: (ns, m, ...a) => call('account', ns, m, ...a),
|
|
166
|
+
roomAccount: (room, ns, m, ...a) => call('roomAccount', room, ns, m, ...a),
|
|
167
|
+
onAsk: (kind, room, fn) => { if (!askers.has(kind)) askers.set(kind, new Map()); askers.get(kind).set(room, fn); return () => { const m = askers.get(kind); if (m && m.get(room) === fn) m.delete(room) } },
|
|
168
|
+
on: (fn) => { listeners.add(fn); return () => listeners.delete(fn) },
|
|
169
|
+
}
|
|
170
|
+
resolve(v)
|
|
171
|
+
}
|
|
172
|
+
let stopped = false
|
|
173
|
+
const timer = setTimeout(() => { stopped = true; win.removeEventListener?.('message', receive); reject(Object.assign(new Error('witbitz: the vault at ' + origin + ' did not answer — is this page framed by it?'), { code: 'not_in_vault' })) }, helloMs)
|
|
174
|
+
if (welcome) return done(welcome)
|
|
175
|
+
onWelcome = (w) => { onWelcome = null; done(w) }
|
|
176
|
+
// the vault may still be starting its worker: say hello until it answers (or the wait ends)
|
|
177
|
+
const hello = () => { if (welcome || stopped) return; try { post({ t: 'hello', v: VAULT_PROTOCOL }) } catch { /* */ } setTimeout(hello, 250) }
|
|
178
|
+
hello()
|
|
179
|
+
})
|
|
180
|
+
}
|
package/sealShare.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// sealShare.js — seal a bundle to an enclave's attested ECDH P-384 share key: the scheme the Sentinel's crypto.go
|
|
2
|
+
// `openShare` and the cloud computer's vm/crypto.go undo. One ephemeral P-384 key, ECDH → HKDF-SHA-256 (salt = the
|
|
3
|
+
// attest nonce, info "witbitz-cc share v1") → AES-GCM-256 with the nonce as AAD. Shared by codeCloud.js (a cloud
|
|
4
|
+
// computer's grant) and connections.js (a standing connection), so the wire has exactly one page-side writer.
|
|
5
|
+
const enc = new TextEncoder()
|
|
6
|
+
const b64 = (u8) => btoa(String.fromCharCode(...new Uint8Array(u8)))
|
|
7
|
+
|
|
8
|
+
/** @returns {{ epk: string, iv: string, ct: string, nonce: string }} — all standard base64 */
|
|
9
|
+
export async function sealTo(enclaveKey, nonce, bundle) {
|
|
10
|
+
const eph = await crypto.subtle.generateKey({ name: 'ECDH', namedCurve: 'P-384' }, true, ['deriveBits'])
|
|
11
|
+
const shared = await crypto.subtle.deriveBits({ name: 'ECDH', public: enclaveKey }, eph.privateKey, 384)
|
|
12
|
+
const hk = await crypto.subtle.importKey('raw', shared, 'HKDF', false, ['deriveKey'])
|
|
13
|
+
const key = await crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: nonce, info: enc.encode('witbitz-cc share v1') }, hk, { name: 'AES-GCM', length: 256 }, false, ['encrypt'])
|
|
14
|
+
const iv = crypto.getRandomValues(new Uint8Array(12))
|
|
15
|
+
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: nonce }, key, enc.encode(JSON.stringify(bundle))))
|
|
16
|
+
const epk = new Uint8Array(await crypto.subtle.exportKey('raw', eph.publicKey))
|
|
17
|
+
return { epk: b64(epk), iv: b64(iv), ct: b64(ct), nonce: b64(nonce) }
|
|
18
|
+
}
|
package/sealedNames.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// sealedNames.js — OPAQUE NAMES for a protected device's stores (docs/desktop-protection.md, phase 2; the owner, 2026-10-11:
|
|
2
|
+
// "Some metadata stays readable — why?"). Sealing a VALUE under its own name still told a disk copy which rooms this device
|
|
3
|
+
// holds (`space:mk:<room>`, idb `chat:<room>`) and every reviewed-clear flag around them. On a protected device every entry is
|
|
4
|
+
// stored under `p:` + an encryption of its real name instead.
|
|
5
|
+
//
|
|
6
|
+
// The name is encrypted DETERMINISTICALLY (a synthetic IV: the AES-GCM nonce is HMAC(name), as in SIV), so the page finds an
|
|
7
|
+
// entry by computing its stored name, and a listing recovers every real name by decrypting the KEYS alone — no value is read
|
|
8
|
+
// (reading every value at unlock is what once killed the page on an iPhone, idb.js § A PREFIX READ). Equal names give equal
|
|
9
|
+
// stored names; that is all a disk copy learns: how many entries there are, and their sizes.
|
|
10
|
+
//
|
|
11
|
+
// Both keys come from the device key's raw bytes by HKDF with their own labels — never the value-sealing key itself.
|
|
12
|
+
const enc = new TextEncoder(), dec = new TextDecoder()
|
|
13
|
+
const SALT = enc.encode('witbitz-sealed-names')
|
|
14
|
+
export const NAME_PREFIX = 'p:'
|
|
15
|
+
export const isOpaqueName = (k) => typeof k === 'string' && k.startsWith(NAME_PREFIX)
|
|
16
|
+
|
|
17
|
+
const subtle = () => { const s = globalThis.crypto && globalThis.crypto.subtle; if (!s) throw new Error('no WebCrypto'); return s }
|
|
18
|
+
const toB64u = (u8) => { let s = ''; for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
|
|
19
|
+
const fromB64u = (s) => { const b = atob(String(s).replace(/-/g, '+').replace(/_/g, '/')); const u = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i); return u }
|
|
20
|
+
const bytes = (x) => (x instanceof Uint8Array ? x : x instanceof ArrayBuffer ? new Uint8Array(x) : Array.isArray(x) ? Uint8Array.from(x) : null)
|
|
21
|
+
|
|
22
|
+
/** The two name keys from the device key's 32 raw bytes. */
|
|
23
|
+
export async function nameKeys (raw) {
|
|
24
|
+
const r = bytes(raw); if (!r || r.length < 16) throw new Error('bad device key')
|
|
25
|
+
const base = await subtle().importKey('raw', r, 'HKDF', false, ['deriveKey'])
|
|
26
|
+
const hk = (info) => ({ name: 'HKDF', hash: 'SHA-256', salt: SALT, info: enc.encode(info) })
|
|
27
|
+
const mac = await subtle().deriveKey(hk('witbitz-names-v1-mac'), base, { name: 'HMAC', hash: 'SHA-256', length: 256 }, false, ['sign'])
|
|
28
|
+
const aes = await subtle().deriveKey(hk('witbitz-names-v1-enc'), base, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])
|
|
29
|
+
return { mac, aes }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function ivFor (keys, name) { return new Uint8Array(await subtle().sign('HMAC', keys.mac, enc.encode(name))).slice(0, 12) }
|
|
33
|
+
|
|
34
|
+
/** The stored name for a real name. */
|
|
35
|
+
export async function opaqueName (keys, name) {
|
|
36
|
+
const iv = await ivFor(keys, String(name))
|
|
37
|
+
const ct = new Uint8Array(await subtle().encrypt({ name: 'AES-GCM', iv }, keys.aes, enc.encode(String(name))))
|
|
38
|
+
const out = new Uint8Array(iv.length + ct.length); out.set(iv); out.set(ct, iv.length)
|
|
39
|
+
return NAME_PREFIX + toB64u(out)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The real name behind a stored name, or null (not ours, another key, or damaged). */
|
|
43
|
+
export async function realName (keys, stored) {
|
|
44
|
+
if (!isOpaqueName(stored)) return null
|
|
45
|
+
try {
|
|
46
|
+
const all = fromB64u(stored.slice(NAME_PREFIX.length)); if (all.length < 29) return null
|
|
47
|
+
const iv = all.slice(0, 12)
|
|
48
|
+
const name = dec.decode(await subtle().decrypt({ name: 'AES-GCM', iv }, keys.aes, all.slice(12)))
|
|
49
|
+
const want = await ivFor(keys, name) // the IV IS the name's MAC: a stored name made by another key, or edited, fails here
|
|
50
|
+
for (let i = 0; i < 12; i++) if (want[i] !== iv[i]) return null
|
|
51
|
+
return name
|
|
52
|
+
} catch { return null }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** A cached namer over one device key: opaque(name) and real(stored), both memoised (names repeat on every write). */
|
|
56
|
+
export async function makeNamer (raw) {
|
|
57
|
+
const keys = await nameKeys(raw)
|
|
58
|
+
const fwd = new Map(), back = new Map()
|
|
59
|
+
return {
|
|
60
|
+
async opaque (name) { const n = String(name); let o = fwd.get(n); if (!o) { o = await opaqueName(keys, n); fwd.set(n, o); back.set(o, n) } return o },
|
|
61
|
+
async real (stored) { if (back.has(stored)) return back.get(stored); const n = await realName(keys, stored); if (n != null) { back.set(stored, n); fwd.set(n, stored) } return n },
|
|
62
|
+
known (name) { return fwd.get(String(name)) || null }, // synchronous: the stored name if computed before
|
|
63
|
+
}
|
|
64
|
+
}
|
package/sealedReceipt.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// sealedReceipt.js — the TRUST RECEIPT a member computes from the ciphertext the server stores: its size, its SHA-256 and
|
|
2
|
+
// who it is sealed to (sync sweep, 2026-10-10). An open room's receipt comes from the keyless `sealed` read, which the
|
|
3
|
+
// server computes; a VERIFIED room refuses that read to non-members on purpose, so a member reads the same stored bytes
|
|
4
|
+
// through the authenticated pollsealed path and computes the receipt here. The SDK's sealedProof() uses it (the app's
|
|
5
|
+
// Trust sheet that also did was removed on 2026-10-10).
|
|
6
|
+
/** `sealed` = what pollsealed / exportSealed returns as `sealed` (a string, or the v3 `{ v, boxes }` wrapper). */
|
|
7
|
+
export async function receiptOf(sealed) {
|
|
8
|
+
if (sealed == null) return null
|
|
9
|
+
const raw = typeof sealed === 'string' ? sealed : JSON.stringify(sealed)
|
|
10
|
+
let env = null; try { env = typeof sealed === 'string' ? JSON.parse(sealed) : sealed } catch { /* opaque */ }
|
|
11
|
+
// v3 (what production writes): `boxes` are per-entry envelopes stored as JSON STRINGS (agent/spaceLedgerV3.mjs).
|
|
12
|
+
const box0 = env && Array.isArray(env.boxes) && env.boxes.length ? (typeof env.boxes[0] === 'string' ? (() => { try { return JSON.parse(env.boxes[0]) } catch { return null } })() : env.boxes[0]) : null
|
|
13
|
+
const rec = env && env.recipients ? env.recipients : (box0 && box0.recipients) || null
|
|
14
|
+
const bytes = new TextEncoder().encode(raw)
|
|
15
|
+
const sha256 = [...new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))].map((b) => b.toString(16).padStart(2, '0')).join('')
|
|
16
|
+
return { bytes: bytes.length, sha256, recipients: rec && typeof rec === 'object' ? Object.keys(rec) : [], alg: env && env.v ? `AES-256-GCM · multi-recipient envelope v${env.v}` : 'opaque', sealed: raw }
|
|
17
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// sentinelRelease.js — A STANDING SENTINEL BUILD THE APP DOES NOT PIN, CHECKED BY ITS RELEASE RECORD, IN THE BROWSER (docs/standing-sentinel.md
|
|
2
|
+
// § Following verified releases; the owner, 2026-11-17: "Make it cheaper"). The Sentinel's front hands, with each attestation, the
|
|
3
|
+
// build enclave's signed verdict for the running build. Here it must hold: made by a build-enclave image pinned below (its AWS
|
|
4
|
+
// Nitro attestation, verified against the pinned AWS root), for THIS verdict (user_data = sha256 of the verdict without its proofs),
|
|
5
|
+
// signed by the key that attestation names (ECDSA P-256), subject standing-sentinel, verdict pass, the image rebuilt from its source.
|
|
6
|
+
// Rekor is checked by the Space Lambda and the turn enclave (agent/sentinelFollow.mjs), not here. A build that passes is then
|
|
7
|
+
// followed exactly as a published one is: at once with "Accept new Witbitz builds automatically", else the person is asked.
|
|
8
|
+
import { verifyAttestation } from './nitroVerify.js'
|
|
9
|
+
import { derSigToRaw } from './x509.js'
|
|
10
|
+
|
|
11
|
+
/** The build-enclave images whose verdicts count — infra/build-enclave/pins.json `buildEnclave` (held equal by a test). */
|
|
12
|
+
export const BUILD_ENCLAVE_PCR0 = Object.freeze([
|
|
13
|
+
"c6a8cbd0c05d8e003e75b266f1dde2a6426b7cd61f845e4b128e59063e40968b44f30d934bbe1925582fe33bbdd0b1d7",
|
|
14
|
+
"f490096d57e4287146e8b8d7bf4c75f423984ca52199efab0ee8684fbee6cfe6ab82c72d54f05a38f24a0d4ad6e2f557",
|
|
15
|
+
"41ec7e0e54beac5759fba7efa06c48081dbd96c7299c29c92a9c619036ce057cec357ad4ad71a165d7f881df120b043b",
|
|
16
|
+
"9f0801335a952bdbac70b6793150738d7ce30bc3a0d520fec6f573de22a822aa5ef762f78648bc8608ca0b2eeccda556",
|
|
17
|
+
"a145e8524bbe8764d4db6b81b4e18d72eae42e8b9e1c834e62e22aba18cce318f9eaa84942671c688c3eeb89ec30b0e8",
|
|
18
|
+
"5d29c3691cd38f6c6ce0da2b2f9d1da82712d9da12a89c99d38a03cae6369ebe6ba7a1ab1060cfa9daf6a19228c7a2dc",
|
|
19
|
+
"6c962286faed81c395bcf3d319011f91893cfec723c2dc7069ad8805980d77e99f75c94671881cc793794521fe5d2ff0",
|
|
20
|
+
"578945d0342d346d72e50b36ffe74a3631e53e111bc010394108457e362d10830ebadcc7ec5ffa4445d5b10b9c522d28",
|
|
21
|
+
"7e9f760db923c6f31fd18db06f6b60a53902beb6b0d80b91b5355d33c461e43bcddc31c08e2380ff9dc75c10909e6acb",
|
|
22
|
+
"5b6bffe6953eef271a69e453072b6e202ae024cd3983fff3a637b7421a60ad92ab3fd19f8ae809e19182a3feebbe94c2",
|
|
23
|
+
"551006e397efd43a619b370ef336a6a594d8a8338cd49860e54845330354c73afd3ba673360d50f78e5f1d702e19946b",
|
|
24
|
+
"eecf817c561e633b30632ca434a28ad56ed46395d765172fedcc0742d8d5c9982845d6ce32b6451b943f4b6f0a55ea36",
|
|
25
|
+
"3df18dce5385b467208bfa325d2f812bd622ef6def87ef97e63116310a896427db9f2c69d7c2631bccc9c65549b3d512",
|
|
26
|
+
"a51fcaeafa6d188b46d11710442f981169304aa4feecc4b40263943966c3dd8ff9b986d30989b4152fa1540c85a76b5e",
|
|
27
|
+
"f977e0490f5abfc77c311b426399bddd6909848bb8175db4142885c839e9cc23c3ca0047317b039883dce4b1a2efe096",
|
|
28
|
+
"d5f13dff5647f5f4ee351dd9e1ba9348ecd39da88acd6ffd9c324897b0ca7563da974b08c2e84504a76dc98b48700b74",
|
|
29
|
+
"2babe4262b2a00949eeef5b04a81327eb606dc347caaf507527d04f8847730a31dd26d6d7be3e0a672c537b51c914133",
|
|
30
|
+
"25a0967ec1366bc0ec43e45e2f89c435adb1a3e54d8702d89599acb442337afcb36f8f64d51a6608cefb3bb1e4f6b8ed",
|
|
31
|
+
"8665867cbb86ea3178f4179cf040fdec9e6df22bdd4f1e3d8df6b2d9096db5aecd8420b42203969bbe9446b585c78870",
|
|
32
|
+
"ef738ca713ddc39dc29505d857c2aac22a0598a714163ae01e2879085e1c262cc5bde3c239b7ce76385d10c5910ed487",
|
|
33
|
+
"41de07c0c12f388f9dc7d87cfa835edce2c58be42f6893f227002329d263285bf78bb209cd69c384dd7566097f2a3d47",
|
|
34
|
+
"a77141c4ac00099cbdd9053e0190b70234aa2eccdb22cb358e9b8b0fef5bef6b7ad6d9b5eb73137244a3790f98869505",
|
|
35
|
+
"70dde35fed128d1cb007f8c6edfa3de70e991955e1748aa500ad4685d1c752b1775565fb9a6d11c483969d5596e3b159",
|
|
36
|
+
"f0ea83ee58b3a4a9ebe7c8c74f102eba17118711573b6ce773b6f31ed223564cbf215992b5a7a30462b70281ae624453",
|
|
37
|
+
"f7adfbec8cf3a014f9585c7decc21bb03a50484339811ea3b44947d23fc16aff8eedb56346915b816e83fc5faad55e7a",
|
|
38
|
+
"917f7d95eabd64eabd1145cc0898c08ff414037775fd416162002c4783b4f95dcb550c3c5493baadaf41eaceb0e7da0d",
|
|
39
|
+
"74b1cbd4398f319a636de05d36eaa40953df4dc0bb86769f7ac4e0fe2c576f55b3c4a15a5583048ded80b0b4d303f55e",
|
|
40
|
+
"420088665bd62edcba51dfbcc55cbc85611529985fde54b655a3476198a8f9421e02d1898db28180b153550ceeb66798",
|
|
41
|
+
])
|
|
42
|
+
|
|
43
|
+
const enc = new TextEncoder()
|
|
44
|
+
const unb64 = (s) => Uint8Array.from(atob(String(s)), (c) => c.charCodeAt(0))
|
|
45
|
+
const hex = (u8) => [...new Uint8Array(u8)].map((b) => b.toString(16).padStart(2, '0')).join('')
|
|
46
|
+
const same = (a, b) => a.length === b.length && a.every((x, i) => x === b[i])
|
|
47
|
+
const PROOFS = ['attestation', 'signature', 'rekor']
|
|
48
|
+
|
|
49
|
+
/** A release record → the standing Sentinel PCR0 it vouches for, or throws with why. `links`: the build-enclave links its front handed
|
|
50
|
+
* beside it (docs/trust-root.md) — the record's builder may be one they make trusted from the anchors. */
|
|
51
|
+
export async function sentinelPcrOfRelease (r, { builders = BUILD_ENCLAVE_PCR0, links = null, verify = verifyAttestation, site = chainFromSite } = {}) {
|
|
52
|
+
const trusted = Array.isArray(links) && links.length ? await trustedBuilders(links, { anchors: builders, verify }) : builders
|
|
53
|
+
try { return await recordPcr(r, 'standing-sentinel', trusted, verify) } catch (e) {
|
|
54
|
+
// NO LIMIT ON THE CHAIN (the owner, 2026-11-23): the record's builder is newer than this app's anchors and the links handed beside
|
|
55
|
+
// it did not reach it — read the WHOLE log from this app's own site and walk it (each link verified here; the site can withhold
|
|
56
|
+
// one, never invent one). Once per page; a site without the log changes nothing.
|
|
57
|
+
if (!site || !/not made by a build enclave this app trusts/.test(String((e && e.message) || e))) throw e
|
|
58
|
+
const all = [...(Array.isArray(links) ? links : []), ...await site()]
|
|
59
|
+
if (!all.length) throw e
|
|
60
|
+
return recordPcr(r, 'standing-sentinel', await trustedBuilders(all, { anchors: builders, verify, max: Infinity }), verify)
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Every passing build-enclave link Witbitz publishes (CHAIN_URLS), newest first — read once per page. */
|
|
65
|
+
let _siteChain = null
|
|
66
|
+
// Witbitz's server first (always the current log: published with each build enclave), then this app's own site (the log as of its deploy).
|
|
67
|
+
export const CHAIN_URLS = Object.freeze(['https://api.witbitz.chat/v1/trust/build-enclave.jsonl', '/audit/releases/build-enclave.jsonl'])
|
|
68
|
+
export function chainFromSite ({ fetchFn = (typeof fetch === 'function' ? fetch : null), urls = CHAIN_URLS } = {}) {
|
|
69
|
+
if (!fetchFn) return Promise.resolve([])
|
|
70
|
+
const own = fetchFn === globalThis.fetch && urls === CHAIN_URLS // only the page's own read is remembered (a caller's fetch is read each time)
|
|
71
|
+
if (own && typeof process !== 'undefined' && process.env && process.env.NODE_TEST_CONTEXT) return Promise.resolve([]) // tests read no network
|
|
72
|
+
if (!own) return readChain(fetchFn, urls)
|
|
73
|
+
return _siteChain || (_siteChain = readChain(fetchFn, urls).then((l) => { if (!l.length) _siteChain = null; return l })) // nothing read: ask again next time
|
|
74
|
+
}
|
|
75
|
+
function readChain (fetchFn, urls) {
|
|
76
|
+
return (async () => {
|
|
77
|
+
for (const u of urls) {
|
|
78
|
+
try {
|
|
79
|
+
const res = await fetchFn(u, { cache: 'no-store' })
|
|
80
|
+
if (!res || res.status !== 200 || /text\/html/.test((res.headers && res.headers.get && res.headers.get('content-type')) || '')) continue
|
|
81
|
+
const l = linksOfLogText(await res.text())
|
|
82
|
+
if (l.length) return l
|
|
83
|
+
} catch { /* the next */ }
|
|
84
|
+
}
|
|
85
|
+
return []
|
|
86
|
+
})()
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The passing `build-enclave` records in a release log's text (jsonl), newest first — tools/build-enclave/trustedNow.mjs linksOfLog. */
|
|
90
|
+
export function linksOfLogText (text) {
|
|
91
|
+
const out = []
|
|
92
|
+
for (const l of String(text || '').split('\n')) { try { const r = JSON.parse(l); if (r && r.subject === 'build-enclave' && r.verdict === 'pass') out.push(r) } catch { /* not a record */ } }
|
|
93
|
+
return out.reverse()
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// THE CHAIN OF BUILD ENCLAVES, the browser's twin of agent/buildEnclaveChain.mjs (held equal by spaces/test/buildEnclaveChainTwin.test.mjs):
|
|
97
|
+
// the anchors + every build enclave a trusted one rebuilt (a `build-enclave` record, checked here as every record is), minus the deny list.
|
|
98
|
+
export const BUILD_ENCLAVE_DENY = Object.freeze([])
|
|
99
|
+
export const LINKS_MAX = 4 // links one ANSWER may carry (agent/buildEnclaveChain.mjs) — the log read here (chainFromSite) is not capped
|
|
100
|
+
// VERIFIED ONCE (as the server's chain): a link that verified is remembered by its signature for this page's life, reused only while
|
|
101
|
+
// the builder that signed it is trusted in this walk — never a wider trust, only the same checks not repeated.
|
|
102
|
+
const verified = new Map()
|
|
103
|
+
export async function trustedBuilders (links = [], { anchors = BUILD_ENCLAVE_PCR0, deny = BUILD_ENCLAVE_DENY, verify = verifyAttestation, max = LINKS_MAX } = {}) {
|
|
104
|
+
const denied = new Set((deny || []).map((x) => String(x).toLowerCase()))
|
|
105
|
+
const trusted = new Set((anchors || []).map((x) => String(x).toLowerCase()).filter((x) => !denied.has(x)))
|
|
106
|
+
const cache = verify === verifyAttestation
|
|
107
|
+
let pending = Array.isArray(links) ? links.slice(0, max) : []
|
|
108
|
+
for (let grew = true; grew && pending.length;) {
|
|
109
|
+
grew = false
|
|
110
|
+
const left = []
|
|
111
|
+
for (const l of pending) {
|
|
112
|
+
try {
|
|
113
|
+
const sig = l && l.signature && typeof l.signature.sig === 'string' ? l.signature.sig : ''
|
|
114
|
+
const known = sig && cache ? verified.get(sig) : null
|
|
115
|
+
let p
|
|
116
|
+
if (known && trusted.has(known.builder) && String((l.measurement && l.measurement.pcr0) || '').toLowerCase() === known.pcr0) p = known.pcr0
|
|
117
|
+
else {
|
|
118
|
+
const got = await recordPcrBy(l, 'build-enclave', [...trusted], verify)
|
|
119
|
+
p = got.pcr0
|
|
120
|
+
if (sig && cache) { if (verified.size >= 4096) verified.delete(verified.keys().next().value); verified.set(sig, got) }
|
|
121
|
+
}
|
|
122
|
+
if (!denied.has(p) && !trusted.has(p)) { trusted.add(p); grew = true }
|
|
123
|
+
} catch (e) { if (/not made by a build enclave this app trusts/.test(String((e && e.message) || e))) left.push(l) }
|
|
124
|
+
}
|
|
125
|
+
pending = left
|
|
126
|
+
}
|
|
127
|
+
return [...trusted]
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** A release record of `subject` → the PCR0 it vouches for, made by one of `builders`; or throws with why. */
|
|
131
|
+
async function recordPcr (r, subject, builders, verify) { return (await recordPcrBy(r, subject, builders, verify)).pcr0 }
|
|
132
|
+
|
|
133
|
+
/** The same, with the builder that made it: { pcr0, builder } — any subject (followImage.js uses it for the images the apps follow). */
|
|
134
|
+
export async function recordPcrBy (r, subject, builders, verify = verifyAttestation) {
|
|
135
|
+
if (!r || typeof r !== 'object') throw new Error('no release record came with the attestation')
|
|
136
|
+
if (r.subject !== subject || r.verdict !== 'pass') throw new Error(`the record is not a passing ${subject} release`)
|
|
137
|
+
const repro = Array.isArray(r.checks) && r.checks.find((c) => c && c.name === 'reproducible-build')
|
|
138
|
+
if (!repro || repro.ok !== true) throw new Error('the record does not say the image was rebuilt from its source')
|
|
139
|
+
const pcr0 = String((r.measurement && r.measurement.pcr0) || '').toLowerCase()
|
|
140
|
+
if (!/^[0-9a-f]{96}$/.test(pcr0) || (r.claim && String(r.claim.pcr0 || '').toLowerCase() !== pcr0)) throw new Error('the record names no single PCR0')
|
|
141
|
+
if (!r.attestation || !r.attestation.doc || !r.signature || !r.signature.key || !r.signature.sig) throw new Error('the record carries no proof')
|
|
142
|
+
const rest = {}; for (const [k, v] of Object.entries(r)) if (!PROOFS.includes(k)) rest[k] = v
|
|
143
|
+
const art = enc.encode(JSON.stringify(rest))
|
|
144
|
+
const doc = await verify(unb64(r.attestation.doc), { atDocTime: true })
|
|
145
|
+
const builder = String((doc.pcrs && doc.pcrs[0]) || '').toLowerCase()
|
|
146
|
+
if (!builders.includes(builder)) throw new Error('the record was not made by a build enclave this app trusts')
|
|
147
|
+
const want = enc.encode(JSON.stringify({ role: 'build-enclave', verdict: hex(await crypto.subtle.digest('SHA-256', art)) }))
|
|
148
|
+
if (!doc.userData || !same(new Uint8Array(doc.userData), want)) throw new Error('the build enclave\'s attestation is not for this record')
|
|
149
|
+
const spki = unb64(r.signature.key)
|
|
150
|
+
if (!doc.publicKey || !same(new Uint8Array(doc.publicKey), spki)) throw new Error('the record is not signed by the key the build enclave attested')
|
|
151
|
+
const key = await crypto.subtle.importKey('spki', spki, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify'])
|
|
152
|
+
const ok = await crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, key, derSigToRaw(unb64(r.signature.sig), 32), art)
|
|
153
|
+
if (!ok) throw new Error('the record\'s signature does not verify')
|
|
154
|
+
return { pcr0, builder }
|
|
155
|
+
}
|