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.

316 lines · 18.0 KBRaw History
1import { Hono } from "hono";
2import { contextStorage } from "hono/context-storage";
3import { getCookie } from "hono/cookie";
4import type { DiffineryEvent } from "@diffinery/shared";
5import type { Env } from "./env.js";
6import { credentialFrom, resolvePrincipal, type AppVars } from "./auth/principal.js";
7import { Directory, pruneAuditLog } from "./lib/directory.js";
8import { pruneExpired } from "./lib/retention.js";
9import { getFirst } from "./lib/storage-keys.js";
10import { BOOKMARK_COOKIE, BOOKMARK_HEADER, d1Session, sessionConstraint } from "./lib/d1.js";
11import { SESSION_COOKIE } from "./auth/sessions.js";
12import { newId, now } from "./lib/util.js";
13import { bucketsFor, overLimit, tooMany } from "./lib/rate-limit.js";
14import { deliverWebhook, type WebhookDeps, type WebhookRetry } from "./lib/webhooks.js";
15import { APP_HOOK_PREFIX, appHook, appWebhookDeps, deliverToApps } from "./apps/service.js";
16import { localOnly } from "./auth/dev.js";
17import { Apps } from "./apps/store.js";
18import { runStages, type Stage, type StageRetry } from "./lib/stages.js";
19import { apiNotFound, errorResponse, loadRepo, repoStub } from "./http/common.js";
20import { git } from "./http/git.js";
21import { runner } from "./http/runner.js";
22import { actionsRuntime } from "./http/actions-runtime.js";
23import { api, wellKnown } from "./http/api.js";
24import { avatars } from "./http/avatars.js";
25import { camo } from "./http/camo.js";
26import { mailApi } from "./mail/api.js";
27import { files } from "./http/files.js";
28import { webhookPayload } from "./lib/webhook-payload.js";
29import { mcp } from "./mcp/server.js";
30import { graphql } from "./http/graphql.js";
31import { registry } from "./registry/http.js";
32import { packagesApi } from "./registry/api.js";
33import { RegistryStore } from "./registry/store.js";
34import { mailCron, notifyEvent } from "./mail/notify.js";
35import { schedulerStub } from "./lib/schedules.js";
36import { mailQueue } from "./mail/send.js";
37import { mailEvents, mailEventsQueue } from "./mail/events.js";
38import { githubWebhook } from "./github-runners/http.js";
39import { securityTxtRoutes } from "./http/security-txt.js";
40import { mcpRegistryAuthRoutes } from "./http/mcp-registry-auth.js";
41import { securityReportsApi } from "./http/security-reports.js";
42import { contactApi } from "./http/contact.js";
43import { earlyAccessApi } from "./http/early-access.js";
44import { statusApi } from "./http/status.js";
45import { onReviewEvent } from "./agentic/reviews.js";
46import { onVerifyEvent } from "./agentic/tasks.js";
47import { recordActivity } from "./agentic/today.js";
48import { modelProxy } from "./agentic/proxy.js";
49import type { MailJob } from "./mail/types.js";
50import { expireExports } from "./accounts/export.js";
51import { cliLogin } from "./http/cli-login.js";
52import { CliLogins } from "./auth/cli-login.js";
53import { OAUTH_API_PATH, oauthApi } from "./http/oauth.js";
54import { OAuth } from "./auth/oauth.js";
55import { Timing, timedEnv } from "./lib/timing.js";
56import { kumoAsset } from "./web/kumo.js";
57
58export const app = new Hono<{ Bindings: Env; Variables: AppVars }>();
59
60app.onError((e, c) => errorResponse(e, c));
61app.notFound((c) => (c.req.path.startsWith("/api/") ? apiNotFound() : c.text("404 Not Found", 404)));
62
63// The model proxy for agent tasks: its own task-scoped token, not an account credential (agentic/proxy.ts).
64app.all("/-/model/:provider/*", (c) => modelProxy(c));
65
66// The islands bundle: public and immutable, sent as built before any session lookup (web/kumo.tsx).
67app.get("/-/kumo/:file", (c) => kumoAsset(c.req.raw));
68
69// The request's context, for code that renders without it in hand (the Markdown component signs image proxy URLs with its settings).
70app.use("*", contextStorage());
71
72// Security headers on every response, then identity: tokens, Access JWT, or anonymous.
73app.use("*", async (c, next) => {
74 // Browser sessions ride on cookies, so refuse state-changing requests that come from another site.
75 // Token-authenticated calls (git, CLI, MCP, runners) carry no ambient credentials and are exempt.
76 // OAuth's token, registration and revocation endpoints use no cookies and take client credentials
77 // of their own (http/oauth.ts): any site's MCP client may call them, and they skip the session lookup.
78 const oauthCall = OAUTH_API_PATH.test(c.req.path);
79 if (!["GET", "HEAD", "OPTIONS"].includes(c.req.method) && !oauthCall && !credentialFrom(c.req.raw)) {
80 const site = c.req.header("sec-fetch-site");
81 const origin = c.req.header("origin");
82 const ours = new URL(c.env.PUBLIC_URL).origin;
83 if ((site && site !== "same-origin" && site !== "none") || (!site && origin && origin !== ours)) {
84 return c.json({ message: "cross-site request refused" }, 403);
85 }
86 }
87 // One D1 session per request: replica reads that still see this client's earlier writes (see lib/d1.ts).
88 const token = !oauthCall && !!credentialFrom(c.req.raw);
89 const cookie = getCookie(c, BOOKMARK_COOKIE);
90 const d1 = d1Session(c.env, sessionConstraint({ header: c.req.header(BOOKMARK_HEADER), cookie, token }));
91 const timing = new Timing();
92 c.env = timedEnv(d1.env, timing);
93 const dir = new Directory(c.env);
94 c.set("dir", dir);
95 // The Actions runtime services authenticate with their own signed tokens and URLs (http/actions-runtime.ts).
96 const runtime = c.req.path.startsWith("/twirp/") || c.req.path.startsWith("/_runtime/");
97 // Avatar and proxied Markdown images are public and on every page many times over: skip the session lookup for them.
98 const avatar = (c.req.method === "GET" || c.req.method === "HEAD") && (c.req.path.startsWith("/api/avatars/") || c.req.path.startsWith("/-/camo/"));
99 c.set("principal", runtime || avatar || oauthCall ? { type: "anonymous" } : await resolvePrincipal(c.req.raw, c.env, dir));
100 const limited = await overLimit(c.env, bucketsFor(c.req.method, c.req.path, c.get("principal"), c.req.header("cf-connecting-ip") ?? "unknown"));
101 if (limited) c.res = tooMany(c, limited);
102 else await next();
103 if (c.res.status === 101) return;
104 const h = c.res.headers;
105 const bookmark = d1.bookmark();
106 if (bookmark) {
107 h.set(BOOKMARK_HEADER, bookmark);
108 // Browsers: remember it once they have written something or are signed in.
109 const browser = !token && (!["GET", "HEAD"].includes(c.req.method) || cookie !== undefined || getCookie(c, SESSION_COOKIE) !== undefined);
110 if (browser && !avatar && bookmark !== cookie) h.append("set-cookie", `${BOOKMARK_COOKIE}=${bookmark}; Max-Age=86400; Path=/; HttpOnly; Secure; SameSite=Lax`);
111 }
112 h.set("strict-transport-security", "max-age=63072000; includeSubDomains; preload");
113 h.set("x-content-type-options", "nosniff");
114 h.set("referrer-policy", "strict-origin-when-cross-origin");
115 if (!h.has("x-frame-options")) h.set("x-frame-options", "DENY");
116 h.set("permissions-policy", "camera=(), microphone=(), geolocation=()");
117 // Where the time went, for signed-in people's developer tools (lib/timing.ts).
118 if (c.get("principal").type === "account" && c.res.status < 400 && !h.has("server-timing")) h.set("server-timing", timing.header((c.req.raw.cf as { colo?: string } | undefined)?.colo));
119});
120
121app.get("/healthz", (c) => c.json({ ok: true }));
122
123app.route("/", avatars);
124app.route("/", camo);
125app.route("/", cliLogin);
126app.route("/", oauthApi);
127app.route("/", wellKnown);
128app.route("/", securityTxtRoutes);
129app.route("/", mcpRegistryAuthRoutes);
130app.route("/", git);
131app.route("/", runner);
132app.route("/", mailApi);
133app.route("/", securityReportsApi);
134app.route("/", earlyAccessApi);
135app.route("/", contactApi);
136app.route("/", statusApi);
137app.route("/", mailEvents);
138app.route("/", githubWebhook);
139app.route("/", registry);
140app.route("/", packagesApi);
141app.route("/", actionsRuntime);
142app.route("/", graphql);
143app.route("/", api);
144app.route("/", files);
145app.route("/", mcp);
146
147// Live updates: authorise in the Worker, then hand the WebSocket to the repository's Durable Object.
148app.get("/:owner/:repo/live", async (c) => {
149 if (c.req.header("upgrade") !== "websocket") return c.text("expected websocket", 426);
150 const { stub } = await loadRepo(c, c.req.param("owner"), c.req.param("repo"), "read", { follow: true });
151 return stub.fetch(c.req.raw);
152});
153
154app.get("/:owner/:repo/actions/runs/:runId/artifacts/:name", async (c) => {
155 const { stub } = await loadRepo(c, c.req.param("owner"), c.req.param("repo"));
156 // By name, or by id (the artifact-url output of upload-artifact).
157 const name = c.req.param("name");
158 const all = await stub.artifacts(c.req.param("runId"));
159 const artifact = all.find((a) => a.name === name) ?? (/^\d+$/.test(name) ? all.find((a) => a.id === Number(name)) : undefined);
160 if (!artifact) return c.json({ message: "artifact not found" }, 404);
161 const obj = await getFirst(c.env.BUCKET, artifact.r2Keys);
162 if (!obj) return c.json({ message: "artifact expired" }, 410);
163 return new Response(obj.body, {
164 headers: {
165 "content-type": artifact.contentType,
166 "content-length": String(obj.size),
167 "content-disposition": `attachment; filename="${artifact.fileName.replace(/[^\w.-]+/g, "_")}"`,
168 },
169 });
170});
171
172// ---------------------------------------------------------------- events queue
173
174const GITHUB_EVENT: Record<DiffineryEvent["type"], string> = {
175 push: "push",
176 pull_request: "pull_request",
177 issues: "issues",
178 issue_comment: "issue_comment",
179 pull_request_review: "pull_request_review",
180 workflow_run: "workflow_run",
181 workflow_dispatch: "workflow_dispatch",
182 release: "release",
183 status: "status",
184 deployment: "deployment",
185 deployment_status: "deployment_status",
186 deployment_review: "deployment_review",
187 repository_dispatch: "repository_dispatch",
188 audit: "audit",
189};
190
191async function deliverWebhooks(env: Env, ev: Exclude<DiffineryEvent, { type: "audit" }>): Promise<void> {
192 const stub = repoStub(env, ev.repoId);
193 const [all, row] = await Promise.all([stub.deliverableWebhooks(), new Directory(env).repoById(ev.repoId)]);
194 const hooks = all.filter((h) => h.events.includes("*") || h.events.includes(GITHUB_EVENT[ev.type]));
195 const payload = webhookPayload(env.PUBLIC_URL, ev, row);
196 // Apps installed on the repository that subscribed to the event (apps/service.ts), each on its own.
197 const apps = row ? deliverToApps(env, row, GITHUB_EVENT[ev.type], payload).catch((e) => console.error("app webhooks failed", ev.type, e)) : null;
198 if (!hooks.length) return void (await apps);
199 const body = JSON.stringify(payload);
200 // Each hook retries on its own (deliverWebhook requeues it). Once a hook may have been sent to,
201 // an error must not fail the stage, or the stage retry would send every hook again.
202 const sent = await Promise.allSettled(hooks.map((h) => deliverWebhook(webhookDeps(env), { type: "webhook_retry", repoId: ev.repoId, hookId: h.id, event: GITHUB_EVENT[ev.type], diffineryEvent: ev.type, body, delivery: newId(), attempt: 0 }, h)));
203 for (const r of sent) if (r.status === "rejected") console.error("webhook delivery bookkeeping failed", ev.type, r.reason);
204 await apps;
205}
206
207/** Repository webhooks, and apps' webhooks (hook ids `app:<id>`) whose retries come back through the same queue. */
208const webhookDeps = (env: Env): WebhookDeps => ({
209 ownHost: new URL(env.PUBLIC_URL).hostname,
210 local: localOnly(env),
211 hook: async (repoId, hookId) => (hookId.startsWith(APP_HOOK_PREFIX) ? appHook(env, hookId) : ((await repoStub(env, repoId).deliverableWebhooks()).find((h) => h.id === hookId) ?? null)),
212 record: (repoId, hookId, status) => (hookId.startsWith(APP_HOOK_PREFIX) ? appWebhookDeps(env).record(repoId, hookId, status) : repoStub(env, repoId).recordDelivery(hookId, status)),
213 requeue: async (r, delaySeconds) => {
214 await env.EVENTS.send(r as unknown as DiffineryEvent, { delaySeconds });
215 },
216});
217
218async function handleEvent(env: Env, dir: Directory, ev: DiffineryEvent): Promise<void> {
219 if (ev.type === "audit") {
220 await dir.audit({ actorId: ev.actor.id, actorLogin: ev.actor.login, onBehalfOf: ev.actor.onBehalfOf, action: ev.action, target: ev.target, detail: ev.detail, at: ev.at });
221 return;
222 }
223 // The Today view finds repositories by their latest activity (agentic/today.ts).
224 await recordActivity(env, ev);
225 if (ev.type === "push") {
226 await dir.audit({ actorId: ev.actor.id, actorLogin: ev.actor.login, onBehalfOf: ev.actor.onBehalfOf, action: ev.forced ? "git.force_push" : ev.deleted ? "git.delete_ref" : "git.push", target: `${ev.owner}/${ev.repo}:${ev.ref}`, detail: { before: ev.before, after: ev.after }, at: ev.at });
227 }
228 if (ev.type === "pull_request" && ev.action === "merged") {
229 await dir.audit({ actorId: ev.actor.id, actorLogin: ev.actor.login, onBehalfOf: ev.actor.onBehalfOf, action: "pull.merge", target: `${ev.owner}/${ev.repo}#${ev.number}`, at: ev.at });
230 }
231 // Agent code review (agentic/reviews.ts): opt-in per repository, best effort, never retried.
232 await onReviewEvent(env, dir, ev).catch((e) => console.error("agent review event failed", e));
233 // Agent tasks' Fix failing checks (agentic/tasks.ts): opt-in per task, best effort.
234 await onVerifyEvent(env, ev).catch((e) => console.error("agent task verify failed", e));
235 await runEventStages(env, dir, ev, ["webhooks", "notify"]);
236}
237
238type RepoEvent = Exclude<DiffineryEvent, { type: "audit" }>;
239
240/** Webhooks and notifications run independently; a failed one is retried alone (see lib/stages.ts). */
241function runEventStages(env: Env, dir: Directory, ev: RepoEvent, stages: Stage[], attempt = 0): Promise<void> {
242 return runStages(
243 ev,
244 stages,
245 (stage) => (stage === "webhooks" ? deliverWebhooks(env, ev) : notifyEvent(env, dir, ev)),
246 async (r, delaySeconds) => {
247 await env.EVENTS.send(r as unknown as DiffineryEvent, { delaySeconds });
248 },
249 attempt,
250 );
251}
252
253export async function queue(batch: MessageBatch<DiffineryEvent | MailJob>, env: Env): Promise<void> {
254 // Bounces and complaints from Cloudflare Email Sending's Event Subscriptions (mail/events.ts).
255 if (batch.queue.startsWith("diffinery-mail-events")) return mailEventsQueue(batch as MessageBatch<unknown>, env);
256 // Email has its own queue (diffinery-mail): its jobs can hold sign-in and invite links, so they stay out of the event archive.
257 if (batch.queue.startsWith("diffinery-mail")) return mailQueue(batch as MessageBatch<MailJob>, env);
258 return events(batch as MessageBatch<DiffineryEvent>, env);
259}
260
261async function events(batch: MessageBatch<DiffineryEvent>, env: Env): Promise<void> {
262 const dir = new Directory(env);
263 // Keep an append-only copy of every event in R2 for long-term audit retention.
264 const day = new Date().toISOString().slice(0, 10).replaceAll("-", "/");
265 const fresh = batch.messages.filter((m) => !["webhook_retry", "stage_retry"].includes((m.body as { type: string }).type));
266 if (fresh.length) await env.BUCKET.put(`events/${day}/${Date.now()}-${newId()}.jsonl`, fresh.map((m) => JSON.stringify(m.body)).join("\n")).catch((e) => console.error("event archive failed", e));
267 for (const msg of batch.messages) {
268 try {
269 const body = msg.body as DiffineryEvent | WebhookRetry | StageRetry<RepoEvent>;
270 if (body.type === "webhook_retry") await deliverWebhook(webhookDeps(env), body);
271 else if (body.type === "stage_retry") await runEventStages(env, dir, body.event, [body.stage], body.attempt);
272 else await handleEvent(env, dir, body);
273 msg.ack();
274 } catch (e) {
275 console.error("event handling failed", msg.body.type, e);
276 msg.retry({ delaySeconds: Math.min(300, 10 * 2 ** msg.attempts) });
277 }
278 }
279}
280
281// ---------------------------------------------------------------- cron: housekeeping
282
283export async function scheduled(controller: ScheduledController, env: Env, ctx?: ExecutionContext): Promise<void> {
284 // Container registry housekeeping: abandoned uploads and bytes no image uses any more.
285 const cleanup = new RegistryStore(env).cleanup().catch((e) => console.error("registry cleanup failed", e));
286 if (ctx) ctx.waitUntil(cleanup);
287 else await cleanup;
288 const at = new Date(controller.scheduledTime);
289 at.setUTCSeconds(0, 0);
290 await Promise.all([
291 // Workflow schedules fire from the scheduler's own alarm (src/scheduler.ts); this trigger only makes sure it is set.
292 schedulerStub(env).ensure().catch((e) => console.error("scheduler alarm check failed", e)),
293 // Token expiry reminders and email log pruning.
294 mailCron(env, new Directory(env), at).catch((e) => console.error("mail cron failed", e)),
295 // Audit log entries past their 2 years, and expired sessions, old notifications and compute
296 // records (lib/retention.ts): a bounded batch each hour, which keeps up with a busy instance.
297 (at.getUTCMinutes() < 5 ? pruneAuditLog(env.DB, at) : Promise.resolve(0)).catch((e) => console.error("audit log pruning failed", e)),
298 (at.getUTCMinutes() < 5 ? pruneExpired(env.DB, at) : Promise.resolve(null)).catch((e) => console.error("retention pruning failed", e)),
299 // Tell search engines about public pages a deploy added, changed or removed, and public repositories pushed since (web/indexnow.ts). Never throws.
300 // Imported here: web/indexnow.ts reaches the docs, whose API reference imports this module.
301 import("./web/indexnow.js").then((m) => m.indexNowCron(env, new Directory(env))).catch((e) => console.error("indexnow failed", e)),
302 // CLI sign-ins a day past their expiry (auth/cli-login.ts).
303 new CliLogins(env).prune().catch((e) => console.error("cli sign-in pruning failed", e)),
304 // Spent OAuth codes, expired connected-app tokens, old connections and unused registrations (auth/oauth.ts).
305 new OAuth(env).prune().catch((e) => console.error("oauth pruning failed", e)),
306 // Installation tokens of apps a day past their expiry (apps/store.ts).
307 new Apps(env).prune().catch((e) => console.error("app token pruning failed", e)),
308 // Account exports past their 7 days (accounts/export.ts).
309 expireExports(env).catch((e) => console.error("export expiry failed", e)),
310 // Expire abandoned draft bulk imports after 7 days, and null their stored GitHub token (Low 5).
311 env.DB.prepare("UPDATE imports SET status = 'cancelled', token_ciphertext = NULL, error = 'draft expired', finished_at = ?, updated_at = ? WHERE status = 'draft' AND created_at < ?")
312 .bind(now(), now(), new Date(Date.now() - 7 * 86400_000).toISOString())
313 .run()
314 .catch((e) => console.error("draft import expiry failed", e)),
315 ]);
316}