@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/deviceKeyCore.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// deviceKeyCore.js — THIS BROWSER'S DEVICE KEY, wherever it is kept: the regular app's page (devices.js, its idb) and the hosted
|
|
2
|
+
// app's VAULT (vault-loader.js, the vault origin's own store — docs/hosted-account-v2-plan.md: the new account service's client
|
|
3
|
+
// runs there, so its device key is the vault's). One P-256 signing key whose private half can never be exported; stored as a
|
|
4
|
+
// CryptoKey under `devkey:v1` (never sealed: sealing a non-extractable key protects nothing — idbSeal IDB_SHARED_NAMES).
|
|
5
|
+
// `store` = { get(key), set(key, value) } over raw IndexedDB values.
|
|
6
|
+
export const DEVKEY_IDB = 'devkey:v1'
|
|
7
|
+
const b64u = (u8) => btoa(String.fromCharCode(...u8)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
8
|
+
|
|
9
|
+
/** A NEW key, kept → { priv, pub, spk, at } */
|
|
10
|
+
export async function newKeyRecord(store) {
|
|
11
|
+
const kp = await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign', 'verify']) // false ⇒ the PRIVATE half can never be exported
|
|
12
|
+
const rec = { priv: kp.privateKey, pub: kp.publicKey, spk: b64u(new Uint8Array(await crypto.subtle.exportKey('raw', kp.publicKey))), at: Date.now() }
|
|
13
|
+
await store.set(DEVKEY_IDB, rec) // CryptoKey is structured-cloneable → the non-extractable key persists as a key, never as bytes
|
|
14
|
+
return rec
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** The kept key, or a new one when there is none — or when what is kept is no key (sealed as JSON by an older protected-storage
|
|
18
|
+
* build → `{}`). → { priv, pub, spk, at } */
|
|
19
|
+
export async function ensureKeyRecord(store) {
|
|
20
|
+
const rec = await store.get(DEVKEY_IDB)
|
|
21
|
+
if (rec && rec.spk && (typeof CryptoKey === 'undefined' || rec.priv instanceof CryptoKey)) return rec
|
|
22
|
+
return newKeyRecord(store)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const KEY_RETRY_MS = [150, 400, 900]
|
|
26
|
+
/** A key store whose `get` THROWS on a read that keeps failing (never null) and whose `set` throws when not kept — so
|
|
27
|
+
* ensureKeyRecord never writes a new key over one it could not read (sync sweep 11-16 #2 in the vault; 10·Q#2 in the regular app). */
|
|
28
|
+
export function retryingKeyStore({ get, set }, { wait = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {
|
|
29
|
+
return {
|
|
30
|
+
get: async (k) => {
|
|
31
|
+
let last = null
|
|
32
|
+
for (let i = 0; i <= KEY_RETRY_MS.length; i++) {
|
|
33
|
+
if (i) await wait(KEY_RETRY_MS[i - 1])
|
|
34
|
+
try { return await get(k) } catch (e) { last = e }
|
|
35
|
+
}
|
|
36
|
+
throw Object.assign(new Error('the device key could not be read'), { code: 'device_key_unreadable', cause: last })
|
|
37
|
+
},
|
|
38
|
+
set: async (k, v) => { if ((await set(k, v)) === false) throw Object.assign(new Error('the device key could not be kept'), { code: 'device_key_unwritable' }) },
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
package/deviceSeal.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// deviceSeal.js — DEVICE STORAGE PROTECTION, the primitive (docs/device-storage-protection.md). A key the authenticator
|
|
2
|
+
// derives (spacePasskey.js: PRF or largeBlob → a 32-byte device secret) becomes an AES-GCM key that is NOWHERE on disk;
|
|
3
|
+
// every secret and every cached message the device keeps is written through `seal()` and read through `open()`. Works in
|
|
4
|
+
// the key worker and on the page alike: no DOM, no storage of its own — the callers decide where a sealed blob lives.
|
|
5
|
+
//
|
|
6
|
+
// deriveSealKey(secret) HKDF-SHA256(secret, info 'witbitz-device-seal-v1') → a non-extractable AES-GCM-256 key. A
|
|
7
|
+
// DIFFERENT derivation from the backup recovery key the same passkey secret feeds (recovery.js),
|
|
8
|
+
// so a local store and a backup never share a key.
|
|
9
|
+
// seal(key, value) → { v: 1, s: base64(iv ‖ ciphertext) } — value is any JSON-able thing; a fresh 12-byte iv each time.
|
|
10
|
+
// open(key, blob) → the value; THROWS on a wrong key or a tampered blob (never a silent null: a reader that
|
|
11
|
+
// cannot open must show the lock, not an empty room).
|
|
12
|
+
// isSealed(x) → true for a blob this module wrote (so a store can hold clear and sealed entries during migration).
|
|
13
|
+
// exportRaw / importRaw move a key between realms (page → worker) as 32 raw bytes over postMessage; the raw bytes never
|
|
14
|
+
// touch storage. The CryptoKey itself is non-extractable once imported, so a realm that only
|
|
15
|
+
// opens and seals cannot read the key back out.
|
|
16
|
+
const enc = new TextEncoder(), dec = new TextDecoder()
|
|
17
|
+
const INFO = enc.encode('witbitz-device-seal-v1')
|
|
18
|
+
const SALT = enc.encode('witbitz-device-seal') // a fixed HKDF salt: the secret already carries the per-credential entropy
|
|
19
|
+
export const SEAL_V = 1
|
|
20
|
+
|
|
21
|
+
const subtle = () => { const s = globalThis.crypto && globalThis.crypto.subtle; if (!s) throw new Error('no WebCrypto'); return s }
|
|
22
|
+
const b64 = (u8) => { let s = ''; for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]); return btoa(s) }
|
|
23
|
+
const fromB64 = (s) => { const b = atob(String(s)); const u = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i); return u }
|
|
24
|
+
const bytes = (x) => (x instanceof Uint8Array ? x : x instanceof ArrayBuffer ? new Uint8Array(x) : Array.isArray(x) ? Uint8Array.from(x) : null)
|
|
25
|
+
|
|
26
|
+
/** The 32 raw key bytes from a device secret — what travels page → worker. Deterministic for one secret. */
|
|
27
|
+
export async function deriveSealRaw (secret) {
|
|
28
|
+
const s = bytes(secret); if (!s || s.length < 16) throw new Error('device secret too short')
|
|
29
|
+
const ikm = await subtle().importKey('raw', s, 'HKDF', false, ['deriveBits'])
|
|
30
|
+
return new Uint8Array(await subtle().deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: SALT, info: INFO }, ikm, 256))
|
|
31
|
+
}
|
|
32
|
+
/** A non-extractable AES-GCM key from the raw bytes (or straight from the secret). */
|
|
33
|
+
export async function importRaw (raw) {
|
|
34
|
+
const r = bytes(raw); if (!r || r.length !== 32) throw new Error('seal key must be 32 bytes')
|
|
35
|
+
return subtle().importKey('raw', r, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt'])
|
|
36
|
+
}
|
|
37
|
+
export async function deriveSealKey (secret) { return importRaw(await deriveSealRaw(secret)) }
|
|
38
|
+
|
|
39
|
+
export async function seal (key, value) {
|
|
40
|
+
if (!key) throw new Error('no seal key')
|
|
41
|
+
const iv = crypto.getRandomValues(new Uint8Array(12))
|
|
42
|
+
const ct = new Uint8Array(await subtle().encrypt({ name: 'AES-GCM', iv }, key, enc.encode(JSON.stringify(value === undefined ? null : value))))
|
|
43
|
+
const out = new Uint8Array(iv.length + ct.length); out.set(iv, 0); out.set(ct, iv.length)
|
|
44
|
+
return { v: SEAL_V, s: b64(out) }
|
|
45
|
+
}
|
|
46
|
+
export async function open (key, blob) {
|
|
47
|
+
if (!key) throw new Error('no seal key')
|
|
48
|
+
if (!isSealed(blob)) throw new Error('not a sealed blob')
|
|
49
|
+
const all = fromB64(blob.s)
|
|
50
|
+
if (all.length < 12 + 16) throw new Error('sealed blob too short')
|
|
51
|
+
const pt = await subtle().decrypt({ name: 'AES-GCM', iv: all.subarray(0, 12) }, key, all.subarray(12)) // a wrong key or a tampered blob throws here
|
|
52
|
+
return JSON.parse(dec.decode(pt))
|
|
53
|
+
}
|
|
54
|
+
export const isSealed = (x) => !!(x && typeof x === 'object' && !Array.isArray(x) && x.v === SEAL_V && typeof x.s === 'string' && x.s.length > 0)
|
|
55
|
+
|
|
56
|
+
/** Seal when a key is present, else store in the clear — the shape every protected store uses while the switch may be off. */
|
|
57
|
+
export const sealIf = async (key, value) => (key ? seal(key, value) : value)
|
|
58
|
+
/** Open a stored value: a sealed blob needs the key (throws without it, as `open` does); a clear value passes through. */
|
|
59
|
+
export const openIf = async (key, stored) => (isSealed(stored) ? open(key, stored) : stored)
|
package/e2ee.js
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
// Client-side E2EE for Collections (docs: witbitz-privacy-certification-northstar). A WIRE-COMPATIBLE browser port
|
|
2
|
+
// of the agent's platform-blind envelope (agent/envelope.mjs) — same v1 shape { v, iv, ct, recipients:{room} },
|
|
3
|
+
// same HKDF(mk,"memwrap")+AES-256-GCM, so a field sealed here in the browser opens with the Node envelope (and the
|
|
4
|
+
// reverse). The `mk` (32 random bytes, base64url) lives in the LINK FRAGMENT, and THIS MODULE never transmits it —
|
|
5
|
+
// it seals and opens locally. Seal to `room` ⇒ admin-blind; an optional user-held `recovery` key can be added (the
|
|
6
|
+
// user's own code) — there is NO operator recipient. What the operator stores is the ciphertext this produces.
|
|
7
|
+
//
|
|
8
|
+
// ★ READ THIS BEFORE REPEATING THE SENTENCE ABOVE. "mk never reaches the server" is true OF THIS FILE and is NOT true
|
|
9
|
+
// of the product on every tier — and the difference decides what you may tell your users. An agent turn runs
|
|
10
|
+
// server-side, so the ops that carry one (`data`, `send`, `state`, `turn` — see spaceClient.js `keyFields`) send the
|
|
11
|
+
// room key ALONGSIDE this envelope:
|
|
12
|
+
// • CONFIDENTIAL tier — sealed to the enclave's ATTESTED key, gated on the room accepting that measured build, and
|
|
13
|
+
// FAIL-CLOSED (no key ⇒ it throws rather than send the key to the relay). The platform sees opaque bytes. Here
|
|
14
|
+
// the sentence holds architecturally.
|
|
15
|
+
// • STANDARD tier — the key is sent in the clear and the Lambda holds it for the turn. The store still holds only
|
|
16
|
+
// ciphertext, so this protects against the STORE; it does not protect against the operator. spaces/public/
|
|
17
|
+
// mkseal.js states the same limit in its own words and is worth reading.
|
|
18
|
+
// A tenant read this header from the deployed file and described our model to his own users as "mk never reaches
|
|
19
|
+
// the platform" (2026-09-20). He was quoting us accurately. Every comment in this client is SERVED, unminified, on
|
|
20
|
+
// an origin we sign and invite people to verify — so a header here is a published claim, not a note to the next
|
|
21
|
+
// engineer, and an unqualified one will be repeated by someone who cannot see which tier they are on.
|
|
22
|
+
//
|
|
23
|
+
// This runs untrusted in the browser; its guarantee against the OPERATOR is only as strong as the tier above.
|
|
24
|
+
// Its guarantee against the APP holds only for a certified, egress-locked build (the CSP + build-attestation blocks)
|
|
25
|
+
// — a malicious build could read the fragment. That composition is the whole point of the north star.
|
|
26
|
+
//
|
|
27
|
+
// Uses only browser-native crypto/atob/btoa/TextEncoder → also runs in modern Node (for the tests). No deps.
|
|
28
|
+
const VERSION = 1
|
|
29
|
+
const enc = new TextEncoder()
|
|
30
|
+
const dec = new TextDecoder()
|
|
31
|
+
|
|
32
|
+
// M4: the AAD that binds a v3 ledger box to its {room, absolute-index}. MUST stay BYTE-IDENTICAL to the agent twin
|
|
33
|
+
// (agent/spaceLedgerV3.mjs ledgerAad) — unit-separated so it can never collide with a room id. A box moved/replayed to a
|
|
34
|
+
// different position fails GCM auth on open() (which applies this as additionalData when the box carries the aad:1 marker).
|
|
35
|
+
export const ledgerAad = (room, index) => enc.encode('v3\x1f' + String(room) + '\x1f' + String(index))
|
|
36
|
+
|
|
37
|
+
// base64url ⇄ bytes, no Buffer (browser-safe; matches Buffer.from(x,'base64url') byte-for-byte).
|
|
38
|
+
function b64(bytes) {
|
|
39
|
+
const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
|
|
40
|
+
let s = ''
|
|
41
|
+
for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i])
|
|
42
|
+
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
43
|
+
}
|
|
44
|
+
function ub64(str) {
|
|
45
|
+
let s = String(str || '').replace(/-/g, '+').replace(/_/g, '/')
|
|
46
|
+
s += '='.repeat((4 - (s.length % 4)) % 4)
|
|
47
|
+
const bin = atob(s)
|
|
48
|
+
const out = new Uint8Array(bin.length)
|
|
49
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
|
|
50
|
+
return out
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// mk (base64url, 32 random bytes) → an AES-256-GCM wrap key via HKDF. Stable `info` so reads match writes AND match
|
|
54
|
+
// the Node envelope (must be byte-identical: salt = empty, info = "memwrap").
|
|
55
|
+
async function roomWrapKey(mk) {
|
|
56
|
+
const ikm = await crypto.subtle.importKey('raw', ub64(mk), 'HKDF', false, ['deriveKey'])
|
|
57
|
+
return crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: enc.encode('memwrap') }, ikm, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A fresh random key (base64url) — mint at collection create, put in the link fragment, NEVER send to the server. */
|
|
61
|
+
export function newKey() {
|
|
62
|
+
return b64(crypto.getRandomValues(new Uint8Array(32)))
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Commitment to a key: base64url(SHA-256(key-string)). Store THIS server-side (never the key) so a reader's mk can
|
|
66
|
+
* be checked (commit(mk) === stored) without the server ever seeing mk. Matches envelope.commit(). */
|
|
67
|
+
export async function commit(mk) {
|
|
68
|
+
const h = await crypto.subtle.digest('SHA-256', enc.encode(String(mk || '')))
|
|
69
|
+
return b64(new Uint8Array(h))
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// ── 2-of-2 SHARED-PRESENCE secret sharing (M1b, docs/shared-presence-m1b.md) ───────────────────────────────────────
|
|
73
|
+
// Split the room key into TWO shares — one per partner — so NEITHER opens the room alone; only BOTH shares together
|
|
74
|
+
// reconstruct mk. XOR = perfect 2-of-2 secrecy: a single share is information-theoretically independent of mk (it's a
|
|
75
|
+
// uniform random value, revealing NOTHING). This makes "the room opens only when BOTH are present" CRYPTOGRAPHIC, not
|
|
76
|
+
// policy — one partner alone, or the operator, holds only a share and cannot open the room. Each share lives in that
|
|
77
|
+
// partner's own link fragment; the server holds only commit(mk). (Exactly 2 required; k-of-n — e.g. a couple + a
|
|
78
|
+
// therapist — is a later generalization to Shamir.)
|
|
79
|
+
/** Split mk into { shareA, shareB } (each base64url). shareA random, shareB = mk XOR shareA. */
|
|
80
|
+
export function splitKey(mk) {
|
|
81
|
+
const k = ub64(mk)
|
|
82
|
+
if (!k.length) throw new Error('splitKey needs a key')
|
|
83
|
+
const a = crypto.getRandomValues(new Uint8Array(k.length))
|
|
84
|
+
const b = new Uint8Array(k.length)
|
|
85
|
+
for (let i = 0; i < k.length; i++) b[i] = k[i] ^ a[i]
|
|
86
|
+
return { shareA: b64(a), shareB: b64(b) }
|
|
87
|
+
}
|
|
88
|
+
/** Reconstruct mk from BOTH shares (ORDER-INDEPENDENT — a partner needn't know if they're "A" or "B"). Returns the
|
|
89
|
+
* base64url mk, or null if the shares don't pair up (empty / different lengths). Verify with commit(mk) before trust. */
|
|
90
|
+
export function combineShares(shareA, shareB) {
|
|
91
|
+
const a = ub64(shareA || '')
|
|
92
|
+
const b = ub64(shareB || '')
|
|
93
|
+
if (!a.length || a.length !== b.length) return null
|
|
94
|
+
const mk = new Uint8Array(a.length)
|
|
95
|
+
for (let i = 0; i < a.length; i++) mk[i] = a[i] ^ b[i]
|
|
96
|
+
return b64(mk)
|
|
97
|
+
}
|
|
98
|
+
/** The both-present OPEN gate: combine two shares AND verify the result against the Space's stored commitment. Returns
|
|
99
|
+
* mk only if both shares are present and reconstruct the committed key — else null (a lone/wrong/tampered share ⇒ the
|
|
100
|
+
* room stays sealed). This is the one call the session uses to unseal "only when both are here". */
|
|
101
|
+
export async function assembleRoomKey(shareA, shareB, expectedCommit) {
|
|
102
|
+
const mk = combineShares(shareA, shareB)
|
|
103
|
+
if (mk == null) return null
|
|
104
|
+
// §6.4 (tenant-split-key-design.md): a MULTI-SHARE reconstruction is only trustworthy once verified against the room's
|
|
105
|
+
// registered commitment. Refuse to hand back a combined key with no commit to check it against — otherwise a malicious
|
|
106
|
+
// share-provider (a hostile app-plane serving a crafted appShare) could steer the client onto an attacker-chosen key.
|
|
107
|
+
if (!expectedCommit) return null
|
|
108
|
+
if ((await commit(mk)) !== expectedCommit) return null
|
|
109
|
+
return mk
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function wrapSym(key, cek) {
|
|
113
|
+
const wk = await roomWrapKey(key)
|
|
114
|
+
const iv = crypto.getRandomValues(new Uint8Array(12))
|
|
115
|
+
const w = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, wk, cek))
|
|
116
|
+
return { iv: b64(iv), w: b64(w) }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Seal a string to a MAP of named symmetric recipients — the app picks its privacy level per field by choosing which
|
|
120
|
+
* keys to include. Every mode is just a recipient set:
|
|
121
|
+
* • admin-blind, no recovery : { room: mk } ← even witbitz can't read; lose the link, lose the data
|
|
122
|
+
* • user-held recovery : { room: mk, recovery: recKey } ← recoverable WITHOUT witbitz reading (a user code)
|
|
123
|
+
* There is NO operator recipient — the platform never holds a reader key (retired 2026-07-31, matching the Node
|
|
124
|
+
* envelope). `room` is the fragment key (the primary reader) and the ONE slot the platform envelope also opens
|
|
125
|
+
* (wire-compat); `recovery` is the user's own second key. Returns the v1 envelope. */
|
|
126
|
+
export async function seal(plaintext, recipients = {}) {
|
|
127
|
+
const entries = Object.entries(recipients).filter(([, k]) => typeof k === 'string' && k)
|
|
128
|
+
if (!entries.length) throw new Error('seal needs at least one recipient key, e.g. { room: mk }')
|
|
129
|
+
const cek = crypto.getRandomValues(new Uint8Array(32))
|
|
130
|
+
const cekKey = await crypto.subtle.importKey('raw', cek, { name: 'AES-GCM' }, false, ['encrypt'])
|
|
131
|
+
const iv = crypto.getRandomValues(new Uint8Array(12))
|
|
132
|
+
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, cekKey, enc.encode(String(plaintext))))
|
|
133
|
+
const out = {}
|
|
134
|
+
for (const [slot, key] of entries) out[slot] = await wrapSym(key, cek)
|
|
135
|
+
return { v: VERSION, iv: b64(iv), ct: b64(ct), recipients: out }
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Open a v1 envelope with a symmetric key → plaintext string, or null on wrong key / tamper / malformed (fail-closed).
|
|
139
|
+
* Tries the key against EVERY symmetric recipient slot, so one call opens whichever slot the caller's key matches
|
|
140
|
+
* (the fragment key or a user recovery key). Any non-symmetric slot on a legacy record is skipped. */
|
|
141
|
+
export async function open(envelope, { mk, aad = null } = {}) {
|
|
142
|
+
if (!isEnvelope(envelope) || !mk) return null
|
|
143
|
+
if (envelope.aad && !aad) return null // M4: a bound ledger box (aad:1) MUST be opened with its {room,index} aad — refuse context-free
|
|
144
|
+
const wk = await roomWrapKey(mk)
|
|
145
|
+
for (const slot of Object.keys(envelope.recipients)) {
|
|
146
|
+
const r = envelope.recipients[slot]
|
|
147
|
+
if (!r || typeof r.iv !== 'string' || typeof r.w !== 'string') continue // skip non-symmetric recipients
|
|
148
|
+
try {
|
|
149
|
+
const cek = new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: ub64(r.iv) }, wk, ub64(r.w)))
|
|
150
|
+
const cekKey = await crypto.subtle.importKey('raw', cek, { name: 'AES-GCM' }, false, ['decrypt'])
|
|
151
|
+
const p = { name: 'AES-GCM', iv: ub64(envelope.iv) }
|
|
152
|
+
if (envelope.aad) p.additionalData = aad // verify the box still sits at its sealed {room,index}; a legacy box (no marker) ignores it
|
|
153
|
+
const pt = new Uint8Array(await crypto.subtle.decrypt(p, cekKey, ub64(envelope.ct)))
|
|
154
|
+
return dec.decode(pt)
|
|
155
|
+
} catch {
|
|
156
|
+
/* wrong key / tamper / moved box for this slot → try the next, else fail closed */
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return null
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** True if a stored value is a v1 envelope (vs plaintext) — has at least one symmetric recipient. */
|
|
163
|
+
export function isEnvelope(o) {
|
|
164
|
+
return !!(
|
|
165
|
+
o && typeof o === 'object' && o.v === VERSION && typeof o.iv === 'string' && typeof o.ct === 'string' &&
|
|
166
|
+
o.recipients && typeof o.recipients === 'object' && Object.values(o.recipients).some((r) => r && typeof r.iv === 'string' && typeof r.w === 'string')
|
|
167
|
+
)
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// ── Binary sealing (keepsake clips/images) — wire-compatible with agent/envelope.mjs sealBytes/openBytes ───────────
|
|
171
|
+
// Same CEK-wrap as seal(), but the ciphertext is RAW BYTES (the `body`, e.g. the S3 object) not base64'd into JSON, so
|
|
172
|
+
// a multi-MB video isn't bloated. The small `header` (wrapped CEK + content IV) is JSON — store it as metadata. The
|
|
173
|
+
// organizer's console opens with openBytes(body, header, { mk }) to decrypt + download the keepsake locally.
|
|
174
|
+
export async function sealBytes(bytes, recipients = {}) {
|
|
175
|
+
const entries = Object.entries(recipients).filter(([, k]) => typeof k === 'string' && k)
|
|
176
|
+
if (!entries.length) throw new Error('sealBytes needs at least one recipient key, e.g. { room: mk }')
|
|
177
|
+
const data = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
|
|
178
|
+
const cek = crypto.getRandomValues(new Uint8Array(32))
|
|
179
|
+
const cekKey = await crypto.subtle.importKey('raw', cek, { name: 'AES-GCM' }, false, ['encrypt'])
|
|
180
|
+
const iv = crypto.getRandomValues(new Uint8Array(12))
|
|
181
|
+
const body = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, cekKey, data))
|
|
182
|
+
const recips = {}
|
|
183
|
+
for (const [slot, key] of entries) recips[slot] = await wrapSym(key, cek)
|
|
184
|
+
return { header: { v: VERSION, alg: 'bin', iv: b64(iv), recipients: recips }, body }
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Open a sealBytes body + header with a symmetric key → plaintext BYTES (Uint8Array), or null (fail-closed). Tries the
|
|
188
|
+
* key against EVERY symmetric slot (room / recovery), so the organizer opens whichever slot their key matches. */
|
|
189
|
+
export async function openBytes(body, header, { mk } = {}) {
|
|
190
|
+
if (!isBinHeader(header) || !mk || !body) return null
|
|
191
|
+
const data = body instanceof Uint8Array ? body : new Uint8Array(body)
|
|
192
|
+
const wk = await roomWrapKey(mk)
|
|
193
|
+
for (const slot of Object.keys(header.recipients)) {
|
|
194
|
+
const r = header.recipients[slot]
|
|
195
|
+
if (!r || typeof r.iv !== 'string' || typeof r.w !== 'string') continue
|
|
196
|
+
try {
|
|
197
|
+
const cek = new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: ub64(r.iv) }, wk, ub64(r.w)))
|
|
198
|
+
const cekKey = await crypto.subtle.importKey('raw', cek, { name: 'AES-GCM' }, false, ['decrypt'])
|
|
199
|
+
return new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: ub64(header.iv) }, cekKey, data))
|
|
200
|
+
} catch {
|
|
201
|
+
/* wrong key / tamper for this slot → try the next, else fail closed */
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return null
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** True if `h` is a v1 binary-envelope header (from sealBytes) — distinct from a string envelope (which carries `ct`). */
|
|
208
|
+
export function isBinHeader(h) {
|
|
209
|
+
return !!(
|
|
210
|
+
h && typeof h === 'object' && h.v === VERSION && h.alg === 'bin' && typeof h.iv === 'string' &&
|
|
211
|
+
h.recipients && typeof h.recipients === 'object' && Object.values(h.recipients).some((r) => r && typeof r.iv === 'string' && typeof r.w === 'string')
|
|
212
|
+
)
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// ── Sealed box (PUBLIC-KEY) — for CONTRIBUTOR wishes ──────────────────────────────────────────────────────────────
|
|
216
|
+
// A friend seals a wish to the ORGANIZER's PUBLIC key (safe to share; encrypt-only); ONLY the organizer's PRIVATE key
|
|
217
|
+
// (recoverable from mk) opens it. Anonymous "sealed box" (like NaCl crypto_box_seal): a fresh EPHEMERAL ECDH-P256 key
|
|
218
|
+
// per message → HKDF → AES-256-GCM, the sender's ephemeral key DISCARDED — so a friend can't reopen their own wish OR
|
|
219
|
+
// read anyone else's; only the recipient can. The secret (mk / the private key) is NEVER shared with contributors.
|
|
220
|
+
// Wire-compatible with agent/envelope.mjs (same ECDH-P256 + HKDF("sealedbox") + AES-GCM + box shape).
|
|
221
|
+
const EC = { name: 'ECDH', namedCurve: 'P-256' }
|
|
222
|
+
async function boxKey(priv, pubJwk) {
|
|
223
|
+
const privKey = priv && priv.kty ? await crypto.subtle.importKey('jwk', priv, EC, false, ['deriveBits']) : priv
|
|
224
|
+
const pub = await crypto.subtle.importKey('jwk', pubJwk, EC, false, [])
|
|
225
|
+
const bits = await crypto.subtle.deriveBits({ name: 'ECDH', public: pub }, privKey, 256)
|
|
226
|
+
const ikm = await crypto.subtle.importKey('raw', bits, 'HKDF', false, ['deriveKey'])
|
|
227
|
+
return crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: enc.encode('sealedbox') }, ikm, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])
|
|
228
|
+
}
|
|
229
|
+
/** Generate a recipient (organizer) keypair → { publicJwk, privateJwk }. PUBLISH publicJwk (in the invite); wrap
|
|
230
|
+
* privateJwk to mk (sealBytes) + store it, so ONLY mk-holders (the organizer + the agent) recover the private key. */
|
|
231
|
+
export async function genRecipientKey() {
|
|
232
|
+
const kp = await crypto.subtle.generateKey(EC, true, ['deriveBits'])
|
|
233
|
+
return { publicJwk: await crypto.subtle.exportKey('jwk', kp.publicKey), privateJwk: await crypto.subtle.exportKey('jwk', kp.privateKey) }
|
|
234
|
+
}
|
|
235
|
+
/** Seal a string to a recipient PUBLIC key (jwk) → an anonymous sealed box. Encrypt-only: no private key is used here. */
|
|
236
|
+
export async function sealTo(plaintext, recipientPublicJwk) {
|
|
237
|
+
if (!recipientPublicJwk) throw new Error('sealTo needs the recipient public key')
|
|
238
|
+
const eph = await crypto.subtle.generateKey(EC, true, ['deriveBits'])
|
|
239
|
+
const key = await boxKey(eph.privateKey, recipientPublicJwk)
|
|
240
|
+
const iv = crypto.getRandomValues(new Uint8Array(12))
|
|
241
|
+
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, enc.encode(String(plaintext))))
|
|
242
|
+
const epk = await crypto.subtle.exportKey('jwk', eph.publicKey)
|
|
243
|
+
return { v: VERSION, alg: 'box', epk: { x: epk.x, y: epk.y }, iv: b64(iv), ct: b64(ct) }
|
|
244
|
+
}
|
|
245
|
+
/** Open a sealed box with the recipient PRIVATE key (jwk) → plaintext string, or null on wrong key / tamper / malformed. */
|
|
246
|
+
export async function openBox(box, recipientPrivateJwk) {
|
|
247
|
+
if (!isBox(box) || !recipientPrivateJwk) return null
|
|
248
|
+
try {
|
|
249
|
+
const key = await boxKey(recipientPrivateJwk, { kty: 'EC', crv: 'P-256', x: box.epk.x, y: box.epk.y })
|
|
250
|
+
const pt = new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: ub64(box.iv) }, key, ub64(box.ct)))
|
|
251
|
+
return dec.decode(pt)
|
|
252
|
+
} catch {
|
|
253
|
+
return null
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
/** True if a stored value is a v1 sealed box (public-key), vs a symmetric envelope / bin header. */
|
|
257
|
+
export function isBox(o) {
|
|
258
|
+
return !!(o && typeof o === 'object' && o.v === VERSION && o.alg === 'box' && o.epk && typeof o.epk.x === 'string' && typeof o.iv === 'string' && typeof o.ct === 'string')
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// ── The collection blob — content-blind append + owner peel (docs/e2ee-collection-blob.md) ────────────────────────
|
|
262
|
+
// The collection is ONE opaque blob: an append-only LIST of sealed boxes. Each contributor sealTo's their item to the
|
|
263
|
+
// owner's PUBLIC key; the SERVER just appends that opaque box to the list — it needs NO key, never decrypts, and the
|
|
264
|
+
// append is a single atomic DynamoDB list_append (no read-modify-write, no version). One row → the item COUNT is not
|
|
265
|
+
// listable ambiently (Part B, docs/trust-model.md). LINEAR in size (unlike onion nesting, which is exponential in
|
|
266
|
+
// base64 and unbounded without an online mk-holder to compact — see nestAppend below). Only the owner's PRIVATE key
|
|
267
|
+
// (from mk) opens the boxes. Wire-compatible Node ⇄ browser.
|
|
268
|
+
/** True if a value is a collection blob (an append-only list of sealed boxes). Accepts the raw DynamoDB shape too. */
|
|
269
|
+
export function isBoxList(o) { return !!(o && typeof o === 'object' && Array.isArray(o.boxes)) }
|
|
270
|
+
/** A stable, opaque id for a box — a prefix of its ciphertext (unique per box: fresh IV + ephemeral key). Sync, needs
|
|
271
|
+
* NO key, so the console and the agent derive the SAME id to key moderation decisions (leave-out) without decrypting. */
|
|
272
|
+
export function boxId(box) { return String((box && box.ct) || '').slice(0, 40) }
|
|
273
|
+
/** Append one contributor box to the blob (immutable — returns a new blob). No key needed; the box is already sealed. */
|
|
274
|
+
export function appendBox(blob, box) {
|
|
275
|
+
const boxes = isBoxList(blob) ? blob.boxes : []
|
|
276
|
+
return { v: VERSION, alg: 'boxlist', boxes: [...boxes, box] }
|
|
277
|
+
}
|
|
278
|
+
/** Owner/agent read: open every box with the PRIVATE key → items. Handles the boxlist blob AND a bounded onion (below).
|
|
279
|
+
* Fail-closed per box (a box that won't open is skipped for the list; the onion stops). */
|
|
280
|
+
export async function peelAll(blob, ownerPrivateJwk) {
|
|
281
|
+
if (isBoxList(blob)) { // the collection-blob form (also the raw DynamoDB { boxes:[...] } item)
|
|
282
|
+
const out = []
|
|
283
|
+
for (const b of blob.boxes) { const item = await openBox(b, ownerPrivateJwk); if (item != null) out.push(item) }
|
|
284
|
+
return out
|
|
285
|
+
}
|
|
286
|
+
const out = [] // bounded onion form (nestAppend) — newest-first
|
|
287
|
+
let cur = blob
|
|
288
|
+
while (cur && isBox(cur)) {
|
|
289
|
+
const layer = await openBox(cur, ownerPrivateJwk)
|
|
290
|
+
if (layer == null) break // can't open this layer → stop (fail-closed)
|
|
291
|
+
let parsed
|
|
292
|
+
try { parsed = JSON.parse(layer) } catch (e) { break }
|
|
293
|
+
if (parsed && parsed.inner) { const item = await openBox(parsed.inner, ownerPrivateJwk); if (item != null) out.push(item) }
|
|
294
|
+
cur = parsed && parsed.prev ? parsed.prev : null
|
|
295
|
+
}
|
|
296
|
+
return out
|
|
297
|
+
}
|
|
298
|
+
/** BOUNDED-USE onion append: wrap { box, prev } in a fresh layer to the PUBLIC key. WARNING: size is EXPONENTIAL in the
|
|
299
|
+
* number of appends (each layer re-base64s the whole blob) — use ONLY for a small, bounded count (e.g. a compaction of
|
|
300
|
+
* ≤K items). The async collection uses appendBox (linear) instead. Kept for bounded nesting; peelAll reads both. */
|
|
301
|
+
export async function nestAppend(oldBlob, contributorBox, ownerPublicJwk) {
|
|
302
|
+
return sealTo(JSON.stringify({ inner: contributorBox, prev: oldBlob || null }), ownerPublicJwk)
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// ── The collection keypair — minted at create, PUBLIC published, PRIVATE wrapped to mk ────────────────────────────
|
|
306
|
+
// The owner's read key is `mk` (never shared). At create the organizer mints a recipient keypair: the PUBLIC jwk is
|
|
307
|
+
// published on the gift record (contributors seal their boxes to it — encrypt-only, safe to expose); the PRIVATE jwk
|
|
308
|
+
// is symmetric-sealed to `mk` and stored as an opaque envelope. Anyone holding `mk` (organizer console, or the agent
|
|
309
|
+
// at call time) unwraps it to peel the blob. The server stores only the public jwk + the wrapped (opaque) private key.
|
|
310
|
+
/** Mint a collection keypair → { publicJwk (publish), wrapped (store; the private jwk sealed to mk) }. */
|
|
311
|
+
export async function sealRecipientKey(mk) {
|
|
312
|
+
if (!mk) throw new Error('sealRecipientKey needs mk')
|
|
313
|
+
const { publicJwk, privateJwk } = await genRecipientKey()
|
|
314
|
+
const wrapped = await seal(JSON.stringify(privateJwk), { room: mk })
|
|
315
|
+
return { publicJwk, wrapped }
|
|
316
|
+
}
|
|
317
|
+
/** Unwrap the private jwk from its mk-sealed envelope → privateJwk, or null (fail-closed on wrong mk / tamper). */
|
|
318
|
+
export async function openRecipientKey(mk, wrapped) {
|
|
319
|
+
if (!mk || !isEnvelope(wrapped)) return null
|
|
320
|
+
const s = await open(wrapped, { mk })
|
|
321
|
+
if (s == null) return null
|
|
322
|
+
try { return JSON.parse(s) } catch (e) { return null }
|
|
323
|
+
}
|
package/eat.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// eat.js — Witbitz attestation as standard ENTITY ATTESTATION TOKENS (RFC 9711, the JSON/JWT form), in the vocabulary of
|
|
2
|
+
// the IETF RATS architecture (RFC 9334). docs/rats-eat.md has the mapping and the profile.
|
|
3
|
+
//
|
|
4
|
+
// Our attesters (the standing Sentinel, the turn enclave) produce AWS Nitro attestation documents — evidence in AWS's own
|
|
5
|
+
// format, which no one can change. An EAT wraps it so a relying party can check it with standard tools:
|
|
6
|
+
// • the token is a JWT, ES256, signed by a P-256 key the ENCLAVE generated;
|
|
7
|
+
// • `measurements` carries the Nitro document as evidence — content format 18 (application/cose; COSE_Sign1) — and that
|
|
8
|
+
// document's `public_key` is the token's signing key, its `nonce` the token's `eat_nonce`;
|
|
9
|
+
// • so: the AWS chain proves the document, the PCRs name the build, and the signature proves THIS token came from it.
|
|
10
|
+
// A turn EAT (one per confidential reply) carries no document — it is signed by the same attested key, which a boot EAT
|
|
11
|
+
// proves — and the audit's verdicts are ATTESTATION RESULTS (attestationResults below), never passed off as evidence.
|
|
12
|
+
import { verifyAttestation } from './nitroVerify.js'
|
|
13
|
+
|
|
14
|
+
export const EAT_PROFILE = 'https://witbitz.chat/eat/nitro-v1'
|
|
15
|
+
export const COSE_SIGN1_CONTENT_FORMAT = 18 // CoAP Content-Format: application/cose; cose-type="cose-sign1"
|
|
16
|
+
const MAX_TOKEN = 64 * 1024
|
|
17
|
+
|
|
18
|
+
const te = new TextEncoder(), td = new TextDecoder()
|
|
19
|
+
const b64u = (u8) => { let s = ''; const b = u8 instanceof Uint8Array ? u8 : new Uint8Array(u8); for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i]); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
|
|
20
|
+
const unb64u = (s) => { const t = String(s).replace(/-/g, '+').replace(/_/g, '/'); const bin = atob(t + '='.repeat((4 - (t.length % 4)) % 4)); const u = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i); return u }
|
|
21
|
+
const jsonPart = (s, what) => { try { return JSON.parse(td.decode(unb64u(s))) } catch { throw new Error(`eat: the ${what} is not base64url JSON`) } }
|
|
22
|
+
|
|
23
|
+
/** A fresh ES256 key: { privateKey, publicKey, spki } (spki: DER bytes — what a Nitro document's public_key carries). */
|
|
24
|
+
export async function makeEatKey() {
|
|
25
|
+
const k = await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify'])
|
|
26
|
+
return { privateKey: k.privateKey, publicKey: k.publicKey, spki: new Uint8Array(await crypto.subtle.exportKey('spki', k.publicKey)) }
|
|
27
|
+
}
|
|
28
|
+
/** The `measurements` entry that carries a Nitro document as evidence: [18, base64url(COSE_Sign1)]. */
|
|
29
|
+
export const evidenceClaim = (doc) => [COSE_SIGN1_CONTENT_FORMAT, b64u(doc)]
|
|
30
|
+
/** Sign a claims-set as a JWT EAT (ES256). WebCrypto's ECDSA signature is already JWS's raw r‖s. */
|
|
31
|
+
export async function signEat(claims, privateKey) {
|
|
32
|
+
const head = b64u(te.encode(JSON.stringify({ alg: 'ES256', typ: 'JWT' })))
|
|
33
|
+
const body = b64u(te.encode(JSON.stringify(claims)))
|
|
34
|
+
const sig = await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, privateKey, te.encode(head + '.' + body))
|
|
35
|
+
return head + '.' + body + '.' + b64u(new Uint8Array(sig))
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Verify a Witbitz EAT. → { ok, claims, doc, userData, pinned }.
|
|
40
|
+
* @param token the JWT
|
|
41
|
+
* @param opts { expectedPCRs, nonce, root, now, maxAgeMs, key, profile } — `expectedPCRs` pins the build (without it the
|
|
42
|
+
* result says pinned:false); `nonce` is YOUR challenge (it must be the token's eat_nonce AND the document's);
|
|
43
|
+
* `key` (SPKI bytes) verifies a detached EAT (a turn's), whose key a boot EAT proved.
|
|
44
|
+
*/
|
|
45
|
+
export async function verifyEat(token, { expectedPCRs = null, nonce = null, root, now = Date.now(), maxAgeMs = 0, key = null, profile = EAT_PROFILE } = {}) {
|
|
46
|
+
if (typeof token !== 'string' || token.length > MAX_TOKEN) throw new Error('eat: not a token')
|
|
47
|
+
const parts = token.split('.')
|
|
48
|
+
if (parts.length !== 3) throw new Error('eat: a JWT has three parts')
|
|
49
|
+
const [h, p, s] = parts
|
|
50
|
+
const header = jsonPart(h, 'header')
|
|
51
|
+
if (header.alg !== 'ES256') throw new Error('eat: only ES256 is accepted (got ' + JSON.stringify(header.alg) + ')')
|
|
52
|
+
const claims = jsonPart(p, 'claims-set')
|
|
53
|
+
if (!claims || typeof claims !== 'object') throw new Error('eat: the claims-set is not an object')
|
|
54
|
+
if (claims.eat_profile !== profile) throw new Error(`eat: profile ${JSON.stringify(claims.eat_profile)} is not ${profile}`)
|
|
55
|
+
if (nonce !== null && claims.eat_nonce !== nonce) throw new Error('eat: eat_nonce is not the nonce you sent')
|
|
56
|
+
|
|
57
|
+
const ev = Array.isArray(claims.measurements) ? claims.measurements.find((m) => Array.isArray(m) && m[0] === COSE_SIGN1_CONTENT_FORMAT && typeof m[1] === 'string') : null
|
|
58
|
+
let doc = null, spki = null
|
|
59
|
+
if (ev) {
|
|
60
|
+
doc = await verifyAttestation(unb64u(ev[1]), {
|
|
61
|
+
...(root ? { root } : {}), now, maxAgeMs,
|
|
62
|
+
...(expectedPCRs ? { expectedPCRs } : {}),
|
|
63
|
+
...(typeof claims.eat_nonce === 'string' ? { nonce: te.encode(claims.eat_nonce) } : {}), // the document was made FOR this token
|
|
64
|
+
})
|
|
65
|
+
if (typeof claims.eat_nonce !== 'string') throw new Error('eat: a token carrying evidence must carry the eat_nonce it was made for')
|
|
66
|
+
if (!doc.publicKey) throw new Error('eat: the attestation document attests no key')
|
|
67
|
+
spki = doc.publicKey
|
|
68
|
+
} else if (key) spki = key instanceof Uint8Array ? key : new Uint8Array(key)
|
|
69
|
+
else throw new Error('eat: no evidence in the token and no attested key to verify it with')
|
|
70
|
+
|
|
71
|
+
let pub
|
|
72
|
+
try { pub = await crypto.subtle.importKey('spki', spki, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify']) } catch { throw new Error('eat: the attested key is not a P-256 signing key') }
|
|
73
|
+
const ok = await crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, pub, unb64u(s), te.encode(h + '.' + p))
|
|
74
|
+
if (!ok) throw new Error('eat: the signature does not verify under the attested key')
|
|
75
|
+
|
|
76
|
+
let userData = null
|
|
77
|
+
if (doc && doc.userData) { try { userData = JSON.parse(td.decode(doc.userData)) } catch { userData = null } }
|
|
78
|
+
return { ok: true, claims, doc, userData, pinned: !!(ev && expectedPCRs) }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The audit's verdict as ATTESTATION RESULTS in EAT vocabulary (RFC 9711 §4.2.17 `measres`, §4.2.18 `submods`): what a
|
|
83
|
+
* VERIFIER concluded, not evidence. Unsigned on purpose — the audit runs on the operator's machine, so a signature would
|
|
84
|
+
* be the operator's claim dressed as a proof; its integrity is the verdict log's hash chain and the commit it names.
|
|
85
|
+
*/
|
|
86
|
+
export function attestationResults({ subject, pass, pcrs = {}, measurement = null, commit = '', at = Date.now(), chain = '' } = {}) {
|
|
87
|
+
const name = String(subject || 'unknown')
|
|
88
|
+
return {
|
|
89
|
+
eat_profile: EAT_PROFILE,
|
|
90
|
+
iat: Math.floor(Number(at) / 1000),
|
|
91
|
+
measres: [['witbitz-audit', [[name, pass ? 'success' : 'fail']]]],
|
|
92
|
+
submods: { [name]: { wbx_pcrs: { ...pcrs }, ...(measurement && typeof measurement === 'object' ? { wbx_measurement: { ...measurement } } : {}), ...(commit ? { wbx_commit: String(commit) } : {}), ...(chain ? { wbx_chain: String(chain) } : {}) } },
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Challenge a door for a fresh EAT and verify it: a random nonce, GET <eatUrl>?nonce=…, verifyEat with your pins.
|
|
97
|
+
* `eatUrl` is the A2A card's attestation extension `params.eat` (https://agents.witbitz.chat/eat). → verifyEat's result. */
|
|
98
|
+
export async function fetchAndVerifyEat(eatUrl, { expectedPCRs = null, fetchImpl = fetch, ...opts } = {}) {
|
|
99
|
+
const nonce = b64u(crypto.getRandomValues(new Uint8Array(24)))
|
|
100
|
+
const res = await fetchImpl(String(eatUrl) + (String(eatUrl).includes('?') ? '&' : '?') + 'nonce=' + nonce, { cache: 'no-store' })
|
|
101
|
+
if (!res.ok) throw new Error(`eat: ${eatUrl} answered ${res.status}`)
|
|
102
|
+
return verifyEat((await res.text()).trim(), { ...opts, expectedPCRs, nonce })
|
|
103
|
+
}
|