// THE SEALED CREDENTIAL STORE (docs/concepts/the-model.md, rule 5): a World seals its // credential beside itself, and the kernel executor is the only reader. Real vendor credentials are: // • WRITE-ONLY through the API: placement and deletion are the tenant's act; reads // return metadata (placedAt, a fingerprint) and NEVER the secret — there is no // read-back door, and none may ever be added. // • ENVELOPE-ENCRYPTED: each credential gets its own random 256-bit DEK (AES-GCM); // the DEK is wrapped by the deployment KEK, which lives in the platform's secret // store (wrangler secret TWINS_CRED_KEK) and never in any bucket. KEK rotation is // a re-wrap of DEKs, not a re-encryption of payloads. // • OUTSIDE every namespace tree (beside keys and links, under '-/creds/'), so no // flush, snapshot, or door can ever carry one. // • CONSUMED only by the remote backing arm and the sync plane, through // `openSealedCredential` — an in-process seam, never an HTTP surface. // // The payload is a JSON object; the convention the forward arm consumes is // `{ headers: { authorization: "Bearer …", … } }` — credential APPLICATION is a value // (which headers), never a per-vendor mechanism. WebCrypto only: workerd-clean. // // `secret` is the RAW material for the strategies that cannot be expressed as a header: a vendor // that reads its key from a query parameter, or one that wants a signature computed per request // (docs/concepts/the-model.md#the-rules, rule 5, "applies the credential by strategy"). It is optional and unread unless // the pack declares such a strategy, so a header-authenticated vendor seals exactly what it sealed // before. It is never logged and never enters pack code — the executor is the only reader. import clockForm from '../world-clock.cjs'; export type CredentialPayload = { headers: Record; secret?: string; keyId?: string } & Record; /** The at-rest form. All byte fields base64. The fingerprint is a short keyed hash (HMAC) * of the payload — enough for an operator to recognize "the key ending a1b2…", never * enough to recover anything. `v: 1` wraps the DEK under a key the host holds; `v: 2` has a * vault's transit engine wrap it (company decision 0034), naming the transit key that did. */ export type SealedCredential = SealedUnderKey | SealedByVault; type SealedBody = { iv: string; ciphertext: string; placedAt: string; fingerprint: string; rotatedAt?: string; /** where the credential may be sent (`origin=https://…`), part of the AEAD's associated data: a record opens for * its own destination and no other, so a root or link pointed elsewhere never carries it there (the executor also * sends it to the hosts its vendor's pack declares: code, not configuration) */ bound?: string; }; export type SealedByVault = SealedBody & { v: 2; /** `/` of the transit key that wrapped the DEK */ transitKey: string; /** the vault's own ciphertext of the DEK (`vault:vN:…`) */ wrappedDek: string; }; export type SealedUnderKey = { v: 1; dekIv: string; wrappedDek: string; iv: string; ciphertext: string; placedAt: string; fingerprint: string; /** when a vendor last rotated a field of it (an OAuth refresh token): placedAt and fingerprint stay the credential's * identity across rotations, the ledgers keyed by the fingerprint with them */ rotatedAt?: string; /** as SealedBody's: the destination the credential is bound to, in its associated data */ bound?: string; }; /** The associated data a record is sealed under: its slot, and its destination when it has one. */ const associatedData = (slot: string, bound: string | undefined): Uint8Array => new Uint8Array(new TextEncoder().encode(bound === undefined ? slot : `${slot}\u0000${bound}`)); /** A record opened for a destination: one bound elsewhere refuses, and so does one bound nowhere. With no destination * asked (a webhook's signing secret, sent nowhere), the record opens under the binding it carries. */ function checkBinding(sealed: { bound?: string }, bound: string | undefined): void { if (bound === undefined) return; if (sealed.bound === undefined) throw new Error(`credential is bound to no destination: set it again for ${bound.replace(/^origin=/, '')}`); if (sealed.bound !== bound) throw new Error(`credential bound to ${sealed.bound}, not ${bound}: set it again for this destination`); } export interface CredentialStorage { getSealed(namespace: string, vendor: string): Promise; putSealed(namespace: string, vendor: string, sealed: SealedCredential): Promise; deleteSealed(namespace: string, vendor: string): Promise; /** Purge every vendor's sealed record for the namespace — the lifecycle DELETE calls * this: a deleted namespace's credentials must not survive to be inherited by * whoever re-provisions the name. */ deleteNamespace(namespace: string): Promise; } const toB64 = (bytes: Uint8Array): string => { // Chunked: a spread of the whole payload blows the arg-count stack well // below the 4 MB body cap (verified ~1 MB on Bun, tens of KB on V8). let bin = ''; for (let i = 0; i < bytes.length; i += 0x1000) bin += String.fromCharCode(...bytes.subarray(i, i + 0x1000)); return btoa(bin); }; const fromB64 = (b64: string): Uint8Array => { const bin = atob(b64); const bytes = new Uint8Array(new ArrayBuffer(bin.length)); for (let i = 0; i < bin.length; i += 1) bytes[i] = bin.charCodeAt(i); return bytes; }; /** The KEK secret string (at least 32 characters) normalizes to 32 key bytes via SHA-256 — * operators paste one strong secret; the digest is the AES key material. */ async function importKek(secret: string): Promise { // ≥32 chars: SHA-256 with no stretching is fine for MACHINE secrets // (`openssl rand -base64 32`) and hopeless against a short human passphrase — the // floor forces the former. if (secret.length < 32) throw new Error('credential KEK must be at least 32 characters (generate with: openssl rand -base64 32)'); const material = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(secret)); return await crypto.subtle.importKey('raw', material, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']); } export async function sealCredential(kekSecret: string, payload: CredentialPayload, placedAt: string, slot = '', bound?: string): Promise { const kek = await importKek(kekSecret); const plaintext = new TextEncoder().encode(JSON.stringify(payload)); const dekBytes = crypto.getRandomValues(new Uint8Array(32)); const dek = await crypto.subtle.importKey('raw', dekBytes, { name: 'AES-GCM' }, false, ['encrypt']); const iv = crypto.getRandomValues(new Uint8Array(12)); const dekIv = crypto.getRandomValues(new Uint8Array(12)); // The SLOT ('{namespace}/{vendor}') rides as AAD (audit L16): a sealed record // transplanted to another slot by a bucket-level writer refuses to open there. const aad = associatedData(slot, bound); const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: aad }, dek, plaintext)); const wrappedDek = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv: dekIv }, kek, dekBytes)); // KEYED fingerprint: an unsalted hash prefix is an offline oracle for // low-entropy payloads; HMAC under KEK-derived material keeps the operator UX // (recognizable short id) with no oracle. const macMaterial = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(`fingerprint:${kekSecret}`)); const macKey = await crypto.subtle.importKey('raw', macMaterial, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']); const digest = new Uint8Array(await crypto.subtle.sign('HMAC', macKey, plaintext)); return { v: 1, dekIv: toB64(dekIv), wrappedDek: toB64(wrappedDek), iv: toB64(iv), ciphertext: toB64(ciphertext), placedAt, fingerprint: [...digest.slice(0, 6)].map((b) => b.toString(16).padStart(2, '0')).join(''), ...(bound === undefined ? {} : { bound }), }; } export async function openSealedCredential(kekSecret: string, sealed: SealedCredential, slot = '', bound?: string): Promise { checkBinding(sealed, bound); if (sealed.v === 2) throw new Error(`credential sealed by a vault (${sealed.transitKey}): open it with that vault's sealer`); const kek = await importKek(kekSecret); let dekBytes: ArrayBuffer; try { dekBytes = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: fromB64(sealed.dekIv) }, kek, fromB64(sealed.wrappedDek)); } catch { throw new Error('credential unseal failed: wrong KEK or corrupted record'); } const dek = await crypto.subtle.importKey('raw', dekBytes, { name: 'AES-GCM' }, false, ['decrypt']); try { const plaintext = new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: fromB64(sealed.iv), additionalData: associatedData(slot, sealed.bound) }, dek, fromB64(sealed.ciphertext))); return JSON.parse(new TextDecoder().decode(plaintext)) as CredentialPayload; } catch { throw new Error('credential unseal failed: wrong KEK or corrupted record'); } } // ── a sealer: what seals and opens a host's credentials ───────────────────────────────────── /** What a rewrap made of a record: its new form, current (already under the newest version), or not this sealer's to * vouch for (another key's, or an answer whose version it could not read): only `current` says nothing is left. */ export type Rewrapped = { status: 'rewrapped'; sealed: SealedCredential } | { status: 'current' } | { status: 'foreign'; reason: string }; /** Seals and opens credentials. A host chooses one (`setSealer`); a key it holds (`keySealer`), or a vault that holds * the key and wraps for it (`transitSealer`). */ export interface Sealer { /** `bound`: the destination the credential may be sent to, sealed into the record (see SealedBody) */ seal(payload: CredentialPayload, placedAt: string, slot?: string, bound?: string): Promise; /** `bound`: the destination it is opened for; a record bound elsewhere refuses */ open(sealed: SealedCredential, slot?: string, bound?: string): Promise; /** The record with its DEK wrapped under the newest version of its key, without the DEK leaving the sealer (a * vault's `transit/rewrap` after a rotation): `rewrapped` with its new form, `current` when it already is, `foreign` * when it is not this sealer's to vouch for. What an operator's sweep runs after rotating a key, before raising its * minimum decryption version. */ rewrap?(sealed: SealedCredential): Promise; } /** Wraps under a key the host holds (the user's key file, a deployment secret): `v: 1` records. */ export function keySealer(kekSecret: () => string): Sealer { return { seal: (payload, placedAt, slot = '', bound) => sealCredential(kekSecret(), payload, placedAt, slot, bound), open: (sealed, slot = '', bound) => openSealedCredential(kekSecret(), sealed, slot, bound), }; } export type TransitSealerOptions = { /** the vault's address (`https://…`, or `http://` to loopback) */ addr: string; /** a token that may encrypt, decrypt and hmac with the key */ token: () => string | Promise; /** the transit key's name */ key: string; /** the transit engine's mount (default `transit`) */ mount?: string; namespace?: string; /** the transit key that keys every fingerprint (default `-fingerprint`): one that is never rotated, so a * credential's fingerprint, and every ledger keyed by it, stays as it was while the wrapping key is rotated and its * min_encryption_version raised (an hmac at a pinned version of a rotated key is refused once that version is too * old). A wrapping key's old versions are never trimmed: a record's DEK stays under the version that wrapped it */ fingerprintKey?: string; /** how long an opened DEK is kept in memory, ms (default 60 000): a burst of vendor calls asks the vault once */ dekCacheMs?: number; /** how long a vault call may take, ms (default 10 000) */ timeoutMs?: number; fetch?: typeof fetch; /** renew the token (auth/token/renew-self) after calls, at most daily (default true); false where something else * holds and renews it (the hosted Worlds' supervisor) */ renew?: boolean; }; /** * OpenBao's (or Vault's) transit engine wraps each credential's DEK: the key never leaves the vault. The payload is * sealed as `v: 1` seals it (a random DEK, AES-GCM, the slot as AAD); the vault encrypts the DEK and keys the * fingerprint (`transit/hmac`). `v: 2` records name `/`; a record from another key refuses. */ export function transitSealer(options: TransitSealerOptions): Sealer { const mount = options.mount ?? 'transit'; const named = `${mount}/${options.key}`; const addr = options.addr.replace(/\/+$/, ''); // the token, every DEK and every credential (hmac) go to this address: https, or http only to this machine const parsed = new URL(addr); if (parsed.username || parsed.password || !(parsed.protocol === 'https:' || (parsed.protocol === 'http:' && /^(127(\.\d{1,3}){3}|localhost|\[::1\])$/.test(parsed.hostname)))) { throw new Error(`the vault address ${parsed.protocol}//${parsed.host} is neither https nor this machine`); } const fingerprintKey = options.fingerprintKey ?? `${options.key}-fingerprint`; // a periodic token lives while it is renewed within its period: after a call it answered, at most once a day, the // sealer renews its own. A vault that refuses (a token that is not renewable, a root or dev token) is asked again the // next day; one that did not answer, after the next call. The token's own period is the bound. let renewedAt = 0; const renew = async (): Promise => { if (options.renew === false || clockForm.machineNow() - renewedAt < 86_400_000) return; renewedAt = clockForm.machineNow(); let status: number; try { status = (await (options.fetch ?? fetch)(`${addr}/v1/auth/token/renew-self`, { method: 'POST', headers: { 'x-vault-token': await options.token(), 'content-type': 'application/json', ...(options.namespace ? { 'x-vault-namespace': options.namespace } : {}) }, body: '{}', signal: AbortSignal.timeout(options.timeoutMs ?? 10_000), // never followed: a redirect would carry the token (and the DEK or credential) to wherever it points redirect: 'manual', })).status; } catch (error) { renewedAt = 0; console.warn(`[credential] the vault at ${addr} did not answer renewing this host's token (${(error as Error).message})`); return; } if (status >= 500) renewedAt = 0; if (status >= 300) console.warn(`[credential] the vault at ${addr} did not renew this host's token (${status})`); }; const call = async (op: 'encrypt' | 'decrypt' | 'hmac' | 'rewrap', body: Record, key = options.key): Promise> => { const which = `${mount}/${key}`; let response: Response; try { response = await (options.fetch ?? fetch)(`${addr}/v1/${mount}/${op}/${encodeURIComponent(key)}`, { method: 'POST', headers: { 'x-vault-token': await options.token(), 'content-type': 'application/json', ...(options.namespace ? { 'x-vault-namespace': options.namespace } : {}) }, body: JSON.stringify(body), signal: AbortSignal.timeout(options.timeoutMs ?? 10_000), // never followed: a redirect would carry the token (and the DEK or credential) to wherever it points redirect: 'manual', }); } catch (error) { throw new Error(`the vault at ${addr} did not answer transit ${op} with ${which} (${(error as Error).message})`); } if (response.status >= 300 && response.status < 400) throw new Error(`the vault at ${addr} redirected transit ${op}: refused`); if (!response.ok) throw new Error(`the vault refused transit ${op} with ${which} (${response.status})`); const answer = (await response.json()) as { data?: Record }; if (!answer.data) throw new Error(`the vault answered transit ${op} with ${which} without data`); void renew(); return answer.data; }; const fingerprintOf = async (plaintext: Uint8Array): Promise => { const { hmac } = await call('hmac', { input: toB64(plaintext) }, fingerprintKey); const digest = fromB64(String(hmac).replace(/^vault:v\d+:/, '')); return [...digest.slice(0, 6)].map((b) => b.toString(16).padStart(2, '0')).join(''); }; // an opened DEK, briefly: the vault's ciphertext names it, so a re-sealed record is a new entry const opened = new Map; until: number }>(); const openedDek = (wrappedDek: string): Promise => { const now = performance.now(); for (const [k, v] of opened) if (v.until <= now) opened.delete(k); const held = opened.get(wrappedDek); if (held) return held.dek; const dek = call('decrypt', { ciphertext: wrappedDek }) .then(({ plaintext }) => crypto.subtle.importKey('raw', fromB64(String(plaintext)), { name: 'AES-GCM' }, false, ['decrypt'])); dek.catch(() => opened.delete(wrappedDek)); opened.set(wrappedDek, { dek, until: now + (options.dekCacheMs ?? 60_000) }); return dek; }; return { async seal(payload, placedAt, slot = '', bound) { const plaintext = new TextEncoder().encode(JSON.stringify(payload)); const dekBytes = crypto.getRandomValues(new Uint8Array(32)); const dek = await crypto.subtle.importKey('raw', dekBytes, { name: 'AES-GCM' }, false, ['encrypt']); const iv = crypto.getRandomValues(new Uint8Array(12)); const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: associatedData(slot, bound) }, dek, plaintext)); const { ciphertext: wrappedDek } = await call('encrypt', { plaintext: toB64(dekBytes) }); if (!wrappedDek) throw new Error(`the vault answered transit encrypt with ${named} without a ciphertext`); return { v: 2, transitKey: named, wrappedDek, iv: toB64(iv), ciphertext: toB64(ciphertext), placedAt, fingerprint: await fingerprintOf(plaintext), ...(bound === undefined ? {} : { bound }) }; }, async open(sealed, slot = '', bound) { checkBinding(sealed, bound); if (sealed.v !== 2) throw new Error(`credential not sealed by ${named}`); if (sealed.transitKey !== named) throw new Error(`credential sealed by ${sealed.transitKey}, not ${named}`); const dek = await openedDek(sealed.wrappedDek); try { const out = new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: fromB64(sealed.iv), additionalData: associatedData(slot, sealed.bound) }, dek, fromB64(sealed.ciphertext))); return JSON.parse(new TextDecoder().decode(out)) as CredentialPayload; } catch { throw new Error('credential unseal failed: wrong slot or corrupted record'); } }, async rewrap(sealed) { // only this sealer's own records: a key's (v1) or another transit key's are not its to rewrap if (sealed.v !== 2) return { status: 'foreign', reason: 'sealed under a host key' }; if (sealed.transitKey !== named) return { status: 'foreign', reason: `sealed by ${sealed.transitKey}` }; const { ciphertext } = await call('rewrap', { ciphertext: sealed.wrappedDek }); const version = (wrapped: unknown): number | null => { const m = typeof wrapped === 'string' ? /^vault:v(\d+):/.exec(wrapped) : null; return m ? Number(m[1]) : null; }; const before = version(sealed.wrappedDek); const after = version(ciphertext); if (before === null || after === null) return { status: 'foreign', reason: 'a wrapped key whose version could not be read' }; // the vault rewraps to a fresh ciphertext at the same version when the key has not moved: current, nothing written return after > before ? { status: 'rewrapped', sealed: { ...sealed, wrappedDek: String(ciphertext) } } : { status: 'current' }; }, }; }