export type GitService = "git-upload-pack" | "git-receive-pack"; export interface GitRoute { repo: string; service: GitService; suffix: string; } const SERVICES = new Set(["git-upload-pack", "git-receive-pack"]); const FORWARDED_REQUEST_HEADERS = ["content-type", "accept", "git-protocol", "content-encoding", "user-agent"]; const FORWARDED_RESPONSE_HEADERS = ["content-type", "cache-control", "expires", "pragma"]; const TOKEN_TTL_SECONDS = 600; export function parseGitRoute(method: string, url: URL): GitRoute | null { const match = url.pathname.match(/^\/([A-Za-z0-9._-]+\/[A-Za-z0-9._-]+)\.git(\/info\/refs|\/git-upload-pack|\/git-receive-pack)$/); if (!match) return null; const [, repo, suffix] = match; if (suffix === "/info/refs") { const service = url.searchParams.get("service"); if (method !== "GET" || !service || !SERVICES.has(service)) return null; return { repo, service: service as GitService, suffix }; } if (method !== "POST") return null; return { repo, service: suffix.slice(1) as GitService, suffix }; } export function scopeFor(service: GitService): "read" | "write" { return service === "git-receive-pack" ? "write" : "read"; } export async function proxyGit(request: Request, artifacts: Artifacts, artifactsName: string, route: GitRoute): Promise { let remote: string; let token: string; try { using repo = await artifacts.get(artifactsName); const [info, minted] = await Promise.all([repo.info(), repo.createToken(scopeFor(route.service), TOKEN_TTL_SECONDS)]); remote = info.remote; token = minted.plaintext; } catch (error) { console.error("artifacts lookup failed", artifactsName, error); return new Response("Repository not found\n", { status: 404 }); } const headers = new Headers({ authorization: `Bearer ${token}` }); for (const name of FORWARDED_REQUEST_HEADERS) { const value = request.headers.get(name); if (value) headers.set(name, value); } const upstream = await fetch(remote + route.suffix + new URL(request.url).search, { method: request.method, headers, body: request.method === "POST" ? request.body : undefined, }); const responseHeaders = new Headers(); for (const name of FORWARDED_RESPONSE_HEADERS) { const value = upstream.headers.get(name); if (value) responseHeaders.set(name, value); } return new Response(upstream.body, { status: upstream.status, headers: responseHeaders }); } export interface Refs { head: string | null; branches: Map; tags: Map; } export async function readRefs(repo: ArtifactsRepo): Promise { const [info, token] = await Promise.all([repo.info(), repo.createToken("read", 60)]); const response = await fetch(`${info.remote}/info/refs?service=git-upload-pack`, { headers: { authorization: `Bearer ${token.plaintext}` }, }); if (!response.ok) throw new Error(`ref advertisement failed with ${response.status}`); return parseRefAdvertisement(new Uint8Array(await response.arrayBuffer())); } export function parseRefAdvertisement(bytes: Uint8Array): Refs { const decoder = new TextDecoder(); const refs: Refs = { head: null, branches: new Map(), tags: new Map() }; for (let offset = 0; offset + 4 <= bytes.length; ) { const length = parseInt(decoder.decode(bytes.subarray(offset, offset + 4)), 16); if (Number.isNaN(length)) break; if (length < 4) { offset += 4; continue; } const line = decoder.decode(bytes.subarray(offset + 4, offset + length)).replace(/\n$/, ""); offset += length; const [ref, capabilities] = line.split("\0"); const symref = capabilities?.match(/(?:^| )symref=HEAD:refs\/heads\/(\S+)/); if (symref) refs.head = symref[1]; const match = ref.match(/^([0-9a-f]{40}) refs\/(heads|tags)\/(.+)$/); if (!match || match[3].endsWith("^{}")) continue; (match[2] === "heads" ? refs.branches : refs.tags).set(match[3], match[1]); } return refs; } export interface RefUpdate { ref: string; from: string | null; to: string | null; } const ZERO_ID = "0".repeat(40); export interface ReceiveCommands { updates: RefUpdate[]; capabilities: string[]; /** Bytes the command list takes at the start of the body, flush packet included. */ length: number; } /** Parses the command list at the start of a receive-pack request. Returns null until the flush packet has been seen. */ export function parseReceiveCommands(bytes: Uint8Array): ReceiveCommands | null { const decoder = new TextDecoder(); const commands: ReceiveCommands = { updates: [], capabilities: [], length: 0 }; for (let offset = 0; offset + 4 <= bytes.length; ) { const length = parseInt(decoder.decode(bytes.subarray(offset, offset + 4)), 16); if (Number.isNaN(length)) return { ...commands, length: offset }; if (length === 0) return { ...commands, length: offset + 4 }; if (offset + length > bytes.length) return null; const [command, capabilities] = decoder.decode(bytes.subarray(offset + 4, offset + length)).replace(/\n$/, "").split("\0"); if (capabilities !== undefined && !commands.updates.length) commands.capabilities = capabilities.split(" ").filter(Boolean); offset += length; const match = command.match(/^([0-9a-f]{40}) ([0-9a-f]{40}) (refs\/\S+)$/); if (match) commands.updates.push({ ref: match[3], from: match[1] === ZERO_ID ? null : match[1], to: match[2] === ZERO_ID ? null : match[2] }); } return null; } const MAX_COMMAND_BYTES = 64 * 1024; /** Reads just enough of a receive-pack body to see its ref updates, then releases the stream. */ export async function readReceiveCommands(body: ReadableStream): Promise { const reader = body.getReader(); let buffered = new Uint8Array(0); try { while (buffered.length < MAX_COMMAND_BYTES) { const { done, value } = await reader.read(); if (done) break; const next = new Uint8Array(buffered.length + value.length); next.set(buffered); next.set(value, buffered.length); buffered = next; const commands = parseReceiveCommands(buffered); if (commands) return commands; } return parseReceiveCommands(buffered) ?? { updates: [], capabilities: [], length: 0 }; } finally { await reader.cancel().catch(() => {}); } } const encoder = new TextEncoder(); function pktLine(payload: Uint8Array): Uint8Array { const line = new Uint8Array(payload.length + 4); line.set(encoder.encode((payload.length + 4).toString(16).padStart(4, "0"))); line.set(payload, 4); return line; } /** * Answers a receive-pack request with a status per ref: `ok` where `results` holds null, `ng` with the * reason otherwise. Git prints each reason next to its ref, and prints `messages` as `remote:` lines * when the client asked for side-band. */ export function reportPush(commands: ReceiveCommands, results: ReadonlyMap, messages: readonly string[] = []): Response { const status = [ pktLine(encoder.encode("unpack ok\n")), ...commands.updates.map((update) => { const reason = results.has(update.ref) ? results.get(update.ref) : "rejected with the other refs in this push"; return pktLine(encoder.encode(reason === null ? `ok ${update.ref}\n` : `ng ${update.ref} ${reason}\n`)); }), encoder.encode("0000"), ]; const sideband = commands.capabilities.includes("side-band-64k") || commands.capabilities.includes("side-band"); const chunks = sideband ? [...messages.map((message) => pktLine(new Uint8Array([2, ...encoder.encode(`${message}\n`)]))), ...status.map((chunk) => pktLine(new Uint8Array([1, ...chunk]))), encoder.encode("0000")] : status; return new Response(new Blob(chunks), { headers: { "content-type": "application/x-git-receive-pack-result", "cache-control": "no-cache" } }); } /** Answers a receive-pack request without forwarding it: every ref is reported as rejected, with `reasons` naming why. */ export function rejectPush(commands: ReceiveCommands, reasons: ReadonlyMap, messages: readonly string[] = []): Response { return reportPush(commands, new Map(commands.updates.map((update) => [update.ref, reasons.get(update.ref) ?? "rejected with the other refs in this push"])), messages); } export const ZERO_OID = ZERO_ID; /** A pack with no objects, which git sends when every object a push needs is already on the remote. */ export const EMPTY_PACK = new Uint8Array([0x50, 0x41, 0x43, 0x4b, 0, 0, 0, 2, 0, 0, 0, 0, ...hexBytes("029d08823bd8a8eab510ad6ac75c823cfd3ed31e")]); function hexBytes(hex: string): number[] { return hex.match(/../g)!.map((pair) => parseInt(pair, 16)); } export interface ReceiveResult { /** `ok`, or why the remote could not unpack the pack. */ unpack: string; /** Null for each ref the remote updated, or its reason for refusing. */ refs: Map; } /** * Sends a push of its own to the repository: `commands` as `" "`, then `pack`. Side-band * is never asked for, so the report comes back plain. */ export async function receivePack(repo: ArtifactsRepo, commands: readonly string[], capabilities: readonly string[], pack: ReadableStream | Uint8Array): Promise { const [info, token] = await Promise.all([repo.info(), repo.createToken("write", TOKEN_TTL_SECONDS)]); const wanted = [...new Set(["report-status", ...capabilities.filter((capability) => !/^(side-band|report-status)/.test(capability))])]; const head = new Blob([...commands.map((command, index) => pktLine(encoder.encode(index === 0 ? `${command}\0${wanted.join(" ")}\n` : `${command}\n`))), encoder.encode("0000")]); const body = pack instanceof Uint8Array ? new Blob([head, pack]).stream() : concatStreams(head.stream(), pack); const response = await fetch(`${info.remote}/git-receive-pack`, { method: "POST", headers: { authorization: `Bearer ${token.plaintext}`, "content-type": "application/x-git-receive-pack-request", accept: "application/x-git-receive-pack-result" }, body, }); if (!response.ok) throw new Error(`receive-pack failed with ${response.status}`); return parseReceiveResult(new Uint8Array(await response.arrayBuffer())); } export function parseReceiveResult(bytes: Uint8Array): ReceiveResult { const decoder = new TextDecoder(); const result: ReceiveResult = { unpack: "no report", refs: new Map() }; for (let offset = 0; offset + 4 <= bytes.length; ) { const length = parseInt(decoder.decode(bytes.subarray(offset, offset + 4)), 16); if (Number.isNaN(length) || length < 4) { offset += 4; continue; } const line = decoder.decode(bytes.subarray(offset + 4, offset + length)).replace(/\n$/, ""); offset += length; const [kind, ref, ...reason] = line.split(" "); if (kind === "unpack") result.unpack = [ref, ...reason].join(" "); else if (kind === "ok") result.refs.set(ref, null); else if (kind === "ng") result.refs.set(ref, reason.join(" ") || "rejected"); } return result; } /** `stream` without its first `count` bytes. */ export function dropBytes(stream: ReadableStream, count: number): ReadableStream { let left = count; return stream.pipeThrough( new TransformStream({ transform(chunk, controller) { if (left >= chunk.length) { left -= chunk.length; return; } controller.enqueue(left ? chunk.subarray(left) : chunk); left = 0; }, }), ); } function concatStreams(first: ReadableStream, second: ReadableStream): ReadableStream { const { readable, writable } = new TransformStream(); (async () => { await first.pipeTo(writable, { preventClose: true }); await second.pipeTo(writable); })().catch((error) => writable.abort(error).catch(() => {})); return readable; }