{"draft":null,"from":150,"to":151,"files":[{"path":"server/src/issues/serve.ts","added":200,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/issues/serve.ts\n@@ -0,0 +1,200 @@\n+// How the open server's Worker reaches a project's issues, and what the IssueProject object does with a\n+// request, apart from Cloudflare's own types so both run under node --test.\n+//\n+//   issuesFetch    the Worker's entry for /issues/p/:project/...: the router has checked the token or key;\n+//                  this checks that a key acts only as its own agent (and a reader's only reads), hands the\n+//                  request to the project's IssueProject, and delivers a write's news to the project.\n+//   IssuesObject   one project's issues: migrations, the store, and its routes (routes.ts). An ask's `of` is\n+//                  checked against the project's agents.\n+//\n+// The project object (env.PROJECT, named by the project) is asked two things, both optional: agents(project)\n+// for the ask check, and news(project, items) to deliver a write's news as announcements. Without them the\n+// check is skipped and the news is dropped with a log line.\n+\n+import type { News } from \"../../../client/src/issues-wire.ts\";\n+import { BODY_MAX, issuesRoute, json, readCapped } from \"./routes.ts\";\n+import { seatRefusal } from \"./seats.ts\";\n+import { IssuesError, IssuesStore, SCHEMA, type Sql } from \"./store.ts\";\n+\n+/** A write's news for the project to deliver: the issue's claimers and those in `to` hear it, never `from`. */\n+export interface IssueNews extends News {\n+\t/** The agent whose write it was. */\n+\tfrom: string;\n+}\n+\n+/** What issues asks of the project's own object. Each method is optional: an older project object may lack it. */\n+export interface ProjectHooks {\n+\t/** The agents in the project, which an ask may go to. */\n+\tagents?(project: string): Promise<string[]>;\n+\t/** Deliver each item as an announcement from `from` to the issue's claimers and `to`. */\n+\tnews?(project: string, items: IssueNews[]): Promise<unknown>;\n+}\n+\n+/** A Durable Object namespace as far as issues uses one; Cloudflare's DurableObjectNamespace fits it. */\n+export interface NamespaceLike {\n+\tidFromName(name: string): unknown;\n+\tget(id: never): object;\n+}\n+\n+/** The bindings issues reads. */\n+export interface IssuesEnv {\n+\t/** One IssueProject per project, named by the project's name. */\n+\tISSUES_DO: NamespaceLike;\n+\t/** The project objects, named by the project's name; their stubs answer ProjectHooks. */\n+\tPROJECT?: NamespaceLike;\n+}\n+\n+/** How the router let the request in: the shared token acts as any agent; a key only as its own agent. */\n+export type IssuesAuth = { kind: \"token\" } | { kind: \"key\"; agent: string; role: string };\n+\n+/** What issuesFetch needs from the Worker's context. */\n+export interface WaitUntil {\n+\twaitUntil(promise: Promise<unknown>): void;\n+}\n+\n+const PROJECT_NAME = /^[A-Za-z0-9._-]{1,64}$/;\n+const AGENT_NAME = /^[A-Za-z0-9._-]{1,64}$/;\n+\n+function stubOf<T>(ns: NamespaceLike, name: string): T {\n+\tconst n = ns as unknown as { idFromName(name: string): unknown; get(id: unknown): T };\n+\treturn n.get(n.idFromName(name));\n+}\n+\n+/** The project object's stub, as far as issues calls it; undefined when PROJECT isn't bound. */\n+function hooksOf(env: IssuesEnv, project: string): ProjectHooks | undefined {\n+\treturn env.PROJECT === undefined ? undefined : stubOf<ProjectHooks>(env.PROJECT, project);\n+}\n+\n+/**\n+ * Whether an RPC call failed because the receiver has no such method. On an RPC stub every property reads as a\n+ * function, so only the call can tell: it fails with this error.\n+ */\n+export function missingMethod(e: unknown): boolean {\n+\tconst message = e instanceof Error ? e.message : String(e);\n+\treturn /does not implement (the )?method|is not a function/i.test(message);\n+}\n+\n+/**\n+ * /issues/p/:project<rest> after the router's sign-in check. `rest` is the path after the project, like\n+ * /a/lead/ask or /issues.\n+ */\n+export async function issuesFetch(\n+\trequest: Request,\n+\tenv: IssuesEnv,\n+\tctx: WaitUntil,\n+\t{ project, rest, auth }: { project: string; rest: string; auth: IssuesAuth },\n+): Promise<Response> {\n+\tif (!PROJECT_NAME.test(project)) return json(404, { error: \"no such project\" });\n+\tif (!rest.startsWith(\"/\")) return json(404, { error: \"no such issues route\" });\n+\tconst m = /^\\/a\\/([^/]+)\\//.exec(rest);\n+\tlet agent: string | undefined;\n+\tif (m) {\n+\t\ttry {\n+\t\t\tagent = decodeURIComponent(m[1]!);\n+\t\t} catch {\n+\t\t\treturn json(400, { error: \"an agent's name is 1-64 of A-Z a-z 0-9 . _ -\" });\n+\t\t}\n+\t\tif (!AGENT_NAME.test(agent)) return json(400, { error: \"an agent's name is 1-64 of A-Z a-z 0-9 . _ -\" });\n+\t}\n+\tconst reading = request.method === \"GET\" || request.method === \"HEAD\";\n+\tif (auth.kind === \"key\") {\n+\t\tif (agent !== undefined && agent !== auth.agent)\n+\t\t\treturn json(403, { error: `this key is ${auth.agent}'s; it acts only as ${auth.agent}` });\n+\t\tif (auth.role === \"reader\" && !reading) return json(403, { error: \"a reader's key only reads issues\" });\n+\t}\n+\tlet body: Uint8Array<ArrayBuffer> | undefined;\n+\tif (!reading) {\n+\t\ttry {\n+\t\t\tbody = await readCapped(request, BODY_MAX);\n+\t\t} catch (e) {\n+\t\t\tif (e instanceof IssuesError) return json(e.status, { error: e.message });\n+\t\t\tthrow e;\n+\t\t}\n+\t}\n+\t// The object sees neither the token nor any header that could name a person.\n+\tconst headers = new Headers(request.headers);\n+\tfor (const h of [\"Authorization\", \"X-Abso-User\", \"X-Avcs-User\", \"Cookie\"]) headers.delete(h);\n+\tconst search = new URL(request.url).search;\n+\tconst forwarded = new Request(`https://issues.invalid/p/${encodeURIComponent(project)}${rest}${search}`, {\n+\t\tmethod: request.method,\n+\t\theaders,\n+\t\t...(body !== undefined ? { body } : {}),\n+\t});\n+\tconst stub = stubOf<{ fetch(request: Request): Promise<Response> }>(env.ISSUES_DO, project);\n+\tconst answer = await stub.fetch(forwarded);\n+\tif (!reading && agent !== undefined && answer.ok) ctx.waitUntil(tell(env, project, agent, answer.clone()));\n+\treturn answer;\n+}\n+\n+/** A write's news to the project object, sent after the answer. A failed send is only logged; the write stands. */\n+async function tell(env: IssuesEnv, project: string, from: string, answer: Response): Promise<void> {\n+\ttry {\n+\t\tconst { news } = (await answer.json()) as { news?: News };\n+\t\tif (!news || typeof news.text !== \"string\") return;\n+\t\tconst hooks = hooksOf(env, project);\n+\t\tif (hooks === undefined) {\n+\t\t\tconsole.log(`issues: news for ${project} dropped: PROJECT isn't bound`);\n+\t\t\treturn;\n+\t\t}\n+\t\tawait hooks.news!(project, [{ from, ...news }]);\n+\t} catch (err) {\n+\t\tif (missingMethod(err)) console.log(`issues: news for ${project} dropped: the project object has no news method`);\n+\t\telse console.error(`issues: news for ${project} not sent`, err);\n+\t}\n+}\n+\n+/** The storage an IssueProject object has: its SQL, and a synchronous transaction. */\n+export interface ObjectStorage {\n+\tsql: Sql;\n+\ttransactionSync<T>(action: () => T): T;\n+}\n+\n+/** One project's issues: the store over the object's SQLite, migrated, and the routes over it. */\n+export class IssuesObject {\n+\treadonly store: IssuesStore;\n+\tprivate readonly storage: ObjectStorage;\n+\tprivate readonly env: IssuesEnv;\n+\n+\tconstructor(storage: ObjectStorage, env: IssuesEnv, now: () => number = Date.now) {\n+\t\tthis.storage = storage;\n+\t\tthis.env = env;\n+\t\tthis.migrate();\n+\t\tthis.store = new IssuesStore(storage.sql, now, (action) => storage.transactionSync(action));\n+\t}\n+\n+\t/** Runs each SCHEMA statement not yet run, once, in order, each in its own transaction. */\n+\tprivate migrate(): void {\n+\t\tconst sql = this.storage.sql;\n+\t\tsql.exec(\"CREATE TABLE IF NOT EXISTS migrations (n INTEGER PRIMARY KEY, at INTEGER NOT NULL)\");\n+\t\tconst done = (sql.exec(\"SELECT COALESCE(MAX(n), 0) AS n FROM migrations\").toArray()[0] as { n: number }).n;\n+\t\tfor (let n = done + 1; n <= SCHEMA.length; n++)\n+\t\t\tthis.storage.transactionSync(() => {\n+\t\t\t\tsql.exec(SCHEMA[n - 1]!);\n+\t\t\t\tsql.exec(\"INSERT INTO migrations (n, at) VALUES (?, ?)\", n, Date.now());\n+\t\t\t});\n+\t}\n+\n+\t/** How many migrations this object has run. */\n+\tmigrations(): number {\n+\t\treturn (this.storage.sql.exec(\"SELECT COUNT(*) AS n FROM migrations\").toArray()[0] as { n: number }).n;\n+\t}\n+\n+\tasync fetch(request: Request): Promise<Response> {\n+\t\tconst name = /^\\/p\\/([^/]+)\\//.exec(new URL(request.url).pathname)?.[1];\n+\t\tconst project = name === undefined ? undefined : decodeURIComponent(name);\n+\t\tconst seatError = async (of: string): Promise<string | null> => {\n+\t\t\tif (project === undefined) return null;\n+\t\t\tconst hooks = hooksOf(this.env, project);\n+\t\t\tif (hooks === undefined) return null;\n+\t\t\tlet seats: string[];\n+\t\t\ttry {\n+\t\t\t\tseats = await hooks.agents!(project);\n+\t\t\t} catch (e) {\n+\t\t\t\tif (missingMethod(e)) return null;\n+\t\t\t\tthrow e;\n+\t\t\t}\n+\t\t\treturn Array.isArray(seats) ? seatRefusal(of, project, seats) : null;\n+\t\t};\n+\t\treturn issuesRoute(this.store, request, seatError);\n+\t}\n+}"}],"unmatched":[]}