- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/server/src/keys.ts?format=json
253 linesspeed 100%Last change speed in version 150, 1 version changed it
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.
5export const KEY_PREFIX = "abso_sk_";
6const FAIL_LIMIT = 8;
7const FAIL_WINDOW_MS = 10 * 60 * 1000;
8const AUDIT_CAP = 200;
9const DAY_MS = 24 * 60 * 60 * 1000;
11export interface KeyEnv {
12 AGENT_KEYS?: string;
13 KEY_HMAC_SECRET?: string;
14}
16/** What a key may do in its project: the admin's choice when it was issued. */
17export type KeyRole = "owner" | "writer" | "reader";
19export interface KeyRow {
20 id: string;
21 hmac: string;
22 agent: string;
23 issuedBy: string;
24 at: number;
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. */
29 role?: KeyRole;
30}
32export interface FailRow {
33 n: number;
34 at: number;
35}
37export interface AuditRow {
38 t: number;
39 kind: "issue" | "revoke" | "use" | "fail";
40 id: string | null;
41 addr: string;
42}
44export interface KeyState {
45 rows: KeyRow[];
46 fails: Record<string, FailRow>;
47 seen: Record<string, string>;
48 audit: AuditRow[];
49}
51export function emptyKeyState(): KeyState {
52 return { rows: [], fails: {}, seen: {}, audit: [] };
53}
55/** Keys run when the switch and the secret are both set. */
56export function keysEnabled(env: KeyEnv): boolean {
57 return env.AGENT_KEYS === "on" && !!env.KEY_HMAC_SECRET;
58}
60/** 90 days when omitted. 1d to 365d otherwise. */
61export 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;
68}
70export function isAgentKey(presented: string | undefined): boolean {
71 return typeof presented === "string" && presented.startsWith(KEY_PREFIX) && presented.length > KEY_PREFIX.length;
72}
74export async function hmac(secret: string, message: string): Promise<string> {
75 const key = await crypto.subtle.importKey(
76 "raw",
77 new TextEncoder().encode(secret),
78 { name: "HMAC", hash: "SHA-256" },
79 false,
80 ["sign"],
81 );
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("");
84}
86/** Whether two strings are equal, taking the same time wherever they differ. */
87export function timingSame(a: string, b: string): boolean {
88 if (a.length !== b.length) return false;
89 let diff = 0;
90 for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
91 return diff === 0;
92}
94function 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("");
98}
100export 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}` };
108}
110function 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);
113}
115export interface Issued {
116 id: string;
117 key: string;
118 agent: string;
119}
121/** Issues a key. The returned value is the only copy; the state keeps the HMAC. */
122export async function issueKey(
123 state: KeyState,
124 secret: string,
125 agent: string,
126 by: string,
127 now: number,
128 address: string,
129 expires: number,
130 role: KeyRole,
131): Promise<Issued> {
132 const made = newKey();
133 const addr = await hmac(secret, address);
134 state.rows.push({
135 id: made.id,
136 hmac: await hmac(secret, made.key),
137 agent,
138 issuedBy: by,
139 at: now,
140 lastUsed: null,
141 revokedAt: null,
142 expiresAt: expires,
143 role,
144 });
145 note(state, { t: now, kind: "issue", id: made.id, addr });
146 return { id: made.id, key: made.key, agent };
147}
149export 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 });
154 return true;
155}
157export function listKeys(state: KeyState, agent?: string) {
158 return state.rows
159 .filter((r) => agent === undefined || r.agent === agent)
160 .map(({ id, agent: a, issuedBy, at, lastUsed, revokedAt, expiresAt: exp, role }) => ({
161 id,
162 agent: a,
163 role: role ?? "reader",
164 issuedBy,
165 at,
166 lastUsed,
167 revokedAt,
168 expiresAt: exp ?? null,
169 }));
170}
172export type KeyDecision =
173 | { ok: true; id: string; as: string; role: KeyRole; dirty: boolean }
174 | { ok: false; status: number; error: string; dirty: boolean };
176/**
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.
180 */
181export async function checkKey(
182 state: KeyState,
183 secret: string | undefined,
184 presented: string,
185 agent: string | undefined,
186 now: number,
187 address: string,
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 };
194 }
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 });
201 };
202 if (!row || row.revokedAt !== null || (row.expiresAt != null && now >= row.expiresAt)) {
203 bump();
204 const error = !row
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 };
210 }
211 if (agent !== undefined && row.agent !== agent) {
212 bump();
213 return { ok: false, status: 403, error: "that key is not for this agent", dirty: true };
214 }
215 let dirty = false;
216 if (state.fails[addr]) {
217 delete state.fails[addr];
218 dirty = true;
219 }
220 if (state.seen[row.id] !== addr) {
221 state.seen[row.id] = addr;
222 note(state, { t: now, kind: "use", id: row.id, addr });
223 dirty = true;
224 }
225 if (row.lastUsed === null || now - row.lastUsed >= 60_000) {
226 row.lastUsed = now;
227 dirty = true;
228 }
229 return { ok: true, id: row.id, as: `key ${row.id}`, role: row.role ?? "reader", dirty };
230}
232/** Project routes only an owner's key may use, whatever the method. */
233const OWNER_ONLY = new Set(["git-remote", "git-sync", "export"]);
235/**
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.
239 */
240export function keyAllows(
241 role: KeyRole,
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 };
253}