Diffinery

homeflare/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

202 lines · 11.6 KBRaw History
1import type { Env } from "../env.js";
2import { mcpChallenge } from "../auth/oauth.js";
3import type { Repo } from "../lib/directory.js";
4import { denied, readOnly, requestPermission, type JobPermissions, type Requirement } from "../lib/job-permissions.js";
5import { HttpError } from "../lib/util.js";
6import { errorRecord, recordServerError, requestId } from "../lib/server-errors.js";
7import { movedPath, movedStatus } from "../lib/redirects.js";
8import { GITHUB_DOCS } from "./gh.js";
9import { callerFor, grantsFor, requireScope, type AppContext } from "../auth/principal.js";
10import { atLeast, type Caller, type Role } from "../repo/types.js";
11import { suspendedIds } from "../lib/moderation.js";
12import { isAppCaller } from "../repo/token-policy.js";
13import { MailStore, type WatchLevel } from "../mail/prefs.js";
14
15export const repoStub = (env: Env, repoId: string) => env.REPO.get(env.REPO.idFromName(repoId));
16
17/** A repository that was transferred or renamed: answered with a redirect to `location` (see loadRepo). */
18export class RepoMoved extends HttpError {
19 constructor(
20 status: 301 | 307,
21 readonly location: string,
22 ) {
23 super(status, "Moved Permanently");
24 }
25}
26
27/**
28 * For `loadRepo`: a settings change that doesn't touch the repository's Git data, issues or pull
29 * requests (secrets, variables, environments, collaborators and invitations) goes through while
30 * an import fills the repository, so people can set it up as it arrives. An import never writes
31 * secret values; its variables and environments step writes GitHub's, so one set here before that
32 * step under the same name ends with GitHub's value. Webhooks stay locked: nothing the import
33 * does may reach one.
34 */
35export const WHILE_IMPORTING = { whileImporting: true } as const;
36
37/**
38 * Load a repository and the caller's role, enforcing a minimum role (404 hides
39 * private repos; signed-out callers get the same answer for private and missing ones). Anonymous callers get read access to public repositories but
40 * may only read: any other method needs a signed-in caller, as on GitHub,
41 * unless the route is a read that happens to use POST (git fetch, LFS
42 * download) and says so. Writes also need a token with the write scope.
43 * Archived repositories refuse every write, whatever role the route needs,
44 * except the few routes that pass `whileArchived` (unarchiving, deleting,
45 * watching), as on GitHub. While a GitHub import fills the repository, every
46 * write is refused with 423 except the import's own (its push token) and the
47 * routes that pass `whileImporting` (watching, settings that don't touch Git
48 * data (see WHILE_IMPORTING), and pushes, which the repository refuses itself
49 * with a message the git client shows).
50 *
51 * An owner/name that a repository was transferred or renamed away from leads
52 * to it, after the same visibility check, so callers who can't read it still
53 * get a 404. Where the old name is in the request path, the answer is a
54 * redirect (RepoMoved: 301 for reads, 307 otherwise, as GitHub does);
55 * `follow` (Git, MCP) serves the repository under the old name instead, and
56 * `moved` says it was reached that way.
57 */
58/** Paths whose reads show issues, pull requests or their comments (the web pages and the REST API). */
59const CONVERSATION_PATH = /\/(?:issues|pulls?|comments)(?:\/|$)/;
60
61export async function loadRepo(c: AppContext, owner: string, name: string, min: Role = "read", opts: { readOnlyPost?: boolean; whileArchived?: boolean; whileImporting?: boolean; follow?: boolean; permission?: Requirement } = {}): Promise<{ repo: Repo; caller: Caller; stub: ReturnType<typeof repoStub>; moved: boolean }> {
62 const dir = c.get("dir");
63 const anonymous = c.get("principal").type === "anonymous";
64 const reading = c.req.method === "GET" || c.req.method === "HEAD" || (opts.readOnlyPost && c.req.method === "POST") || c.get("readOnly") === true;
65 // Signed-out callers can't tell a private repository from one that doesn't exist: writes are
66 // refused before the lookup, and reads of either get the same answer. That is a 404 from the REST
67 // API, as on GitHub, and a 401 everywhere else, so git asks for credentials and the web offers sign-in.
68 if (anonymous && !reading) throw new HttpError(401, "authentication required");
69 const hidden = () => (anonymous && !c.req.path.startsWith("/api/") ? new HttpError(401, "authentication required") : new HttpError(404, "repository not found"));
70 // Reads of conversations leave out suspended people's posts (hiddenAuthors): look them up alongside the repository.
71 if (reading && CONVERSATION_PATH.test(c.req.path)) hiddenAuthors(c).catch(() => {});
72 // The repository and the grants that decide the caller's role in it, side by side.
73 const [found, grants] = await Promise.all([dir.repo(owner, name.replace(/\.git$/, "")), grantsFor(c, owner, name)]);
74 let repo = found;
75 const moved = !repo;
76 repo ??= await dir.movedRepo(owner, name);
77 if (!repo) throw hidden();
78 const caller = await callerFor(c, repo, grants);
79 if (!caller) throw hidden();
80 // A job or sandbox token reading another public repository acts as nobody in particular: it may read, never write.
81 if (caller.id === "anonymous" && !reading) throw new HttpError(403, c.get("principal").type === "installation" ? "Resource not accessible by integration (the app isn't installed on this repository, or the token wasn't made for it)" : "this token can only write to its own repository");
82 if (moved && !opts.follow) {
83 const url = new URL(c.req.url);
84 const path = movedPath(url.pathname, { owner, name }, { owner: repo.owner_login, name: repo.name });
85 if (path) throw new RepoMoved(movedStatus(c.req.method), new URL(path + url.search, url).toString());
86 }
87 // After the visibility check, so a read token's write to a private repository it can't see is still a 404.
88 if (!reading) requireScope(c, "write");
89 if (!atLeast(caller.role, min)) throw new HttpError(403, `${min} access required`);
90 if (caller.permissions) {
91 // A workflow's GITHUB_TOKEN: each kind of endpoint needs its permission (issues, contents, ...).
92 // What anyone may read in a public repository stays readable with `permissions: { contents: none }`.
93 // `permission`: what an endpoint that isn't one REST path per resource (GraphQL) needs for this lookup.
94 const req = opts.permission ?? requestPermission(c.req.method, c.req.path, min);
95 const reason = denied(caller.permissions as JobPermissions, req, isAppCaller(caller) ? "app" : "job");
96 if (reason && !(repo.visibility === "public" && readOnly(req))) throw new HttpError(403, reason);
97 }
98 if (repo.archived && !reading && !opts.whileArchived) throw new HttpError(403, "repository is archived (read-only)");
99 const stub = repoStub(c.env, repo.id);
100 // A page a person opens shows whether they watch the repository: start reading it now, alongside the page's own reads.
101 const p = c.get("principal");
102 if (reading && c.req.method === "GET" && p.type === "account" && p.via !== "token" && !c.req.path.startsWith("/api/") && !c.req.path.endsWith("/live")) {
103 watchLevelOnce(c, repo.id).catch(() => {});
104 }
105 if (!reading && !opts.whileImporting) {
106 const holder = await stub.importLockHolder();
107 if (holder && !(p.type === "account" && p.importId === holder)) throw new HttpError(423, "repository is locked by an import in progress; try again when it finishes, or cancel the import");
108 }
109 return { repo, caller, stub, moved };
110}
111
112/** The signed-in person's watch level for a repository, read once per request: the page header and a conversation's subscription box both show it. */
113export function watchLevelOnce(c: AppContext, repoId: string): Promise<WatchLevel> {
114 const p = c.get("principal");
115 if (p.type !== "account") return Promise.resolve("participating");
116 const known = c.get("watch");
117 if (known?.repoId === repoId) return known.level;
118 const level = new MailStore(c.env.DB).watchLevel(p.account.id, repoId);
119 c.set("watch", { repoId, level });
120 return level;
121}
122
123/**
124 * Suspended people (lib/moderation.ts): the issues, pull requests, reviews and comments they wrote are
125 * left out for everyone but site administrators. Looked up once per request.
126 */
127export function hiddenAuthors(c: AppContext): Promise<string[]> {
128 const p = c.get("principal");
129 if (p.type === "account" && p.account.site_admin) return Promise.resolve([]);
130 let v = c.get("hidden");
131 if (!v) {
132 v = suspendedIds(c.env);
133 c.set("hidden", v);
134 }
135 return v;
136}
137
138/** Record a repository settings change made through the API, like the web settings pages do. */
139export function auditRepo(c: AppContext, caller: Caller, repo: Pick<Repo, "owner_login" | "name">, action: string, detail: Record<string, unknown> = {}): void {
140 c.executionCtx.waitUntil(
141 c
142 .get("dir")
143 .audit({ actorId: caller.id, actorLogin: caller.login, onBehalfOf: caller.onBehalfOf, action, target: `${repo.owner_login}/${repo.name}`, detail: { ...detail, via: "api" } })
144 .catch((e) => console.error("audit failed", e)),
145 );
146}
147
148/** Secrets and Actions variables are managed by people only. */
149export function refuseAgent(caller: Caller, what = "secrets and variables"): void {
150 if (caller.kind === "agent") throw new HttpError(403, `agents cannot manage ${what}`);
151}
152
153/** API clients get GitHub's JSON 404 for unknown paths, never the HTML page. */
154export function apiNotFound(): Response {
155 return new Response(JSON.stringify({ message: "Not Found", documentation_url: GITHUB_DOCS }), { status: 404, headers: { "content-type": "application/json" } });
156}
157
158/**
159 * Records a 5xx answer for site administrators (lib/server-errors.ts) and returns the request id
160 * the answer reports, so a failure seen in a client or CI log can be looked up.
161 */
162export function noteServerError(c: AppContext, e: unknown, status: number): string {
163 const id = requestId(c.req.raw);
164 let route: string | null = null;
165 try {
166 route = c.req.routePath;
167 } catch {
168 // No route matched.
169 }
170 const saved = recordServerError(c.env, errorRecord(e, { id, method: c.req.method, route, path: c.req.path, status }));
171 try {
172 c.executionCtx.waitUntil(saved);
173 } catch {
174 // No execution context (tests): the write runs on its own.
175 }
176 return id;
177}
178
179export function errorResponse(e: unknown, c?: AppContext): Response {
180 const json = (status: number, body: Record<string, unknown>, headers: Record<string, string> = {}) => {
181 if (status >= 500 && c) {
182 const id = noteServerError(c, e, status);
183 body = { ...body, request_id: id };
184 headers = { ...headers, "x-request-id": id };
185 }
186 return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...headers } });
187 };
188 if (e instanceof HttpError) {
189 const headers: Record<string, string> = {};
190 // MCP clients learn from /mcp's challenge where to sign in with OAuth (auth/oauth.ts); git and curl get Basic.
191 if (e.status === 401) headers["www-authenticate"] = c && c.req.path === "/mcp" ? mcpChallenge(c.env, c.get("principal")?.type === "anonymous" ? undefined : "invalid_token") : 'Basic realm="Diffinery", charset="UTF-8"';
192 // GitHub's answer for a renamed or transferred repository: the new URL in Location and in the body.
193 if (e instanceof RepoMoved) return json(e.status, { message: e.detail, url: e.location, documentation_url: GITHUB_DOCS }, { ...headers, location: e.location });
194 return json(e.status, { message: e.detail, documentation_url: GITHUB_DOCS, ...e.extra }, headers);
195 }
196 // Errors thrown inside Durable Objects arrive as plain Errors; recover HttpError-like status when present.
197 const msg = (e as Error)?.message ?? String(e);
198 const remote = /^(\d{3}):/.exec(msg);
199 if (remote) return json(Number(remote[1]), { message: msg.slice(5), documentation_url: GITHUB_DOCS });
200 console.error(e);
201 return json(500, { message: "internal error" });
202}