/** * Two locks the Worker itself holds, each under a Worker secret of its own * (32 random bytes, base64url), never in the object's SQLite, a log line or * an answer. No key is a refusal, never a value kept in the clear. * * - **k1, VAULT_KEY**: a saved secret's value (a password the Worker sealed * before the vault moved to the device; it opens only for an owner token's * dev_reveal_secret). * * "k1:" + base64url(nonce12 || AES-256-GCM(VAULT_KEY, nonce, plaintext, aad = "secret:" || row)) * * - **t1, SERVICE_TOKEN_KEY**: a refresh token the Worker uses itself to * reach a service for the person (Google Calendar, Spotify), named for what * it is so VAULT_KEY never means "your services" (sealing plan §7 step 6). * * "t1:" + base64url(nonce12 || AES-256-GCM(SERVICE_TOKEN_KEY, nonce, plaintext, aad = "service-token:" || row)) * * The row id is bound, so a sealed value copied into another row does not * open there, and the prefixes keep one lock's value from ever being opened * by the other. */importtype { Env } from"./env.ts";import { fromBase64Url, toBase64Url } from"./base64.ts";export { fromBase64Url, toBase64Url };import { refuse } from"./http.ts";interfaceLock { prefix: string; aad: string; secret: "VAULT_KEY" | "SERVICE_TOKEN_KEY"; unavailable: string;}const VAULT: Lock = { prefix: "k1:", aad: "secret:", secret: "VAULT_KEY", unavailable: "vault_unavailable" };const SERVICE: Lock = { prefix: "t1:", aad: "service-token:", secret: "SERVICE_TOKEN_KEY", unavailable: "service_token_unavailable" };asyncfunction key(env: Env, lock: Lock): Promise<CryptoKey> {const raw = env[lock.secret];if (!raw) refuse(503, lock.unavailable, `this Worker has no ${lock.secret}`);const bytes = fromBase64Url(raw.trim());if (bytes.length !== 32) refuse(503, lock.unavailable, `${lock.secret} must be 32 bytes, base64url`);return crypto.subtle.importKey("raw", bytes, "AES-GCM", false, ["encrypt", "decrypt"]);}asyncfunction sealUnder(env: Env, lock: Lock, rowId: string, plaintext: string): Promise<string> {const nonce = crypto.getRandomValues(newUint8Array(12));const ct = newUint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: newTextEncoder().encode(`${lock.aad}${rowId}`) }, await key(env, lock), newTextEncoder().encode(plaintext)), );const body = newUint8Array(nonce.length + ct.length); body.set(nonce, 0); body.set(ct, nonce.length);return lock.prefix + toBase64Url(body);}asyncfunction openUnder(env: Env, lock: Lock, rowId: string, sealed: string): Promise<string | null> {if (!sealed.startsWith(lock.prefix)) returnnull;const k = await key(env, lock);let body: Uint8Array;try { body = fromBase64Url(sealed.slice(lock.prefix.length)); } catch {returnnull; }if (body.length < 12 + 16) returnnull;try {const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv: body.slice(0, 12), additionalData: newTextEncoder().encode(`${lock.aad}${rowId}`) }, k, body.slice(12));returnnewTextDecoder().decode(pt); } catch {returnnull; }}/** A saved secret's value sealed under VAULT_KEY (k1). */exportfunction seal(env: Env, rowId: string, plaintext: string): Promise<string> {return sealUnder(env, VAULT, rowId, plaintext);}/** The plaintext of a k1 value, or null when it does not open under this key for this row. */exportfunction open(env: Env, rowId: string, sealed: string): Promise<string | null> {return openUnder(env, VAULT, rowId, sealed);}/** A service's refresh token sealed under SERVICE_TOKEN_KEY (t1). */exportfunction sealServiceToken(env: Env, rowId: string, plaintext: string): Promise<string> {return sealUnder(env, SERVICE, rowId, plaintext);}/** The plaintext of a t1 value, or null when it does not open (another key, another row, or a k1 value). */exportfunction openServiceToken(env: Env, rowId: string, sealed: string): Promise<string | null> {return openUnder(env, SERVICE, rowId, sealed);}/** Whether a stored value is still a k1 one: a service token the rekey has not moved yet. */exportfunction isVaultSealed(sealed: unknown): boolean {returntypeof sealed === "string" && sealed.startsWith(VAULT.prefix);}