Diffinery

codician/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.

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