{"draft":null,"from":2,"to":318,"files":[{"path":"server/src/router.ts","added":311,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/router.ts\n@@ -0,0 +1,311 @@\n+// 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\n+// deploy`). Every project is a Durable Object named by the project's name; its shared is pushed out to an Artifacts\n+// repo abso-<project>. The routes are the platform's core routes, so the stock client works against it:\n+//\n+//   GET  /version                          the deployed version's tag; no token needed\n+//   /p/<project>/<read or init>            init, status, log, show, file, blame, feed and the other reads (http.ts)\n+//   /p/<project>/a/<agent>/<op>            an agent's calls: record, publish, sync, draft, land, announce, ...\n+//   GET  /p/<project>/head                 shared's newest version, read from storage without loading the project\n+//   PUT|GET /p/<project>/blobs/<sha256>    a binary file's bytes; a PUT whose bytes don't hash to the name is refused\n+//   GET  /p/<project>/out                  the push out to Artifacts: repo, last version pushed, plain-git intake\n+//   POST /p/<project>/git-remote           the repo's remote and a write token good for an hour, for plain git\n+//   POST /p/<project>/git-sync             takes in commits pushed with plain git now (the alarm also does)\n+//   GET  /p/<project>/export?from=&limit=  the log as JSON lines, for backups\n+//   /issues/p/<project>/...                issues, asks and news (issues-entry.ts)\n+//   GET|POST /admin/agent-keys?project=    per-agent keys: list, or issue (?agent=&role=&expires=); POST .../revoke?id=\n+//\n+// Every route but /version needs Authorization: Bearer <ABSO_TOKEN>, or an agent's key when AGENT_KEYS is on. With no\n+// ABSO_TOKEN set, the server refuses every call.\n+\n+import { type Answer, validName } from \"../../worker/project/http.ts\";\n+import { withAdvice } from \"./autosettle.ts\";\n+import { artifactsOf, type Env, secret } from \"./env.ts\";\n+import type { IssuesAuth, issuesFetch } from \"./issues-entry.ts\";\n+import { isAgentKey, type KeyRole, keyAllows, keysEnabled, timingSame } from \"./keys.ts\";\n+import type { KeyForCall } from \"./project-object.ts\";\n+import { repoName, writeAccess } from \"./push.ts\";\n+\n+const AGENT_OPS =\n+\t\"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\";\n+const TOP_ROUTES =\n+\t\"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\";\n+\n+/** A project's routes: the project, the top-level route, and an agent's name and op under /a/. */\n+export const PROJECT_ROUTE = new RegExp(`^/p/([^/]+)/(${TOP_ROUTES}|a/([^/]+)/(${AGENT_OPS}))$`);\n+/** Issues, asks and news: the project and the rest of the path, handed to the issues code. */\n+export const ISSUES_ROUTE = /^\\/issues\\/p\\/([^/]+)(\\/.*)?$/;\n+\n+/** Routes answered here or by a direct object method, not through the project call. */\n+const DIRECT = new Set([\"head\", \"out\", \"export\", \"git-remote\", \"git-sync\", \"ci\", \"queue\", \"visibility\"]);\n+/** Reads whose query string is the call's body. */\n+const QUERY_READS = new Set([\n+\t\"status\",\n+\t\"blame\",\n+\t\"why\",\n+\t\"tree\",\n+\t\"path\",\n+\t\"follow\",\n+\t\"collisions\",\n+\t\"draft-state\",\n+\t\"refusals\",\n+\t\"labels\",\n+\t\"log\",\n+\t\"show\",\n+\t\"file\",\n+\t\"files\",\n+\t\"compare\",\n+\t\"without\",\n+\t\"where\",\n+\t\"feed\",\n+\t\"drafts\",\n+\t\"diff\",\n+\t\"ribbon\",\n+\t\"position\",\n+\t\"changes\",\n+\t\"notes\",\n+]);\n+const SHA = /^[0-9a-f]{64}$/;\n+\n+const json = (status: number, body: unknown) =>\n+\tResponse.json(body, { status, headers: { \"cache-control\": \"no-store\" } });\n+\n+/** Whether two secrets match, in constant time whatever their lengths: their SHA-256 digests are compared. */\n+export async function sameSecret(a: string, b: string): Promise<boolean> {\n+\tconst digest = async (s: string) =>\n+\t\t[...new Uint8Array(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(s)))]\n+\t\t\t.map((n) => n.toString(16).padStart(2, \"0\"))\n+\t\t\t.join(\"\");\n+\treturn timingSame(await digest(a), await digest(b));\n+}\n+\n+export type Caller = { kind: \"token\" } | { kind: \"key\"; presented: string };\n+\n+/**\n+ * Who is calling: the shared token, or an agent key to be checked by its project. A Response is a refusal. With no\n+ * shared token set, everything is refused.\n+ */\n+export async function authorize(request: Request, env: Env): Promise<Caller | Response> {\n+\tconst shared = secret(env, \"TOKEN\");\n+\tif (!shared)\n+\t\treturn json(503, {\n+\t\t\terror:\n+\t\t\t\t\"this server has no ABSO_TOKEN set, so it refuses every call; set one with npx wrangler secret put ABSO_TOKEN\",\n+\t\t});\n+\tconst presented = (request.headers.get(\"authorization\") ?? \"\").replace(/^Bearer /, \"\");\n+\tif (presented && isAgentKey(presented) && keysEnabled(env)) return { kind: \"key\", presented };\n+\tif (presented && (await sameSecret(presented, shared))) return { kind: \"token\" };\n+\treturn json(401, { error: \"missing or wrong token\" });\n+}\n+\n+/** The x-abso-admin header against ABSO_ADMIN_TOKEN, in constant time. */\n+async function isAdmin(request: Request, env: Env): Promise<boolean> {\n+\tconst token = secret(env, \"ADMIN_TOKEN\");\n+\tconst sent = request.headers.get(\"x-abso-admin\") ?? request.headers.get(\"x-avcs-admin\");\n+\treturn !!token && !!sent && (await sameSecret(sent, token));\n+}\n+\n+const addressOf = (request: Request) => request.headers.get(\"cf-connecting-ip\") ?? \"unknown\";\n+const projectObject = (env: Env, project: string) => env.PROJECT.get(env.PROJECT.idFromName(project));\n+\n+/** Per-agent keys for one project: list (GET), issue (POST ?agent=&role=&expires=), revoke (POST .../revoke?id=). */\n+async function agentKeys(request: Request, env: Env, url: URL, caller: Caller): Promise<Response> {\n+\tif (!keysEnabled(env))\n+\t\treturn json(404, { error: \"agent keys are off here: AGENT_KEYS=on and KEY_HMAC_SECRET turn them on\" });\n+\tif (caller.kind !== \"token\") return json(401, { error: \"missing or wrong token\" });\n+\tif (!(await isAdmin(request, env))) return json(403, { error: \"agent keys need x-abso-admin: <the admin token>\" });\n+\tconst project = url.searchParams.get(\"project\") ?? \"\";\n+\tif (!validName(project)) return json(400, { error: \"agent keys need ?project=<name>\" });\n+\tconst obj = projectObject(env, project);\n+\tif (url.pathname === \"/admin/agent-keys/revoke\") {\n+\t\tif (request.method !== \"POST\") return json(405, { error: \"revoking a key is a POST\" });\n+\t\treturn json(200, await obj.revokeAgentKey(url.searchParams.get(\"id\") ?? \"\", addressOf(request)));\n+\t}\n+\tif (request.method === \"GET\")\n+\t\treturn json(200, { keys: await obj.listAgentKeys(url.searchParams.get(\"agent\") ?? undefined) });\n+\tif (request.method !== \"POST\") return json(405, { error: \"agent keys take GET or POST\" });\n+\tconst agent = url.searchParams.get(\"agent\") ?? \"\";\n+\tif (!validName(agent)) return json(400, { error: \"issuing a key needs ?agent=<name>\" });\n+\tconst role = url.searchParams.get(\"role\") ?? \"writer\";\n+\tif (role !== \"owner\" && role !== \"writer\" && role !== \"reader\")\n+\t\treturn json(400, { error: \"role is owner, writer or reader\" });\n+\tconst issued = await obj.issueAgentKey(agent, addressOf(request), url.searchParams.get(\"expires\"), role);\n+\treturn \"error\" in issued ? json(400, issued) : json(200, issued);\n+}\n+\n+/** The engine's ci and queue reads, for a server with neither: empty, so status and log say nothing about them. */\n+const NO_CI = { latest: null, checked: null, running: null, red: null, behind: null };\n+const NO_QUEUE = { items: [], paused: null };\n+\n+async function projectRoute(\n+\trequest: Request,\n+\tenv: Env,\n+\turl: URL,\n+\tcaller: Caller,\n+\tmatch: RegExpExecArray,\n+): Promise<Response> {\n+\tconst [, project, top, agent, op] = match as unknown as [\n+\t\tstring,\n+\t\tstring,\n+\t\tstring,\n+\t\tstring | undefined,\n+\t\tstring | undefined,\n+\t];\n+\tif (!validName(project)) return json(400, { error: \"project names use letters, digits, '.', '_' and '-'\" });\n+\tconst obj = projectObject(env, project);\n+\tconst route = agent === undefined ? top : op;\n+\tconst write = request.method !== \"GET\" && request.method !== \"HEAD\";\n+\tconst blob = top.startsWith(\"blobs/\");\n+\tlet keyForCall: KeyForCall | undefined;\n+\tlet how: string | undefined;\n+\tif (caller.kind === \"key\") {\n+\t\tif (DIRECT.has(top) || blob) {\n+\t\t\tconst decided = await obj.checkAgentKey(caller.presented, agent, addressOf(request));\n+\t\t\tif (!decided.ok) return json(decided.status, { error: decided.error });\n+\t\t\tconst allowed = keyAllows(decided.role, { write, agent, route, method: request.method });\n+\t\t\tif (!allowed.ok) return json(allowed.status, { error: allowed.error });\n+\t\t\thow = decided.as;\n+\t\t} else keyForCall = { presented: caller.presented, address: addressOf(request), write, route };\n+\t}\n+\n+\tif (top === \"head\") {\n+\t\tif (request.method !== \"GET\") return json(405, { error: \"head is a GET\" });\n+\t\tconst head = await obj.head();\n+\t\treturn head ? json(200, head) : json(404, { error: \"no such project; run init first\" });\n+\t}\n+\tif (top === \"out\") return json(200, await obj.out());\n+\tif (top === \"ci\") return json(200, NO_CI);\n+\tif (top === \"queue\") return json(200, NO_QUEUE);\n+\tif (top === \"visibility\") {\n+\t\tif (request.method !== \"GET\")\n+\t\t\treturn json(400, { error: \"every project on this server is private: it answers only its token and keys\" });\n+\t\treturn json(200, { project, visibility: \"private\" });\n+\t}\n+\tif (blob) {\n+\t\tconst sha = top.slice(\"blobs/\".length);\n+\t\tif (!SHA.test(sha)) return json(400, { error: \"a blob's name is its SHA-256 in lowercase hex\" });\n+\t\tif (request.method === \"PUT\") {\n+\t\t\tif (!request.body) return json(400, { error: \"PUT the blob's bytes as the body\" });\n+\t\t\tconst a = (await obj.putBlob(sha, request.body)) as unknown as Answer;\n+\t\t\treturn json(a.status, a.body);\n+\t\t}\n+\t\tif (request.method !== \"GET\") return json(405, { error: \"blobs take GET or PUT\" });\n+\t\tconst bytes = await obj.getBlob(sha);\n+\t\tif (!bytes) return json(404, { error: `no blob ${sha} in this project` });\n+\t\treturn new Response(bytes, {\n+\t\t\theaders: { \"content-type\": \"application/octet-stream\", \"cache-control\": \"private, max-age=31536000, immutable\" },\n+\t\t});\n+\t}\n+\tif (top === \"export\") {\n+\t\tconst from = Number(url.searchParams.get(\"from\") ?? \"0\");\n+\t\tconst limit = Number(url.searchParams.get(\"limit\") ?? \"500\");\n+\t\tif (!Number.isInteger(from) || from < 0 || !Number.isInteger(limit) || limit < 1 || limit > 5000)\n+\t\t\treturn json(400, { error: \"export takes ?from=<seq>&limit=<1-5000>\" });\n+\t\tconst page = await obj.exportLog(from, limit);\n+\t\tif (page === null) return json(404, { error: \"no such project; run init first\" });\n+\t\treturn new Response(page.lines, {\n+\t\t\theaders: {\n+\t\t\t\t\"content-type\": \"application/x-ndjson\",\n+\t\t\t\t\"x-abso-next\": page.next === null ? \"\" : String(page.next),\n+\t\t\t\t\"cache-control\": \"no-store\",\n+\t\t\t},\n+\t\t});\n+\t}\n+\tif (top === \"git-remote\") {\n+\t\t// For a person who works with plain git: clone, commit, push; the project takes the commits in.\n+\t\tif (request.method !== \"POST\") return json(405, { error: \"git-remote is a POST\" });\n+\t\tconst artifacts = artifactsOf(env);\n+\t\tif (!artifacts) return json(501, { error: \"this server has no Artifacts binding, so no git remote\" });\n+\t\tif ((await obj.head()) === null) return json(404, { error: \"no such project; run init first\" });\n+\t\tconst { remote, secret: token } = await writeAccess(artifacts, repoName(project), 3600);\n+\t\t// The token goes in a header for each git call, never in the remote URL or a credential store.\n+\t\tconst header = `Authorization: Basic ${btoa(`x:${token}`)}`;\n+\t\tconst git = `git -c credential.helper= -c http.extraHeader=\"${header}\"`;\n+\t\treturn json(200, {\n+\t\t\tremote,\n+\t\t\ttoken,\n+\t\t\texpiresIn: 3600,\n+\t\t\theader,\n+\t\t\tclone: `${git} clone ${remote}`,\n+\t\t\tfetch: `${git} fetch`,\n+\t\t\tpush: `${git} push`,\n+\t\t});\n+\t}\n+\tif (top === \"git-sync\") {\n+\t\tif (request.method !== \"POST\") return json(405, { error: \"git-sync is a POST\" });\n+\t\ttry {\n+\t\t\treturn json(200, { taken: await obj.gitSync() });\n+\t\t} catch (e) {\n+\t\t\treturn json(502, { error: `could not read the project's repo: ${e instanceof Error ? e.message : String(e)}` });\n+\t\t}\n+\t}\n+\n+\tlet body: unknown;\n+\tif (request.method === \"POST\") {\n+\t\tconst text = await request.text();\n+\t\tif (text) {\n+\t\t\ttry {\n+\t\t\t\tbody = JSON.parse(text);\n+\t\t\t} catch {\n+\t\t\t\treturn json(400, { error: \"the body must be JSON\" });\n+\t\t\t}\n+\t\t}\n+\t} else if (request.method === \"GET\" && (QUERY_READS.has(route ?? \"\") || top.startsWith(\"change/\"))) {\n+\t\tbody = Object.fromEntries(url.searchParams);\n+\t} else return json(405, { error: `${route} is a POST` });\n+\t// Which client sent a recording goes in the log with it.\n+\tif ((op === \"edit\" || op === \"record\") && body && typeof body === \"object\") {\n+\t\tconst client = request.headers.get(\"x-abso-client\") ?? request.headers.get(\"x-avcs-client\") ?? \"\";\n+\t\tconst { client: _, ...rest } = body as Record<string, unknown>;\n+\t\tbody = { ...rest, ...(/^[\\w.+-]{1,20}\\/[\\w.+-]{1,40}$/.test(client) ? { client } : {}) };\n+\t}\n+\ttry {\n+\t\tconst a = (await obj.call(\n+\t\t\tproject,\n+\t\t\t(op ?? top)!,\n+\t\t\tagent,\n+\t\t\tbody,\n+\t\t\tfalse,\n+\t\t\thow,\n+\t\t\tkeyForCall,\n+\t\t\trequest.headers.get(\"Idempotency-Key\") ?? undefined,\n+\t\t)) as unknown as Answer;\n+\t\t// A held push gets a first opinion on each collision (#19), when the server is set up for it.\n+\t\treturn json(a.status, await withAdvice(env, op, agent, body, a.body));\n+\t} catch (e) {\n+\t\tconst error = `the project object failed: ${e instanceof Error ? e.message : String(e)}`;\n+\t\tconsole.error(`${project} ${op ?? top}: ${error}`);\n+\t\treturn json(500, { error });\n+\t}\n+}\n+\n+/** One request. The issues code comes in as an argument, so this file loads without the Workers runtime (tests). */\n+export async function handle(\n+\trequest: Request,\n+\tenv: Env,\n+\tctx: ExecutionContext,\n+\tissues: typeof issuesFetch,\n+): Promise<Response> {\n+\tconst url = new URL(request.url);\n+\tif (url.pathname === \"/version\") return json(200, { commit: env.CF_VERSION_METADATA?.tag || null });\n+\tconst caller = await authorize(request, env);\n+\tif (caller instanceof Response) return caller;\n+\tif (url.pathname === \"/\")\n+\t\treturn new Response(\"abso: agent-first version control. The API lives under /p/<project>.\\n\");\n+\tif (url.pathname === \"/admin/agent-keys\" || url.pathname === \"/admin/agent-keys/revoke\")\n+\t\treturn agentKeys(request, env, url, caller);\n+\tconst onIssues = ISSUES_ROUTE.exec(url.pathname);\n+\tif (onIssues) {\n+\t\tconst project = decodeURIComponent(onIssues[1]!);\n+\t\tif (!validName(project)) return json(400, { error: \"project names use letters, digits, '.', '_' and '-'\" });\n+\t\tlet auth: IssuesAuth = { kind: \"token\" };\n+\t\tif (caller.kind === \"key\") {\n+\t\t\tconst decided = await projectObject(env, project).checkAgentKey(caller.presented, undefined, addressOf(request));\n+\t\t\tif (!decided.ok) return json(decided.status, { error: decided.error });\n+\t\t\tauth = { kind: \"key\", agent: decided.agent, role: decided.role as KeyRole };\n+\t\t}\n+\t\treturn issues(request, env, ctx, { project, rest: onIssues[2] ?? \"\", auth });\n+\t}\n+\tconst m = PROJECT_ROUTE.exec(url.pathname);\n+\tif (!m) return json(404, { error: \"no such route\" });\n+\treturn projectRoute(request, env, url, caller, m);\n+}"}],"unmatched":[]}