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 149 to 150

Compare

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