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.

258 lines · 13.2 KBRaw History
1import { Hono } from "hono";
2import type { Env } from "../env.js";
3import type { AppVars } from "../auth/principal.js";
4import { HttpError } from "../lib/util.js";
5import { BodyTooLarge, putStream, type BlobBucket } from "../lib/blob-store.js";
6import { pushBodyKey, type SpilledBody } from "../lib/storage-keys.js";
7import { importPushAllowed } from "../imports/service.js";
8import { loadRepo, repoStub } from "./common.js";
9import type { Caller } from "../repo/types.js";
10import { resetByDeploy, UPLOAD_PACK_PATH } from "../git/protocol.js";
11
12/**
13 * Git smart HTTP (protocol v2 for fetch/clone, v0 for push) and the Git LFS
14 * batch API, at https://diffinery.com/<owner>/<repo>.git
15 *
16 * A transferred or renamed repository is served under its old name too (`follow`),
17 * as GitHub does, and a push there says where it moved. A redirect would not do:
18 * git follows one only on info/refs (never on its POSTs), and then rebuilds its
19 * credentials from the new URL, which drops a token embedded in the remote URL.
20 */
21export const git = new Hono<{ Bindings: Env; Variables: AppVars }>();
22
23const noCache = { "cache-control": "no-cache, max-age=0, must-revalidate", pragma: "no-cache" };
24
25git.get("/:owner/:repo/info/refs", async (c) => {
26 const service = c.req.query("service");
27 if (service !== "git-upload-pack" && service !== "git-receive-pack") throw new HttpError(403, "dumb HTTP protocol is not supported; update git");
28 // Git only offers credentials after a 401, so an anonymous push must be asked for them (as GitHub does), even to a public repository.
29 if (service === "git-receive-pack" && c.get("principal").type === "anonymous") throw new HttpError(401, "authentication required");
30 const { stub, repo } = await loadRepo(c, c.req.param("owner"), c.req.param("repo"), service === "git-receive-pack" ? "write" : "read", { follow: true });
31 if (service === "git-receive-pack" && repo.archived) throw new HttpError(403, "repository is archived (read-only)");
32 if (service === "git-upload-pack" && !/version=2/.test(c.req.header("git-protocol") ?? "")) {
33 throw new HttpError(400, "Diffinery requires Git protocol v2 (git 2.26 or newer, or run: git config --global protocol.version 2)");
34 }
35 const body = await stub.gitInfoRefs(service);
36 return new Response(body, { headers: { "content-type": `application/x-${service}-advertisement`, ...noCache } });
37});
38
39git.post("/:owner/:repo/git-upload-pack", async (c) => {
40 const { stub } = await loadRepo(c, c.req.param("owner"), c.req.param("repo"), "read", { readOnlyPost: true, follow: true });
41 const body = await readBody(c.req.raw, MAX_UPLOAD_PACK_REQUEST, "fetch request exceeds 16 MB");
42 // Through RepoDO.fetch rather than RPC, so the pack streams on celld too.
43 const out = await stub.fetch(`https://repo${UPLOAD_PACK_PATH}`, { method: "POST", body });
44 return new Response(out.body, { headers: { "content-type": "application/x-git-upload-pack-result", ...noCache } });
45});
46
47git.post("/:owner/:repo/git-receive-pack", async (c) => {
48 // During someone else's import the repository refuses the push itself, with a message the client prints.
49 const { stub, caller, repo, moved } = await loadRepo(c, c.req.param("owner"), c.req.param("repo"), "write", { follow: true, whileImporting: true });
50 // A GitHub import's own token, while that import is running and filling this repository, may push in import mode.
51 const p = c.get("principal");
52 if (p.type === "account" && p.importId && p.tokenId && (await importPushAllowed(c.env, p.importId, repo.id, p.tokenId))) caller.importId = p.importId;
53 const { body, release } = await readPushBody(c.env, repo.id, c.req.raw);
54 const out = await receiveWithRetry(c.env, repo.id, stub, body, caller, moved).finally(release);
55 c.executionCtx.waitUntil(c.get("dir").touchPushed(repo.id));
56 return new Response(out, { headers: { "content-type": "application/x-git-receive-pack-result", ...noCache } });
57});
58
59/**
60 * A deploy resets every Durable Object, and one doing a push then fails it mid-way: git doesn't
61 * retry a push, so it would print a 500. The push is handed over once more (to the new code; a
62 * large one is still staged in R2: only this function deletes it, once the push is done either way).
63 * Nothing is lost or moved twice: objects are stored by their ids, and refs move only at the end,
64 * each by compare-and-swap; one the cut-off attempt already moved to the pushed commit is reported
65 * as updated.
66 */
67export async function receiveWithRetry(env: Env, repoId: string, stub: ReturnType<typeof repoStub>, body: Uint8Array | SpilledBody, caller: Caller, moved: boolean): Promise<Uint8Array> {
68 try {
69 for (let attempt = 1; ; attempt++) {
70 try {
71 return await stub.gitReceivePack(body, caller, { moved, retry: attempt > 1 });
72 } catch (e) {
73 if (attempt >= PUSH_TRIES || !(resetByDeploy(e) || resetForMemory(e))) throw e;
74 // A stub that saw its object reset is broken; a new one reaches the new code.
75 stub = repoStub(env, repoId);
76 }
77 }
78 } finally {
79 if (!(body instanceof Uint8Array)) await env.BUCKET.delete(body.spilled).catch(() => {});
80 }
81}
82
83const PUSH_TRIES = 2;
84
85/**
86 * The repository's object was reset for going past its memory. Pushes to one repository take turns
87 * for memory (RepoDO.gitReceivePack), so a push cut off this way was most likely caught up in another
88 * request's reset, not the cause: like a deploy's reset, it is handed over once more, which moves the
89 * refs the cut-off attempt didn't and sends the push events it may not have sent.
90 */
91export const resetForMemory = (e: unknown) => e instanceof Error && /exceeded its memory limit and was reset/i.test(e.message);
92
93export { resetByDeploy };
94
95/** A fetch's wants and haves; git's own negotiation stays far below this. */
96const MAX_UPLOAD_PACK_REQUEST = 16 * 1024 * 1024;
97/** The repository refuses pushes over 100 MB with a clear message; this stops anything far beyond. */
98const MAX_RECEIVE_PACK_REQUEST = 101 * 1024 * 1024;
99
100/**
101 * The request body, gunzipped when the client compressed it. Reading stops at `max` bytes
102 * (after decompression), so neither a huge body nor a gzip bomb is ever held in memory.
103 */
104async function readBody(req: Request, max: number, tooLarge: string): Promise<Uint8Array> {
105 let stream = req.body;
106 if (!stream) return new Uint8Array(0);
107 if (req.headers.get("content-encoding") === "gzip") stream = stream.pipeThrough(new DecompressionStream("gzip"));
108 const chunks: Uint8Array[] = [];
109 let total = 0;
110 const reader = stream.getReader();
111 for (;;) {
112 const { done, value } = await reader.read();
113 if (done) break;
114 total += value.length;
115 if (total > max) {
116 await reader.cancel().catch(() => {});
117 throw new HttpError(413, tooLarge);
118 }
119 chunks.push(value);
120 }
121 const out = new Uint8Array(total);
122 let at = 0;
123 for (const ch of chunks) {
124 out.set(ch, at);
125 at += ch.length;
126 }
127 return out;
128}
129
130/** Pushes up to this size are handed to the repository in memory; larger ones go through R2. */
131const IN_MEMORY_PUSH = 16 * 1024 * 1024;
132/**
133 * Push bodies one Worker isolate holds in memory at once, across its requests (it has 128 MB, and a
134 * body is held twice while it is joined): past this, a push goes through R2 even under IN_MEMORY_PUSH.
135 */
136const ISOLATE_PUSH_BYTES = 32 * 1024 * 1024;
137let bufferedPushBytes = 0;
138
139/**
140 * A push's body. A large one is staged in R2 as it arrives (a Worker and a Durable Object each
141 * have 128 MB of memory, and holding a 70 MB push twice, then copying it to the repository, does
142 * not fit); the repository reads it from there once and deletes it.
143 */
144async function readPushBody(env: Env, repoId: string, req: Request): Promise<{ body: Uint8Array | SpilledBody; release: () => void }> {
145 let counted = 0;
146 const release = () => {
147 bufferedPushBytes -= counted;
148 counted = 0;
149 };
150 try {
151 return { body: await readPushBodyCounted(env, repoId, req, (n) => ((counted += n), (bufferedPushBytes += n))), release };
152 } catch (e) {
153 release();
154 throw e;
155 }
156}
157
158/** readPushBody's body; `count` is told of every byte held in memory (ISOLATE_PUSH_BYTES). */
159async function readPushBodyCounted(env: Env, repoId: string, req: Request, count: (bytes: number) => void): Promise<Uint8Array | SpilledBody> {
160 const tooLarge = "push exceeds 100 MB; split it into smaller pushes";
161 let stream = req.body;
162 if (!stream) return new Uint8Array(0);
163 if (req.headers.get("content-encoding") === "gzip") stream = stream.pipeThrough(new DecompressionStream("gzip"));
164 const chunks: Uint8Array[] = [];
165 let total = 0;
166 const reader = stream.getReader();
167 for (;;) {
168 const { done, value } = await reader.read();
169 if (done) break;
170 total += value.length;
171 chunks.push(value);
172 count(value.length);
173 if (total > IN_MEMORY_PUSH || bufferedPushBytes > ISOLATE_PUSH_BYTES) {
174 // Too big to pass along in memory (or this isolate holds enough already): what came so far, then the rest, goes to R2.
175 count(-total);
176 const key = pushBodyKey(repoId);
177 const rest = new ReadableStream<Uint8Array>({
178 start(controller) {
179 for (const ch of chunks.splice(0)) controller.enqueue(ch);
180 },
181 async pull(controller) {
182 const next = await reader.read();
183 if (next.done) controller.close();
184 else controller.enqueue(next.value);
185 },
186 cancel: () => reader.cancel(),
187 });
188 try {
189 const size = await putStream(env.BUCKET as unknown as BlobBucket, key, rest, MAX_RECEIVE_PACK_REQUEST);
190 return { spilled: key, size };
191 } catch (e) {
192 await env.BUCKET.delete(key).catch(() => {});
193 if (e instanceof BodyTooLarge) throw new HttpError(413, tooLarge);
194 throw e;
195 }
196 }
197 }
198 const out = new Uint8Array(total);
199 let at = 0;
200 for (const ch of chunks) {
201 out.set(ch, at);
202 at += ch.length;
203 }
204 return out;
205}
206
207// ---------------------------------------------------------------- Git LFS
208
209const lfsKey = (repoId: string, oid: string) => `repos/${repoId}/lfs/${oid.slice(0, 2)}/${oid.slice(2, 4)}/${oid}`;
210const LFS_TYPE = "application/vnd.git-lfs+json";
211
212git.post("/:owner/:repo/info/lfs/objects/batch", async (c) => {
213 const req = (await c.req.json()) as { operation: "upload" | "download"; objects: Array<{ oid: string; size: number }> };
214 const { repo, stub } = await loadRepo(c, c.req.param("owner"), c.req.param("repo"), req.operation === "upload" ? "write" : "read", { readOnlyPost: req.operation !== "upload", follow: true });
215 const base = `${c.env.PUBLIC_URL}/${c.req.param("owner")}/${c.req.param("repo")}/info/lfs/objects`;
216 const auth = c.req.header("authorization");
217 const objects = [];
218 const uploads: Array<{ oid: string; size: number }> = [];
219 for (const o of req.objects.slice(0, 1000)) {
220 if (!/^[0-9a-f]{64}$/.test(o.oid)) {
221 objects.push({ oid: o.oid, size: o.size, error: { code: 422, message: "invalid oid" } });
222 continue;
223 }
224 const head = await c.env.BUCKET.head(lfsKey(repo.id, o.oid));
225 if (req.operation === "download") {
226 if (!head) objects.push({ oid: o.oid, size: o.size, error: { code: 404, message: "object not found" } });
227 else objects.push({ oid: o.oid, size: head.size, authenticated: true, actions: { download: { href: `${base}/${o.oid}`, header: auth ? { Authorization: auth } : {}, expires_in: 3600 } } });
228 } else if (head) objects.push({ oid: o.oid, size: o.size, authenticated: true });
229 else uploads.push(o);
230 }
231 // Past the owner's storage quota (lib/quotas.ts) no new object is taken: each gets the reason instead.
232 const full = uploads.length ? await stub.storageRefusal(uploads.reduce((n, o) => n + (Number(o.size) || 0), 0)) : null;
233 for (const o of uploads) objects.push(full ? { oid: o.oid, size: o.size, error: { code: 507, message: full } } : { oid: o.oid, size: o.size, authenticated: true, actions: { upload: { href: `${base}/${o.oid}`, header: auth ? { Authorization: auth } : {}, expires_in: 3600 } } });
234 return c.body(JSON.stringify({ transfer: "basic", objects, hash_algo: "sha256" }), 200, { "content-type": LFS_TYPE });
235});
236
237git.get("/:owner/:repo/info/lfs/objects/:oid", async (c) => {
238 const { repo } = await loadRepo(c, c.req.param("owner"), c.req.param("repo"), "read", { follow: true });
239 const obj = await c.env.BUCKET.get(lfsKey(repo.id, c.req.param("oid")));
240 if (!obj) throw new HttpError(404, "object not found");
241 return new Response(obj.body, { headers: { "content-type": "application/octet-stream", "content-length": String(obj.size) } });
242});
243
244git.put("/:owner/:repo/info/lfs/objects/:oid", async (c) => {
245 const { repo, stub } = await loadRepo(c, c.req.param("owner"), c.req.param("repo"), "write", { follow: true });
246 const oid = c.req.param("oid");
247 if (!/^[0-9a-f]{64}$/.test(oid)) throw new HttpError(422, "invalid oid");
248 const length = Number(c.req.header("content-length"));
249 const full = await stub.storageRefusal(Number.isFinite(length) ? length : 0);
250 if (full) throw new HttpError(507, full);
251 // Verify the content hash while storing: R2 checks the SHA-256 we pass.
252 const body = await c.req.arrayBuffer();
253 const digest = [...new Uint8Array(await crypto.subtle.digest("SHA-256", body))].map((b) => b.toString(16).padStart(2, "0")).join("");
254 if (digest !== oid) throw new HttpError(422, "content does not match oid");
255 await c.env.BUCKET.put(lfsKey(repo.id, oid), body);
256 await stub.recordLfs(oid, body.byteLength);
257 return c.body(null, 200);
258});