Cotton code
97 lines · 4.2 KB · TypeScriptRaw
/** * 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. */import type { Env } from "./env.ts";import { fromBase64Url, toBase64Url } from "./base64.ts";export { fromBase64Url, toBase64Url };import { refuse } from "./http.ts";interface Lock {  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" };async function 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"]);}async function sealUnder(env: Env, lock: Lock, rowId: string, plaintext: string): Promise<string> {  const nonce = crypto.getRandomValues(new Uint8Array(12));  const ct = new Uint8Array(    await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: new TextEncoder().encode(`${lock.aad}${rowId}`) }, await key(env, lock), new TextEncoder().encode(plaintext)),  );  const body = new Uint8Array(nonce.length + ct.length);  body.set(nonce, 0);  body.set(ct, nonce.length);  return lock.prefix + toBase64Url(body);}async function openUnder(env: Env, lock: Lock, rowId: string, sealed: string): Promise<string | null> {  if (!sealed.startsWith(lock.prefix)) return null;  const k = await key(env, lock);  let body: Uint8Array;  try {    body = fromBase64Url(sealed.slice(lock.prefix.length));  } catch {    return null;  }  if (body.length < 12 + 16) return null;  try {    const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv: body.slice(0, 12), additionalData: new TextEncoder().encode(`${lock.aad}${rowId}`) }, k, body.slice(12));    return new TextDecoder().decode(pt);  } catch {    return null;  }}/** A saved secret's value sealed under VAULT_KEY (k1). */export function 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. */export function 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). */export function 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). */export function 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. */export function isVaultSealed(sealed: unknown): boolean {  return typeof sealed === "string" && sealed.startsWith(VAULT.prefix);}