import { readFileSync, rmSync } from "node:fs"; import path from "node:path"; import { Elysia, t } from "elysia"; import { fileTypeFromBuffer } from "file-type"; import { sql } from "kysely"; import config from "../config.ts"; import { BINARY_DETECT_BYTES, BRANCHES_PER_PAGE, COMMITS_PER_PAGE, MAX_BRANCH_NAME_LENGTH, MAX_LABEL_NAME_LENGTH, paths, REPOS_PER_PAGE, TAGS_PER_PAGE, VALID_REPO_NAME_RE, YEAR_SECONDS, } from "../constants.ts"; import { db } from "../db/index.ts"; import { contentDisposition } from "../lib/contentDisposition.ts"; import { redirect } from "../lib/redirect.ts"; import { requireAdmin, resolveSession } from "../middleware/session.ts"; import { git, repoPath, type TreeEntry } from "../services/git.ts"; import { hasBinaryContent, prepareDiff, serveFile, } from "../services/highlightWorker.ts"; import { renderMarkdown } from "../services/markdown.ts"; import { ensureRepoRecord, repoDiskExists } from "../services/repoSync.ts"; import { html } from "../views/render.tsx"; import { BranchList } from "../views/repos/BranchList.tsx"; import { CommitDetail } from "../views/repos/CommitDetail.tsx"; import { CommitLog } from "../views/repos/CommitLog.tsx"; import { FileBlob } from "../views/repos/FileBlob.tsx"; import { FileEdit } from "../views/repos/FileEdit.tsx"; import { FileTree } from "../views/repos/FileTree.tsx"; import { NewFileForm } from "../views/repos/NewFileForm.tsx"; import { NewRepo } from "../views/repos/NewRepo.tsx"; import { RepoHome } from "../views/repos/RepoHome.tsx"; import { RepoList } from "../views/repos/RepoList.tsx"; import { RepoSettings } from "../views/repos/RepoSettings.tsx"; import { TagList } from "../views/repos/TagList.tsx"; async function getRepo(name: string, isAdmin: boolean) { if (!repoDiskExists(name)) return null; const repo = await ensureRepoRecord(name); if (repo.is_private && !isAdmin) return null; return repo; } /** * Read a byte range out of a streaming source without ever holding * the full content in memory. Used by the /raw endpoint to honour * HTTP Range headers against `git show`'s pipe. */ function sliceStream( source: ReadableStream, start: number, length: number, onDone: () => void, ): ReadableStream { const reader = source.getReader(); let skipped = 0; let emitted = 0; let finished = false; const finish = () => { if (finished) return; finished = true; reader.cancel().catch(() => {}); onDone(); }; return new ReadableStream({ async pull(controller) { while (emitted < length) { const { value, done } = await reader.read(); if (done) { controller.close(); finish(); return; } let chunk = value; if (skipped < start) { const drop = Math.min(start - skipped, chunk.length); skipped += drop; chunk = chunk.subarray(drop); if (chunk.length === 0) continue; } const remaining = length - emitted; if (chunk.length > remaining) chunk = chunk.subarray(0, remaining); emitted += chunk.length; controller.enqueue(chunk); if (emitted >= length) { controller.close(); finish(); } return; } controller.close(); finish(); }, cancel() { finish(); }, }); } /** Wrap a process stdout stream so the underlying process is killed on * close or cancel. Without this, a client disconnect partway through a * large blob leaves `git cat-file` running until its pipe back-pressures. */ function streamWithKill( source: ReadableStream, proc: { kill: () => void }, ): ReadableStream { const reader = source.getReader(); let killed = false; const finish = () => { if (killed) return; killed = true; reader.cancel().catch(() => {}); proc.kill(); }; return new ReadableStream({ async pull(controller) { try { const { value, done } = await reader.read(); if (done) { controller.close(); finish(); return; } controller.enqueue(value); } catch (err) { controller.error(err); finish(); } }, cancel() { finish(); }, }); } async function mimeForContent( filename: string, content: Buffer, ): Promise { const result = await fileTypeFromBuffer(content); if (result) return result.mime; const typeFromName = Bun.file(filename).type; if (typeFromName !== "application/octet-stream") { return typeFromName; } return hasBinaryContent(content.subarray(0, BINARY_DETECT_BYTES)) ? "application/octet-stream" : "text/plain; charset=utf-8"; } const README_NAMES = ["README.md", "readme.md", "README", "readme"]; async function readReadme( repo: string, ref: string, dir = "", knownEntries: TreeEntry[], ): Promise<{ content: Buffer; filename: string } | null> { const prefix = dir ? `${dir}/` : ""; // Fast path: we already have the tree listing — find the README name and // fetch only that one file, avoiding up to 3 wasted git-show calls. const entryNames = new Set(knownEntries.map((e) => e.name)); const name = README_NAMES.find((n) => entryNames.has(n)); if (!name) return null; const content = await git.show(repo, ref, `${prefix}${name}`); return content ? { content, filename: `${prefix}${name}` } : null; } export const repoRoutes = new Elysia() .get("/allowed_signers", () => { return new Response(readFileSync(paths.ALLOWED_SIGNERS_PATH), { headers: { "Content-Type": "text/plain; charset=utf-8" }, }); }) .guard({ cookie: t.Cookie({ session: t.Optional(t.String()), repo_sort: t.Optional(t.String()), }), }) .post( "/sort", ({ body }) => { const sort = body.sort === "name" ? "name" : "created"; const secure = config.PUBLIC_HTTPS ? "; Secure" : ""; return redirect( "/", `repo_sort=${sort}; Path=/; SameSite=Lax${secure}; Max-Age=${YEAR_SECONDS}`, ); }, { body: t.Object({ sort: t.String() }) }, ) .get( "/", async ({ cookie, query }) => { const user = await resolveSession(cookie.session.value); const search = query.q?.trim() || undefined; const page = Math.max(1, query.page ?? 1); const sort = cookie.repo_sort.value === "name" ? "name" : "created"; const isAdmin = user?.isAdmin ?? false; const searchPattern = search ? `%${search.replace(/[\\%_]/g, "\\$&")}%` : undefined; const countResult = await db .selectFrom("repositories") .select(db.fn.countAll().as("count")) .where((eb) => isAdmin ? eb.or([ eb("is_private", "=", 0), eb("is_private", "=", 1), ]) : eb("is_private", "=", 0), ) .$if(!!searchPattern, (qb) => qb.where( sql`("name" LIKE ${searchPattern} ESCAPE '\\' OR "description" LIKE ${searchPattern} ESCAPE '\\')`, ), ) .executeTakeFirst(); const totalCount = Number(countResult?.count ?? 0); const totalPages = Math.max( 1, Math.ceil(totalCount / REPOS_PER_PAGE), ); const safePage = Math.min(page, totalPages); const repos = await db .selectFrom("repositories") .selectAll() .where((eb) => isAdmin ? eb.or([ eb("is_private", "=", 0), eb("is_private", "=", 1), ]) : eb("is_private", "=", 0), ) .$if(!!searchPattern, (qb) => qb.where( sql`("name" LIKE ${searchPattern} ESCAPE '\\' OR "description" LIKE ${searchPattern} ESCAPE '\\')`, ), ) .orderBy("is_pinned", "desc") .$if(sort === "name", (qb) => qb.orderBy("name", "asc")) .$if(sort === "created", (qb) => qb.orderBy("created_at", "desc"), ) .limit(REPOS_PER_PAGE) .offset((safePage - 1) * REPOS_PER_PAGE) .execute(); const searchParam = search ? `&q=${encodeURIComponent(search)}` : ""; const pagination = { page: safePage, totalPages, pageUrlTemplate: `/?page={page}${searchParam}`, }; return html( , ); }, { query: t.Object({ q: t.Optional(t.String()), page: t.Optional(t.Numeric()), }), }, ) .get("/new", async ({ cookie }) => { const user = await resolveSession(cookie.session.value); const deny = requireAdmin(user); if (deny) return deny; return html(); }) .post( "/new", async ({ body, cookie }) => { const user = await resolveSession(cookie.session.value); const deny = requireAdmin(user); if (deny) return deny; const { name, description, is_private, default_branch } = body; if (!VALID_REPO_NAME_RE.test(name)) { return html( , ); } const branch = (default_branch?.trim() || "main").replace( /[^a-zA-Z0-9._/-]/g, "", ); const existing = await db .selectFrom("repositories") .select("id") .where("name", "=", name) .executeTakeFirst(); if (existing) { return html( , ); } const now = new Date().toISOString(); await db .insertInto("repositories") .values({ name, description: description || null, is_private: is_private === "1" ? 1 : 0, default_branch: branch, created_at: now, }) .execute(); // Initialise the git repo after the DB record is committed. If // git.init fails we roll back the DB record so the two stay in sync. try { await git.init(name, branch); } catch (err) { await db .deleteFrom("repositories") .where("name", "=", name) .execute(); throw err; } return new Response(null, { status: 302, headers: { Location: `/${name}` }, }); }, { body: t.Object({ name: t.String(), description: t.Optional(t.String()), is_private: t.Optional(t.String()), default_branch: t.Optional(t.String()), }), }, ) .get("/:repo", async ({ params, cookie }) => { const user = await resolveSession(cookie.session.value); const repo = await getRepo(params.repo, user?.isAdmin ?? false); if (!repo) return new Response("Not found", { status: 404 }); const hasContent = await git.hasCommits(repo.name); let readmeHtml: string | null = null; let readmePath: string | undefined; let entries: Awaited> = []; let branches: string[] = []; let tags: string[] = []; if (hasContent) { const [lsResult, branchResult, tagResult, resolved] = await Promise.all([ git.lsTree(repo.name, repo.default_branch), git.branches(repo.name), git.tags(repo.name), git.resolveRef(repo.name, repo.default_branch), ]); entries = lsResult; branches = branchResult; tags = tagResult; const readme = await readReadme( repo.name, repo.default_branch, "", lsResult, ); if (readme) { const key = resolved ? `readme:${repo.name}:${resolved}:` : undefined; readmeHtml = renderMarkdown( readme.content.toString("utf-8"), key, { repo: repo.name, ref: repo.default_branch, dir: "", }, ); readmePath = readme.filename; } } return html( , ); }) .get( "/:repo/branch-switch", async ({ params, query, cookie }) => { const user = await resolveSession(cookie.session.value); const repo = await getRepo(params.repo, user?.isAdmin ?? false); if (!repo) return new Response("Not found", { status: 404 }); const ref = query.rev?.trim(); if (!ref) return new Response(null, { status: 302, headers: { Location: `/${repo.name}` }, }); const view = query.view; const subpath = query.path ?? ""; if (view === "commits") { return new Response(null, { status: 302, headers: { Location: `/${repo.name}/commits/${ref}` }, }); } if (view === "blob" && subpath) { return new Response(null, { status: 302, headers: { Location: `/${repo.name}/blob/${ref}/${subpath}`, }, }); } const location = subpath ? `/${repo.name}/tree/${ref}/${subpath}` : `/${repo.name}/tree/${ref}`; return new Response(null, { status: 302, headers: { Location: location }, }); }, { query: t.Object({ rev: t.Optional(t.String()), view: t.Optional(t.String()), path: t.Optional(t.String()), }), }, ) .get("/:repo/tree/:ref", async ({ params, cookie }) => { const user = await resolveSession(cookie.session.value); const repo = await getRepo(params.repo, user?.isAdmin ?? false); if (!repo) return new Response("Not found", { status: 404 }); const resolved = await git.resolveRef(repo.name, params.ref); if (!resolved) return new Response("Not found", { status: 404 }); const [entries, branches, tags] = await Promise.all([ git.lsTree(repo.name, params.ref), git.branches(repo.name), git.tags(repo.name), ]); const readme = await readReadme(repo.name, params.ref, "", entries); const readmeHtml = readme ? renderMarkdown( readme.content.toString("utf-8"), `readme:${repo.name}:${resolved}:`, { repo: repo.name, ref: params.ref, dir: "" }, ) : null; return html( , ); }) .get("/:repo/tree/:ref/*", async ({ params, cookie }) => { const user = await resolveSession(cookie.session.value); const repo = await getRepo(params.repo, user?.isAdmin ?? false); if (!repo) return new Response("Not found", { status: 404 }); const resolved = await git.resolveRef(repo.name, params.ref); if (!resolved) return new Response("Not found", { status: 404 }); const subpath = decodeURIComponent(params["*"]); const [entries, branches, tags] = await Promise.all([ git.lsTree(repo.name, params.ref, subpath), git.branches(repo.name), git.tags(repo.name), ]); if (entries.length === 0) { // Could be a file — redirect to blob return new Response(null, { status: 302, headers: { Location: `/${repo.name}/blob/${params.ref}/${subpath}`, }, }); } const readme = await readReadme( repo.name, params.ref, subpath, entries, ); const readmeHtml = readme ? renderMarkdown( readme.content.toString("utf-8"), `readme:${repo.name}:${resolved}:${subpath}`, { repo: repo.name, ref: params.ref, dir: subpath }, ) : null; return html( , ); }) .get("/:repo/blob/:ref/*", async ({ params, cookie }) => { const user = await resolveSession(cookie.session.value); const repo = await getRepo(params.repo, user?.isAdmin ?? false); if (!repo) return new Response("Not found", { status: 404 }); const filePath = decodeURIComponent(params["*"]); // Size-gate before reading the blob into memory: holding a // huge content buffer (and then running shiki/marked over it) // is the cheapest DOS vector against unauthenticated users on // a public repo. const size = await git.getFileSize(repo.name, params.ref, filePath); const filename = path.basename(filePath); if (size !== null && size > config.MAX_RENDER_BYTES) { const [branches, tags] = await Promise.all([ git.branches(repo.name), git.tags(repo.name), ]); return html( , ); } const [content, branches, tags, commitSHA] = await Promise.all([ git.show(repo.name, params.ref, filePath), git.branches(repo.name), git.tags(repo.name), git.resolveRef(repo.name, params.ref), ]); if (!content || !commitSHA) return new Response("Not found", { status: 404 }); const [view, markdownHtml] = await Promise.all([ serveFile( content, filename, `${repo.name}:${commitSHA}:${filePath}`, ), /\.mdx?$/i.test(filename) ? Promise.resolve( renderMarkdown( content.toString("utf-8"), `${repo.name}:${commitSHA}:${filePath}`, { repo: repo.name, ref: params.ref, dir: path.dirname(filePath) === "." ? "" : path.dirname(filePath), }, ), ) : Promise.resolve(undefined), ]); return html( , ); }) .get("/:repo/raw/:ref/*", async ({ params, cookie, request }) => { const user = await resolveSession(cookie.session.value); const repo = await getRepo(params.repo, user?.isAdmin ?? false); if (!repo) return new Response("Not found", { status: 404 }); const filePath = decodeURIComponent(params["*"]); // Resolve the file's blob hash and size up front. cat-file -s // is O(1) and lets us stream the blob below without ever // holding it whole in memory — old code did // `await arrayBuffer()` and sliced for Range, peaking at // file_size × concurrent_requests of RSS. const total = await git.getFileSize(repo.name, params.ref, filePath); if (total === null) return new Response("Not found", { status: 404 }); if ( config.MAX_RAW_DOWNLOAD_BYTES > 0 && total > config.MAX_RAW_DOWNLOAD_BYTES ) { return new Response("File exceeds raw download size limit", { status: 413, }); } const filename = path.basename(filePath); // We use `cat-file blob` rather than `git show` so the bytes // streamed exactly match what `cat-file -s` reported above — // `git show` can apply smudge filters / autocrlf, which would // make Content-Length wrong on filtered repos. const blobArgs = [ "git", "-C", repoPath(repo.name), "cat-file", "blob", `${params.ref}:${filePath}`, ]; // Sniff content-type from the first bytes only — same idea as // the old mimeForContent but without buffering the full blob. const sniffStream = Bun.spawn(blobArgs, { stdout: "pipe", stderr: "ignore", }); const sniffReader = sniffStream.stdout.getReader(); const { value: firstChunk } = await sniffReader.read(); sniffReader.cancel().catch(() => {}); sniffStream.kill(); const head = firstChunk ? Buffer.from(firstChunk.subarray(0, BINARY_DETECT_BYTES)) : Buffer.alloc(0); const contentType = await mimeForContent(filename, head); const rangeHeader = request.headers.get("Range"); const fullProc = Bun.spawn(blobArgs, { stdout: "pipe", stderr: "ignore", }); if (rangeHeader) { const match = rangeHeader.match(/bytes=(\d*)-(\d*)/); if (match) { const start = match[1] ? parseInt(match[1], 10) : 0; const end = match[2] ? parseInt(match[2], 10) : total - 1; const clampedEnd = Math.min(end, total - 1); const length = clampedEnd - start + 1; // sliceStream kills fullProc once the slice is exhausted or // the consumer cancels — without this, requesting a tiny // range from a huge blob leaves `git cat-file` running. const sliced = sliceStream(fullProc.stdout, start, length, () => fullProc.kill(), ); return new Response(sliced, { status: 206, headers: { "Content-Type": contentType, "Content-Range": `bytes ${start}-${clampedEnd}/${total}`, "Accept-Ranges": "bytes", "Content-Length": String(length), }, }); } } // Wrap the full stream too so a client disconnect during a large // download kills the underlying git process instead of leaving it // wedged on a back-pressured pipe. return new Response(streamWithKill(fullProc.stdout, fullProc), { headers: { "Content-Type": contentType, "Content-Disposition": contentDisposition("inline", filename), "Content-Length": String(total), "Accept-Ranges": "bytes", }, }); }) .get("/:repo/edit/:ref/*", async ({ params, query, cookie }) => { const user = await resolveSession(cookie.session.value); const deny = requireAdmin(user); if (deny) return deny; const repo = await getRepo(params.repo, true); if (!repo) return new Response("Not found", { status: 404 }); const filePath = decodeURIComponent(params["*"]); const branches = await git.branches(repo.name); if (!branches.includes(params.ref)) return new Response("Not found", { status: 404 }); const content = await git.show(repo.name, params.ref, filePath); if (!content) return new Response("Not found", { status: 404 }); if (hasBinaryContent(content.subarray(0, 8000))) return new Response("Not found", { status: 404 }); const queryError = typeof query.error === "string" ? query.error : undefined; return html( , ); }) .post( "/:repo/edit/:ref/*", async ({ params, body, cookie }) => { const user = await resolveSession(cookie.session.value); const deny = requireAdmin(user); if (deny) return deny; const repo = await getRepo(params.repo, true); if (!repo) return new Response("Not found", { status: 404 }); const filePath = decodeURIComponent(params["*"]); const branches = await git.branches(repo.name); if (!branches.includes(params.ref)) return new Response("Not found", { status: 404 }); const newPath = body.new_path?.trim() || undefined; const targetPath = newPath && newPath !== filePath ? newPath : filePath; if ( newPath && newPath !== filePath && (newPath.startsWith("/") || newPath.includes("..") || newPath.includes("\0")) ) { return redirect( `/${repo.name}/edit/${params.ref}/${filePath}?error=${encodeURIComponent("Invalid file path.")}`, ); } const defaultMessage = targetPath !== filePath ? `Rename ${path.basename(filePath)} to ${path.basename(targetPath)}` : `Edited ${path.basename(filePath)}`; const message = body.message?.trim() || defaultMessage; const content = (body.content ?? "").replaceAll("\r\n", "\n"); const commit = await git.editFile( repo.name, params.ref, filePath, content, message, config.COMMITTER_NAME, config.COMMITTER_EMAIL, newPath, ); return new Response(null, { status: 302, headers: { Location: `/${repo.name}/commit/${commit}`, }, }); }, { body: t.Object({ content: t.Optional(t.String()), message: t.Optional(t.String()), new_path: t.Optional(t.String()), }), }, ) .get( "/:repo/commits/:ref", async ({ params, cookie, query }) => { const user = await resolveSession(cookie.session.value); const repo = await getRepo(params.repo, user?.isAdmin ?? false); if (!repo) return new Response("Not found", { status: 404 }); // Cursor-based pagination — O(1) regardless of history depth. // `after` = SHA of the last commit on the previous page (resume cursor). // `prev` = the `after` value used on the page that linked here, so we can // reconstruct a "← Newer" link without a full history traversal. const after = query.after?.trim() || null; const prev = query.prev?.trim() || null; const [rawCommits, branches, tags] = await Promise.all([ // When `after` is set: start at that SHA and skip it (--skip=1 is O(1)), // then fetch LIMIT+1 to detect whether another page exists. after ? git.log(repo.name, after, COMMITS_PER_PAGE + 1, 1) : git.log(repo.name, params.ref, COMMITS_PER_PAGE + 1, 0), git.branches(repo.name), git.tags(repo.name), ]); const hasNext = rawCommits.length > COMMITS_PER_PAGE; const commits = rawCommits.slice(0, COMMITS_PER_PAGE); // Build cursor URLs. // "Older" advances past the last commit on this page. // "Newer" goes back one page using the `prev` cursor saved in the URL, // or to the first page if we're on page 2. const base = `/${repo.name}/commits/${params.ref}`; const olderUrl = hasNext ? `${base}?after=${commits[commits.length - 1]?.hash}&prev=${after ?? ""}` : null; const newerUrl = after ? prev ? `${base}?after=${prev}` : base : null; return html( , ); }, { query: t.Object({ after: t.Optional(t.String()), prev: t.Optional(t.String()), }), }, ) .get("/:repo/commit/:sha", async ({ params, cookie }) => { const user = await resolveSession(cookie.session.value); const repo = await getRepo(params.repo, user?.isAdmin ?? false); if (!repo) return new Response("Not found", { status: 404 }); const [meta, rawDiff] = await Promise.all([ git.commitMeta(repo.name, params.sha), git.diff(repo.name, params.sha), ]); if (!meta) return new Response("Commit not found", { status: 404 }); // Reject oversized diffs after generation but before highlighting. // Avoids running marked / shiki / DOMPurify over a multi-megabyte // diff which would synchronously stall the worker pool. if (rawDiff.length > config.MAX_RENDER_BYTES) { return html( , ); } const files = await prepareDiff( rawDiff, `commit:${repo.name}:${params.sha}`, repo.name, ); return html( , ); }) .get("/:repo/settings", async ({ params, query, cookie }) => { const user = await resolveSession(cookie.session.value); const deny = requireAdmin(user); if (deny) return deny; const repo = await getRepo(params.repo, true); if (!repo) return new Response("Not found", { status: 404 }); const branches = await git.branches(repo.name); const [labels, secrets] = await Promise.all([ db .selectFrom("labels") .selectAll() .where("repo_id", "=", repo.id) .orderBy("name", "asc") .execute(), db .selectFrom("ci_secrets") .select(["id", "name", "description", "created_at"]) .where("repo_id", "=", repo.id) .orderBy("name", "asc") .execute(), ]); const success = typeof query.success === "string" ? query.success : undefined; const error = typeof query.error === "string" ? query.error : undefined; return html( , ); }) .post( "/:repo/settings", async ({ params, body, cookie }) => { const user = await resolveSession(cookie.session.value); const deny = requireAdmin(user); if (deny) return deny; const repo = await getRepo(params.repo, true); if (!repo) return new Response("Not found", { status: 404 }); const { description, is_private, is_pinned, allow_user_labels, default_branch, issue_template, patch_template, } = body; const branches = await git.branches(repo.name); const newBranch = default_branch?.trim() || repo.default_branch; // Validate the selected branch exists (only if repo has commits) if (branches.length > 0 && !branches.includes(newBranch)) { return redirect( `/${repo.name}/settings?error=${encodeURIComponent(`Branch "${newBranch}" does not exist.`)}`, ); } await db .updateTable("repositories") .set({ description: description?.trim() || null, is_private: is_private === "1" ? 1 : 0, is_pinned: is_pinned === "1" ? 1 : 0, allow_user_labels: allow_user_labels === "1" ? 1 : 0, default_branch: newBranch, issue_template: issue_template?.trim() || null, patch_template: patch_template?.trim() || null, }) .where("id", "=", repo.id) .execute(); // Keep git HEAD in sync if the branch actually exists if (branches.includes(newBranch)) { await git .setHead(repo.name, newBranch) .catch((e) => console.error( `setHead failed for ${repo.name}/${newBranch}:`, e, ), ); } return redirect(`/${repo.name}/settings?success=Settings+saved.`); }, { body: t.Object({ description: t.Optional(t.String()), is_private: t.Optional(t.String()), is_pinned: t.Optional(t.String()), allow_user_labels: t.Optional(t.String()), default_branch: t.Optional(t.String()), issue_template: t.Optional(t.String()), patch_template: t.Optional(t.String()), }), }, ) .post("/:repo/settings/delete", async ({ params, cookie }) => { const user = await resolveSession(cookie.session.value); const deny = requireAdmin(user); if (deny) return deny; const repo = await getRepo(params.repo, true); if (!repo) return new Response("Not found", { status: 404 }); // Remove the on-disk repo first. If this fails (e.g. permission error), // we abort before touching the DB so the repo remains accessible. rmSync(repoPath(repo.name), { recursive: true, force: true }); await db.deleteFrom("repositories").where("id", "=", repo.id).execute(); return new Response(null, { status: 302, headers: { Location: "/" } }); }) .post( "/:repo/settings/labels", async ({ params, body, cookie }) => { const user = await resolveSession(cookie.session.value); const deny = requireAdmin(user); if (deny) return deny; const repo = await getRepo(params.repo, true); if (!repo) return new Response("Not found", { status: 404 }); const name = body.name?.trim(); const color = body.color?.trim(); if (!name || name.length > MAX_LABEL_NAME_LENGTH) { return redirect( `/${repo.name}/settings?error=${encodeURIComponent("Label name must be 1–50 characters.")}`, ); } if (!color || !/^#[0-9a-fA-F]{6}$/.test(color)) { return redirect( `/${repo.name}/settings?error=${encodeURIComponent("Invalid color.")}`, ); } try { await db .insertInto("labels") .values({ repo_id: repo.id, name, color, created_at: new Date().toISOString(), }) .execute(); } catch { return redirect( `/${repo.name}/settings?error=${encodeURIComponent("A label with that name already exists.")}`, ); } return redirect(`/${repo.name}/settings?success=Label+created.`); }, { body: t.Object({ name: t.String(), color: t.String(), }), }, ) .post( "/:repo/settings/labels/delete", async ({ params, body, cookie }) => { const user = await resolveSession(cookie.session.value); const deny = requireAdmin(user); if (deny) return deny; const repo = await getRepo(params.repo, true); if (!repo) return new Response("Not found", { status: 404 }); const label = await db .selectFrom("labels") .select(["id", "repo_id"]) .where("id", "=", body.id) .executeTakeFirst(); if (!label || label.repo_id !== repo.id) { return redirect( `/${repo.name}/settings?error=${encodeURIComponent("Label not found.")}`, ); } await db.deleteFrom("labels").where("id", "=", body.id).execute(); return redirect(`/${repo.name}/settings?success=Label+deleted.`); }, { body: t.Object({ id: t.Numeric() }), }, ) // ── Branches ────────────────────────────────────────────────────────────── .get("/:repo/branches", async ({ params, query, cookie }) => { const user = await resolveSession(cookie.session.value); const repo = await getRepo(params.repo, user?.isAdmin ?? false); if (!repo) return new Response("Not found", { status: 404 }); const allBranches = await git.branchesWithInfo(repo.name); const page = Math.max(1, parseInt(String(query.page ?? "1"), 10) || 1); const totalPages = Math.max( 1, Math.ceil(allBranches.length / BRANCHES_PER_PAGE), ); const safePage = Math.min(page, totalPages); const branches = allBranches.slice( (safePage - 1) * BRANCHES_PER_PAGE, safePage * BRANCHES_PER_PAGE, ); const success = typeof query.success === "string" ? query.success : undefined; const error = typeof query.error === "string" ? query.error : undefined; return html( , ); }) .post( "/:repo/branches/create", async ({ params, body, cookie }) => { const user = await resolveSession(cookie.session.value); const deny = requireAdmin(user); if (deny) return deny; const repo = await getRepo(params.repo, true); if (!repo) return new Response("Not found", { status: 404 }); const name = body.name?.trim() ?? ""; const sourceRef = body.source_ref?.trim() ?? ""; if ( !name || !/^[a-zA-Z0-9._][a-zA-Z0-9._\-/]*$/.test(name) || name.includes("..") || name.length > MAX_BRANCH_NAME_LENGTH ) { return redirect( `/${repo.name}/branches?error=${encodeURIComponent("Invalid branch name.")}`, ); } if (!sourceRef) { return redirect( `/${repo.name}/branches?error=${encodeURIComponent("Source ref is required.")}`, ); } const result = await git.createBranch(repo.name, name, sourceRef); if (result === "ok") { return redirect( `/${repo.name}/branches?success=${encodeURIComponent(`Branch "${name}" created.`)}`, ); } if (result === "already_exists") { return redirect( `/${repo.name}/branches?error=${encodeURIComponent(`Branch "${name}" already exists.`)}`, ); } if (result === "bad_ref") { return redirect( `/${repo.name}/branches?error=${encodeURIComponent(`"${sourceRef}" is not a valid ref.`)}`, ); } return redirect( `/${repo.name}/branches?error=${encodeURIComponent("Failed to create branch.")}`, ); }, { body: t.Object({ name: t.String(), source_ref: t.String(), }), }, ) .post( "/:repo/branches/delete", async ({ params, body, cookie }) => { const user = await resolveSession(cookie.session.value); const deny = requireAdmin(user); if (deny) return deny; const repo = await getRepo(params.repo, true); if (!repo) return new Response("Not found", { status: 404 }); const name = body.name?.trim() ?? ""; if (!name) { return redirect( `/${repo.name}/branches?error=${encodeURIComponent("Branch name is required.")}`, ); } if (name === repo.default_branch) { return redirect( `/${repo.name}/branches?error=${encodeURIComponent("Cannot delete the default branch.")}`, ); } const result = await git.deleteBranch(repo.name, name); if (result === "ok") { return redirect( `/${repo.name}/branches?success=${encodeURIComponent(`Branch "${name}" deleted.`)}`, ); } if (result === "not_found") { return redirect( `/${repo.name}/branches?error=${encodeURIComponent(`Branch "${name}" not found.`)}`, ); } return redirect( `/${repo.name}/branches?error=${encodeURIComponent("Failed to delete branch.")}`, ); }, { body: t.Object({ name: t.String() }), }, ) .post( "/:repo/branches/rename", async ({ params, body, cookie }) => { const user = await resolveSession(cookie.session.value); const deny = requireAdmin(user); if (deny) return deny; const repo = await getRepo(params.repo, true); if (!repo) return new Response("Not found", { status: 404 }); const oldName = body.old_name?.trim() ?? ""; const newName = body.new_name?.trim() ?? ""; if ( !newName || !/^[a-zA-Z0-9._][a-zA-Z0-9._\-/]*$/.test(newName) || newName.includes("..") || newName.length > MAX_BRANCH_NAME_LENGTH ) { return redirect( `/${repo.name}/branches?error=${encodeURIComponent("Invalid branch name.")}`, ); } const result = await git.renameBranch(repo.name, oldName, newName); if (result === "ok") { // Keep default_branch in DB in sync if we renamed it if (oldName === repo.default_branch) { await db .updateTable("repositories") .set({ default_branch: newName }) .where("id", "=", repo.id) .execute(); await git .setHead(repo.name, newName) .catch((e) => console.error( `setHead failed for ${repo.name}/${newName}:`, e, ), ); } return redirect( `/${repo.name}/branches?success=${encodeURIComponent(`Branch renamed to "${newName}".`)}`, ); } if (result === "not_found") { return redirect( `/${repo.name}/branches?error=${encodeURIComponent(`Branch "${oldName}" not found.`)}`, ); } if (result === "already_exists") { return redirect( `/${repo.name}/branches?error=${encodeURIComponent(`Branch "${newName}" already exists.`)}`, ); } return redirect( `/${repo.name}/branches?error=${encodeURIComponent("Failed to rename branch.")}`, ); }, { body: t.Object({ old_name: t.String(), new_name: t.String(), }), }, ) // ── Tags ────────────────────────────────────────────────────────────────── .get("/:repo/tags", async ({ params, query, cookie }) => { const user = await resolveSession(cookie.session.value); const repo = await getRepo(params.repo, user?.isAdmin ?? false); if (!repo) return new Response("Not found", { status: 404 }); const [allTags, releases] = await Promise.all([ git.tagsWithInfo(repo.name), db .selectFrom("releases") .select(["id", "tag_name"]) .where("repo_id", "=", repo.id) .where("tag_name", "is not", null) .execute(), ]); const tagReleaseMap = new Map(); for (const r of releases) { if (r.tag_name) tagReleaseMap.set(r.tag_name, r.id); } const page = Math.max(1, parseInt(String(query.page ?? "1"), 10) || 1); const totalPages = Math.max( 1, Math.ceil(allTags.length / TAGS_PER_PAGE), ); const safePage = Math.min(page, totalPages); const tags = allTags.slice( (safePage - 1) * TAGS_PER_PAGE, safePage * TAGS_PER_PAGE, ); const success = typeof query.success === "string" ? query.success : undefined; const error = typeof query.error === "string" ? query.error : undefined; return html( , ); }) .post( "/:repo/tags/create", async ({ params, body, cookie }) => { const user = await resolveSession(cookie.session.value); const deny = requireAdmin(user); if (deny) return deny; const repo = await getRepo(params.repo, true); if (!repo) return new Response("Not found", { status: 404 }); const tagName = body.name?.trim() ?? ""; const ref = body.ref?.trim() ?? ""; const message = body.message?.trim() || undefined; if (!tagName || !/^[a-zA-Z0-9._\-+]+$/.test(tagName)) { return redirect( `/${repo.name}/tags?error=${encodeURIComponent("Invalid tag name.")}`, ); } if (!ref) { return redirect( `/${repo.name}/tags?error=${encodeURIComponent("Target ref is required.")}`, ); } const result = await git.createTag( repo.name, tagName, ref, message, message ? config.COMMITTER_NAME : undefined, message ? config.COMMITTER_EMAIL : undefined, ); if (result === "ok") { return redirect( `/${repo.name}/tags?success=${encodeURIComponent(`Tag "${tagName}" created.`)}`, ); } if (result === "already_exists") { return redirect( `/${repo.name}/tags?error=${encodeURIComponent(`Tag "${tagName}" already exists.`)}`, ); } if (result === "bad_ref") { return redirect( `/${repo.name}/tags?error=${encodeURIComponent(`"${ref}" is not a valid ref.`)}`, ); } return redirect( `/${repo.name}/tags?error=${encodeURIComponent("Failed to create tag.")}`, ); }, { body: t.Object({ name: t.String(), ref: t.String(), message: t.Optional(t.String()), }), }, ) .post( "/:repo/tags/delete", async ({ params, body, cookie }) => { const user = await resolveSession(cookie.session.value); const deny = requireAdmin(user); if (deny) return deny; const repo = await getRepo(params.repo, true); if (!repo) return new Response("Not found", { status: 404 }); const tagName = body.name?.trim() ?? ""; if (!tagName) { return redirect( `/${repo.name}/tags?error=${encodeURIComponent("Tag name is required.")}`, ); } const result = await git.deleteTag(repo.name, tagName); if (result === "ok") { return redirect( `/${repo.name}/tags?success=${encodeURIComponent(`Tag "${tagName}" deleted.`)}`, ); } if (result === "not_found") { return redirect( `/${repo.name}/tags?error=${encodeURIComponent(`Tag "${tagName}" not found.`)}`, ); } return redirect( `/${repo.name}/tags?error=${encodeURIComponent("Failed to delete tag.")}`, ); }, { body: t.Object({ name: t.String() }), }, ) // ── File creation ───────────────────────────────────────────────────────── .get("/:repo/new-file/:ref", async ({ params, query, cookie }) => { const user = await resolveSession(cookie.session.value); const deny = requireAdmin(user); if (deny) return deny; const repo = await getRepo(params.repo, true); if (!repo) return new Response("Not found", { status: 404 }); const dir = typeof query.dir === "string" ? query.dir : ""; const error = typeof query.error === "string" ? query.error : undefined; return html( , ); }) .post( "/:repo/new-file/:ref", async ({ params, body, cookie }) => { const user = await resolveSession(cookie.session.value); const deny = requireAdmin(user); if (deny) return deny; const repo = await getRepo(params.repo, true); if (!repo) return new Response("Not found", { status: 404 }); const filePath = body.path?.trim() ?? ""; const content = body.content ?? ""; const message = body.message?.trim() || `Add ${filePath}`; if ( !filePath || filePath.startsWith("/") || filePath.includes("..") || filePath.includes("\0") ) { return redirect( `/${repo.name}/new-file/${params.ref}?error=${encodeURIComponent("Invalid file path.")}`, ); } // Ensure we're on a branch const branches = await git.branches(repo.name); if (branches.length > 0 && !branches.includes(params.ref)) { return redirect( `/${repo.name}/new-file/${params.ref}?error=${encodeURIComponent("Can only create files on a branch.")}`, ); } try { const commit = await git.createFile( repo.name, params.ref, filePath, content, message, config.COMMITTER_NAME, config.COMMITTER_EMAIL, ); return redirect(`/${repo.name}/commit/${commit}`); } catch { return redirect( `/${repo.name}/new-file/${params.ref}?error=${encodeURIComponent("Failed to create file.")}`, ); } }, { body: t.Object({ path: t.String(), content: t.Optional(t.String()), message: t.Optional(t.String()), }), }, ) // ── File deletion ───────────────────────────────────────────────────────── .post( "/:repo/delete-file/:ref/*", async ({ params, body, cookie }) => { const user = await resolveSession(cookie.session.value); const deny = requireAdmin(user); if (deny) return deny; const repo = await getRepo(params.repo, true); if (!repo) return new Response("Not found", { status: 404 }); const filePath = decodeURIComponent(params["*"]); const message = body.message?.trim() || `Delete ${filePath}`; try { const commit = await git.deleteFile( repo.name, params.ref, filePath, message, config.COMMITTER_NAME, config.COMMITTER_EMAIL, ); return redirect(`/${repo.name}/commit/${commit}`); } catch { return redirect( `/${repo.name}/blob/${params.ref}/${filePath}?error=${encodeURIComponent("Failed to delete file.")}`, ); } }, { body: t.Object({ message: t.Optional(t.String()), }), }, );