Versions 30 to 318
new file, 253 lines
1+// Per-agent keys, ported from the platform's worker/src/keys.ts. They run when AGENT_KEYS is "on" and 2+// KEY_HMAC_SECRET is set. Each key belongs to one agent of one project; the project's Durable Object keeps only the 3+// key's HMAC, never the key. Without keys, the shared token (ABSO_TOKEN) is the only way in. 5+export const KEY_PREFIX = "abso_sk_"; 7+const FAIL_WINDOW_MS = 10 * 60 * 1000; 9+const DAY_MS = 24 * 60 * 60 * 1000; 11+export interface KeyEnv { 13+ KEY_HMAC_SECRET?: string; 16+/** What a key may do in its project: the admin's choice when it was issued. */ 17+export type KeyRole = "owner" | "writer" | "reader"; 19+export interface KeyRow { 25+ lastUsed: number | null; 26+ revokedAt: number | null; 27+ expiresAt?: number | null; 28+ /** Absent on a key issued before roles existed: it counts as reader, so it fails closed. */ 32+export interface FailRow { 37+export interface AuditRow { 39+ kind: "issue" | "revoke" | "use" | "fail"; 44+export interface KeyState { 46+ fails: Record<string, FailRow>; 47+ seen: Record<string, string>; 51+export function emptyKeyState(): KeyState { 52+ return { rows: [], fails: {}, seen: {}, audit: [] }; 55+/** Keys run when the switch and the secret are both set. */ 56+export function keysEnabled(env: KeyEnv): boolean { 57+ return env.AGENT_KEYS === "on" && !!env.KEY_HMAC_SECRET; 60+/** 90 days when omitted. 1d to 365d otherwise. */ 61+export function expiresAt(now: number, raw: string | null): number | { error: string } { 62+ if (raw === null || raw === "") return now + 90 * DAY_MS; 63+ const match = /^(\d+)d$/.exec(raw); 64+ if (!match) return { error: "expires is a number of days, like 7d, from 1d to 365d" }; 65+ const days = Number(match[1]); 66+ if (days < 1 || days > 365) return { error: "expires is from 1d to 365d" }; 67+ return now + days * DAY_MS; 70+export function isAgentKey(presented: string | undefined): boolean { 71+ return typeof presented === "string" && presented.startsWith(KEY_PREFIX) && presented.length > KEY_PREFIX.length; 74+export async function hmac(secret: string, message: string): Promise<string> { 75+ const key = await crypto.subtle.importKey( 77+ new TextEncoder().encode(secret), 78+ { name: "HMAC", hash: "SHA-256" }, 82+ const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(message))); 83+ return [...mac].map((b) => b.toString(16).padStart(2, "0")).join(""); 86+/** Whether two strings are equal, taking the same time wherever they differ. */ 87+export function timingSame(a: string, b: string): boolean { 88+ if (a.length !== b.length) return false; 90+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i); 94+function randomHex(bytes: number): string { 95+ const b = new Uint8Array(bytes); 96+ crypto.getRandomValues(b); 97+ return [...b].map((n) => n.toString(16).padStart(2, "0")).join(""); 100+export function newKey(): { id: string; key: string } { 101+ const raw = new Uint8Array(32); 102+ crypto.getRandomValues(raw); 103+ const body = btoa(String.fromCharCode(...raw)) 104+ .replaceAll("+", "-") 105+ .replaceAll("/", "_") 106+ .replace(/=+$/, ""); 107+ return { id: `k_${randomHex(4)}`, key: `${KEY_PREFIX}${body}` }; 110+function note(state: KeyState, row: AuditRow): void { 111+ state.audit.push(row); 112+ if (state.audit.length > AUDIT_CAP) state.audit.splice(0, state.audit.length - AUDIT_CAP); 115+export interface Issued { 121+/** Issues a key. The returned value is the only copy; the state keeps the HMAC. */ 122+export async function issueKey( 132+ const made = newKey(); 133+ const addr = await hmac(secret, address); 136+ hmac: await hmac(secret, made.key), 145+ note(state, { t: now, kind: "issue", id: made.id, addr }); 146+ return { id: made.id, key: made.key, agent }; 149+export function revokeKey(state: KeyState, id: string, now: number, addr: string): boolean { 150+ const row = state.rows.find((r) => r.id === id); 151+ if (!row || row.revokedAt !== null) return false; 152+ row.revokedAt = now; 153+ note(state, { t: now, kind: "revoke", id, addr }); 157+export function listKeys(state: KeyState, agent?: string) { 159+ .filter((r) => agent === undefined || r.agent === agent) 160+ .map(({ id, agent: a, issuedBy, at, lastUsed, revokedAt, expiresAt: exp, role }) => ({ 163+ role: role ?? "reader", 168+ expiresAt: exp ?? null, 172+export type KeyDecision = 173+ | { ok: true; id: string; as: string; role: KeyRole; dirty: boolean } 174+ | { ok: false; status: number; error: string; dirty: boolean }; 177+ * Checks a presented key against one project. The URL's agent must match the key's agent: a mismatch is a 403, and 178+ * the agent is not rewritten. A missing secret is a 503 that names no key. Failures are counted per address and 179+ * slowed after a few. Nothing returned or recorded contains the key. 181+export async function checkKey( 183+ secret: string | undefined, 185+ agent: string | undefined, 188+): Promise<KeyDecision> { 189+ if (!secret) return { ok: false, status: 503, error: "the key secret (KEY_HMAC_SECRET) is not set", dirty: false }; 190+ const addr = await hmac(secret, address); 191+ const fail = state.fails[addr]; 192+ if (fail && now - fail.at < FAIL_WINDOW_MS && fail.n >= FAIL_LIMIT) { 193+ return { ok: false, status: 429, error: "too many failed keys; try again shortly", dirty: false }; 195+ const mac = await hmac(secret, presented); 196+ const row = state.rows.find((r) => timingSame(r.hmac, mac)); 197+ const bump = () => { 198+ const cur = state.fails[addr]; 199+ state.fails[addr] = !cur || now - cur.at >= FAIL_WINDOW_MS ? { n: 1, at: now } : { n: cur.n + 1, at: cur.at }; 200+ note(state, { t: now, kind: "fail", id: row?.id ?? null, addr }); 202+ if (!row || row.revokedAt !== null || (row.expiresAt != null && now >= row.expiresAt)) { 205+ ? "that key is not for this project" 206+ : row.revokedAt !== null 207+ ? "that key was revoked" 208+ : "that key has expired"; 209+ return { ok: false, status: 403, error, dirty: true }; 211+ if (agent !== undefined && row.agent !== agent) { 213+ return { ok: false, status: 403, error: "that key is not for this agent", dirty: true }; 216+ if (state.fails[addr]) { 217+ delete state.fails[addr]; 220+ if (state.seen[row.id] !== addr) { 221+ state.seen[row.id] = addr; 222+ note(state, { t: now, kind: "use", id: row.id, addr }); 225+ if (row.lastUsed === null || now - row.lastUsed >= 60_000) { 229+ return { ok: true, id: row.id, as: `key ${row.id}`, role: row.role ?? "reader", dirty }; 232+/** Project routes only an owner's key may use, whatever the method. */ 233+const OWNER_ONLY = new Set(["git-remote", "git-sync", "export"]); 236+ * Whether a key's role allows a request. A reader only reads. A writer also writes, but only on its own agent's 237+ * routes (/a/:agent/..., where checkKey has matched the agent), and blob uploads, which a record needs. Owner-only 238+ * routes need an owner's key. 240+export function keyAllows( 242+ request: { write: boolean; agent: string | undefined; route: string | undefined; method?: string }, 243+): { ok: true } | { ok: false; status: number; error: string } { 244+ if (role === "owner") return { ok: true }; 245+ if (request.route !== undefined && OWNER_ONLY.has(request.route)) 246+ return { ok: false, status: 403, error: `${request.route} needs an owner's key` }; 247+ if (!request.write) return { ok: true }; 248+ if (role === "reader") return { ok: false, status: 403, error: "this key only reads" }; 249+ if (request.method === "PUT" && /^blobs\/[0-9a-f]{64}$/.test(request.route ?? "")) return { ok: true }; 250+ if (request.agent === undefined) 251+ return { ok: false, status: 403, error: "a writer's key writes only on its own agent's routes" }; 252+ return { ok: true };