| author | Divy Srivastava <me@littledivy.com> | 2026-08-20 03:40:23 +0530 |
|---|---|---|
| committer | Divy Srivastava <me@littledivy.com> | 2026-08-20 03:40:23 +0530 |
| commit | 0fa57ce9fe4fc8314ab6d6a93ae1e42ec9acec78 (patch) | |
| tree | f1cd08f4d336430234802ef5fc663f5c4e575126 | |
| parent | 17b03631eb6676f3b2c86b6662d9af4aa9237bef (diff) | |
| download | dgit-0fa57ce9fe.tar.gz zip | |
v0.0.4v0.0.4
Diffstat
| .github/workflows/publish.yml (new) | +34 | -0 |
| README.md | +57 | -0 |
| docs/api.md (new) | +194 | -0 |
| examples/platform.ts (new) | +73 | -0 |
| package.json | +25 | -3 |
| src/index.ts | +6 | -417 |
| src/mod.ts (new) | +545 | -0 |
| src/repo.ts | +212 | -6 |
| src/ui/style.ts | +49 | -0 |
| tsconfig.json | +4 | -2 |
10 files changed, 1199 insertions(+), 428 deletions(-)
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml @@ -0,0 +1,34 @@ +name: publish + +on: + push: + tags: ["v*"] + +jobs: + publish: + runs-on: ubuntu-latest + permissions: + contents: read + # npm trusted publishing: the workflow's OIDC identity is the credential, + # no NPM_TOKEN secret anywhere (configured on npmjs.com under the + # package's Trusted Publisher settings) + id-token: write + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + # npm >= 11.5 for OIDC publishing; node 24 bundles it + node-version: 24 + registry-url: https://registry.npmjs.org + - run: npm ci + - run: npm run typecheck + - name: tag matches package.json + run: test "v$(node -p "require('./package.json').version")" = "$GITHUB_REF_NAME" + - name: publish, unless the version is already on the registry + run: | + v=$(node -p "require('./package.json').version") + if npm view "durable-git@$v" version >/dev/null 2>&1; then + echo "durable-git@$v already published, skipping" + else + npm publish + fi diff --git a/README.md b/README.md @@ -93,6 +93,63 @@ The heap and durability-deadline variables give large single-cell ingests the room the defaults do not. +## Build on dgit + +dgit is also a library, published as +[`durable-git`](https://www.npmjs.com/package/durable-git). The deployed +Worker above is three lines around it: + +```ts +import { createDurableGit, secretsEqual } from "durable-git"; +export { RepoCell, Registry } from "durable-git"; + +export default createDurableGit({ + async authorize({ repo, op, private: priv, credentials, env }) { + if (op === "read" && !priv) return true; + return secretsEqual(credentials?.pass ?? "", await lookupDeployKey(env, repo)); + }, + onPush(event, env) { + return fetch("https://ci.example.com/hook", { method: "POST", body: JSON.stringify(event) }); + }, +}); +``` + +The package ships TypeScript source, which wrangler bundles directly; +bind the Durable Object classes as [wrangler.jsonc](wrangler.jsonc) does +and re-export them from your entry module. + +`authorize` gates every repository-scoped request — `read` (pages, +clones, the content API), `write` (push), or `admin` (config, gc, +delete) — ahead of the page cache and the R2 clone path. `false` sends +the Basic challenge; a `Response` is sent verbatim. It replaces the +stock `GIT_TOKEN` policy entirely, so the private flag protects nothing +unless the hook consults it. `onPush` fires off the response path with +the ref updates a push applied. [docs/api.md](docs/api.md) has the full +contract; [examples/platform.ts](examples/platform.ts) is a multi-tenant +host built from both. + +Reading a repository from code needs no git client. Every repository +serves a JSON API, gated like its pages: + +``` +/myrepo/api/refs refs and HEAD, tags peeled +/myrepo/api/log?h=main&path=src&n=50 commit log, filtered and paged +/myrepo/api/commit?id=v1 one commit (branch, tag, or oid) +/myrepo/api/tree?h=main&path=src tree listing with blob sizes +/myrepo/api/blob?h=main&path=a.ts raw blob bytes (oid in x-oid) +``` + +and the same surface is typed RPC on the cell, for Workers holding the +`REPO` binding — which bypasses `authorize`, so gate such routes +yourself: + +```ts +const repo = env.REPO.getByName("myrepo"); +const { head, refs } = await repo.listRefs(); +const log = await repo.listLog("main", { path: "src", n: 20 }); +const blob = await repo.readBlob("main", "src/a.ts"); +``` + ## Operate ```sh diff --git a/docs/api.md b/docs/api.md @@ -0,0 +1,194 @@ +# durable-git API + +The library (`createDurableGit`), the JSON API every repository serves, +and the RPC surface on the repository cell. Operational endpoints +(config, gc, delete) are in the [README](../README.md#operate). + +```sh +npm install durable-git +``` + +The package ships TypeScript source; wrangler bundles it directly. Bind +the Durable Object classes as dgit's own +[wrangler.jsonc](../wrangler.jsonc) does — `REPO` → `RepoCell`, +`REGISTRY` → `Registry`, both in `new_sqlite_classes` — and re-export +them from your entry module. + +## createDurableGit(options?) + +```ts +import { createDurableGit } from "durable-git"; +export { RepoCell, Registry } from "durable-git"; + +export default createDurableGit(options); +``` + +Returns `{ fetch }` — a valid Worker default export that a wrapping +router can also delegate to. `createDurableGit<Env>` types the hooks' +`env` with your own bindings. + +### authorize + +```ts +authorize?: (ctx: AuthContext) => boolean | Response | Promise<boolean | Response>; +``` + +Runs for every repository-scoped request before any repository data is +touched, ahead of the page cache and the R2 clone path. The index page +is not repository-scoped; it lists public repositories regardless. + +| `ctx` field | | +|---|---| +| `repo` | repository name, already validated against `[A-Za-z0-9][A-Za-z0-9._-]*` | +| `op` | `"read"` pages, clones, the JSON API · `"write"` push · `"admin"` config, gc, delete | +| `private` | the registry's private flag; `false` for a repository that does not exist yet | +| `credentials` | `{ user, pass }` from HTTP Basic, or `null` | +| `request` | headers and URL only — the body is consumed downstream; a hook that reads it breaks every push | +| `env` | your bindings | + +Return `true` to allow, `false` for the 401 Basic challenge (git +clients then prompt), or a `Response` to send verbatim. The hook +replaces the default policy entirely: `private` protects nothing unless +the hook consults it, and the mistake is silent because private +repositories are hidden from the index either way. The safe skeleton: + +```ts +async authorize({ op, private: priv, credentials, env }) { + if (op === "read" && !priv) return true; + return checkCredentials(env, credentials); +} +``` + +The default hook: public reads open; everything else requires a +`GIT_TOKEN`/`GIT_TOKENS` match, compared timing-safely, with per-IP +failure rate limiting. + +### onPush + +```ts +onPush?: (event: PushEvent, env: Env) => void | Promise<void>; + +interface PushEvent { + repo: string; + updates: { ref: string; old: string; new: string }[]; + commitTime: number; // unix millis of the newest committer date +} +``` + +Fires after a push applies at least one ref update, via `waitUntil`: a +slow or throwing hook never fails the push. `old`/`new` are all-zeros +for a created/deleted ref; rejected commands never appear. Delivery is +at-most-once, and a push updating very many refs at once arrives +truncated (8 KB budget) — a consumer that must not miss updates +reconciles against `/api/refs`. + +### secretsEqual(a, b) + +Timing-safe string comparison for hooks. `credentials.pass === secret` +leaks the match through timing. + +### Env + +| | | +|---|---| +| `REPO`, `REGISTRY` | the Durable Object namespaces | +| `PACK_CACHE?` | R2 pack offload + full-clone cache; absent falls back to SQLite-only | +| `GIT_TOKEN?`, `GIT_TOKENS?` | passwords for the default authorize | +| `MAX_PUSH_MB?` | single-push cap, default 512 | +| `SHA1DC?` | `"1"` screens pushed objects for SHA-1 collisions | +| `SITE_NAME?`, `SITE_DESC?`, `SITE_OWNER?` | page chrome | + +## JSON API + +`/<repo>/api/*`, GET only, gated like the repository's pages +(`op: "read"`). Errors are `{ "error": "..." }` with a 404. `h` and +`id` take a branch, tag, full ref, or full 40-char oid — an oid is +served only when reachable from a current ref. Omitted means HEAD; tags +peel to commits. + +### GET /\<repo\>/api/refs + +```json +{ + "head": "refs/heads/main", + "refs": [ + { "name": "refs/heads/main", "target": "9e3c2c…" }, + { "name": "refs/tags/v1", "target": "77afdb…", "peeled": "9e3c2c…" } + ] +} +``` + +`head` is null when unborn; `peeled` appears on annotated tags. + +### GET /\<repo\>/api/log?h=\<ref\>&path=\<path\>&ofs=\<n\>&n=\<limit\> + +`{ "commits": [<commit>, …], "more": true }`, newest first. `path` +filters to commits that changed it; `n` is 1–100, default 50. The walk +is bounded: 5000 commits, 2000 when path-filtered. + +### GET /\<repo\>/api/commit?id=\<ref-or-oid\> + +```json +{ + "oid": "9e3c2c…", + "tree": "b1de8b…", + "parents": ["d29562…"], + "author": { "name": "T", "email": "t@t.co", "time": 1787162584, "tz": "+0530" }, + "committer": { "name": "T", "email": "t@t.co", "time": 1787162584, "tz": "+0530" }, + "subject": "second", + "message": "second\n" +} +``` + +`time` is unix seconds, git's own unit (`PushEvent.commitTime` is +millis). + +### GET /\<repo\>/api/tree?h=\<ref\>&path=\<dir\> + +```json +{ + "oid": "ead936…", + "entries": [ + { "name": "a.ts", "mode": "100644", "type": "blob", "oid": "ad1d38…", "size": 20 }, + { "name": "vendor", "mode": "160000", "type": "commit", "oid": "abc123…" } + ] +} +``` + +`type` is blob, tree, or commit (a gitlink); `size` on blobs only. 404 +when `path` names a blob or nothing. + +### GET /\<repo\>/api/blob?h=\<ref\>&path=\<file\> + +The raw bytes, not JSON. Content type from the extension with nosniff; +the blob's oid in the `x-oid` header. + +## RPC + +The same surface as typed methods on the cell, for same-account Workers +holding the `REPO` binding: + +```ts +const repo = env.REPO.getByName("myrepo"); +await repo.listRefs(); // RefsResult +await repo.readCommit("v1"); // CommitJson | null +await repo.listLog("main", { path: "src", n: 20 }); // LogResult +await repo.listTree("main", "src"); // TreeResult | null +await repo.readBlob("main", "src/a.ts"); // BlobResult | null — { oid, mode, data } +``` + +Resolution, bounds, and reachability match the JSON API; pass +`undefined` as the ref for HEAD. Every shape is an exported type, +alongside `PushEvent`, `AuthContext`, `DurableGitOptions`, `Env`, and +`RepoInfo`. + +RPC runs no auth — a binding is trusted infrastructure. A route built +on it gates itself: validate the name before `getByName` (an unchecked +name materializes a billable cell per probe), check the registry, and +hold private reads to real credentials. +[examples/platform.ts](../examples/platform.ts) shows the pattern; the +registry is addressed the same way: + +```ts +await env.REGISTRY.getByName("registry").get(repo); // RepoInfo | null +``` diff --git a/examples/platform.ts b/examples/platform.ts @@ -0,0 +1,73 @@ +// A minimal platform on durable-git: public reads of public repos, +// per-repository deploy keys in KV, a CI webhook on push, and a route that +// reads repository content over RPC. Bind the Durable Objects as dgit's own +// wrangler.jsonc does and re-export the classes. +import { createDurableGit, secretsEqual, type Env as DgitEnv, type PushEvent } from "durable-git"; + +export { RepoCell, Registry } from "durable-git"; + +interface Env extends DgitEnv { + /** key: repository name, value: its push token */ + DEPLOY_KEYS: KVNamespace; + CI_WEBHOOK: string; +} + +/** a repository's deploy key also grants private reads and admin ops */ +async function holdsDeployKey(env: Env, repo: string, pass: string | undefined): Promise<boolean> { + const key = await env.DEPLOY_KEYS.get(repo); + return key !== null && (await secretsEqual(pass ?? "", key)); +} + +const git = createDurableGit<Env>({ + // consulting ctx.private is on the hook: it replaces the default policy + async authorize({ repo, op, private: priv, credentials, env }) { + if (op === "read" && !priv) return true; + return holdsDeployKey(env, repo, credentials?.pass); + }, + async onPush(event: PushEvent, env: Env) { + await fetch(env.CI_WEBHOOK, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(event), + }); + }, +}); + +const REPO_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; + +export default { + async fetch(req: Request, env: Env, ctx: ExecutionContext): Promise<Response> { + const url = new URL(req.url); + // serve any repository's README at /_readme/<repo> over RPC. RPC bypasses + // authorize, so the route gates itself: validate the name (an unchecked + // getByName materializes a cell per probe), then hold private repos to + // the same key as a push. + if (url.pathname.startsWith("/_readme/")) { + const repo = url.pathname.slice("/_readme/".length); + if (!REPO_NAME.test(repo)) return new Response("bad repository name\n", { status: 400 }); + const info = await env.REGISTRY.getByName("registry").get(repo); + if (!info) return new Response("not found\n", { status: 404 }); + if (info.priv && !(await holdsDeployKey(env, repo, parseBasicPass(req)))) { + return new Response("auth required\n", { + status: 401, + headers: { "www-authenticate": 'Basic realm="platform"' }, + }); + } + const blob = await env.REPO.getByName(repo).readBlob(undefined, "README.md"); + if (!blob) return new Response("no README\n", { status: 404 }); + return new Response(blob.data, { headers: { "content-type": "text/markdown; charset=utf-8" } }); + } + return git.fetch(req, env, ctx); + }, +} satisfies ExportedHandler<Env>; + +function parseBasicPass(req: Request): string | undefined { + const header = req.headers.get("authorization") ?? ""; + if (!header.startsWith("Basic ")) return undefined; + try { + const decoded = atob(header.slice(6)); + return decoded.slice(decoded.indexOf(":") + 1); + } catch { + return undefined; + } +} diff --git a/package.json b/package.json @@ -1,8 +1,30 @@ { - "name": "dgit", - "version": "0.1.0", - "private": true, + "name": "durable-git", + "version": "0.0.4", + "description": "Durable git: a git server as a Cloudflare Durable Object. Smart HTTP, a cgit-style web interface, pluggable auth, push events, and a typed content API.", "type": "module", + "main": "src/mod.ts", + "types": "src/mod.ts", + "exports": { + ".": "./src/mod.ts" + }, + "files": [ + "src", + "README.md", + "LICENSE" + ], + "keywords": [ + "git", + "cloudflare-workers", + "durable-objects", + "cgit", + "git-server" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/littledivy/dgit.git" + }, "scripts": { "dev": "wrangler dev", "deploy": "wrangler deploy", diff --git a/src/index.ts b/src/index.ts @@ -1,419 +1,8 @@ -import type { Env } from "./env"; -import type { RepoInfo } from "./registry"; -import { esc, age, layout, htmlResponse, errorPage } from "./ui/html"; -import { CSS } from "./ui/style"; -import { parseUploadRequest, streamingCloneResponse } from "./git/protocol"; -import { isOid } from "./git/util"; -import { gunzipLimited } from "./git/zlib"; -import type { RepoCell } from "./repo"; +// Deploy entry for the stock dgit Worker: default options (token auth, no +// push hook). To build your own, `import { createDurableGit } from +// "durable-git"` in your Worker and pass authorize/onPush — see the README. +import { createDurableGit } from "./mod"; -/** an upload-pack negotiation body is wants/haves/caps only — a few hundred KB */ -const MAX_UPLOAD_PACK_BYTES = 16 * 1024 * 1024; +export { RepoCell, Registry } from "./mod"; -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"' }, - }); -} - -function tooManyRequests(retryAfterMs: number): Response { - return new Response("too many failed attempts\n", { - status: 429, - headers: { "retry-after": String(Math.ceil(retryAfterMs / 1000)) }, - }); -} - -async function digest(s: string): Promise<Uint8Array> { - return new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s))); -} - -/** Fixed-length SHA-256 digests, so this leaks nothing about input length. */ -function digestsEqual(a: Uint8Array, b: Uint8Array): boolean { - let diff = a.length ^ b.length; - for (let i = 0; i < Math.max(a.length, b.length); i++) diff |= (a[i] ?? 0) ^ (b[i] ?? 0); - return diff === 0; -} - -function clientIp(req: Request): string { - return ( - req.headers.get("cf-connecting-ip") ?? - req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? - "unknown" - ); -} - -const RATE_LIMIT_WINDOW_MS = 60_000; -const RATE_LIMIT_MAX = 10; -const RATE_LIMIT_MAX_IPS = 5000; -const authFailures = new Map<string, { count: number; resetAt: number }>(); - -function pruneAuthFailures(now: number): void { - if (authFailures.size <= RATE_LIMIT_MAX_IPS) return; - for (const [ip, e] of authFailures) { - if (e.resetAt <= now) authFailures.delete(ip); - } - while (authFailures.size > RATE_LIMIT_MAX_IPS) { - const oldest = authFailures.keys().next().value; - if (oldest === undefined) break; - authFailures.delete(oldest); - } -} - -function rateLimited(ip: string): number | null { - const e = authFailures.get(ip); - if (!e || e.resetAt <= Date.now()) return null; - return e.count >= RATE_LIMIT_MAX ? e.resetAt - Date.now() : null; -} - -function recordAuthFailure(ip: string): void { - const now = Date.now(); - const e = authFailures.get(ip); - if (!e || e.resetAt <= now) { - authFailures.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS }); - } else { - e.count++; - } - pruneAuthFailures(now); -} - -/** HTTP Basic where the password (only) is one of the configured tokens. */ -async function checkAuth(req: Request, env: Env): Promise<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(); - - const ip = clientIp(req); - const retryMs = rateLimited(ip); - if (retryMs !== null) return tooManyRequests(retryMs); - - let pass = ""; - try { - const decoded = atob(header.slice(6)); - const colon = decoded.indexOf(":"); - pass = colon === -1 ? "" : decoded.slice(colon + 1); - } catch { - recordAuthFailure(ip); - return unauthorized(); - } - - const passDigest = await digest(pass); - let ok = false; - for (const v of valid) ok = digestsEqual(passDigest, await digest(v)) || ok; - if (!ok) { - recordAuthFailure(ip); - 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(); - let rows = ""; - for (const r of repos) { - 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'>Updated</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). Bounded - * and short-TTL'd on misses so enumerating random repo names can't grow it - * unbounded. - */ -const infoMemo = new Map<string, { at: number; info: RepoInfo | null }>(); -const INFO_TTL_MS = 20_000; -const INFO_NEG_TTL_MS = 2_000; -const INFO_MEMO_MAX = 5000; - -function pruneInfoMemo(): void { - while (infoMemo.size > INFO_MEMO_MAX) { - const oldest = infoMemo.keys().next().value; - if (oldest === undefined) break; - infoMemo.delete(oldest); - } -} - -async function repoInfo(env: Env, repo: string, fresh: boolean): Promise<RepoInfo | null> { - const hit = infoMemo.get(repo); - if (!fresh && hit && Date.now() - hit.at < (hit.info ? INFO_TTL_MS : INFO_NEG_TTL_MS)) return hit.info; - const info = await env.REGISTRY.getByName("registry").get(repo); - infoMemo.set(repo, { at: Date.now(), info }); - pruneInfoMemo(); - 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; - } -} - -/** - * R2 full-clone fast path, served entirely from the Worker so the DO is never - * contacted for bytes (this is the read-offload that avoids the workerd - * DO->response stall on large packs). Detects a true full clone from the tiny - * negotiation body — wants, no haves, `done`, not shallow/deepen, side-band-64k - * — then asks the DO only for the cheap versioned key (no pack generation) and - * streams the stored raw pack from R2 with on-the-fly side-band framing. Returns - * null (a miss, a partial/shallow fetch, or any failure) to fall through to the - * normal DO clone path. Callers MUST invoke this only after the auth gate, so a - * private repo never streams R2 bytes to an anonymous client. - */ -async function serveCloneFromR2( - env: Env, - repo: string, - body: Uint8Array, - stub: DurableObjectStub<RepoCell> -): Promise<Response | null> { - const bucket = env.PACK_CACHE; - if (!bucket) return null; - const req = parseUploadRequest(body); - const fullClone = - req.wants.length > 0 && - req.wants.every(isOid) && - req.haves.length === 0 && - req.done && - req.deepen === 0 && - req.clientShallows.length === 0 && - req.caps.has("side-band-64k"); - if (!fullClone) return null; - let key: string | null; - try { - key = await stub.currentPackKey(repo, req.wants); - } catch { - return null; - } - if (!key) return null; - let obj: R2ObjectBody | null; - try { - obj = await bucket.get(key); - } catch { - return null; - } - if (!obj) return null; - const objects = parseInt(obj.customMetadata?.objects ?? "", 10); - if (!Number.isFinite(objects)) return null; - return streamingCloneResponse(obj.body, objects, req.caps.has("no-progress")); -} - -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 = await 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) { - const declared = parseInt(req.headers.get("content-length") ?? "", 10); - const smallUploadPack = - sub === "/git-upload-pack" && (!Number.isFinite(declared) || declared <= MAX_UPLOAD_PACK_BYTES); - if (smallUploadPack) { - // buffer the tiny negotiation body so a full clone can be served straight - // from R2 (never touching the DO for bytes); the auth gate above has - // already run, so a private repo cannot reach this point anonymously. - const raw = new Uint8Array(await req.arrayBuffer()); - let parsed: Uint8Array = raw; - if (req.headers.get("content-encoding")?.includes("gzip")) { - try { - parsed = gunzipLimited(raw, MAX_UPLOAD_PACK_BYTES); - } catch { - parsed = new Uint8Array(0); - } - } - if (env.PACK_CACHE && parsed.length) { - const hit = await serveCloneFromR2(env, repo, parsed, stub); - if (hit) return hit; - } - fwdBody = raw; // miss: forward the original (still-encoded) bytes to the DO - } else { - 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. idle is the newest committer date - // (x-commit-time), computed by the DO which alone can read the object graph - if (res.ok && sub === "/git-receive-pack" && res.headers.get("x-changed") === "1") { - const idle = parseInt(res.headers.get("x-commit-time") ?? "", 10) || Date.now(); - try { - // a registry hiccup must not fail an already-applied push; next push heals - await registry.upsert(repo, idle); - } catch { - // registry deferred - } - } - 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; - }; - const idle = parseInt(res.headers.get("x-commit-time") ?? "", 10) || Date.now(); - if (!info) await registry.upsert(repo, idle); - await registry.setConfig( - repo, - { - desc: cfg.description, - owner: cfg.owner, - section: cfg.section, - priv: cfg.private, - }, - idle - ); - } 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>; +export default createDurableGit(); diff --git a/src/mod.ts b/src/mod.ts @@ -0,0 +1,545 @@ +/** + * durable-git library entry. `createDurableGit(options)` returns the Worker + * handler; re-export `RepoCell` and `Registry` from your entry module so the + * runtime can find the Durable Object classes: + * + * import { createDurableGit } from "durable-git"; + * export { RepoCell, Registry } from "durable-git"; + * export default createDurableGit({ authorize, onPush }); + */ +import type { Env } from "./env"; +import type { RepoInfo } from "./registry"; +import { esc, age, layout, htmlResponse, errorPage } from "./ui/html"; +import { CSS } from "./ui/style"; +import { parseUploadRequest, streamingCloneResponse } from "./git/protocol"; +import { isOid } from "./git/util"; +import { gunzipLimited } from "./git/zlib"; +import type { RepoCell } from "./repo"; + +export { RepoCell } from "./repo"; +export { Registry } from "./registry"; +export type { Env } from "./env"; +export type { RepoInfo, RepoConfig } from "./registry"; +export type { RefsResult, CommitJson, TreeResult, TreeEntryJson, BlobResult, LogResult } from "./repo"; +export type { Person } from "./git/objects"; + +/** an upload-pack negotiation body is wants/haves/caps only — a few hundred KB */ +const MAX_UPLOAD_PACK_BYTES = 16 * 1024 * 1024; + +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; + +/** What a request is asking to do, from the repository's point of view. */ +export type AuthOp = "read" | "write" | "admin"; + +export interface AuthContext<E extends Env = Env> { + repo: string; + /** read: pages, clones, fetches, the content API; write: git push; admin: config/gc/delete */ + op: AuthOp; + /** the repository's private flag (false for a repository that does not exist yet) */ + private: boolean; + /** HTTP Basic credentials on the request, if any */ + credentials: { user: string; pass: string } | null; + /** the live incoming request: headers and URL only — do NOT read its body, + * which is consumed downstream (a hook that drains it breaks every push) */ + request: Request; + env: E; +} + +export interface RefUpdate { + ref: string; + /** all-zeros for a created ref */ + old: string; + /** all-zeros for a deleted ref */ + new: string; +} + +export interface PushEvent { + repo: string; + /** the ref updates this push actually applied (rejected commands excluded) */ + updates: RefUpdate[]; + /** unix millis of the newest committer date after the push */ + commitTime: number; +} + +export interface DurableGitOptions<E extends Env = Env> { + /** + * Gate every repository-scoped request. Return true to allow, false for the + * default 401 Basic challenge, or a Response to send verbatim (a custom + * challenge, a redirect to your login page). The default implementation is + * the stock token check: reads of public repositories are open; writes, + * admin operations, and anything on a private repository require a + * GIT_TOKEN/GIT_TOKENS match, with per-IP failure rate limiting. + */ + authorize?: (ctx: AuthContext<E>) => boolean | Response | Promise<boolean | Response>; + /** + * Fired after a push applies at least one ref update, off the response path + * (via waitUntil), so a slow or throwing hook never fails the push. + */ + onPush?: (event: PushEvent, env: E) => void | Promise<void>; +} + +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"' }, + }); +} + +function tooManyRequests(retryAfterMs: number): Response { + return new Response("too many failed attempts\n", { + status: 429, + headers: { "retry-after": String(Math.ceil(retryAfterMs / 1000)) }, + }); +} + +async function digest(s: string): Promise<Uint8Array> { + return new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s))); +} + +/** Fixed-length SHA-256 digests, so this leaks nothing about input length. */ +function digestsEqual(a: Uint8Array, b: Uint8Array): boolean { + let diff = a.length ^ b.length; + for (let i = 0; i < Math.max(a.length, b.length); i++) diff |= (a[i] ?? 0) ^ (b[i] ?? 0); + return diff === 0; +} + +/** + * Timing-safe string comparison for authorize hooks. `credentials.pass === + * secret` leaks the match length through timing; compare through this instead. + */ +export async function secretsEqual(a: string, b: string): Promise<boolean> { + return digestsEqual(await digest(a), await digest(b)); +} + +function clientIp(req: Request): string { + return ( + req.headers.get("cf-connecting-ip") ?? + req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? + "unknown" + ); +} + +function parseBasic(req: Request): { user: string; pass: string } | null { + const header = req.headers.get("authorization") ?? ""; + if (!header.startsWith("Basic ")) return null; + try { + const decoded = atob(header.slice(6)); + const colon = decoded.indexOf(":"); + if (colon === -1) return { user: decoded, pass: "" }; + return { user: decoded.slice(0, colon), pass: decoded.slice(colon + 1) }; + } catch { + return null; + } +} + +const RATE_LIMIT_WINDOW_MS = 60_000; +const RATE_LIMIT_MAX = 10; +const RATE_LIMIT_MAX_IPS = 5000; +const authFailures = new Map<string, { count: number; resetAt: number }>(); + +function pruneAuthFailures(now: number): void { + if (authFailures.size <= RATE_LIMIT_MAX_IPS) return; + for (const [ip, e] of authFailures) { + if (e.resetAt <= now) authFailures.delete(ip); + } + while (authFailures.size > RATE_LIMIT_MAX_IPS) { + const oldest = authFailures.keys().next().value; + if (oldest === undefined) break; + authFailures.delete(oldest); + } +} + +function rateLimited(ip: string): number | null { + const e = authFailures.get(ip); + if (!e || e.resetAt <= Date.now()) return null; + return e.count >= RATE_LIMIT_MAX ? e.resetAt - Date.now() : null; +} + +function recordAuthFailure(ip: string): void { + const now = Date.now(); + const e = authFailures.get(ip); + if (!e || e.resetAt <= now) { + authFailures.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS }); + } else { + e.count++; + } + pruneAuthFailures(now); +} + +/** The default authorize: HTTP Basic where the password is one of the configured tokens. */ +async function tokenAuthorize(ctx: AuthContext): Promise<boolean | Response> { + if (ctx.op === "read" && !ctx.private) return true; + const valid = tokens(ctx.env); + if (!valid.length) { + return new Response("access is disabled: set the GIT_TOKEN secret\n", { status: 403 }); + } + const header = ctx.request.headers.get("authorization") ?? ""; + if (!header.startsWith("Basic ")) return unauthorized(); + + const ip = clientIp(ctx.request); + const retryMs = rateLimited(ip); + if (retryMs !== null) return tooManyRequests(retryMs); + + // a Basic header that failed to decode is a failed attempt, same as a wrong + // password — otherwise malformed headers probe the endpoint rate-limit-free + if (!ctx.credentials) { + recordAuthFailure(ip); + return unauthorized(); + } + + const passDigest = await digest(ctx.credentials.pass); + let ok = false; + for (const v of valid) ok = digestsEqual(passDigest, await digest(v)) || ok; + if (!ok) { + recordAuthFailure(ip); + return unauthorized(); + } + return true; +} + +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(); + let rows = ""; + for (const r of repos) { + 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'>Updated</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). Bounded + * and short-TTL'd on misses so enumerating random repo names can't grow it + * unbounded. + */ +const infoMemo = new Map<string, { at: number; info: RepoInfo | null }>(); +const INFO_TTL_MS = 20_000; +const INFO_NEG_TTL_MS = 2_000; +const INFO_MEMO_MAX = 5000; + +function pruneInfoMemo(): void { + while (infoMemo.size > INFO_MEMO_MAX) { + const oldest = infoMemo.keys().next().value; + if (oldest === undefined) break; + infoMemo.delete(oldest); + } +} + +async function repoInfo(env: Env, repo: string, fresh: boolean): Promise<RepoInfo | null> { + const hit = infoMemo.get(repo); + if (!fresh && hit && Date.now() - hit.at < (hit.info ? INFO_TTL_MS : INFO_NEG_TTL_MS)) return hit.info; + const info = await env.REGISTRY.getByName("registry").get(repo); + infoMemo.set(repo, { at: Date.now(), info }); + pruneInfoMemo(); + 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; + } +} + +/** + * R2 full-clone fast path, served entirely from the Worker so the DO is never + * contacted for bytes (this is the read-offload that avoids the workerd + * DO->response stall on large packs). Detects a true full clone from the tiny + * negotiation body — wants, no haves, `done`, not shallow/deepen, side-band-64k + * — then asks the DO only for the cheap versioned key (no pack generation) and + * streams the stored raw pack from R2 with on-the-fly side-band framing. Returns + * null (a miss, a partial/shallow fetch, or any failure) to fall through to the + * normal DO clone path. Callers MUST invoke this only after the auth gate, so a + * private repo never streams R2 bytes to an anonymous client. + */ +async function serveCloneFromR2( + env: Env, + repo: string, + body: Uint8Array, + stub: DurableObjectStub<RepoCell> +): Promise<Response | null> { + const bucket = env.PACK_CACHE; + if (!bucket) return null; + const req = parseUploadRequest(body); + const fullClone = + req.wants.length > 0 && + req.wants.every(isOid) && + req.haves.length === 0 && + req.done && + req.deepen === 0 && + req.clientShallows.length === 0 && + req.caps.has("side-band-64k"); + if (!fullClone) return null; + let key: string | null; + try { + key = await stub.currentPackKey(repo, req.wants); + } catch { + return null; + } + if (!key) return null; + let obj: R2ObjectBody | null; + try { + obj = await bucket.get(key); + } catch { + return null; + } + if (!obj) return null; + const objects = parseInt(obj.customMetadata?.objects ?? "", 10); + if (!Number.isFinite(objects)) return null; + return streamingCloneResponse(obj.body, objects, req.caps.has("no-progress")); +} + +function parseRefUpdates(res: Response): RefUpdate[] { + const header = res.headers.get("x-ref-updates"); + if (!header) return []; + try { + const parsed = JSON.parse(decodeURIComponent(header)) as RefUpdate[]; + return Array.isArray(parsed) ? parsed : []; + } catch { + return []; + } +} + +/** The returned handler: a valid Worker default export, with `fetch` non-optional + * so it can also be delegated to from a wrapping router. */ +export interface DurableGitHandler<E extends Env = Env> { + fetch(req: Request, env: E, ctx: ExecutionContext): Promise<Response>; +} + +export function createDurableGit<E extends Env = Env>(options: DurableGitOptions<E> = {}): DurableGitHandler<E> { + const authorize = options.authorize ?? tokenAuthorize; + return { + async fetch(req: Request, env: E, 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 isApi = sub.startsWith("/api/"); + 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); + + // every repo-scoped request passes through authorize; the default hook + // waves reads of public repositories straight through + const op: AuthOp = isReceive ? "write" : isAdmin ? "admin" : "read"; + const decision = await authorize({ + repo, + op, + private: !!info?.priv, + credentials: parseBasic(req), + request: req, + env, + }); + if (decision instanceof Response) return decision; + if (!decision) return unauthorized(); + + // only pushes and admin ops may touch repos that don't exist yet + if (!info && !isReceive && !isAdmin) { + if (isApi) return Response.json({ error: `repository not found: ${repo}` }, { status: 404 }); + 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) { + const declared = parseInt(req.headers.get("content-length") ?? "", 10); + const smallUploadPack = + sub === "/git-upload-pack" && (!Number.isFinite(declared) || declared <= MAX_UPLOAD_PACK_BYTES); + if (smallUploadPack) { + // buffer the tiny negotiation body so a full clone can be served straight + // from R2 (never touching the DO for bytes); the auth gate above has + // already run, so a private repo cannot reach this point anonymously. + const raw = new Uint8Array(await req.arrayBuffer()); + let parsed: Uint8Array = raw; + if (req.headers.get("content-encoding")?.includes("gzip")) { + try { + parsed = gunzipLimited(raw, MAX_UPLOAD_PACK_BYTES); + } catch { + parsed = new Uint8Array(0); + } + } + if (env.PACK_CACHE && parsed.length) { + const hit = await serveCloneFromR2(env, repo, parsed, stub); + if (hit) return hit; + } + fwdBody = raw; // miss: forward the original (still-encoded) bytes to the DO + } else { + 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. idle is the newest committer date + // (x-commit-time), computed by the DO which alone can read the object graph + if (res.ok && sub === "/git-receive-pack" && res.headers.get("x-changed") === "1") { + const idle = parseInt(res.headers.get("x-commit-time") ?? "", 10) || Date.now(); + try { + // a registry hiccup must not fail an already-applied push; next push heals + await registry.upsert(repo, idle); + } catch { + // registry deferred + } + if (options.onPush) { + const event: PushEvent = { repo, updates: parseRefUpdates(res), commitTime: idle }; + ctx.waitUntil( + Promise.resolve(options.onPush(event, env)).catch((err) => { + console.log(`[onPush ${repo}] hook failed: ${err instanceof Error ? err.message : String(err)}`); + }) + ); + } + } + 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; + }; + const idle = parseInt(res.headers.get("x-commit-time") ?? "", 10) || Date.now(); + if (!info) await registry.upsert(repo, idle); + await registry.setConfig( + repo, + { + desc: cfg.description, + owner: cfg.owner, + section: cfg.section, + priv: cfg.private, + }, + idle + ); + } 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)); + } + // x-ref-updates is a Worker<->cell event channel, not client data + if (res.headers.has("x-ref-updates")) { + const out = new Response(res.body, res); + out.headers.delete("x-ref-updates"); + return out; + } + return res; + }, + }; +} diff --git a/src/repo.ts b/src/repo.ts @@ -20,6 +20,7 @@ } from "./git/protocol"; import { Commit, + Person, parseCommit, parseTag, parseTree, @@ -53,6 +54,8 @@ const DEFAULT_MAX_PUSH_MB = 512; /** an upload-pack request is wants/haves/caps only — a few hundred KB at most */ const MAX_UPLOAD_PACK_BYTES = 16 * 1024 * 1024; +/** encoded-byte budget for the x-ref-updates response header */ +const MAX_REF_UPDATES_HEADER = 8 * 1024; // like cgit's about-file: a dedicated about page wins over the README const README_NAMES = [ "about.md", @@ -76,6 +79,55 @@ q?: string; } +/** a ref update a push actually applied (threaded to the Worker's onPush hook) */ +interface AppliedUpdate { + ref: string; + old: string; + new: string; +} + +// The shapes returned by the cell's typed content surface (see the methods +// below currentPackKey). + +export interface RefsResult { + head: string | null; + refs: { name: string; target: string; peeled?: string }[]; +} + +export interface CommitJson { + oid: string; + tree: string; + parents: string[]; + author: Person; + committer: Person; + subject: string; + message: string; +} + +export interface LogResult { + commits: CommitJson[]; + more: boolean; +} + +export interface TreeEntryJson { + name: string; + mode: string; + type: "tree" | "blob" | "commit"; + oid: string; + size?: number; +} + +export interface TreeResult { + oid: string; + entries: TreeEntryJson[]; +} + +export interface BlobResult { + oid: string; + mode: string; + data: Uint8Array; +} + interface FileDiff { path: string; o: { oid: string; mode: string } | null; @@ -361,7 +413,123 @@ return `pack/${repo}/${this.store.reachableVersion()}`; } + // ---- typed content surface ---------------------------------------------- + // Public methods callable two ways: over HTTP as /<repo>/api/* (JSON; the + // Worker's authorize gate applies) and directly as Workers RPC by any + // same-account Worker holding the REPO binding — that path carries no HTTP + // auth, a service binding is already trusted infrastructure. + /** + * Rebind R2 for a direct RPC call, which has no request to read x-repo from; + * the name was persisted by the first push (absent before any push, when + * there are no R2-backed packs to read either). + */ + private rpcBind(): void { + const name = this.store.getMeta("repo"); + if (name) this.bindR2(name); + } + + async listRefs(): Promise<RefsResult> { + this.rpcBind(); + const refs: RefsResult["refs"] = []; + for (const r of this.store.refs()) { + const entry: RefsResult["refs"][number] = { name: r.name, target: r.target }; + if (r.name.startsWith("refs/tags/")) { + const peeled = await this.peelToCommit(r.target); + if (peeled && peeled.oid !== r.target) entry.peeled = peeled.oid; + } + refs.push(entry); + } + return { head: this.store.resolveHead() ? this.store.head() : null, refs }; + } + + /** `id` is a branch, tag, full ref, or reachable oid; absent means HEAD. */ + async readCommit(id?: string): Promise<CommitJson | null> { + this.rpcBind(); + const rr = await this.resolveRef(id); + if (!rr) return null; + const c = await this.peelToCommit(rr.oid); + return c ? commitJson(c.oid, c.commit) : null; + } + + async listLog(ref?: string, opts: { path?: string; ofs?: number; n?: number } = {}): Promise<LogResult> { + this.rpcBind(); + const rr = await this.resolveRef(ref); + if (!rr) return { commits: [], more: false }; + const n = Math.min(Math.max(opts.n ?? LOG_PAGE, 1), 100); + const ofs = Math.max(opts.ofs ?? 0, 0); + const filter: LogFilter = opts.path ? { path: decodePath("/" + opts.path) } : {}; + const { entries, more } = await this.walkLog(rr.oid, ofs, n, filter); + return { commits: entries.map((e) => commitJson(e.oid, e.commit)), more }; + } + + async listTree(ref?: string, path = ""): Promise<TreeResult | null> { + this.rpcBind(); + const rr = await this.resolveRef(ref); + if (!rr) return null; + const head = await this.peelToCommit(rr.oid); + if (!head) return null; + const segs = decodePath("/" + path); + const found = await this.lookupPath(head.commit.tree, segs); + if (!found || found.kind !== "tree") return null; + const entries: TreeEntryJson[] = found.entries.map((e) => { + const type = isTreeMode(e.mode) ? ("tree" as const) : isGitlinkMode(e.mode) ? ("commit" as const) : ("blob" as const); + const out: TreeEntryJson = { name: e.name, mode: e.mode, type, oid: e.oid }; + const meta = type === "blob" ? this.store.typeAndSize(e.oid) : null; + if (meta) out.size = meta.size; + return out; + }); + return { oid: found.oid, entries }; + } + + async readBlob(ref: string | undefined, path: string): Promise<BlobResult | null> { + this.rpcBind(); + const rr = await this.resolveRef(ref); + if (!rr) return null; + const head = await this.peelToCommit(rr.oid); + if (!head) return null; + const found = await this.lookupPath(head.commit.tree, decodePath("/" + path)); + if (!found || found.kind !== "blob") return null; + const obj = await this.store.get(found.entry.oid); + if (!obj || obj.type !== "blob") return null; + return { oid: found.entry.oid, mode: found.entry.mode, data: obj.data }; + } + + /** The content methods over HTTP. GET-only; routed from ui(). */ + private async api(path: string, q: URLSearchParams): Promise<Response> { + const h = q.get("h") ?? undefined; + const json = (data: unknown, status = 200) => + Response.json(data, { status, headers: { "x-content-type-options": "nosniff" } }); + const notFound = (what: string) => json({ error: what }, 404); + if (path === "/api/refs") return json(await this.listRefs()); + if (path === "/api/log") { + return json( + await this.listLog(h, { + path: q.get("path") ?? undefined, + ofs: parseInt(q.get("ofs") ?? "0", 10) || 0, + n: parseInt(q.get("n") ?? "", 10) || undefined, + }) + ); + } + if (path === "/api/commit") { + const c = await this.readCommit(q.get("id") ?? h); + return c ? json(c) : notFound("commit not found"); + } + if (path === "/api/tree") { + const t = await this.listTree(h, q.get("path") ?? ""); + return t ? json(t) : notFound("tree not found"); + } + if (path === "/api/blob") { + const blob = await this.readBlob(h, q.get("path") ?? ""); + if (!blob) return notFound("blob not found"); + const res = rawBlobResponse(blob.data, (q.get("path") ?? "").split("/").pop() ?? ""); + res.headers.set("x-oid", blob.oid); + return res; + } + return notFound(`no such endpoint: ${path}`); + } + + /** * R2 full-clone offload adapter (write side), or undefined when no bucket is * bound (celld and Workers without the binding both fall back to the pure DO * path). A throwing createMultipartUpload (celld deliberately makes R2 throw) @@ -450,8 +618,9 @@ () => {} ); let commitTime: number | null; + let updates: AppliedUpdate[]; try { - commitTime = await run; + ({ commitTime, updates } = await run); } catch (err) { console.log(`[receive ${repo}] FAILED: ${err instanceof Error ? err.stack ?? err.message : String(err)}`); const msg = err instanceof Error ? err.message : String(err); @@ -467,6 +636,20 @@ if (commitTime !== null) { headers["x-changed"] = "1"; headers["x-commit-time"] = String(commitTime); + // the applied ref updates, for the Worker's onPush hook. URI-encoded to + // stay header-safe. The cap is on encoded bytes, not entries: ref names + // are attacker-controlled up to 255 chars and non-ASCII encodes at 9 + // bytes per char, so an entry-count cap could still blow the response + // header budget. Halve until it fits; the hook sees a truncated list. + let take = updates; + let encoded = encodeURIComponent(JSON.stringify(take)); + while (encoded.length > MAX_REF_UPDATES_HEADER && take.length > 1) { + take = take.slice(0, Math.ceil(take.length / 2)); + encoded = encodeURIComponent(JSON.stringify(take)); + } + if (take.length && encoded.length <= MAX_REF_UPDATES_HEADER) { + headers["x-ref-updates"] = encoded; + } } return new Response(concat(chunks) as unknown as BodyInit, { headers }); } @@ -476,7 +659,7 @@ repo: string, maxBytes: number, emit: (chunk: Uint8Array) => void - ): Promise<number | null> { + ): Promise<{ commitTime: number | null; updates: AppliedUpdate[] }> { console.log(`[receive ${repo}] processing push request`); let reader: ReadableStreamDefaultReader<Uint8Array> | null = null; let buf: Uint8Array; @@ -579,7 +762,15 @@ } } if (wantStatus) emit(renderStatus(results, unpackError, sideband)); - return commitTime; + // the updates a push actually applied. results[i] is the outcome of + // commands[i] (validatePush and commitPush each emit exactly one entry per + // input, in order) — the join must be by index, not ref name: a crafted + // request can send two commands for the same ref, and a name join would + // let the rejected one inherit the applied one's success + const updates = commands + .filter((_, i) => results[i]?.ok === true) + .map((c) => ({ ref: c.ref, old: c.old, new: c.next })); + return { commitTime, updates }; } @@ -606,6 +797,7 @@ private async ui(repo: string, host: string, proto: string, path: string, q: URLSearchParams): Promise<Response> { const h = q.get("h") ?? undefined; + if (path.startsWith("/api/")) return this.api(path, q); if (path === "/" || path === "") return this.summaryPage(repo, host, proto); if (path === "/about/" || path === "/about") return this.aboutPage(repo, h); if (path === "/log/" || path === "/log") @@ -850,7 +1042,7 @@ private async lookupPath( rootTree: string, path: string[] - ): Promise<{ kind: "tree"; entries: TreeEntry[] } | { kind: "blob"; entry: TreeEntry } | null> { + ): Promise<{ kind: "tree"; oid: string; entries: TreeEntry[] } | { kind: "blob"; entry: TreeEntry } | null> { let treeOid = rootTree; for (let i = 0; i < path.length; i++) { const obj = await this.store.get(treeOid); @@ -865,7 +1057,7 @@ } const obj = await this.store.get(treeOid); if (obj?.type !== "tree") return null; - return { kind: "tree", entries: parseTree(obj.data) }; + return { kind: "tree", oid: treeOid, entries: parseTree(obj.data) }; } private async findReadme(): Promise<{ name: string; oid: string } | null> { @@ -1695,7 +1887,9 @@ png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", svg: "text/plain; charset=utf-8", pdf: "application/pdf", html: "text/plain", }; - const ct = types[ext] ?? (isBinary(data) ? "application/octet-stream" : "text/plain; charset=utf-8"); + // hasOwn: ext is attacker-named, and a bare index would reach prototype + // members for names like "constructor" + const ct = (Object.hasOwn(types, ext) ? types[ext] : undefined) ?? (isBinary(data) ? "application/octet-stream" : "text/plain; charset=utf-8"); return new Response(data as unknown as BodyInit, { headers: { "content-type": ct, @@ -1705,6 +1899,18 @@ }); } +function commitJson(oid: string, c: Commit): CommitJson { + return { + oid, + tree: c.tree, + parents: c.parents, + author: c.author, + committer: c.committer, + subject: c.subject, + message: c.message, + }; +} + function decodePath(p: string): string[] { return p .split("/") diff --git a/src/ui/style.ts b/src/ui/style.ts @@ -434,4 +434,53 @@ div#cgit form select, div#cgit form input { font-size: 90%; } +/* small screens: keep the cgit look but shrink the chrome, let the tabs + wrap, and scroll wide tables inside their own box instead of the page */ +@media (max-width: 700px) { + div#cgit table#header td.main { + font-size: 150%; + white-space: normal; + padding-left: 4px; + } + div#cgit table#header td.sub { + padding-left: 4px; + } + div#cgit table.tabs, div#cgit table.tabs tr, div#cgit table.tabs td { + display: block; + } + div#cgit table.tabs { + margin-top: 1em; + } + div#cgit table.tabs td { + padding: 0 0.25em; + } + div#cgit table.tabs td a { + display: inline-block; + padding: 3px 0.6em; + } + div#cgit table.tabs td.form { + text-align: left; + padding: 3px 0.6em; + } + div#cgit div.path { + padding: 5px 0.75em 2px 0.75em; + } + div#cgit div.content { + padding: 1em 0.75em; + } + div#cgit table.list, div#cgit table.blob, div#cgit table.blame, + div#cgit table.commit-info, div#cgit table.stats { + display: block; + overflow-x: auto; + } + div#cgit div.commit-msg { + overflow-x: auto; + } + div#cgit td.ls-mode, div#cgit td.ls-size { + width: auto; + } + div#cgit form input[type='text'] { + width: 8em; + } +} `; diff --git a/tsconfig.json b/tsconfig.json @@ -9,7 +9,9 @@ "noEmit": true, "skipLibCheck": true, "isolatedModules": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + // lets examples/ import the package by its published name + "paths": { "durable-git": ["./src/mod.ts"] } }, - "include": ["src/**/*.ts"] + "include": ["src/**/*.ts", "examples/**/*.ts"] } |