// SMART HTTP (gitprotocol-http, protocol v0): what `git clone|fetch|push` speak to a server. The // twin answers the advertisement (`info/refs?service=`), upload-pack (wants, haves, done → NAK // and a pack of the closure the client lacks) and receive-pack (ref commands, a pack, a // report-status) with nothing but the object store, the refs and a push policy. Protocol v2 is // not advertised; a client that asks for it falls back to v0 on this answer, as git specifies. import { GitObjectStore, decodeCommit, decodeTag, decodeTree, type GitObjectType } from './objects.ts'; import { readPack, writePack } from './pack.ts'; import { gunzip } from '../bytes.ts'; import type { GitRefs } from './refs.ts'; const ENC = new TextEncoder(); const DEC = new TextDecoder(); export const ZERO_SHA = '0'.repeat(40); export const FLUSH = new Uint8Array([0x30, 0x30, 0x30, 0x30]); export function pktLine(s: string | Uint8Array): Uint8Array { const body = typeof s === 'string' ? ENC.encode(s) : s; const len = (body.length + 4).toString(16).padStart(4, '0'); const out = new Uint8Array(body.length + 4); out.set(ENC.encode(len), 0); out.set(body, 4); return out; } /** Pkt-lines up to and including the first flush; `rest` is what follows (a pack, on push). */ export function readPktLines(bytes: Uint8Array): { lines: string[]; rest: Uint8Array } { const lines: string[] = []; let at = 0; while (at + 4 <= bytes.length) { const len = parseInt(DEC.decode(bytes.subarray(at, at + 4)), 16); if (Number.isNaN(len)) return { lines, rest: bytes.subarray(at) }; if (len === 0) return { lines, rest: bytes.subarray(at + 4) }; if (len < 4) { at += 4; continue; } // v2 delimiter/response-end packets: no payload lines.push(DEC.decode(bytes.subarray(at + 4, at + len))); at += len; } return { lines, rest: bytes.subarray(at) }; } /** Every pkt-line in the body across all flushes (stateless clients batch haves between flushes); `rest` follows the first flush. */ export function readAllPktLines(bytes: Uint8Array): { lines: string[]; rest: Uint8Array } { const first = readPktLines(bytes); const lines = [...first.lines]; let cur = first.rest; while (cur.length >= 4 && /^[0-9a-f]{4}$/.test(DEC.decode(cur.subarray(0, 4))) && !cur.subarray(0, 4).every((b, i) => b === 'PACK'.charCodeAt(i))) { const n = readPktLines(cur); lines.push(...n.lines); if (n.rest.length === cur.length) break; cur = n.rest; } return { lines, rest: first.rest }; } const SHA = /^[0-9a-f]{40}$/; function cat(...parts: Uint8Array[]): Uint8Array { const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); let o = 0; for (const p of parts) { out.set(p, o); o += p.length; } return out; } export type Service = 'git-upload-pack' | 'git-receive-pack'; const CAPS: Record = { 'git-upload-pack': 'ofs-delta shallow no-progress agent=volter-twin', 'git-receive-pack': 'report-status delete-refs ofs-delta agent=volter-twin' }; /** `GET info/refs?service=`: the ref advertisement, HEAD first as a symref. */ export function advertisement(service: Service, refs: GitRefs): Uint8Array { const all = refs.list(); const head = refs.head(); const headSha = refs.get(head); const caps = `${CAPS[service]} symref=HEAD:${head}`; const lines: Uint8Array[] = [pktLine(`# service=${service}\n`), FLUSH]; if (headSha) lines.push(pktLine(`${headSha} HEAD\0${caps}\n`)); const rest = all; if (!headSha && rest.length === 0) lines.push(pktLine(`${ZERO_SHA} capabilities^{}\0${caps}\n`)); let first = headSha === null; for (const r of rest) { lines.push(pktLine(first ? `${r.sha} ${r.name}\0${caps}\n` : `${r.sha} ${r.name}\n`)); first = false; } lines.push(FLUSH); return cat(...lines); } /** Every object reachable from `roots`, stopping at `seen`. */ async function closure(store: GitObjectStore, roots: string[], seen: Set): Promise> { const out: Array<{ type: GitObjectType; payload: Uint8Array; sha: string }> = []; const stack = [...roots]; while (stack.length) { const sha = stack.pop()!; if (seen.has(sha)) continue; seen.add(sha); const obj = await store.read(sha); if (!obj) continue; out.push({ ...obj, sha }); if (obj.type === 'commit') { const c = decodeCommit(obj.payload); stack.push(c.tree, ...c.parents); } else if (obj.type === 'tree') { for (const e of decodeTree(obj.payload)) if (e.mode !== '160000') stack.push(e.sha); } else if (obj.type === 'tag') stack.push(decodeTag(obj.payload).object); } return out; } async function reachable(store: GitObjectStore, roots: string[]): Promise> { const seen = new Set(); await closure(store, roots, seen); return seen; } /** The pack of every object `wants` reach that the `haves` the store holds do not: what a push sends (a client's * send-pack, smart-http-client.ts). */ export async function packObjects(store: GitObjectStore, wants: string[], haves: string[]): Promise { const known: string[] = []; for (const h of haves) if (await store.has(h)) known.push(h); return writePack(await closure(store, wants, await reachable(store, known))); } /** * A shallow request's commits (gitprotocol-pack, "Shallow requests"): every commit within `depth` of a want (a want is * depth 1), and the boundary, the commits whose parents the client will not have. The client's own shallow commits it * already has are boundaries it keeps unless this walk passes through them. */ async function deepened(store: GitObjectStore, wants: string[], depth: number): Promise<{ commits: string[]; boundary: string[] }> { const at = new Map(); const boundary = new Set(); let frontier = wants.map((sha) => ({ sha, d: 1 })); while (frontier.length) { const next: Array<{ sha: string; d: number }> = []; for (const { sha, d } of frontier) { if ((at.get(sha) ?? Infinity) <= d) continue; at.set(sha, d); const obj = await store.read(sha); if (obj?.type !== 'commit') continue; const parents = decodeCommit(obj.payload).parents; if (d >= depth) { if (parents.length) boundary.add(sha); continue; } boundary.delete(sha); for (const p of parents) next.push({ sha: p, d: d + 1 }); } frontier = next; } return { commits: [...at.keys()], boundary: [...boundary].filter((sha) => at.get(sha)! >= depth) }; } /** `POST git-upload-pack`: wants and haves in, NAK and (once `done`) the pack out. A request with `deepen ` is shallow: * its answer opens with the shallow-update section (`shallow ` for each boundary commit, `unshallow ` for a * commit the client held shallow whose parents it now receives, then a flush), and its pack stops at the boundary. */ export async function uploadPack(body: Uint8Array, store: GitObjectStore): Promise { const { lines } = readAllPktLines(body); const wants = lines.filter((l) => l.startsWith('want ')).map((l) => l.slice(5, 45)).filter((s) => SHA.test(s)); const haves = lines.filter((l) => l.startsWith('have ')).map((l) => l.slice(5, 45)).filter((s) => SHA.test(s)); const clientShallow = lines.filter((l) => l.startsWith('shallow ')).map((l) => l.slice(8, 48)).filter((s) => SHA.test(s)); const depth = Number(/^deepen (\d+)/.exec(lines.find((l) => l.startsWith('deepen ')) ?? '')?.[1] ?? 0); const done = lines.some((l) => l.trim() === 'done'); const known: string[] = []; for (const h of haves) if (await store.has(h)) known.push(h); for (const w of wants) if (!(await store.has(w))) return pktLine(`ERR upload-pack: not our ref ${w}\n`); const shallow = depth > 0 ? await deepened(store, wants, depth) : undefined; const update = shallow ? cat(...shallow.boundary.filter((sha) => !clientShallow.includes(sha)).map((sha) => pktLine(`shallow ${sha}\n`)), ...clientShallow.filter((sha) => shallow.commits.includes(sha) && !shallow.boundary.includes(sha)).map((sha) => pktLine(`unshallow ${sha}\n`)), FLUSH) : new Uint8Array(); // a stateless client sends its wants and `deepen` alone first and reads only the shallow section back (git's // fetch-pack, find_common); every later request carries haves or `done`, and its answer repeats the section before NAK if (!done && shallow && haves.length === 0) return update; if (!done) return cat(update, pktLine('NAK\n')); const seen = await reachable(store, known); let objects: Array<{ type: GitObjectType; payload: Uint8Array; sha: string }>; if (shallow) { objects = []; for (const sha of shallow.commits) { if (seen.has(sha)) continue; seen.add(sha); const obj = await store.read(sha); if (!obj) continue; objects.push({ ...obj, sha }); if (obj.type === 'commit') objects.push(...await closure(store, [decodeCommit(obj.payload).tree], seen)); } } else objects = await closure(store, wants, seen); return cat(update, pktLine('NAK\n'), await writePack(objects)); } export type RefCommand = { old: string; new: string; name: string; /** false when `new` does not descend from `old` (a force push); true for creates, deletes and fast-forwards. */ fastForward: boolean }; /** Bounded ancestry walk: is `ancestor` reachable from `sha` through parents? */ export async function isAncestor(store: GitObjectStore, ancestor: string, sha: string, limit = 5000): Promise { const seen = new Set(); const stack = [sha]; while (stack.length && seen.size < limit) { const s = stack.pop()!; if (s === ancestor) return true; if (seen.has(s)) continue; seen.add(s); const o = await store.read(s); if (o?.type === 'commit') stack.push(...decodeCommit(o.payload).parents); } return false; } export type PushPolicy = (cmd: RefCommand) => string | null | Promise; /** `POST git-receive-pack`: commands and a pack in, refs updated under `policy`, report-status out. */ export async function receivePack(body: Uint8Array, store: GitObjectStore, refs: GitRefs, policy: PushPolicy = () => null): Promise<{ response: Uint8Array; applied: RefCommand[] }> { const { lines, rest } = readPktLines(body); const commands: RefCommand[] = lines.map((l) => l.split('\0')[0]!.trim()).filter(Boolean).map((l) => { const [o, n, name] = l.split(' '); return { old: o!, new: n!, name: name!, fastForward: true }; }).filter((c) => SHA.test(c.old) && SHA.test(c.new) && /^refs\/[^\s]+$/.test(c.name)); const report: Uint8Array[] = []; let unpack = 'ok'; if (rest.length >= 12) { try { await readPack(rest, store); } catch (e) { unpack = (e as Error).message; } } report.push(pktLine(`unpack ${unpack}\n`)); const applied: RefCommand[] = []; const existing = refs.list().map((r) => r.name); const verdicts: Array<{ cmd: RefCommand; reason: string | null }> = []; for (const cmd of commands) { const current = refs.get(cmd.name) ?? ZERO_SHA; let reason: string | null = unpack === 'ok' ? null : 'unpacker error'; if (!reason && current !== cmd.old) reason = 'fetch first'; if (!reason && current === ZERO_SHA && existing.some((n) => n.startsWith(`${cmd.name}/`) || cmd.name.startsWith(`${n}/`))) reason = 'ref name conflict'; if (!reason && cmd.new !== ZERO_SHA && !(await store.has(cmd.new))) reason = 'missing necessary objects'; if (!reason && cmd.old !== ZERO_SHA && cmd.new !== ZERO_SHA) cmd.fastForward = await isAncestor(store, cmd.old, cmd.new); if (!reason) reason = await policy(cmd); verdicts.push({ cmd, reason }); } // Apply under the refs lock, re-reading each old value: a racing push that won in between is // told `fetch first` rather than silently overwritten. refs.withLock(() => { for (const v of verdicts) { if (!v.reason && (refs.get(v.cmd.name) ?? ZERO_SHA) !== v.cmd.old) v.reason = 'fetch first'; if (v.reason) { report.push(pktLine(`ng ${v.cmd.name} ${v.reason}\n`)); continue; } if (v.cmd.new === ZERO_SHA) refs.delete(v.cmd.name); else refs.set(v.cmd.name, v.cmd.new); applied.push(v.cmd); report.push(pktLine(`ok ${v.cmd.name}\n`)); } }); report.push(FLUSH); return { response: cat(...report), applied }; } export type GitRepo = { store: GitObjectStore; refs: GitRefs; policy?: PushPolicy; onPush?: (applied: RefCommand[]) => void | Promise }; /** Route one request under a repo: returns null when the path is not a smart-HTTP endpoint. */ export async function serveSmartHttp(req: Request, repo: GitRepo, tailPath: string): Promise { const url = new URL(req.url); if (req.method === 'GET' && tailPath === 'info/refs') { const service = url.searchParams.get('service') as Service | null; if (service !== 'git-upload-pack' && service !== 'git-receive-pack') return new Response('smart HTTP only', { status: 403 }); return new Response(advertisement(service, repo.refs) as unknown as BodyInit, { headers: { 'content-type': `application/x-${service}-advertisement`, 'cache-control': 'no-cache' } }); } if (req.method === 'POST' && (tailPath === 'git-upload-pack' || tailPath === 'git-receive-pack')) { return serveSmartHttpPost(new Uint8Array(await req.arrayBuffer()), req.headers.get('content-encoding') ?? '', repo, tailPath); } return null; } /** The POST half of `serveSmartHttp` for a caller that already holds the body: a push pack is * the size of the repository, so re-wrapping it in a Request only to read it back is a full copy. */ export async function serveSmartHttpPost(body: Uint8Array, contentEncoding: string, repo: GitRepo, tailPath: 'git-upload-pack' | 'git-receive-pack'): Promise { if (contentEncoding.includes('gzip')) body = await gunzip(body); const headers = { 'content-type': `application/x-${tailPath}-result`, 'cache-control': 'no-cache' }; if (tailPath === 'git-upload-pack') return new Response((await uploadPack(body, repo.store)) as unknown as BodyInit, { headers }); const { response, applied } = await receivePack(body, repo.store, repo.refs, repo.policy); if (applied.length && repo.onPush) await repo.onPush(applied); return new Response(response as unknown as BodyInit, { headers }); }