Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed

Versions 32 to 318

Compare

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