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 116 to 318

Compare

+200 −0 in 1 place
new file, 200 lines
1+// How the open server's Worker reaches a project's issues, and what the IssueProject object does with a
2+// request, apart from Cloudflare's own types so both run under node --test.
3+//
4+// issuesFetch the Worker's entry for /issues/p/:project/...: the router has checked the token or key;
5+// this checks that a key acts only as its own agent (and a reader's only reads), hands the
6+// request to the project's IssueProject, and delivers a write's news to the project.
7+// IssuesObject one project's issues: migrations, the store, and its routes (routes.ts). An ask's `of` is
8+// checked against the project's agents.
9+//
10+// The project object (env.PROJECT, named by the project) is asked two things, both optional: agents(project)
11+// for the ask check, and news(project, items) to deliver a write's news as announcements. Without them the
12+// check is skipped and the news is dropped with a log line.
14+import type { News } from "../../../client/src/issues-wire.ts";
15+import { BODY_MAX, issuesRoute, json, readCapped } from "./routes.ts";
16+import { seatRefusal } from "./seats.ts";
17+import { IssuesError, IssuesStore, SCHEMA, type Sql } from "./store.ts";
19+/** A write's news for the project to deliver: the issue's claimers and those in `to` hear it, never `from`. */
20+export interface IssueNews extends News {
21+ /** The agent whose write it was. */
22+ from: string;
23+}
25+/** What issues asks of the project's own object. Each method is optional: an older project object may lack it. */
26+export interface ProjectHooks {
27+ /** The agents in the project, which an ask may go to. */
28+ agents?(project: string): Promise<string[]>;
29+ /** Deliver each item as an announcement from `from` to the issue's claimers and `to`. */
30+ news?(project: string, items: IssueNews[]): Promise<unknown>;
31+}
33+/** A Durable Object namespace as far as issues uses one; Cloudflare's DurableObjectNamespace fits it. */
34+export interface NamespaceLike {
35+ idFromName(name: string): unknown;
36+ get(id: never): object;
37+}
39+/** The bindings issues reads. */
40+export interface IssuesEnv {
41+ /** One IssueProject per project, named by the project's name. */
42+ ISSUES_DO: NamespaceLike;
43+ /** The project objects, named by the project's name; their stubs answer ProjectHooks. */
44+ PROJECT?: NamespaceLike;
45+}
47+/** How the router let the request in: the shared token acts as any agent; a key only as its own agent. */
48+export type IssuesAuth = { kind: "token" } | { kind: "key"; agent: string; role: string };
50+/** What issuesFetch needs from the Worker's context. */
51+export interface WaitUntil {
52+ waitUntil(promise: Promise<unknown>): void;
53+}
55+const PROJECT_NAME = /^[A-Za-z0-9._-]{1,64}$/;
56+const AGENT_NAME = /^[A-Za-z0-9._-]{1,64}$/;
58+function stubOf<T>(ns: NamespaceLike, name: string): T {
59+ const n = ns as unknown as { idFromName(name: string): unknown; get(id: unknown): T };
60+ return n.get(n.idFromName(name));
61+}
63+/** The project object's stub, as far as issues calls it; undefined when PROJECT isn't bound. */
64+function hooksOf(env: IssuesEnv, project: string): ProjectHooks | undefined {
65+ return env.PROJECT === undefined ? undefined : stubOf<ProjectHooks>(env.PROJECT, project);
66+}
68+/**
69+ * Whether an RPC call failed because the receiver has no such method. On an RPC stub every property reads as a
70+ * function, so only the call can tell: it fails with this error.
71+ */
72+export function missingMethod(e: unknown): boolean {
73+ const message = e instanceof Error ? e.message : String(e);
74+ return /does not implement (the )?method|is not a function/i.test(message);
75+}
77+/**
78+ * /issues/p/:project<rest> after the router's sign-in check. `rest` is the path after the project, like
79+ * /a/lead/ask or /issues.
80+ */
81+export async function issuesFetch(
82+ request: Request,
83+ env: IssuesEnv,
84+ ctx: WaitUntil,
85+ { project, rest, auth }: { project: string; rest: string; auth: IssuesAuth },
86+): Promise<Response> {
87+ if (!PROJECT_NAME.test(project)) return json(404, { error: "no such project" });
88+ if (!rest.startsWith("/")) return json(404, { error: "no such issues route" });
89+ const m = /^\/a\/([^/]+)\//.exec(rest);
90+ let agent: string | undefined;
91+ if (m) {
92+ try {
93+ agent = decodeURIComponent(m[1]!);
94+ } catch {
95+ return json(400, { error: "an agent's name is 1-64 of A-Z a-z 0-9 . _ -" });
96+ }
97+ if (!AGENT_NAME.test(agent)) return json(400, { error: "an agent's name is 1-64 of A-Z a-z 0-9 . _ -" });
98+ }
99+ const reading = request.method === "GET" || request.method === "HEAD";
100+ if (auth.kind === "key") {
101+ if (agent !== undefined && agent !== auth.agent)
102+ return json(403, { error: `this key is ${auth.agent}'s; it acts only as ${auth.agent}` });
103+ if (auth.role === "reader" && !reading) return json(403, { error: "a reader's key only reads issues" });
104+ }
105+ let body: Uint8Array<ArrayBuffer> | undefined;
106+ if (!reading) {
107+ try {
108+ body = await readCapped(request, BODY_MAX);
109+ } catch (e) {
110+ if (e instanceof IssuesError) return json(e.status, { error: e.message });
111+ throw e;
112+ }
113+ }
114+ // The object sees neither the token nor any header that could name a person.
115+ const headers = new Headers(request.headers);
116+ for (const h of ["Authorization", "X-Abso-User", "X-Avcs-User", "Cookie"]) headers.delete(h);
117+ const search = new URL(request.url).search;
118+ const forwarded = new Request(`https://issues.invalid/p/${encodeURIComponent(project)}${rest}${search}`, {
119+ method: request.method,
120+ headers,
121+ ...(body !== undefined ? { body } : {}),
122+ });
123+ const stub = stubOf<{ fetch(request: Request): Promise<Response> }>(env.ISSUES_DO, project);
124+ const answer = await stub.fetch(forwarded);
125+ if (!reading && agent !== undefined && answer.ok) ctx.waitUntil(tell(env, project, agent, answer.clone()));
126+ return answer;
127+}
129+/** A write's news to the project object, sent after the answer. A failed send is only logged; the write stands. */
130+async function tell(env: IssuesEnv, project: string, from: string, answer: Response): Promise<void> {
131+ try {
132+ const { news } = (await answer.json()) as { news?: News };
133+ if (!news || typeof news.text !== "string") return;
134+ const hooks = hooksOf(env, project);
135+ if (hooks === undefined) {
136+ console.log(`issues: news for ${project} dropped: PROJECT isn't bound`);
137+ return;
138+ }
139+ await hooks.news!(project, [{ from, ...news }]);
140+ } catch (err) {
141+ if (missingMethod(err)) console.log(`issues: news for ${project} dropped: the project object has no news method`);
142+ else console.error(`issues: news for ${project} not sent`, err);
143+ }
144+}
146+/** The storage an IssueProject object has: its SQL, and a synchronous transaction. */
147+export interface ObjectStorage {
148+ sql: Sql;
149+ transactionSync<T>(action: () => T): T;
150+}
152+/** One project's issues: the store over the object's SQLite, migrated, and the routes over it. */
153+export class IssuesObject {
154+ readonly store: IssuesStore;
155+ private readonly storage: ObjectStorage;
156+ private readonly env: IssuesEnv;
158+ constructor(storage: ObjectStorage, env: IssuesEnv, now: () => number = Date.now) {
159+ this.storage = storage;
160+ this.env = env;
161+ this.migrate();
162+ this.store = new IssuesStore(storage.sql, now, (action) => storage.transactionSync(action));
163+ }
165+ /** Runs each SCHEMA statement not yet run, once, in order, each in its own transaction. */
166+ private migrate(): void {
167+ const sql = this.storage.sql;
168+ sql.exec("CREATE TABLE IF NOT EXISTS migrations (n INTEGER PRIMARY KEY, at INTEGER NOT NULL)");
169+ const done = (sql.exec("SELECT COALESCE(MAX(n), 0) AS n FROM migrations").toArray()[0] as { n: number }).n;
170+ for (let n = done + 1; n <= SCHEMA.length; n++)
171+ this.storage.transactionSync(() => {
172+ sql.exec(SCHEMA[n - 1]!);
173+ sql.exec("INSERT INTO migrations (n, at) VALUES (?, ?)", n, Date.now());
174+ });
175+ }
177+ /** How many migrations this object has run. */
178+ migrations(): number {
179+ return (this.storage.sql.exec("SELECT COUNT(*) AS n FROM migrations").toArray()[0] as { n: number }).n;
180+ }
182+ async fetch(request: Request): Promise<Response> {
183+ const name = /^\/p\/([^/]+)\//.exec(new URL(request.url).pathname)?.[1];
184+ const project = name === undefined ? undefined : decodeURIComponent(name);
185+ const seatError = async (of: string): Promise<string | null> => {
186+ if (project === undefined) return null;
187+ const hooks = hooksOf(this.env, project);
188+ if (hooks === undefined) return null;
189+ let seats: string[];
190+ try {
191+ seats = await hooks.agents!(project);
192+ } catch (e) {
193+ if (missingMethod(e)) return null;
194+ throw e;
195+ }
196+ return Array.isArray(seats) ? seatRefusal(of, project, seats) : null;
197+ };
198+ return issuesRoute(this.store, request, seatError);
199+ }
200+}
MCP
compare on this site's /mcp
CLI
abso diff 116 318 server/src/issues/serve.ts --json
JSON
/christopher/abso-core/compare/116..318?file=server%2Fsrc%2Fissues%2Fserve.ts&format=json