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.

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