- MCP
- blame on this site's /mcp
- CLI
- abso blame server/src/router.ts --version 190 --json
- JSON
- /christopher/abso-core/blame/server/src/router.ts?version=190&format=json
309 linesspeed 96% · codex-capacity-chair 3% · candidates 1%Last change candidates in version 186,
309 lines from 3 changes in 3 versions.
speed150Open server: the project Worker, Durable Object and Artifacts (issue 17)Compare1// The open server's router (index.ts is the Worker's entry). abso's open server: one Worker that anyone deploys to their own Cloudflare account (`cd server && npx wrangler
2// deploy`). Every project is a Durable Object named by the project's name; its shared is pushed out to an Artifacts
3// repo abso-<project>. The routes are the platform's core routes, so the stock client works against it:
4//
5// GET /version the deployed version's tag; no token needed
6// /p/<project>/<read or init> init, status, log, show, file, blame, feed and the other reads (http.ts)
7// /p/<project>/a/<agent>/<op> an agent's calls: record, publish, sync, draft, land, announce, ...
8// GET /p/<project>/head shared's newest version, read from storage without loading the project
9// PUT|GET /p/<project>/blobs/<sha256> a binary file's bytes; a PUT whose bytes don't hash to the name is refused
10// GET /p/<project>/out the push out to Artifacts: repo, last version pushed, plain-git intake
11// POST /p/<project>/git-remote the repo's remote and a write token good for an hour, for plain git
12// POST /p/<project>/git-sync takes in commits pushed with plain git now (the alarm also does)
13// GET /p/<project>/export?from=&limit= the log as JSON lines, for backups
14// /issues/p/<project>/... issues, asks and news (issues-entry.ts)
15// GET|POST /admin/agent-keys?project= per-agent keys: list, or issue (?agent=&role=&expires=); POST .../revoke?id=
16//
17// Every route but /version needs Authorization: Bearer <ABSO_TOKEN>, or an agent's key when AGENT_KEYS is on. With no
18// ABSO_TOKEN set, the server refuses every call.
20import { type Answer, validName } from "../../worker/project/http.ts";
21import { artifactsOf, type Env, secret } from "./env.ts";
22import type { IssuesAuth, issuesFetch } from "./issues-entry.ts";
23import { isAgentKey, type KeyRole, keyAllows, keysEnabled, timingSame } from "./keys.ts";
24import type { KeyForCall } from "./project-object.ts";
25import { repoName, writeAccess } from "./push.ts";
27const AGENT_OPS =
28 "edit|record|publish|sync|draft|draft-sync|land|pluck|amend|diff|restore|drop|label|announce|news|note|note-close|move|starting|reader|files|status|unqueue";
29const TOP_ROUTES =
30 "init|status|head|out|export|blobs/[^/]+|git-sync|git-remote|blame|why|tree|path|follow|collisions|draft-state|where|feed|drafts|diff|ribbon|position|changes|notes|change/[0-9]{1,12}|refusals|labels|files|announce|log|show|file|compare|visibility|ci|queue";
32/** A project's routes: the project, the top-level route, and an agent's name and op under /a/. */
33export const PROJECT_ROUTE = new RegExp(`^/p/([^/]+)/(${TOP_ROUTES}|a/([^/]+)/(${AGENT_OPS}))$`);
34/** Issues, asks and news: the project and the rest of the path, handed to the issues code. */
35export const ISSUES_ROUTE = /^\/issues\/p\/([^/]+)(\/.*)?$/;
37/** Routes answered here or by a direct object method, not through the project call. */
38const DIRECT = new Set(["head", "out", "export", "git-remote", "git-sync", "ci", "queue", "visibility"]);
39/** Reads whose query string is the call's body. */
40const QUERY_READS = new Set([
41 "status",
42 "blame",
43 "why",
44 "tree",
45 "path",
46 "follow",
47 "collisions",
48 "draft-state",
49 "refusals",
50 "labels",
51 "log",
52 "show",
53 "file",
54 "files",
55 "compare",
candidates186Read a version of shared without some earlier versions: abso show <N> --without A,B shows what differs and abso export <dir> --version N --without A,B writes the files. The server's GET without?version=&versions= checks the set left exactly as asked: when a version it keeps builds on one left out, it refuses with that chain, the files and the wider set that works, and never widens it. Atoms keep their ids and authors; shared and its log don't change; the same ask gives the same tree hash.Compare56 "without",
58 "feed",
59 "drafts",
60 "diff",
61 "ribbon",
62 "position",
63 "changes",
64 "notes",
65]);
66const SHA = /^[0-9a-f]{64}$/;
68const json = (status: number, body: unknown) =>
69 Response.json(body, { status, headers: { "cache-control": "no-store" } });
71/** Whether two secrets match, in constant time whatever their lengths: their SHA-256 digests are compared. */
72export async function sameSecret(a: string, b: string): Promise<boolean> {
73 const digest = async (s: string) =>
74 [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)))]
75 .map((n) => n.toString(16).padStart(2, "0"))
76 .join("");
77 return timingSame(await digest(a), await digest(b));
78}
80export type Caller = { kind: "token" } | { kind: "key"; presented: string };
82/**
83 * Who is calling: the shared token, or an agent key to be checked by its project. A Response is a refusal. With no
84 * shared token set, everything is refused.
85 */
86export async function authorize(request: Request, env: Env): Promise<Caller | Response> {
87 const shared = secret(env, "TOKEN");
88 if (!shared)
89 return json(503, {
90 error:
91 "this server has no ABSO_TOKEN set, so it refuses every call; set one with npx wrangler secret put ABSO_TOKEN",
92 });
93 const presented = (request.headers.get("authorization") ?? "").replace(/^Bearer /, "");
94 if (presented && isAgentKey(presented) && keysEnabled(env)) return { kind: "key", presented };
95 if (presented && (await sameSecret(presented, shared))) return { kind: "token" };
96 return json(401, { error: "missing or wrong token" });
97}
99/** The x-abso-admin header against ABSO_ADMIN_TOKEN, in constant time. */
100async function isAdmin(request: Request, env: Env): Promise<boolean> {
101 const token = secret(env, "ADMIN_TOKEN");
102 const sent = request.headers.get("x-abso-admin") ?? request.headers.get("x-avcs-admin");
103 return !!token && !!sent && (await sameSecret(sent, token));
104}
106const addressOf = (request: Request) => request.headers.get("cf-connecting-ip") ?? "unknown";
107const projectObject = (env: Env, project: string) => env.PROJECT.get(env.PROJECT.idFromName(project));
109/** Per-agent keys for one project: list (GET), issue (POST ?agent=&role=&expires=), revoke (POST .../revoke?id=). */
110async function agentKeys(request: Request, env: Env, url: URL, caller: Caller): Promise<Response> {
111 if (!keysEnabled(env))
112 return json(404, { error: "agent keys are off here: AGENT_KEYS=on and KEY_HMAC_SECRET turn them on" });
113 if (caller.kind !== "token") return json(401, { error: "missing or wrong token" });
114 if (!(await isAdmin(request, env))) return json(403, { error: "agent keys need x-abso-admin: <the admin token>" });
115 const project = url.searchParams.get("project") ?? "";
116 if (!validName(project)) return json(400, { error: "agent keys need ?project=<name>" });
117 const obj = projectObject(env, project);
118 if (url.pathname === "/admin/agent-keys/revoke") {
119 if (request.method !== "POST") return json(405, { error: "revoking a key is a POST" });
120 return json(200, await obj.revokeAgentKey(url.searchParams.get("id") ?? "", addressOf(request)));
121 }
122 if (request.method === "GET")
123 return json(200, { keys: await obj.listAgentKeys(url.searchParams.get("agent") ?? undefined) });
124 if (request.method !== "POST") return json(405, { error: "agent keys take GET or POST" });
125 const agent = url.searchParams.get("agent") ?? "";
126 if (!validName(agent)) return json(400, { error: "issuing a key needs ?agent=<name>" });
127 const role = url.searchParams.get("role") ?? "writer";
128 if (role !== "owner" && role !== "writer" && role !== "reader")
129 return json(400, { error: "role is owner, writer or reader" });
130 const issued = await obj.issueAgentKey(agent, addressOf(request), url.searchParams.get("expires"), role);
131 return "error" in issued ? json(400, issued) : json(200, issued);
132}
134/** The engine's ci and queue reads, for a server with neither: empty, so status and log say nothing about them. */
135const NO_CI = { latest: null, checked: null, running: null, red: null, behind: null };
136const NO_QUEUE = { items: [], paused: null };
138async function projectRoute(
139 request: Request,
140 env: Env,
141 url: URL,
142 caller: Caller,
143 match: RegExpExecArray,
144): Promise<Response> {
145 const [, project, top, agent, op] = match as unknown as [
146 string,
147 string,
148 string,
149 string | undefined,
150 string | undefined,
151 ];
152 if (!validName(project)) return json(400, { error: "project names use letters, digits, '.', '_' and '-'" });
153 const obj = projectObject(env, project);
154 const route = agent === undefined ? top : op;
155 const write = request.method !== "GET" && request.method !== "HEAD";
156 const blob = top.startsWith("blobs/");
157 let keyForCall: KeyForCall | undefined;
158 let how: string | undefined;
159 if (caller.kind === "key") {
160 if (DIRECT.has(top) || blob) {
161 const decided = await obj.checkAgentKey(caller.presented, agent, addressOf(request));
162 if (!decided.ok) return json(decided.status, { error: decided.error });
163 const allowed = keyAllows(decided.role, { write, agent, route, method: request.method });
164 if (!allowed.ok) return json(allowed.status, { error: allowed.error });
165 how = decided.as;
166 } else keyForCall = { presented: caller.presented, address: addressOf(request), write, route };
167 }
169 if (top === "head") {
170 if (request.method !== "GET") return json(405, { error: "head is a GET" });
171 const head = await obj.head();
172 return head ? json(200, head) : json(404, { error: "no such project; run init first" });
173 }
174 if (top === "out") return json(200, await obj.out());
175 if (top === "ci") return json(200, NO_CI);
176 if (top === "queue") return json(200, NO_QUEUE);
177 if (top === "visibility") {
178 if (request.method !== "GET")
179 return json(400, { error: "every project on this server is private: it answers only its token and keys" });
180 return json(200, { project, visibility: "private" });
181 }
182 if (blob) {
183 const sha = top.slice("blobs/".length);
184 if (!SHA.test(sha)) return json(400, { error: "a blob's name is its SHA-256 in lowercase hex" });
185 if (request.method === "PUT") {
186 if (!request.body) return json(400, { error: "PUT the blob's bytes as the body" });
187 const a = (await obj.putBlob(sha, request.body)) as unknown as Answer;
188 return json(a.status, a.body);
189 }
190 if (request.method !== "GET") return json(405, { error: "blobs take GET or PUT" });
191 const bytes = await obj.getBlob(sha);
192 if (!bytes) return json(404, { error: `no blob ${sha} in this project` });
193 return new Response(bytes, {
194 headers: { "content-type": "application/octet-stream", "cache-control": "private, max-age=31536000, immutable" },
195 });
196 }
197 if (top === "export") {
198 const from = Number(url.searchParams.get("from") ?? "0");
199 const limit = Number(url.searchParams.get("limit") ?? "500");
200 if (!Number.isInteger(from) || from < 0 || !Number.isInteger(limit) || limit < 1 || limit > 5000)
201 return json(400, { error: "export takes ?from=<seq>&limit=<1-5000>" });
202 const page = await obj.exportLog(from, limit);
203 if (page === null) return json(404, { error: "no such project; run init first" });
204 return new Response(page.lines, {
205 headers: {
206 "content-type": "application/x-ndjson",
207 "x-abso-next": page.next === null ? "" : String(page.next),
208 "cache-control": "no-store",
209 },
210 });
211 }
212 if (top === "git-remote") {
213 // For a person who works with plain git: clone, commit, push; the project takes the commits in.
214 if (request.method !== "POST") return json(405, { error: "git-remote is a POST" });
215 const artifacts = artifactsOf(env);
216 if (!artifacts) return json(501, { error: "this server has no Artifacts binding, so no git remote" });
217 if ((await obj.head()) === null) return json(404, { error: "no such project; run init first" });
218 const { remote, secret: token } = await writeAccess(artifacts, repoName(project), 3600);
219 // The token goes in a header for each git call, never in the remote URL or a credential store.
220 const header = `Authorization: Basic ${btoa(`x:${token}`)}`;
221 const git = `git -c credential.helper= -c http.extraHeader="${header}"`;
222 return json(200, {
223 remote,
224 token,
225 expiresIn: 3600,
226 header,
227 clone: `${git} clone ${remote}`,
228 fetch: `${git} fetch`,
229 push: `${git} push`,
230 });
231 }
232 if (top === "git-sync") {
233 if (request.method !== "POST") return json(405, { error: "git-sync is a POST" });
234 try {
235 return json(200, { taken: await obj.gitSync() });
236 } catch (e) {
237 return json(502, { error: `could not read the project's repo: ${e instanceof Error ? e.message : String(e)}` });
238 }
239 }
241 let body: unknown;
242 if (request.method === "POST") {
243 const text = await request.text();
244 if (text) {
245 try {
246 body = JSON.parse(text);
247 } catch {
248 return json(400, { error: "the body must be JSON" });
249 }
250 }
251 } else if (request.method === "GET" && (QUERY_READS.has(route ?? "") || top.startsWith("change/"))) {
252 body = Object.fromEntries(url.searchParams);
253 } else return json(405, { error: `${route} is a POST` });
254 // Which client sent a recording goes in the log with it.
255 if ((op === "edit" || op === "record") && body && typeof body === "object") {
256 const client = request.headers.get("x-abso-client") ?? request.headers.get("x-avcs-client") ?? "";
257 const { client: _, ...rest } = body as Record<string, unknown>;
258 body = { ...rest, ...(/^[\w.+-]{1,20}\/[\w.+-]{1,40}$/.test(client) ? { client } : {}) };
259 }
260 try {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare261 const a = (await obj.call(
262 project,
263 (op ?? top)!,
264 agent,
265 body,
266 false,
267 how,
268 keyForCall,
269 request.headers.get("Idempotency-Key") ?? undefined,
270 )) as unknown as Answer;
speed150Open server: the project Worker, Durable Object and Artifacts (issue 17)Compare271 return json(a.status, a.body);
272 } catch (e) {
273 const error = `the project object failed: ${e instanceof Error ? e.message : String(e)}`;
274 console.error(`${project} ${op ?? top}: ${error}`);
275 return json(500, { error });
276 }
277}
279/** One request. The issues code comes in as an argument, so this file loads without the Workers runtime (tests). */
280export async function handle(
281 request: Request,
282 env: Env,
283 ctx: ExecutionContext,
284 issues: typeof issuesFetch,
285): Promise<Response> {
286 const url = new URL(request.url);
287 if (url.pathname === "/version") return json(200, { commit: env.CF_VERSION_METADATA?.tag || null });
288 const caller = await authorize(request, env);
289 if (caller instanceof Response) return caller;
290 if (url.pathname === "/")
291 return new Response("abso: agent-first version control. The API lives under /p/<project>.\n");
292 if (url.pathname === "/admin/agent-keys" || url.pathname === "/admin/agent-keys/revoke")
293 return agentKeys(request, env, url, caller);
294 const onIssues = ISSUES_ROUTE.exec(url.pathname);
295 if (onIssues) {
296 const project = decodeURIComponent(onIssues[1]!);
297 if (!validName(project)) return json(400, { error: "project names use letters, digits, '.', '_' and '-'" });
298 let auth: IssuesAuth = { kind: "token" };
299 if (caller.kind === "key") {
300 const decided = await projectObject(env, project).checkAgentKey(caller.presented, undefined, addressOf(request));
301 if (!decided.ok) return json(decided.status, { error: decided.error });
302 auth = { kind: "key", agent: decided.agent, role: decided.role as KeyRole };
303 }
304 return issues(request, env, ctx, { project, rest: onIssues[2] ?? "", auth });
305 }
306 const m = PROJECT_ROUTE.exec(url.pathname);
307 if (!m) return json(404, { error: "no such route" });
308 return projectRoute(request, env, url, caller, m);
309}