repos.tsx
Raw
1import { readFileSync, rmSync } from "node:fs";
2import path from "node:path";
3import { Elysia, t } from "elysia";
4import { fileTypeFromBuffer } from "file-type";
5import { sql } from "kysely";
6import config from "../config.ts";
7import {
8 BINARY_DETECT_BYTES,
9 BRANCHES_PER_PAGE,
10 COMMITS_PER_PAGE,
11 MAX_BRANCH_NAME_LENGTH,
12 MAX_LABEL_NAME_LENGTH,
13 paths,
14 REPOS_PER_PAGE,
15 TAGS_PER_PAGE,
16 VALID_REPO_NAME_RE,
17 YEAR_SECONDS,
18} from "../constants.ts";
19import { db } from "../db/index.ts";
20import { contentDisposition } from "../lib/contentDisposition.ts";
21import { redirect } from "../lib/redirect.ts";
22import { requireAdmin, resolveSession } from "../middleware/session.ts";
23import { git, repoPath, type TreeEntry } from "../services/git.ts";
24import {
25 hasBinaryContent,
26 prepareDiff,
27 serveFile,
28} from "../services/highlightWorker.ts";
29import { renderMarkdown } from "../services/markdown.ts";
30import { ensureRepoRecord, repoDiskExists } from "../services/repoSync.ts";
31import { html } from "../views/render.tsx";
32import { BranchList } from "../views/repos/BranchList.tsx";
33import { CommitDetail } from "../views/repos/CommitDetail.tsx";
34import { CommitLog } from "../views/repos/CommitLog.tsx";
35import { FileBlob } from "../views/repos/FileBlob.tsx";
36import { FileEdit } from "../views/repos/FileEdit.tsx";
37import { FileTree } from "../views/repos/FileTree.tsx";
38import { NewFileForm } from "../views/repos/NewFileForm.tsx";
39import { NewRepo } from "../views/repos/NewRepo.tsx";
40import { RepoHome } from "../views/repos/RepoHome.tsx";
41import { RepoList } from "../views/repos/RepoList.tsx";
42import { RepoSettings } from "../views/repos/RepoSettings.tsx";
43import { TagList } from "../views/repos/TagList.tsx";
44
45async function getRepo(name: string, isAdmin: boolean) {
46 if (!repoDiskExists(name)) return null;
47 const repo = await ensureRepoRecord(name);
48 if (repo.is_private && !isAdmin) return null;
49 return repo;
50}
51
52/**
53 * Read a byte range out of a streaming source without ever holding
54 * the full content in memory. Used by the /raw endpoint to honour
55 * HTTP Range headers against `git show`'s pipe.
56 */
57function sliceStream(
58 source: ReadableStream<Uint8Array>,
59 start: number,
60 length: number,
61 onDone: () => void,
62): ReadableStream<Uint8Array> {
63 const reader = source.getReader();
64 let skipped = 0;
65 let emitted = 0;
66 let finished = false;
67 const finish = () => {
68 if (finished) return;
69 finished = true;
70 reader.cancel().catch(() => {});
71 onDone();
72 };
73 return new ReadableStream<Uint8Array>({
74 async pull(controller) {
75 while (emitted < length) {
76 const { value, done } = await reader.read();
77 if (done) {
78 controller.close();
79 finish();
80 return;
81 }
82 let chunk = value;
83 if (skipped < start) {
84 const drop = Math.min(start - skipped, chunk.length);
85 skipped += drop;
86 chunk = chunk.subarray(drop);
87 if (chunk.length === 0) continue;
88 }
89 const remaining = length - emitted;
90 if (chunk.length > remaining)
91 chunk = chunk.subarray(0, remaining);
92 emitted += chunk.length;
93 controller.enqueue(chunk);
94 if (emitted >= length) {
95 controller.close();
96 finish();
97 }
98 return;
99 }
100 controller.close();
101 finish();
102 },
103 cancel() {
104 finish();
105 },
106 });
107}
108
109/** Wrap a process stdout stream so the underlying process is killed on
110 * close or cancel. Without this, a client disconnect partway through a
111 * large blob leaves `git cat-file` running until its pipe back-pressures. */
112function streamWithKill(
113 source: ReadableStream<Uint8Array>,
114 proc: { kill: () => void },
115): ReadableStream<Uint8Array> {
116 const reader = source.getReader();
117 let killed = false;
118 const finish = () => {
119 if (killed) return;
120 killed = true;
121 reader.cancel().catch(() => {});
122 proc.kill();
123 };
124 return new ReadableStream<Uint8Array>({
125 async pull(controller) {
126 try {
127 const { value, done } = await reader.read();
128 if (done) {
129 controller.close();
130 finish();
131 return;
132 }
133 controller.enqueue(value);
134 } catch (err) {
135 controller.error(err);
136 finish();
137 }
138 },
139 cancel() {
140 finish();
141 },
142 });
143}
144
145async function mimeForContent(
146 filename: string,
147 content: Buffer,
148): Promise<string> {
149 const result = await fileTypeFromBuffer(content);
150 if (result) return result.mime;
151
152 const typeFromName = Bun.file(filename).type;
153 if (typeFromName !== "application/octet-stream") {
154 return typeFromName;
155 }
156
157 return hasBinaryContent(content.subarray(0, BINARY_DETECT_BYTES))
158 ? "application/octet-stream"
159 : "text/plain; charset=utf-8";
160}
161
162const README_NAMES = ["README.md", "readme.md", "README", "readme"];
163
164async function readReadme(
165 repo: string,
166 ref: string,
167 dir = "",
168 knownEntries: TreeEntry[],
169): Promise<{ content: Buffer; filename: string } | null> {
170 const prefix = dir ? `${dir}/` : "";
171 // Fast path: we already have the tree listing — find the README name and
172 // fetch only that one file, avoiding up to 3 wasted git-show calls.
173 const entryNames = new Set(knownEntries.map((e) => e.name));
174 const name = README_NAMES.find((n) => entryNames.has(n));
175 if (!name) return null;
176 const content = await git.show(repo, ref, `${prefix}${name}`);
177 return content ? { content, filename: `${prefix}${name}` } : null;
178}
179
180export const repoRoutes = new Elysia()
181 .get("/allowed_signers", () => {
182 return new Response(readFileSync(paths.ALLOWED_SIGNERS_PATH), {
183 headers: { "Content-Type": "text/plain; charset=utf-8" },
184 });
185 })
186 .guard({
187 cookie: t.Cookie({
188 session: t.Optional(t.String()),
189 repo_sort: t.Optional(t.String()),
190 }),
191 })
192 .post(
193 "/sort",
194 ({ body }) => {
195 const sort = body.sort === "name" ? "name" : "created";
196 const secure = config.PUBLIC_HTTPS ? "; Secure" : "";
197 return redirect(
198 "/",
199 `repo_sort=${sort}; Path=/; SameSite=Lax${secure}; Max-Age=${YEAR_SECONDS}`,
200 );
201 },
202 { body: t.Object({ sort: t.String() }) },
203 )
204 .get(
205 "/",
206 async ({ cookie, query }) => {
207 const user = await resolveSession(cookie.session.value);
208 const search = query.q?.trim() || undefined;
209 const page = Math.max(1, query.page ?? 1);
210 const sort = cookie.repo_sort.value === "name" ? "name" : "created";
211
212 const isAdmin = user?.isAdmin ?? false;
213
214 const searchPattern = search
215 ? `%${search.replace(/[\\%_]/g, "\\$&")}%`
216 : undefined;
217
218 const countResult = await db
219 .selectFrom("repositories")
220 .select(db.fn.countAll<number>().as("count"))
221 .where((eb) =>
222 isAdmin
223 ? eb.or([
224 eb("is_private", "=", 0),
225 eb("is_private", "=", 1),
226 ])
227 : eb("is_private", "=", 0),
228 )
229 .$if(!!searchPattern, (qb) =>
230 qb.where(
231 sql<boolean>`("name" LIKE ${searchPattern} ESCAPE '\\' OR "description" LIKE ${searchPattern} ESCAPE '\\')`,
232 ),
233 )
234 .executeTakeFirst();
235
236 const totalCount = Number(countResult?.count ?? 0);
237 const totalPages = Math.max(
238 1,
239 Math.ceil(totalCount / REPOS_PER_PAGE),
240 );
241 const safePage = Math.min(page, totalPages);
242
243 const repos = await db
244 .selectFrom("repositories")
245 .selectAll()
246 .where((eb) =>
247 isAdmin
248 ? eb.or([
249 eb("is_private", "=", 0),
250 eb("is_private", "=", 1),
251 ])
252 : eb("is_private", "=", 0),
253 )
254 .$if(!!searchPattern, (qb) =>
255 qb.where(
256 sql<boolean>`("name" LIKE ${searchPattern} ESCAPE '\\' OR "description" LIKE ${searchPattern} ESCAPE '\\')`,
257 ),
258 )
259 .orderBy("is_pinned", "desc")
260 .$if(sort === "name", (qb) => qb.orderBy("name", "asc"))
261 .$if(sort === "created", (qb) =>
262 qb.orderBy("created_at", "desc"),
263 )
264 .limit(REPOS_PER_PAGE)
265 .offset((safePage - 1) * REPOS_PER_PAGE)
266 .execute();
267
268 const searchParam = search
269 ? `&q=${encodeURIComponent(search)}`
270 : "";
271 const pagination = {
272 page: safePage,
273 totalPages,
274 pageUrlTemplate: `/?page={page}${searchParam}`,
275 };
276
277 return html(
278 <RepoList
279 user={user}
280 repos={repos}
281 search={search}
282 sort={sort}
283 pagination={pagination}
284 />,
285 );
286 },
287 {
288 query: t.Object({
289 q: t.Optional(t.String()),
290 page: t.Optional(t.Numeric()),
291 }),
292 },
293 )
294
295 .get("/new", async ({ cookie }) => {
296 const user = await resolveSession(cookie.session.value);
297 const deny = requireAdmin(user);
298 if (deny) return deny;
299 return html(<NewRepo user={user!} />);
300 })
301
302 .post(
303 "/new",
304 async ({ body, cookie }) => {
305 const user = await resolveSession(cookie.session.value);
306 const deny = requireAdmin(user);
307 if (deny) return deny;
308
309 const { name, description, is_private, default_branch } = body;
310
311 if (!VALID_REPO_NAME_RE.test(name)) {
312 return html(
313 <NewRepo user={user!} error="Invalid repository name" />,
314 );
315 }
316
317 const branch = (default_branch?.trim() || "main").replace(
318 /[^a-zA-Z0-9._/-]/g,
319 "",
320 );
321
322 const existing = await db
323 .selectFrom("repositories")
324 .select("id")
325 .where("name", "=", name)
326 .executeTakeFirst();
327 if (existing) {
328 return html(
329 <NewRepo
330 user={user!}
331 error="Repository name already taken"
332 />,
333 );
334 }
335
336 const now = new Date().toISOString();
337 await db
338 .insertInto("repositories")
339 .values({
340 name,
341 description: description || null,
342 is_private: is_private === "1" ? 1 : 0,
343 default_branch: branch,
344 created_at: now,
345 })
346 .execute();
347
348 // Initialise the git repo after the DB record is committed. If
349 // git.init fails we roll back the DB record so the two stay in sync.
350 try {
351 await git.init(name, branch);
352 } catch (err) {
353 await db
354 .deleteFrom("repositories")
355 .where("name", "=", name)
356 .execute();
357 throw err;
358 }
359 return new Response(null, {
360 status: 302,
361 headers: { Location: `/${name}` },
362 });
363 },
364 {
365 body: t.Object({
366 name: t.String(),
367 description: t.Optional(t.String()),
368 is_private: t.Optional(t.String()),
369 default_branch: t.Optional(t.String()),
370 }),
371 },
372 )
373
374 .get("/:repo", async ({ params, cookie }) => {
375 const user = await resolveSession(cookie.session.value);
376 const repo = await getRepo(params.repo, user?.isAdmin ?? false);
377 if (!repo) return new Response("Not found", { status: 404 });
378
379 const hasContent = await git.hasCommits(repo.name);
380 let readmeHtml: string | null = null;
381 let readmePath: string | undefined;
382 let entries: Awaited<ReturnType<typeof git.lsTree>> = [];
383 let branches: string[] = [];
384 let tags: string[] = [];
385
386 if (hasContent) {
387 const [lsResult, branchResult, tagResult, resolved] =
388 await Promise.all([
389 git.lsTree(repo.name, repo.default_branch),
390 git.branches(repo.name),
391 git.tags(repo.name),
392 git.resolveRef(repo.name, repo.default_branch),
393 ]);
394 entries = lsResult;
395 branches = branchResult;
396 tags = tagResult;
397 const readme = await readReadme(
398 repo.name,
399 repo.default_branch,
400 "",
401 lsResult,
402 );
403 if (readme) {
404 const key = resolved
405 ? `readme:${repo.name}:${resolved}:`
406 : undefined;
407 readmeHtml = renderMarkdown(
408 readme.content.toString("utf-8"),
409 key,
410 {
411 repo: repo.name,
412 ref: repo.default_branch,
413 dir: "",
414 },
415 );
416 readmePath = readme.filename;
417 }
418 }
419
420 return html(
421 <RepoHome
422 user={user}
423 repo={repo}
424 entries={entries}
425 readmeHtml={readmeHtml}
426 readmePath={readmePath}
427 hasContent={hasContent}
428 branches={branches}
429 tags={tags}
430 />,
431 );
432 })
433
434 .get(
435 "/:repo/branch-switch",
436 async ({ params, query, cookie }) => {
437 const user = await resolveSession(cookie.session.value);
438 const repo = await getRepo(params.repo, user?.isAdmin ?? false);
439 if (!repo) return new Response("Not found", { status: 404 });
440
441 const ref = query.rev?.trim();
442 if (!ref)
443 return new Response(null, {
444 status: 302,
445 headers: { Location: `/${repo.name}` },
446 });
447
448 const view = query.view;
449 const subpath = query.path ?? "";
450
451 if (view === "commits") {
452 return new Response(null, {
453 status: 302,
454 headers: { Location: `/${repo.name}/commits/${ref}` },
455 });
456 }
457 if (view === "blob" && subpath) {
458 return new Response(null, {
459 status: 302,
460 headers: {
461 Location: `/${repo.name}/blob/${ref}/${subpath}`,
462 },
463 });
464 }
465 const location = subpath
466 ? `/${repo.name}/tree/${ref}/${subpath}`
467 : `/${repo.name}/tree/${ref}`;
468 return new Response(null, {
469 status: 302,
470 headers: { Location: location },
471 });
472 },
473 {
474 query: t.Object({
475 rev: t.Optional(t.String()),
476 view: t.Optional(t.String()),
477 path: t.Optional(t.String()),
478 }),
479 },
480 )
481
482 .get("/:repo/tree/:ref", async ({ params, cookie }) => {
483 const user = await resolveSession(cookie.session.value);
484 const repo = await getRepo(params.repo, user?.isAdmin ?? false);
485 if (!repo) return new Response("Not found", { status: 404 });
486
487 const resolved = await git.resolveRef(repo.name, params.ref);
488 if (!resolved) return new Response("Not found", { status: 404 });
489
490 const [entries, branches, tags] = await Promise.all([
491 git.lsTree(repo.name, params.ref),
492 git.branches(repo.name),
493 git.tags(repo.name),
494 ]);
495 const readme = await readReadme(repo.name, params.ref, "", entries);
496 const readmeHtml = readme
497 ? renderMarkdown(
498 readme.content.toString("utf-8"),
499 `readme:${repo.name}:${resolved}:`,
500 { repo: repo.name, ref: params.ref, dir: "" },
501 )
502 : null;
503 return html(
504 <FileTree
505 user={user}
506 repo={repo}
507 ref={params.ref}
508 subpath=""
509 entries={entries}
510 branches={branches}
511 tags={tags}
512 readmeHtml={readmeHtml}
513 readmePath={readme?.filename}
514 />,
515 );
516 })
517
518 .get("/:repo/tree/:ref/*", async ({ params, cookie }) => {
519 const user = await resolveSession(cookie.session.value);
520 const repo = await getRepo(params.repo, user?.isAdmin ?? false);
521 if (!repo) return new Response("Not found", { status: 404 });
522
523 const resolved = await git.resolveRef(repo.name, params.ref);
524 if (!resolved) return new Response("Not found", { status: 404 });
525
526 const subpath = decodeURIComponent(params["*"]);
527 const [entries, branches, tags] = await Promise.all([
528 git.lsTree(repo.name, params.ref, subpath),
529 git.branches(repo.name),
530 git.tags(repo.name),
531 ]);
532 if (entries.length === 0) {
533 // Could be a file — redirect to blob
534 return new Response(null, {
535 status: 302,
536 headers: {
537 Location: `/${repo.name}/blob/${params.ref}/${subpath}`,
538 },
539 });
540 }
541 const readme = await readReadme(
542 repo.name,
543 params.ref,
544 subpath,
545 entries,
546 );
547 const readmeHtml = readme
548 ? renderMarkdown(
549 readme.content.toString("utf-8"),
550 `readme:${repo.name}:${resolved}:${subpath}`,
551 { repo: repo.name, ref: params.ref, dir: subpath },
552 )
553 : null;
554 return html(
555 <FileTree
556 user={user}
557 repo={repo}
558 ref={params.ref}
559 subpath={subpath}
560 entries={entries}
561 branches={branches}
562 tags={tags}
563 readmeHtml={readmeHtml}
564 readmePath={readme?.filename}
565 />,
566 );
567 })
568
569 .get("/:repo/blob/:ref/*", async ({ params, cookie }) => {
570 const user = await resolveSession(cookie.session.value);
571 const repo = await getRepo(params.repo, user?.isAdmin ?? false);
572 if (!repo) return new Response("Not found", { status: 404 });
573
574 const filePath = decodeURIComponent(params["*"]);
575 // Size-gate before reading the blob into memory: holding a
576 // huge content buffer (and then running shiki/marked over it)
577 // is the cheapest DOS vector against unauthenticated users on
578 // a public repo.
579 const size = await git.getFileSize(repo.name, params.ref, filePath);
580 const filename = path.basename(filePath);
581 if (size !== null && size > config.MAX_RENDER_BYTES) {
582 const [branches, tags] = await Promise.all([
583 git.branches(repo.name),
584 git.tags(repo.name),
585 ]);
586 return html(
587 <FileBlob
588 user={user}
589 repo={repo}
590 ref={params.ref}
591 filePath={filePath}
592 view={{ type: "download", size }}
593 branches={branches}
594 tags={tags}
595 markdownHtml={undefined}
596 />,
597 );
598 }
599 const [content, branches, tags, commitSHA] = await Promise.all([
600 git.show(repo.name, params.ref, filePath),
601 git.branches(repo.name),
602 git.tags(repo.name),
603 git.resolveRef(repo.name, params.ref),
604 ]);
605 if (!content || !commitSHA)
606 return new Response("Not found", { status: 404 });
607
608 const [view, markdownHtml] = await Promise.all([
609 serveFile(
610 content,
611 filename,
612 `${repo.name}:${commitSHA}:${filePath}`,
613 ),
614 /\.mdx?$/i.test(filename)
615 ? Promise.resolve(
616 renderMarkdown(
617 content.toString("utf-8"),
618 `${repo.name}:${commitSHA}:${filePath}`,
619 {
620 repo: repo.name,
621 ref: params.ref,
622 dir:
623 path.dirname(filePath) === "."
624 ? ""
625 : path.dirname(filePath),
626 },
627 ),
628 )
629 : Promise.resolve(undefined),
630 ]);
631 return html(
632 <FileBlob
633 user={user}
634 repo={repo}
635 ref={params.ref}
636 filePath={filePath}
637 view={view}
638 branches={branches}
639 tags={tags}
640 markdownHtml={markdownHtml}
641 />,
642 );
643 })
644
645 .get("/:repo/raw/:ref/*", async ({ params, cookie, request }) => {
646 const user = await resolveSession(cookie.session.value);
647 const repo = await getRepo(params.repo, user?.isAdmin ?? false);
648 if (!repo) return new Response("Not found", { status: 404 });
649
650 const filePath = decodeURIComponent(params["*"]);
651 // Resolve the file's blob hash and size up front. cat-file -s
652 // is O(1) and lets us stream the blob below without ever
653 // holding it whole in memory — old code did
654 // `await arrayBuffer()` and sliced for Range, peaking at
655 // file_size × concurrent_requests of RSS.
656 const total = await git.getFileSize(repo.name, params.ref, filePath);
657 if (total === null) return new Response("Not found", { status: 404 });
658 if (
659 config.MAX_RAW_DOWNLOAD_BYTES > 0 &&
660 total > config.MAX_RAW_DOWNLOAD_BYTES
661 ) {
662 return new Response("File exceeds raw download size limit", {
663 status: 413,
664 });
665 }
666
667 const filename = path.basename(filePath);
668 // We use `cat-file blob` rather than `git show` so the bytes
669 // streamed exactly match what `cat-file -s` reported above —
670 // `git show` can apply smudge filters / autocrlf, which would
671 // make Content-Length wrong on filtered repos.
672 const blobArgs = [
673 "git",
674 "-C",
675 repoPath(repo.name),
676 "cat-file",
677 "blob",
678 `${params.ref}:${filePath}`,
679 ];
680
681 // Sniff content-type from the first bytes only — same idea as
682 // the old mimeForContent but without buffering the full blob.
683 const sniffStream = Bun.spawn(blobArgs, {
684 stdout: "pipe",
685 stderr: "ignore",
686 });
687 const sniffReader = sniffStream.stdout.getReader();
688 const { value: firstChunk } = await sniffReader.read();
689 sniffReader.cancel().catch(() => {});
690 sniffStream.kill();
691 const head = firstChunk
692 ? Buffer.from(firstChunk.subarray(0, BINARY_DETECT_BYTES))
693 : Buffer.alloc(0);
694 const contentType = await mimeForContent(filename, head);
695
696 const rangeHeader = request.headers.get("Range");
697 const fullProc = Bun.spawn(blobArgs, {
698 stdout: "pipe",
699 stderr: "ignore",
700 });
701 if (rangeHeader) {
702 const match = rangeHeader.match(/bytes=(\d*)-(\d*)/);
703 if (match) {
704 const start = match[1] ? parseInt(match[1], 10) : 0;
705 const end = match[2] ? parseInt(match[2], 10) : total - 1;
706 const clampedEnd = Math.min(end, total - 1);
707 const length = clampedEnd - start + 1;
708 // sliceStream kills fullProc once the slice is exhausted or
709 // the consumer cancels — without this, requesting a tiny
710 // range from a huge blob leaves `git cat-file` running.
711 const sliced = sliceStream(fullProc.stdout, start, length, () =>
712 fullProc.kill(),
713 );
714 return new Response(sliced, {
715 status: 206,
716 headers: {
717 "Content-Type": contentType,
718 "Content-Range": `bytes ${start}-${clampedEnd}/${total}`,
719 "Accept-Ranges": "bytes",
720 "Content-Length": String(length),
721 },
722 });
723 }
724 }
725
726 // Wrap the full stream too so a client disconnect during a large
727 // download kills the underlying git process instead of leaving it
728 // wedged on a back-pressured pipe.
729 return new Response(streamWithKill(fullProc.stdout, fullProc), {
730 headers: {
731 "Content-Type": contentType,
732 "Content-Disposition": contentDisposition("inline", filename),
733 "Content-Length": String(total),
734 "Accept-Ranges": "bytes",
735 },
736 });
737 })
738
739 .get("/:repo/edit/:ref/*", async ({ params, query, cookie }) => {
740 const user = await resolveSession(cookie.session.value);
741 const deny = requireAdmin(user);
742 if (deny) return deny;
743 const repo = await getRepo(params.repo, true);
744 if (!repo) return new Response("Not found", { status: 404 });
745
746 const filePath = decodeURIComponent(params["*"]);
747 const branches = await git.branches(repo.name);
748 if (!branches.includes(params.ref))
749 return new Response("Not found", { status: 404 });
750
751 const content = await git.show(repo.name, params.ref, filePath);
752 if (!content) return new Response("Not found", { status: 404 });
753
754 if (hasBinaryContent(content.subarray(0, 8000)))
755 return new Response("Not found", { status: 404 });
756
757 const queryError =
758 typeof query.error === "string" ? query.error : undefined;
759 return html(
760 <FileEdit
761 user={user!}
762 repo={repo}
763 ref={params.ref}
764 filePath={filePath}
765 content={content.toString("utf-8")}
766 queryError={queryError}
767 />,
768 );
769 })
770
771 .post(
772 "/:repo/edit/:ref/*",
773 async ({ params, body, cookie }) => {
774 const user = await resolveSession(cookie.session.value);
775 const deny = requireAdmin(user);
776 if (deny) return deny;
777 const repo = await getRepo(params.repo, true);
778 if (!repo) return new Response("Not found", { status: 404 });
779
780 const filePath = decodeURIComponent(params["*"]);
781 const branches = await git.branches(repo.name);
782 if (!branches.includes(params.ref))
783 return new Response("Not found", { status: 404 });
784
785 const newPath = body.new_path?.trim() || undefined;
786 const targetPath =
787 newPath && newPath !== filePath ? newPath : filePath;
788
789 if (
790 newPath &&
791 newPath !== filePath &&
792 (newPath.startsWith("/") ||
793 newPath.includes("..") ||
794 newPath.includes("\0"))
795 ) {
796 return redirect(
797 `/${repo.name}/edit/${params.ref}/${filePath}?error=${encodeURIComponent("Invalid file path.")}`,
798 );
799 }
800
801 const defaultMessage =
802 targetPath !== filePath
803 ? `Rename ${path.basename(filePath)} to ${path.basename(targetPath)}`
804 : `Edited ${path.basename(filePath)}`;
805 const message = body.message?.trim() || defaultMessage;
806 const content = (body.content ?? "").replaceAll("\r\n", "\n");
807
808 const commit = await git.editFile(
809 repo.name,
810 params.ref,
811 filePath,
812 content,
813 message,
814 config.COMMITTER_NAME,
815 config.COMMITTER_EMAIL,
816 newPath,
817 );
818
819 return new Response(null, {
820 status: 302,
821 headers: {
822 Location: `/${repo.name}/commit/${commit}`,
823 },
824 });
825 },
826 {
827 body: t.Object({
828 content: t.Optional(t.String()),
829 message: t.Optional(t.String()),
830 new_path: t.Optional(t.String()),
831 }),
832 },
833 )
834
835 .get(
836 "/:repo/commits/:ref",
837 async ({ params, cookie, query }) => {
838 const user = await resolveSession(cookie.session.value);
839 const repo = await getRepo(params.repo, user?.isAdmin ?? false);
840 if (!repo) return new Response("Not found", { status: 404 });
841
842 // Cursor-based pagination — O(1) regardless of history depth.
843 // `after` = SHA of the last commit on the previous page (resume cursor).
844 // `prev` = the `after` value used on the page that linked here, so we can
845 // reconstruct a "← Newer" link without a full history traversal.
846 const after = query.after?.trim() || null;
847 const prev = query.prev?.trim() || null;
848
849 const [rawCommits, branches, tags] = await Promise.all([
850 // When `after` is set: start at that SHA and skip it (--skip=1 is O(1)),
851 // then fetch LIMIT+1 to detect whether another page exists.
852 after
853 ? git.log(repo.name, after, COMMITS_PER_PAGE + 1, 1)
854 : git.log(repo.name, params.ref, COMMITS_PER_PAGE + 1, 0),
855 git.branches(repo.name),
856 git.tags(repo.name),
857 ]);
858
859 const hasNext = rawCommits.length > COMMITS_PER_PAGE;
860 const commits = rawCommits.slice(0, COMMITS_PER_PAGE);
861
862 // Build cursor URLs.
863 // "Older" advances past the last commit on this page.
864 // "Newer" goes back one page using the `prev` cursor saved in the URL,
865 // or to the first page if we're on page 2.
866 const base = `/${repo.name}/commits/${params.ref}`;
867 const olderUrl = hasNext
868 ? `${base}?after=${commits[commits.length - 1]?.hash}&prev=${after ?? ""}`
869 : null;
870 const newerUrl = after
871 ? prev
872 ? `${base}?after=${prev}`
873 : base
874 : null;
875
876 return html(
877 <CommitLog
878 user={user}
879 repo={repo}
880 ref={params.ref}
881 commits={commits}
882 branches={branches}
883 tags={tags}
884 olderUrl={olderUrl}
885 newerUrl={newerUrl}
886 />,
887 );
888 },
889 {
890 query: t.Object({
891 after: t.Optional(t.String()),
892 prev: t.Optional(t.String()),
893 }),
894 },
895 )
896
897 .get("/:repo/commit/:sha", async ({ params, cookie }) => {
898 const user = await resolveSession(cookie.session.value);
899 const repo = await getRepo(params.repo, user?.isAdmin ?? false);
900 if (!repo) return new Response("Not found", { status: 404 });
901
902 const [meta, rawDiff] = await Promise.all([
903 git.commitMeta(repo.name, params.sha),
904 git.diff(repo.name, params.sha),
905 ]);
906 if (!meta) return new Response("Commit not found", { status: 404 });
907 // Reject oversized diffs after generation but before highlighting.
908 // Avoids running marked / shiki / DOMPurify over a multi-megabyte
909 // diff which would synchronously stall the worker pool.
910 if (rawDiff.length > config.MAX_RENDER_BYTES) {
911 return html(
912 <CommitDetail
913 user={user}
914 repo={repo}
915 sha={params.sha}
916 meta={meta}
917 files={[]}
918 tooLarge={rawDiff.length}
919 />,
920 );
921 }
922 const files = await prepareDiff(
923 rawDiff,
924 `commit:${repo.name}:${params.sha}`,
925 repo.name,
926 );
927 return html(
928 <CommitDetail
929 user={user}
930 repo={repo}
931 sha={params.sha}
932 meta={meta}
933 files={files}
934 />,
935 );
936 })
937
938 .get("/:repo/settings", async ({ params, query, cookie }) => {
939 const user = await resolveSession(cookie.session.value);
940 const deny = requireAdmin(user);
941 if (deny) return deny;
942 const repo = await getRepo(params.repo, true);
943 if (!repo) return new Response("Not found", { status: 404 });
944 const branches = await git.branches(repo.name);
945 const [labels, secrets] = await Promise.all([
946 db
947 .selectFrom("labels")
948 .selectAll()
949 .where("repo_id", "=", repo.id)
950 .orderBy("name", "asc")
951 .execute(),
952 db
953 .selectFrom("ci_secrets")
954 .select(["id", "name", "description", "created_at"])
955 .where("repo_id", "=", repo.id)
956 .orderBy("name", "asc")
957 .execute(),
958 ]);
959 const success =
960 typeof query.success === "string" ? query.success : undefined;
961 const error = typeof query.error === "string" ? query.error : undefined;
962 return html(
963 <RepoSettings
964 user={user!}
965 repo={repo}
966 branches={branches}
967 labels={labels}
968 secrets={secrets}
969 success={success}
970 error={error}
971 />,
972 );
973 })
974
975 .post(
976 "/:repo/settings",
977 async ({ params, body, cookie }) => {
978 const user = await resolveSession(cookie.session.value);
979 const deny = requireAdmin(user);
980 if (deny) return deny;
981 const repo = await getRepo(params.repo, true);
982 if (!repo) return new Response("Not found", { status: 404 });
983
984 const {
985 description,
986 is_private,
987 is_pinned,
988 allow_user_labels,
989 default_branch,
990 issue_template,
991 patch_template,
992 } = body;
993
994 const branches = await git.branches(repo.name);
995 const newBranch = default_branch?.trim() || repo.default_branch;
996
997 // Validate the selected branch exists (only if repo has commits)
998 if (branches.length > 0 && !branches.includes(newBranch)) {
999 return redirect(
1000 `/${repo.name}/settings?error=${encodeURIComponent(`Branch "${newBranch}" does not exist.`)}`,
1001 );
1002 }
1003
1004 await db
1005 .updateTable("repositories")
1006 .set({
1007 description: description?.trim() || null,
1008 is_private: is_private === "1" ? 1 : 0,
1009 is_pinned: is_pinned === "1" ? 1 : 0,
1010 allow_user_labels: allow_user_labels === "1" ? 1 : 0,
1011 default_branch: newBranch,
1012 issue_template: issue_template?.trim() || null,
1013 patch_template: patch_template?.trim() || null,
1014 })
1015 .where("id", "=", repo.id)
1016 .execute();
1017
1018 // Keep git HEAD in sync if the branch actually exists
1019 if (branches.includes(newBranch)) {
1020 await git
1021 .setHead(repo.name, newBranch)
1022 .catch((e) =>
1023 console.error(
1024 `setHead failed for ${repo.name}/${newBranch}:`,
1025 e,
1026 ),
1027 );
1028 }
1029
1030 return redirect(`/${repo.name}/settings?success=Settings+saved.`);
1031 },
1032 {
1033 body: t.Object({
1034 description: t.Optional(t.String()),
1035 is_private: t.Optional(t.String()),
1036 is_pinned: t.Optional(t.String()),
1037 allow_user_labels: t.Optional(t.String()),
1038 default_branch: t.Optional(t.String()),
1039 issue_template: t.Optional(t.String()),
1040 patch_template: t.Optional(t.String()),
1041 }),
1042 },
1043 )
1044
1045 .post("/:repo/settings/delete", async ({ params, cookie }) => {
1046 const user = await resolveSession(cookie.session.value);
1047 const deny = requireAdmin(user);
1048 if (deny) return deny;
1049 const repo = await getRepo(params.repo, true);
1050 if (!repo) return new Response("Not found", { status: 404 });
1051
1052 // Remove the on-disk repo first. If this fails (e.g. permission error),
1053 // we abort before touching the DB so the repo remains accessible.
1054 rmSync(repoPath(repo.name), { recursive: true, force: true });
1055 await db.deleteFrom("repositories").where("id", "=", repo.id).execute();
1056
1057 return new Response(null, { status: 302, headers: { Location: "/" } });
1058 })
1059
1060 .post(
1061 "/:repo/settings/labels",
1062 async ({ params, body, cookie }) => {
1063 const user = await resolveSession(cookie.session.value);
1064 const deny = requireAdmin(user);
1065 if (deny) return deny;
1066 const repo = await getRepo(params.repo, true);
1067 if (!repo) return new Response("Not found", { status: 404 });
1068
1069 const name = body.name?.trim();
1070 const color = body.color?.trim();
1071
1072 if (!name || name.length > MAX_LABEL_NAME_LENGTH) {
1073 return redirect(
1074 `/${repo.name}/settings?error=${encodeURIComponent("Label name must be 1–50 characters.")}`,
1075 );
1076 }
1077 if (!color || !/^#[0-9a-fA-F]{6}$/.test(color)) {
1078 return redirect(
1079 `/${repo.name}/settings?error=${encodeURIComponent("Invalid color.")}`,
1080 );
1081 }
1082
1083 try {
1084 await db
1085 .insertInto("labels")
1086 .values({
1087 repo_id: repo.id,
1088 name,
1089 color,
1090 created_at: new Date().toISOString(),
1091 })
1092 .execute();
1093 } catch {
1094 return redirect(
1095 `/${repo.name}/settings?error=${encodeURIComponent("A label with that name already exists.")}`,
1096 );
1097 }
1098
1099 return redirect(`/${repo.name}/settings?success=Label+created.`);
1100 },
1101 {
1102 body: t.Object({
1103 name: t.String(),
1104 color: t.String(),
1105 }),
1106 },
1107 )
1108
1109 .post(
1110 "/:repo/settings/labels/delete",
1111 async ({ params, body, cookie }) => {
1112 const user = await resolveSession(cookie.session.value);
1113 const deny = requireAdmin(user);
1114 if (deny) return deny;
1115 const repo = await getRepo(params.repo, true);
1116 if (!repo) return new Response("Not found", { status: 404 });
1117
1118 const label = await db
1119 .selectFrom("labels")
1120 .select(["id", "repo_id"])
1121 .where("id", "=", body.id)
1122 .executeTakeFirst();
1123
1124 if (!label || label.repo_id !== repo.id) {
1125 return redirect(
1126 `/${repo.name}/settings?error=${encodeURIComponent("Label not found.")}`,
1127 );
1128 }
1129
1130 await db.deleteFrom("labels").where("id", "=", body.id).execute();
1131
1132 return redirect(`/${repo.name}/settings?success=Label+deleted.`);
1133 },
1134 {
1135 body: t.Object({ id: t.Numeric() }),
1136 },
1137 )
1138
1139 // ── Branches ──────────────────────────────────────────────────────────────
1140
1141 .get("/:repo/branches", async ({ params, query, cookie }) => {
1142 const user = await resolveSession(cookie.session.value);
1143 const repo = await getRepo(params.repo, user?.isAdmin ?? false);
1144 if (!repo) return new Response("Not found", { status: 404 });
1145 const allBranches = await git.branchesWithInfo(repo.name);
1146 const page = Math.max(1, parseInt(String(query.page ?? "1"), 10) || 1);
1147 const totalPages = Math.max(
1148 1,
1149 Math.ceil(allBranches.length / BRANCHES_PER_PAGE),
1150 );
1151 const safePage = Math.min(page, totalPages);
1152 const branches = allBranches.slice(
1153 (safePage - 1) * BRANCHES_PER_PAGE,
1154 safePage * BRANCHES_PER_PAGE,
1155 );
1156 const success =
1157 typeof query.success === "string" ? query.success : undefined;
1158 const error = typeof query.error === "string" ? query.error : undefined;
1159 return html(
1160 <BranchList
1161 user={user}
1162 repo={repo}
1163 branches={branches}
1164 page={safePage}
1165 totalPages={totalPages}
1166 success={success}
1167 error={error}
1168 />,
1169 );
1170 })
1171
1172 .post(
1173 "/:repo/branches/create",
1174 async ({ params, body, cookie }) => {
1175 const user = await resolveSession(cookie.session.value);
1176 const deny = requireAdmin(user);
1177 if (deny) return deny;
1178 const repo = await getRepo(params.repo, true);
1179 if (!repo) return new Response("Not found", { status: 404 });
1180
1181 const name = body.name?.trim() ?? "";
1182 const sourceRef = body.source_ref?.trim() ?? "";
1183
1184 if (
1185 !name ||
1186 !/^[a-zA-Z0-9._][a-zA-Z0-9._\-/]*$/.test(name) ||
1187 name.includes("..") ||
1188 name.length > MAX_BRANCH_NAME_LENGTH
1189 ) {
1190 return redirect(
1191 `/${repo.name}/branches?error=${encodeURIComponent("Invalid branch name.")}`,
1192 );
1193 }
1194 if (!sourceRef) {
1195 return redirect(
1196 `/${repo.name}/branches?error=${encodeURIComponent("Source ref is required.")}`,
1197 );
1198 }
1199
1200 const result = await git.createBranch(repo.name, name, sourceRef);
1201 if (result === "ok") {
1202 return redirect(
1203 `/${repo.name}/branches?success=${encodeURIComponent(`Branch "${name}" created.`)}`,
1204 );
1205 }
1206 if (result === "already_exists") {
1207 return redirect(
1208 `/${repo.name}/branches?error=${encodeURIComponent(`Branch "${name}" already exists.`)}`,
1209 );
1210 }
1211 if (result === "bad_ref") {
1212 return redirect(
1213 `/${repo.name}/branches?error=${encodeURIComponent(`"${sourceRef}" is not a valid ref.`)}`,
1214 );
1215 }
1216 return redirect(
1217 `/${repo.name}/branches?error=${encodeURIComponent("Failed to create branch.")}`,
1218 );
1219 },
1220 {
1221 body: t.Object({
1222 name: t.String(),
1223 source_ref: t.String(),
1224 }),
1225 },
1226 )
1227
1228 .post(
1229 "/:repo/branches/delete",
1230 async ({ params, body, cookie }) => {
1231 const user = await resolveSession(cookie.session.value);
1232 const deny = requireAdmin(user);
1233 if (deny) return deny;
1234 const repo = await getRepo(params.repo, true);
1235 if (!repo) return new Response("Not found", { status: 404 });
1236
1237 const name = body.name?.trim() ?? "";
1238 if (!name) {
1239 return redirect(
1240 `/${repo.name}/branches?error=${encodeURIComponent("Branch name is required.")}`,
1241 );
1242 }
1243 if (name === repo.default_branch) {
1244 return redirect(
1245 `/${repo.name}/branches?error=${encodeURIComponent("Cannot delete the default branch.")}`,
1246 );
1247 }
1248
1249 const result = await git.deleteBranch(repo.name, name);
1250 if (result === "ok") {
1251 return redirect(
1252 `/${repo.name}/branches?success=${encodeURIComponent(`Branch "${name}" deleted.`)}`,
1253 );
1254 }
1255 if (result === "not_found") {
1256 return redirect(
1257 `/${repo.name}/branches?error=${encodeURIComponent(`Branch "${name}" not found.`)}`,
1258 );
1259 }
1260 return redirect(
1261 `/${repo.name}/branches?error=${encodeURIComponent("Failed to delete branch.")}`,
1262 );
1263 },
1264 {
1265 body: t.Object({ name: t.String() }),
1266 },
1267 )
1268
1269 .post(
1270 "/:repo/branches/rename",
1271 async ({ params, body, cookie }) => {
1272 const user = await resolveSession(cookie.session.value);
1273 const deny = requireAdmin(user);
1274 if (deny) return deny;
1275 const repo = await getRepo(params.repo, true);
1276 if (!repo) return new Response("Not found", { status: 404 });
1277
1278 const oldName = body.old_name?.trim() ?? "";
1279 const newName = body.new_name?.trim() ?? "";
1280
1281 if (
1282 !newName ||
1283 !/^[a-zA-Z0-9._][a-zA-Z0-9._\-/]*$/.test(newName) ||
1284 newName.includes("..") ||
1285 newName.length > MAX_BRANCH_NAME_LENGTH
1286 ) {
1287 return redirect(
1288 `/${repo.name}/branches?error=${encodeURIComponent("Invalid branch name.")}`,
1289 );
1290 }
1291
1292 const result = await git.renameBranch(repo.name, oldName, newName);
1293 if (result === "ok") {
1294 // Keep default_branch in DB in sync if we renamed it
1295 if (oldName === repo.default_branch) {
1296 await db
1297 .updateTable("repositories")
1298 .set({ default_branch: newName })
1299 .where("id", "=", repo.id)
1300 .execute();
1301 await git
1302 .setHead(repo.name, newName)
1303 .catch((e) =>
1304 console.error(
1305 `setHead failed for ${repo.name}/${newName}:`,
1306 e,
1307 ),
1308 );
1309 }
1310 return redirect(
1311 `/${repo.name}/branches?success=${encodeURIComponent(`Branch renamed to "${newName}".`)}`,
1312 );
1313 }
1314 if (result === "not_found") {
1315 return redirect(
1316 `/${repo.name}/branches?error=${encodeURIComponent(`Branch "${oldName}" not found.`)}`,
1317 );
1318 }
1319 if (result === "already_exists") {
1320 return redirect(
1321 `/${repo.name}/branches?error=${encodeURIComponent(`Branch "${newName}" already exists.`)}`,
1322 );
1323 }
1324 return redirect(
1325 `/${repo.name}/branches?error=${encodeURIComponent("Failed to rename branch.")}`,
1326 );
1327 },
1328 {
1329 body: t.Object({
1330 old_name: t.String(),
1331 new_name: t.String(),
1332 }),
1333 },
1334 )
1335
1336 // ── Tags ──────────────────────────────────────────────────────────────────
1337
1338 .get("/:repo/tags", async ({ params, query, cookie }) => {
1339 const user = await resolveSession(cookie.session.value);
1340 const repo = await getRepo(params.repo, user?.isAdmin ?? false);
1341 if (!repo) return new Response("Not found", { status: 404 });
1342 const [allTags, releases] = await Promise.all([
1343 git.tagsWithInfo(repo.name),
1344 db
1345 .selectFrom("releases")
1346 .select(["id", "tag_name"])
1347 .where("repo_id", "=", repo.id)
1348 .where("tag_name", "is not", null)
1349 .execute(),
1350 ]);
1351 const tagReleaseMap = new Map<string, number>();
1352 for (const r of releases) {
1353 if (r.tag_name) tagReleaseMap.set(r.tag_name, r.id);
1354 }
1355 const page = Math.max(1, parseInt(String(query.page ?? "1"), 10) || 1);
1356 const totalPages = Math.max(
1357 1,
1358 Math.ceil(allTags.length / TAGS_PER_PAGE),
1359 );
1360 const safePage = Math.min(page, totalPages);
1361 const tags = allTags.slice(
1362 (safePage - 1) * TAGS_PER_PAGE,
1363 safePage * TAGS_PER_PAGE,
1364 );
1365 const success =
1366 typeof query.success === "string" ? query.success : undefined;
1367 const error = typeof query.error === "string" ? query.error : undefined;
1368 return html(
1369 <TagList
1370 user={user}
1371 repo={repo}
1372 tags={tags}
1373 tagReleaseMap={tagReleaseMap}
1374 page={safePage}
1375 totalPages={totalPages}
1376 success={success}
1377 error={error}
1378 />,
1379 );
1380 })
1381
1382 .post(
1383 "/:repo/tags/create",
1384 async ({ params, body, cookie }) => {
1385 const user = await resolveSession(cookie.session.value);
1386 const deny = requireAdmin(user);
1387 if (deny) return deny;
1388 const repo = await getRepo(params.repo, true);
1389 if (!repo) return new Response("Not found", { status: 404 });
1390
1391 const tagName = body.name?.trim() ?? "";
1392 const ref = body.ref?.trim() ?? "";
1393 const message = body.message?.trim() || undefined;
1394
1395 if (!tagName || !/^[a-zA-Z0-9._\-+]+$/.test(tagName)) {
1396 return redirect(
1397 `/${repo.name}/tags?error=${encodeURIComponent("Invalid tag name.")}`,
1398 );
1399 }
1400 if (!ref) {
1401 return redirect(
1402 `/${repo.name}/tags?error=${encodeURIComponent("Target ref is required.")}`,
1403 );
1404 }
1405
1406 const result = await git.createTag(
1407 repo.name,
1408 tagName,
1409 ref,
1410 message,
1411 message ? config.COMMITTER_NAME : undefined,
1412 message ? config.COMMITTER_EMAIL : undefined,
1413 );
1414 if (result === "ok") {
1415 return redirect(
1416 `/${repo.name}/tags?success=${encodeURIComponent(`Tag "${tagName}" created.`)}`,
1417 );
1418 }
1419 if (result === "already_exists") {
1420 return redirect(
1421 `/${repo.name}/tags?error=${encodeURIComponent(`Tag "${tagName}" already exists.`)}`,
1422 );
1423 }
1424 if (result === "bad_ref") {
1425 return redirect(
1426 `/${repo.name}/tags?error=${encodeURIComponent(`"${ref}" is not a valid ref.`)}`,
1427 );
1428 }
1429 return redirect(
1430 `/${repo.name}/tags?error=${encodeURIComponent("Failed to create tag.")}`,
1431 );
1432 },
1433 {
1434 body: t.Object({
1435 name: t.String(),
1436 ref: t.String(),
1437 message: t.Optional(t.String()),
1438 }),
1439 },
1440 )
1441
1442 .post(
1443 "/:repo/tags/delete",
1444 async ({ params, body, cookie }) => {
1445 const user = await resolveSession(cookie.session.value);
1446 const deny = requireAdmin(user);
1447 if (deny) return deny;
1448 const repo = await getRepo(params.repo, true);
1449 if (!repo) return new Response("Not found", { status: 404 });
1450
1451 const tagName = body.name?.trim() ?? "";
1452 if (!tagName) {
1453 return redirect(
1454 `/${repo.name}/tags?error=${encodeURIComponent("Tag name is required.")}`,
1455 );
1456 }
1457
1458 const result = await git.deleteTag(repo.name, tagName);
1459 if (result === "ok") {
1460 return redirect(
1461 `/${repo.name}/tags?success=${encodeURIComponent(`Tag "${tagName}" deleted.`)}`,
1462 );
1463 }
1464 if (result === "not_found") {
1465 return redirect(
1466 `/${repo.name}/tags?error=${encodeURIComponent(`Tag "${tagName}" not found.`)}`,
1467 );
1468 }
1469 return redirect(
1470 `/${repo.name}/tags?error=${encodeURIComponent("Failed to delete tag.")}`,
1471 );
1472 },
1473 {
1474 body: t.Object({ name: t.String() }),
1475 },
1476 )
1477
1478 // ── File creation ─────────────────────────────────────────────────────────
1479
1480 .get("/:repo/new-file/:ref", async ({ params, query, cookie }) => {
1481 const user = await resolveSession(cookie.session.value);
1482 const deny = requireAdmin(user);
1483 if (deny) return deny;
1484 const repo = await getRepo(params.repo, true);
1485 if (!repo) return new Response("Not found", { status: 404 });
1486 const dir = typeof query.dir === "string" ? query.dir : "";
1487 const error = typeof query.error === "string" ? query.error : undefined;
1488 return html(
1489 <NewFileForm
1490 user={user!}
1491 repo={repo}
1492 ref={params.ref}
1493 dir={dir}
1494 error={error}
1495 />,
1496 );
1497 })
1498
1499 .post(
1500 "/:repo/new-file/:ref",
1501 async ({ params, body, cookie }) => {
1502 const user = await resolveSession(cookie.session.value);
1503 const deny = requireAdmin(user);
1504 if (deny) return deny;
1505 const repo = await getRepo(params.repo, true);
1506 if (!repo) return new Response("Not found", { status: 404 });
1507
1508 const filePath = body.path?.trim() ?? "";
1509 const content = body.content ?? "";
1510 const message = body.message?.trim() || `Add ${filePath}`;
1511
1512 if (
1513 !filePath ||
1514 filePath.startsWith("/") ||
1515 filePath.includes("..") ||
1516 filePath.includes("\0")
1517 ) {
1518 return redirect(
1519 `/${repo.name}/new-file/${params.ref}?error=${encodeURIComponent("Invalid file path.")}`,
1520 );
1521 }
1522
1523 // Ensure we're on a branch
1524 const branches = await git.branches(repo.name);
1525 if (branches.length > 0 && !branches.includes(params.ref)) {
1526 return redirect(
1527 `/${repo.name}/new-file/${params.ref}?error=${encodeURIComponent("Can only create files on a branch.")}`,
1528 );
1529 }
1530
1531 try {
1532 const commit = await git.createFile(
1533 repo.name,
1534 params.ref,
1535 filePath,
1536 content,
1537 message,
1538 config.COMMITTER_NAME,
1539 config.COMMITTER_EMAIL,
1540 );
1541 return redirect(`/${repo.name}/commit/${commit}`);
1542 } catch {
1543 return redirect(
1544 `/${repo.name}/new-file/${params.ref}?error=${encodeURIComponent("Failed to create file.")}`,
1545 );
1546 }
1547 },
1548 {
1549 body: t.Object({
1550 path: t.String(),
1551 content: t.Optional(t.String()),
1552 message: t.Optional(t.String()),
1553 }),
1554 },
1555 )
1556
1557 // ── File deletion ─────────────────────────────────────────────────────────
1558
1559 .post(
1560 "/:repo/delete-file/:ref/*",
1561 async ({ params, body, cookie }) => {
1562 const user = await resolveSession(cookie.session.value);
1563 const deny = requireAdmin(user);
1564 if (deny) return deny;
1565 const repo = await getRepo(params.repo, true);
1566 if (!repo) return new Response("Not found", { status: 404 });
1567
1568 const filePath = decodeURIComponent(params["*"]);
1569 const message = body.message?.trim() || `Delete ${filePath}`;
1570
1571 try {
1572 const commit = await git.deleteFile(
1573 repo.name,
1574 params.ref,
1575 filePath,
1576 message,
1577 config.COMMITTER_NAME,
1578 config.COMMITTER_EMAIL,
1579 );
1580 return redirect(`/${repo.name}/commit/${commit}`);
1581 } catch {
1582 return redirect(
1583 `/${repo.name}/blob/${params.ref}/${filePath}?error=${encodeURIComponent("Failed to delete file.")}`,
1584 );
1585 }
1586 },
1587 {
1588 body: t.Object({
1589 message: t.Optional(t.String()),
1590 }),
1591 },
1592 );
1593