1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251 | import type { Env } from "./env";
import type { RepoInfo } from "./registry";
import { esc, age, layout, htmlResponse, errorPage } from "./ui/html";
import { CSS } from "./ui/style";
export { RepoCell } from "./repo";
export { Registry } from "./registry";
const REPO_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
const RESERVED = new Set(["cgit.css", "favicon.ico", "robots.txt", "info", "git-upload-pack", "git-receive-pack"]);
const CACHE_TTL = 60;
function tokens(env: Env): string[] {
const list = [env.GIT_TOKEN ?? "", ...(env.GIT_TOKENS ?? "").split(",")];
return list.map((t) => t.trim()).filter(Boolean);
}
function unauthorized(): Response {
return new Response("auth required\n", {
status: 401,
headers: { "www-authenticate": 'Basic realm="dgit"' },
});
}
/** HTTP Basic where the password (or username) is one of the configured tokens. */
function checkAuth(req: Request, env: Env): Response | null {
const valid = tokens(env);
if (!valid.length) {
return new Response("access is disabled: set the GIT_TOKEN secret\n", { status: 403 });
}
const header = req.headers.get("authorization") ?? "";
if (!header.startsWith("Basic ")) return unauthorized();
let user = "", pass = "";
try {
const decoded = atob(header.slice(6));
const colon = decoded.indexOf(":");
user = colon === -1 ? decoded : decoded.slice(0, colon);
pass = colon === -1 ? "" : decoded.slice(colon + 1);
} catch {
return unauthorized();
}
if (!valid.includes(pass) && !valid.includes(user)) return unauthorized();
return null;
}
function siteBase(env: Env) {
return {
site: env.SITE_NAME ?? "dgit",
siteDesc: env.SITE_DESC ?? "",
title: env.SITE_NAME ?? "dgit",
sub: env.SITE_DESC ?? "",
tab: "index",
};
}
async function indexPage(env: Env): Promise<Response> {
const registry = env.REGISTRY.getByName("registry");
const repos = (await registry.list()).filter((r) => !r.priv);
let rows = "";
let lastSection: string | null = null;
for (const r of repos) {
if (r.section !== lastSection) {
if (r.section) {
rows += `<tr class='nohover'><td class='reposection' colspan='4'>${esc(r.section)}</td></tr>`;
}
lastSection = r.section;
}
rows +=
`<tr><td><a href='/${encodeURIComponent(r.name)}/'>${esc(r.name)}</a></td>` +
`<td>${esc(r.desc || "[no description]")}</td>` +
`<td>${esc(r.owner || env.SITE_OWNER || "")}</td>` +
`<td>${age(Math.floor(r.idle / 1000))}</td></tr>`;
}
const body = `
<table class='list nowrap'>
<tr class='nohover'><th class='left'>Name</th><th class='left'>Description</th><th class='left'>Owner</th><th class='left'>Idle</th></tr>
${rows || "<tr class='nohover'><td colspan='4'>no repositories yet — create one by pushing: <code>git push https://<this-host>/myrepo.git main</code></td></tr>"}
</table>`;
return htmlResponse(layout({ ...siteBase(env), body }));
}
/**
* Per-isolate memo of registry lookups. Without it every page view — cache
* hit or not — funnels through the single Registry DO, which becomes the
* global bottleneck under a traffic spike. Staleness window is small and
* only affects metadata (descriptions, versions, the private flag).
*/
const infoMemo = new Map<string, { at: number; info: RepoInfo | null }>();
const INFO_TTL_MS = 20_000;
async function repoInfo(env: Env, repo: string, fresh: boolean): Promise<RepoInfo | null> {
const hit = infoMemo.get(repo);
if (!fresh && hit && Date.now() - hit.at < INFO_TTL_MS) return hit.info;
const info = await env.REGISTRY.getByName("registry").get(repo);
infoMemo.set(repo, { at: Date.now(), info });
return info;
}
/** Cache API is a Cloudflare-only surface; celld has none, so feature-detect. */
function pageCache(): Cache | null {
try {
// eslint-disable-next-line no-undef
return typeof caches !== "undefined" && (caches as unknown as { default?: Cache }).default
? (caches as unknown as { default: Cache }).default
: null;
} catch {
return null;
}
}
export default {
async fetch(req: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const url = new URL(req.url);
const path = url.pathname;
if (path === "/" || path === "") {
// the index is the front door under load: cache it briefly at the edge
const cache = pageCache();
if (cache) {
const key = new Request(`${url.origin}/?__index`, { method: "GET" });
const hit = await cache.match(key);
if (hit) return hit;
const res = await indexPage(env);
const toCache = new Response(res.clone().body, res);
toCache.headers.set("cache-control", "public, max-age=30");
ctx.waitUntil(cache.put(key, toCache));
return res;
}
return indexPage(env);
}
if (path === "/cgit.css") {
return new Response(CSS, { headers: { "content-type": "text/css", "cache-control": "public, max-age=3600" } });
}
if (path === "/robots.txt") {
return new Response(
"User-agent: *\nDisallow: /*/snapshot/\nDisallow: /*/blame/\nDisallow: /*/stats/\nDisallow: /*/diff/\nDisallow: /*/rawdiff/\nDisallow: /*/patch/\n",
{ headers: { "content-type": "text/plain" } }
);
}
if (path === "/favicon.ico") {
return new Response("not found\n", { status: 404 });
}
const m = path.match(/^\/([^/]+?)(\.git)?(\/.*)?$/);
if (!m) return errorPage(siteBase(env), "bad request", 400);
const repo = decodeURIComponent(m[1]);
const sub = m[3] ?? "/";
if (!REPO_NAME.test(repo) || RESERVED.has(repo)) {
return errorPage(siteBase(env), `no such repository: ${repo}`, 404);
}
const registry = env.REGISTRY.getByName("registry");
const isReceive =
sub === "/git-receive-pack" ||
(sub === "/info/refs" && url.searchParams.get("service") === "git-receive-pack");
const isProtocol = isReceive || sub === "/git-upload-pack" || sub === "/info/refs";
const isAdmin =
((sub === "/config" || sub === "/description") && req.method === "PUT") ||
(sub === "/gc" && req.method === "POST") ||
((sub === "/" || sub === "") && req.method === "DELETE");
// mutations read the registry fresh; page views tolerate a short memo
const info: RepoInfo | null = await repoInfo(env, repo, isReceive || isAdmin);
// pushes, admin operations, and everything on a private repo require auth
if (isReceive || isAdmin || info?.priv) {
const denied = checkAuth(req, env);
if (denied) return denied;
}
// only pushes and admin ops may touch repos that don't exist yet
if (!info && !isReceive && !isAdmin) {
if (isProtocol) return new Response(`repository not found: ${repo}\n`, { status: 404 });
return errorPage(siteBase(env), `no such repository: ${repo}`, 404);
}
// page cache for public repo GET pages (versioned key; skipped on celld)
const cache = pageCache();
const cacheable =
cache !== null &&
req.method === "GET" &&
!isProtocol &&
info !== null &&
!info.priv &&
!req.headers.has("authorization");
let cacheKey: Request | null = null;
if (cacheable) {
const keyUrl = new URL(url.toString());
keyUrl.searchParams.set("__v", String(info!.ver));
cacheKey = new Request(keyUrl.toString(), { method: "GET" });
const hit = await cache!.match(cacheKey);
if (hit) return hit;
}
const stub = env.REPO.getByName(repo);
const doUrl = new URL(req.url);
doUrl.pathname = sub;
// On celld, re-wrapping a bytes-backed request yields a stream-backed one
// whose consumption UTF-8-decodes the whole body (fatal for multi-hundred-
// MB binary packs). Forward explicit bytes there; stream on workerd.
let fwdBody: BodyInit | null = null;
if (req.method !== "GET" && req.method !== "HEAD" && req.body) {
fwdBody = pageCache() === null ? ((await req.arrayBuffer()) as ArrayBuffer) : req.body;
}
const fwd = new Request(doUrl.toString(), {
method: req.method,
headers: req.headers,
body: fwdBody,
});
fwd.headers.set("x-repo", repo);
fwd.headers.set("x-host", url.host);
fwd.headers.set("x-proto", url.protocol.replace(":", ""));
const res = await stub.fetch(fwd);
// bookkeeping after successful mutations
if (res.ok && sub === "/git-receive-pack" && res.headers.get("x-changed") === "1") {
await registry.upsert(repo, Date.now());
}
if (res.ok && (sub === "/config" || sub === "/description") && req.method === "PUT") {
try {
const cfg = (await res.clone().json()) as {
description: string;
owner: string;
section: string;
private: boolean;
};
if (!info) await registry.upsert(repo, Date.now());
await registry.setConfig(repo, {
desc: cfg.description,
owner: cfg.owner,
section: cfg.section,
priv: cfg.private,
});
} catch {
// non-JSON response; skip registry sync
}
}
if (res.ok && (sub === "/" || sub === "") && req.method === "DELETE") {
await registry.remove(repo);
}
if (isReceive || isAdmin) infoMemo.delete(repo); // this isolate sees its own mutations
if (cacheable && cacheKey && res.ok && !res.headers.has("set-cookie")) {
const toCache = new Response(res.clone().body, res);
toCache.headers.set("cache-control", `public, max-age=${CACHE_TTL}`);
ctx.waitUntil(cache!.put(cacheKey, toCache));
}
return res;
},
} satisfies ExportedHandler<Env>;
|