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.

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