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.

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