{"draft":null,"from":73,"to":318,"files":[{"path":"server/src/keys.ts","added":253,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/keys.ts\n@@ -0,0 +1,253 @@\n+// Per-agent keys, ported from the platform's worker/src/keys.ts. They run when AGENT_KEYS is \"on\" and\n+// KEY_HMAC_SECRET is set. Each key belongs to one agent of one project; the project's Durable Object keeps only the\n+// key's HMAC, never the key. Without keys, the shared token (ABSO_TOKEN) is the only way in.\n+\n+export const KEY_PREFIX = \"abso_sk_\";\n+const FAIL_LIMIT = 8;\n+const FAIL_WINDOW_MS = 10 * 60 * 1000;\n+const AUDIT_CAP = 200;\n+const DAY_MS = 24 * 60 * 60 * 1000;\n+\n+export interface KeyEnv {\n+\tAGENT_KEYS?: string;\n+\tKEY_HMAC_SECRET?: string;\n+}\n+\n+/** What a key may do in its project: the admin's choice when it was issued. */\n+export type KeyRole = \"owner\" | \"writer\" | \"reader\";\n+\n+export interface KeyRow {\n+\tid: string;\n+\thmac: string;\n+\tagent: string;\n+\tissuedBy: string;\n+\tat: number;\n+\tlastUsed: number | null;\n+\trevokedAt: number | null;\n+\texpiresAt?: number | null;\n+\t/** Absent on a key issued before roles existed: it counts as reader, so it fails closed. */\n+\trole?: KeyRole;\n+}\n+\n+export interface FailRow {\n+\tn: number;\n+\tat: number;\n+}\n+\n+export interface AuditRow {\n+\tt: number;\n+\tkind: \"issue\" | \"revoke\" | \"use\" | \"fail\";\n+\tid: string | null;\n+\taddr: string;\n+}\n+\n+export interface KeyState {\n+\trows: KeyRow[];\n+\tfails: Record<string, FailRow>;\n+\tseen: Record<string, string>;\n+\taudit: AuditRow[];\n+}\n+\n+export function emptyKeyState(): KeyState {\n+\treturn { rows: [], fails: {}, seen: {}, audit: [] };\n+}\n+\n+/** Keys run when the switch and the secret are both set. */\n+export function keysEnabled(env: KeyEnv): boolean {\n+\treturn env.AGENT_KEYS === \"on\" && !!env.KEY_HMAC_SECRET;\n+}\n+\n+/** 90 days when omitted. 1d to 365d otherwise. */\n+export function expiresAt(now: number, raw: string | null): number | { error: string } {\n+\tif (raw === null || raw === \"\") return now + 90 * DAY_MS;\n+\tconst match = /^(\\d+)d$/.exec(raw);\n+\tif (!match) return { error: \"expires is a number of days, like 7d, from 1d to 365d\" };\n+\tconst days = Number(match[1]);\n+\tif (days < 1 || days > 365) return { error: \"expires is from 1d to 365d\" };\n+\treturn now + days * DAY_MS;\n+}\n+\n+export function isAgentKey(presented: string | undefined): boolean {\n+\treturn typeof presented === \"string\" && presented.startsWith(KEY_PREFIX) && presented.length > KEY_PREFIX.length;\n+}\n+\n+export async function hmac(secret: string, message: string): Promise<string> {\n+\tconst key = await crypto.subtle.importKey(\n+\t\t\"raw\",\n+\t\tnew TextEncoder().encode(secret),\n+\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n+\t\tfalse,\n+\t\t[\"sign\"],\n+\t);\n+\tconst mac = new Uint8Array(await crypto.subtle.sign(\"HMAC\", key, new TextEncoder().encode(message)));\n+\treturn [...mac].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n+}\n+\n+/** Whether two strings are equal, taking the same time wherever they differ. */\n+export function timingSame(a: string, b: string): boolean {\n+\tif (a.length !== b.length) return false;\n+\tlet diff = 0;\n+\tfor (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n+\treturn diff === 0;\n+}\n+\n+function randomHex(bytes: number): string {\n+\tconst b = new Uint8Array(bytes);\n+\tcrypto.getRandomValues(b);\n+\treturn [...b].map((n) => n.toString(16).padStart(2, \"0\")).join(\"\");\n+}\n+\n+export function newKey(): { id: string; key: string } {\n+\tconst raw = new Uint8Array(32);\n+\tcrypto.getRandomValues(raw);\n+\tconst body = btoa(String.fromCharCode(...raw))\n+\t\t.replaceAll(\"+\", \"-\")\n+\t\t.replaceAll(\"/\", \"_\")\n+\t\t.replace(/=+$/, \"\");\n+\treturn { id: `k_${randomHex(4)}`, key: `${KEY_PREFIX}${body}` };\n+}\n+\n+function note(state: KeyState, row: AuditRow): void {\n+\tstate.audit.push(row);\n+\tif (state.audit.length > AUDIT_CAP) state.audit.splice(0, state.audit.length - AUDIT_CAP);\n+}\n+\n+export interface Issued {\n+\tid: string;\n+\tkey: string;\n+\tagent: string;\n+}\n+\n+/** Issues a key. The returned value is the only copy; the state keeps the HMAC. */\n+export async function issueKey(\n+\tstate: KeyState,\n+\tsecret: string,\n+\tagent: string,\n+\tby: string,\n+\tnow: number,\n+\taddress: string,\n+\texpires: number,\n+\trole: KeyRole,\n+): Promise<Issued> {\n+\tconst made = newKey();\n+\tconst addr = await hmac(secret, address);\n+\tstate.rows.push({\n+\t\tid: made.id,\n+\t\thmac: await hmac(secret, made.key),\n+\t\tagent,\n+\t\tissuedBy: by,\n+\t\tat: now,\n+\t\tlastUsed: null,\n+\t\trevokedAt: null,\n+\t\texpiresAt: expires,\n+\t\trole,\n+\t});\n+\tnote(state, { t: now, kind: \"issue\", id: made.id, addr });\n+\treturn { id: made.id, key: made.key, agent };\n+}\n+\n+export function revokeKey(state: KeyState, id: string, now: number, addr: string): boolean {\n+\tconst row = state.rows.find((r) => r.id === id);\n+\tif (!row || row.revokedAt !== null) return false;\n+\trow.revokedAt = now;\n+\tnote(state, { t: now, kind: \"revoke\", id, addr });\n+\treturn true;\n+}\n+\n+export function listKeys(state: KeyState, agent?: string) {\n+\treturn state.rows\n+\t\t.filter((r) => agent === undefined || r.agent === agent)\n+\t\t.map(({ id, agent: a, issuedBy, at, lastUsed, revokedAt, expiresAt: exp, role }) => ({\n+\t\t\tid,\n+\t\t\tagent: a,\n+\t\t\trole: role ?? \"reader\",\n+\t\t\tissuedBy,\n+\t\t\tat,\n+\t\t\tlastUsed,\n+\t\t\trevokedAt,\n+\t\t\texpiresAt: exp ?? null,\n+\t\t}));\n+}\n+\n+export type KeyDecision =\n+\t| { ok: true; id: string; as: string; role: KeyRole; dirty: boolean }\n+\t| { ok: false; status: number; error: string; dirty: boolean };\n+\n+/**\n+ * Checks a presented key against one project. The URL's agent must match the key's agent: a mismatch is a 403, and\n+ * the agent is not rewritten. A missing secret is a 503 that names no key. Failures are counted per address and\n+ * slowed after a few. Nothing returned or recorded contains the key.\n+ */\n+export async function checkKey(\n+\tstate: KeyState,\n+\tsecret: string | undefined,\n+\tpresented: string,\n+\tagent: string | undefined,\n+\tnow: number,\n+\taddress: string,\n+): Promise<KeyDecision> {\n+\tif (!secret) return { ok: false, status: 503, error: \"the key secret (KEY_HMAC_SECRET) is not set\", dirty: false };\n+\tconst addr = await hmac(secret, address);\n+\tconst fail = state.fails[addr];\n+\tif (fail && now - fail.at < FAIL_WINDOW_MS && fail.n >= FAIL_LIMIT) {\n+\t\treturn { ok: false, status: 429, error: \"too many failed keys; try again shortly\", dirty: false };\n+\t}\n+\tconst mac = await hmac(secret, presented);\n+\tconst row = state.rows.find((r) => timingSame(r.hmac, mac));\n+\tconst bump = () => {\n+\t\tconst cur = state.fails[addr];\n+\t\tstate.fails[addr] = !cur || now - cur.at >= FAIL_WINDOW_MS ? { n: 1, at: now } : { n: cur.n + 1, at: cur.at };\n+\t\tnote(state, { t: now, kind: \"fail\", id: row?.id ?? null, addr });\n+\t};\n+\tif (!row || row.revokedAt !== null || (row.expiresAt != null && now >= row.expiresAt)) {\n+\t\tbump();\n+\t\tconst error = !row\n+\t\t\t? \"that key is not for this project\"\n+\t\t\t: row.revokedAt !== null\n+\t\t\t\t? \"that key was revoked\"\n+\t\t\t\t: \"that key has expired\";\n+\t\treturn { ok: false, status: 403, error, dirty: true };\n+\t}\n+\tif (agent !== undefined && row.agent !== agent) {\n+\t\tbump();\n+\t\treturn { ok: false, status: 403, error: \"that key is not for this agent\", dirty: true };\n+\t}\n+\tlet dirty = false;\n+\tif (state.fails[addr]) {\n+\t\tdelete state.fails[addr];\n+\t\tdirty = true;\n+\t}\n+\tif (state.seen[row.id] !== addr) {\n+\t\tstate.seen[row.id] = addr;\n+\t\tnote(state, { t: now, kind: \"use\", id: row.id, addr });\n+\t\tdirty = true;\n+\t}\n+\tif (row.lastUsed === null || now - row.lastUsed >= 60_000) {\n+\t\trow.lastUsed = now;\n+\t\tdirty = true;\n+\t}\n+\treturn { ok: true, id: row.id, as: `key ${row.id}`, role: row.role ?? \"reader\", dirty };\n+}\n+\n+/** Project routes only an owner's key may use, whatever the method. */\n+const OWNER_ONLY = new Set([\"git-remote\", \"git-sync\", \"export\"]);\n+\n+/**\n+ * Whether a key's role allows a request. A reader only reads. A writer also writes, but only on its own agent's\n+ * routes (/a/:agent/..., where checkKey has matched the agent), and blob uploads, which a record needs. Owner-only\n+ * routes need an owner's key.\n+ */\n+export function keyAllows(\n+\trole: KeyRole,\n+\trequest: { write: boolean; agent: string | undefined; route: string | undefined; method?: string },\n+): { ok: true } | { ok: false; status: number; error: string } {\n+\tif (role === \"owner\") return { ok: true };\n+\tif (request.route !== undefined && OWNER_ONLY.has(request.route))\n+\t\treturn { ok: false, status: 403, error: `${request.route} needs an owner's key` };\n+\tif (!request.write) return { ok: true };\n+\tif (role === \"reader\") return { ok: false, status: 403, error: \"this key only reads\" };\n+\tif (request.method === \"PUT\" && /^blobs\\/[0-9a-f]{64}$/.test(request.route ?? \"\")) return { ok: true };\n+\tif (request.agent === undefined)\n+\t\treturn { ok: false, status: 403, error: \"a writer's key writes only on its own agent's routes\" };\n+\treturn { ok: true };\n+}"}],"unmatched":[]}