33 lines · 1.6 KB
import { isAdminClaimableName, isReservedName } from "~/lib/reserved-names";

/** Account and repository path segments as the forge allows them; anything else is never a module path. */
const SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;

function escapeHtml(value: string): string {
  return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}

/**
 * `go get` discovery (`?go-get=1`): maps `<host>/<owner>/<repo>[/subpackage...]` to the repository's git URL with a
 * `go-import` meta tag. It answers the same way whether or not the repository exists or is private, so it never
 * reveals what is there; `go` then clones over HTTPS with the user's own credentials.
 */
export function handleGoGet(request: Request, url: URL): Response | null {
  if (url.searchParams.get("go-get") !== "1") return null;
  if (request.method !== "GET" && request.method !== "HEAD") return null;
  const [owner, rawRepo] = url.pathname.split("/").filter(Boolean);
  if (!owner || !rawRepo || (isReservedName(owner) && !isAdminClaimableName(owner))) return null;
  const repo = rawRepo.replace(/\.git$/, "");
  if (!SEGMENT.test(owner) || !SEGMENT.test(repo)) return null;
  const root = `${url.host}/${owner}/${repo}`;
  const web = `${url.origin}/${owner}/${repo}`;
  const body = `<!doctype html>
<html><head>
<meta name="go-import" content="${escapeHtml(`${root} git ${web}.git`)}">
</head><body>go get ${escapeHtml(root)}</body></html>
`;
  return new Response(request.method === "HEAD" ? null : body, {
    headers: { "content-type": "text/html; charset=utf-8", "cache-control": "public, max-age=300" },
  });
}