commit
aaa
diff --git a/.env.example b/.env.example
index e53e052..7c74ffb 100644
--- a/.env.example
+++ b/.env.example
@@ -66,7 +66,9 @@ MINIGIT_AUTO_CREATE=true
# to the repository listing.
#
# How many days a deleted repository stays recoverable. 0 keeps them forever.
-# Purging is lazy — it happens when you open the recovery page, never on a timer.
+# The server sweeps every owner's trash at startup and every six hours after,
+# and opening the recovery page also purges that owner's expired copies, so the
+# window is enforced whether or not anyone looks.
MINIGIT_TRASH_DAYS=30
# --- notifications and mirror status -----------------------------------------
diff --git a/package.json b/package.json
index 2e11426..6f36e1b 100644
--- a/package.json
+++ b/package.json
@@ -9,7 +9,7 @@
"start": "node --experimental-sqlite --disable-warning=ExperimentalWarning dist/server.js",
"dev": "npm run build && npm start",
"typecheck": "tsc --noEmit",
- "test": "node --experimental-strip-types test/urls.test.mjs && node --experimental-strip-types test/transport.test.mjs && node --experimental-strip-types test/markdown.test.mjs && node --experimental-strip-types test/icons.test.mjs && node --experimental-sqlite --disable-warning=ExperimentalWarning --experimental-strip-types test/ownership.test.mjs && node --experimental-sqlite --disable-warning=ExperimentalWarning --experimental-strip-types test/access.test.mjs && node --experimental-strip-types test/refs.test.mjs && node --experimental-sqlite --disable-warning=ExperimentalWarning --experimental-strip-types test/lifecycle.test.mjs && node --experimental-sqlite --disable-warning=ExperimentalWarning --experimental-strip-types test/mirror.test.mjs && node --experimental-sqlite --disable-warning=ExperimentalWarning --experimental-strip-types test/notify.test.mjs"
+ "test": "node --experimental-sqlite --disable-warning=ExperimentalWarning --experimental-strip-types --test test/*.test.mjs"
},
"dependencies": {
"@hono/node-server": "^2.1.1",
diff --git a/src/access.ts b/src/access.ts
index 215f222..bf8c0a1 100644
--- a/src/access.ts
+++ b/src/access.ts
@@ -25,6 +25,11 @@ db.exec(`
);
`);
+// The primary key answers "who may touch this repo", which is the question the
+// transport asks. sharedWith() asks the mirror image — "which repos may this
+// person touch" — on every repo listing, and that one needs its own index.
+db.exec("CREATE INDEX IF NOT EXISTS collaborators_slug ON collaborators (slug)");
+
export type Level = "read" | "write";
export type Access = "none" | "read" | "write";
diff --git a/src/git.ts b/src/git.ts
index ad0224a..3ca7c7c 100644
--- a/src/git.ts
+++ b/src/git.ts
@@ -49,6 +49,38 @@ function safeSegment(s: string): boolean {
return SEGMENT.test(s) && !s.startsWith(".") && !s.includes("..");
}
+// The "+" namespace.
+//
+// A leading "+" marks a name the forge owns rather than the user. It buys two
+// things at once: route segments like /:owner/+repos can never collide with a
+// real repository, and the profile repo cannot be created by accident or
+// squatted by someone typing a plausible name.
+//
+// Exactly one "+" name is a real repository — PROFILE_REPO, whose README is
+// rendered on its owner's profile page. Every other "+" name is refused
+// everywhere a name is accepted, so `git push` cannot conjure one and neither
+// can the create form. "+" is not allowed anywhere else in a name, which keeps
+// the prefix a namespace marker rather than a character.
+export const PROFILE_REPO = "+dough";
+
+// The owner-level repositories page lives at /<owner>/+repos. It is a route,
+// not a repository, and it is deliberately spelled with the reserved prefix:
+// safeName() refuses every "+" name but PROFILE_REPO, so no repository can ever
+// exist that would answer to this URL.
+export const PROFILE_REPOS_PATH = "+repos";
+
+const NAME_SEGMENT = /^[A-Za-z0-9._+-]+$/;
+
+function safeName(s: string): boolean {
+ if (!NAME_SEGMENT.test(s) || s.startsWith(".") || s.includes("..")) return false;
+ if (s.startsWith("+")) return s === PROFILE_REPO;
+ return !s.includes("+");
+}
+
+export function isProfileRepo(name: string): boolean {
+ return name === PROFILE_REPO;
+}
+
const OBJECT_ID = /^[0-9a-fA-F]{4,64}$/;
export function safeObjectId(sha: string): string | null {
@@ -57,7 +89,7 @@ export function safeObjectId(sha: string): string | null {
export function safeRef(owner: string, nameRaw: string): RepoRef | null {
const name = nameRaw.replace(/\.git$/, "");
- if (!safeSegment(owner) || !safeSegment(name)) return null;
+ if (!safeSegment(owner) || !safeName(name)) return null;
return { owner, name };
}
@@ -144,7 +176,7 @@ const TRASH_DIR = ".trash";
export const DELETED_META = "dough-deleted.json";
-const TRASH_ENTRY = /^[A-Za-z0-9._-]+\.\d+\.git$/;
+const TRASH_ENTRY = /^\+?[A-Za-z0-9._-]+\.\d+\.git$/;
export interface DeletedGrant {
slug: string;
@@ -184,6 +216,7 @@ function trashEntryDir(owner: string, entry: string): string | null {
return null;
}
if (!TRASH_ENTRY.test(entry)) return null;
+ if (!safeName(nameFromEntry(entry))) return null;
const root = resolve(trashRoot());
const full = resolve(join(root, owner, entry));
@@ -250,7 +283,7 @@ export async function listTrash(owner: string): Promise<TrashEntry[]> {
if (
parsed &&
typeof parsed.name === "string" &&
- safeSegment(parsed.name) &&
+ safeName(parsed.name) &&
parsed.owner === owner
) {
meta = parsed as DeletedMeta;
@@ -337,6 +370,30 @@ export async function purgeExpired(owner: string): Promise<TrashEntry[]> {
return purged;
}
+// Retention across every owner.
+//
+// purgeExpired() only sweeps the owner whose page is being rendered, which
+// makes MINIGIT_TRASH_DAYS a promise that is only kept for people who happen to
+// visit. This is the sweep the server runs on a timer so the retention window
+// means what it says.
+export async function purgeAllExpired(): Promise<TrashEntry[]> {
+ if (config.trashDays <= 0) return [];
+
+ let owners: string[];
+ try {
+ owners = await readdir(trashRoot());
+ } catch {
+ return [];
+ }
+
+ const purged: TrashEntry[] = [];
+ for (const owner of owners) {
+ if (!safeSegment(owner)) continue;
+ purged.push(...(await purgeExpired(owner)));
+ }
+ return purged;
+}
+
export async function isRepoPublic(ref: RepoRef): Promise<boolean> {
try {
await access(join(refDir(ref), config.publicMarker));
@@ -380,7 +437,9 @@ export async function listRepos(): Promise<RepoSummary[]> {
}
for (const entry of entries) {
if (!entry.endsWith(".git")) continue;
- const ref: RepoRef = { owner, name: entry.replace(/\.git$/, "") };
+ const name = entry.replace(/\.git$/, "");
+ if (!safeName(name)) continue;
+ const ref: RepoRef = { owner, name };
const dir = refDir(ref);
try {
repos.push({
@@ -863,6 +922,17 @@ export async function readme(ref: RepoRef, refspec: string): Promise<Readme | nu
return { path: hit.name, text: content.text };
}
+// The README at a repo's default branch, for callers that want it without
+// caring which revision they are on. tree() already swallows a bad refspec and
+// returns nothing, so an empty repo, a dangling HEAD and a repo with no README
+// all arrive here as the same null.
+export async function headReadme(ref: RepoRef): Promise<Readme | null> {
+ const refs = await listRefs(ref);
+ if (refs.branches.length === 0) return null;
+ const rev = refs.branches.includes(refs.head) ? refs.head : refs.branches[0]!;
+ return readme(ref, rev);
+}
+
export async function description(ref: RepoRef): Promise<string> {
return readDescription(refDir(ref));
}
diff --git a/src/server.ts b/src/server.ts
index 34c170e..5359c38 100644
--- a/src/server.ts
+++ b/src/server.ts
@@ -3,7 +3,7 @@
// HTTP entrypoint: wires the git smart-HTTP transport and the read-only viewer
// onto one Hono app. Run with `npm start`.
-import { Hono } from "hono";
+import { Hono, type Context } from "hono";
import { getCookie, setCookie, deleteCookie } from "hono/cookie";
import { serve } from "@hono/node-server";
import { createReadStream, existsSync, statSync } from "node:fs";
@@ -54,6 +54,10 @@ import {
dropMirrorStatusKind,
} from "./mirror.ts";
import {
+ PROFILE_REPO,
+ PROFILE_REPOS_PATH,
+ isProfileRepo,
+ headReadme,
safeRef,
refDir,
refSlug,
@@ -65,6 +69,7 @@ import {
restoreFromTrash,
purgeFromTrash,
purgeExpired,
+ purgeAllExpired,
trashHasName,
isRepoPublic,
setRepoPublic,
@@ -82,6 +87,7 @@ import {
setLinks,
localMirrorRefs,
type MirrorLink,
+ type Readme,
type RepoRef,
type RepoSummary,
type RefList,
@@ -448,6 +454,17 @@ app.post("/new", async (c) => {
return c.redirect(`/${result.ref.owner}/${result.ref.name}/`);
});
+// Route params are typed as possibly-absent on a generic Context. These routes
+// always define them, but reading them through one helper keeps that assumption
+// in a single place instead of scattering casts, and gives a missing param the
+// same "no such repo" answer as an unsafe one.
+function refFromPath(c: Context<Env>, nameParam: "name" | "repo"): RepoRef | null {
+ const owner = c.req.param("owner");
+ const name = c.req.param(nameParam);
+ if (!owner || !name) return null;
+ return safeRef(owner, name);
+}
+
const GIT_SERVICES: GitService[] = ["git-upload-pack", "git-receive-pack"];
function authChallenge(message = "authentication required"): Response {
@@ -457,66 +474,82 @@ function authChallenge(message = "authentication required"): Response {
});
}
+// The outcome of the transport gate. It carries the actor as well as the
+// verdict because verifying a token is a hash lookup *and* a `last_used`
+// write: re-deriving the actor afterwards would bill every clone and push for
+// two of each, and leave two places that could disagree about who is pushing.
+interface GitGate {
+ response: Response | null;
+ actor: string | null;
+}
+
+const ALLOW = (actor: string | null): GitGate => ({ response: null, actor });
+const DENY = (response: Response): GitGate => ({ response, actor: null });
+
async function gitGate(
c: { req: { header: (n: string) => string | undefined } },
ref: RepoRef,
needPush: boolean,
-): Promise<Response | null> {
+): Promise<GitGate> {
const auth = authenticateGit(c.req.header("authorization"));
const actor = gitActor(auth);
const exists = await repoExists(ref);
if (auth.kind === "rejected") {
console.warn(`[git] denied ${refSlug(ref)}: ${auth.message}`);
- return new Response(`${auth.message}\n`, { status: 403 });
+ return DENY(new Response(`${auth.message}\n`, { status: 403 }));
}
if (needPush) {
- if (!actor) return authChallenge();
+ if (!actor) return DENY(authChallenge());
if (!exists) {
if (actor !== ref.owner) {
console.warn(`[git] denied create of ${refSlug(ref)} by ${actor}`);
- return new Response(
- `${actor} can only create repositories under ${actor}/\n`,
- { status: 403 },
+ return DENY(
+ new Response(`${actor} can only create repositories under ${actor}/\n`, {
+ status: 403,
+ }),
);
}
if (await trashHasName(ref.owner, ref.name)) {
console.warn(`[git] refused auto-create of trashed ${refSlug(ref)}`);
- return new Response(
- `${refSlug(ref)} is in Recently Deleted. Restore it, or delete it ` +
- `permanently, before pushing to that name again.\n`,
- { status: 409 },
+ return DENY(
+ new Response(
+ `${refSlug(ref)} is in Recently Deleted. Restore it, or delete it ` +
+ `permanently, before pushing to that name again.\n`,
+ { status: 409 },
+ ),
);
}
if (!config.autoCreate) {
- return new Response("repository not found\n", { status: 404 });
+ return DENY(new Response("repository not found\n", { status: 404 }));
}
await initBareRepo(ref);
clearRepoMetadata(ref);
console.log(`[git] auto-created ${refSlug(ref)}.git on first push`);
notifyRepoCreated(ref, actor, false);
- return null;
+ return ALLOW(actor);
}
const isPublic = await isRepoPublic(ref);
if (!canWrite({ ref, isPublic, viewer: actor })) {
console.warn(`[git] denied push to ${refSlug(ref)} by ${actor}`);
- return new Response(
- `${actor} does not have write access to ${refSlug(ref)}\n`,
- { status: 403 },
+ return DENY(
+ new Response(`${actor} does not have write access to ${refSlug(ref)}\n`, {
+ status: 403,
+ }),
);
}
- return null;
+ return ALLOW(actor);
}
if (exists) {
const isPublic = await isRepoPublic(ref);
- if (canRead({ ref, isPublic, viewer: actor })) return null;
+ if (canRead({ ref, isPublic, viewer: actor })) return ALLOW(actor);
}
- if (auth.kind === "anonymous") return authChallenge();
- return new Response("repository not found\n", { status: 404 });
+ if (auth.kind === "anonymous") return DENY(authChallenge());
+ return DENY(new Response("repository not found\n", { status: 404 }));
}
app.get("/:owner/:repo/info/refs", async (c) => {
@@ -526,19 +559,19 @@ app.get("/:owner/:repo/info/refs", async (c) => {
return c.text("only smart HTTP is supported\n", 400);
}
const gate = await gitGate(c, ref, service === "git-receive-pack");
- if (gate) return gate;
+ if (gate.response) return gate.response;
return advertiseResponse(refDir(ref), service);
});
-async function rpcHandler(c: any, service: GitService): Promise<Response> {
- const ref = safeRef(c.req.param("owner"), c.req.param("repo"));
+async function rpcHandler(c: Context<Env>, service: GitService): Promise<Response> {
+ const ref = refFromPath(c, "repo");
if (!ref) return c.text("bad repo\n", 400);
const gate = await gitGate(c, ref, service === "git-receive-pack");
- if (gate) return gate;
+ if (gate.response) return gate.response;
const isPush = service === "git-receive-pack";
const before = isPush ? await localMirrorRefs(ref) : new Map<string, string>();
- const actor = gitActor(authenticateGit(c.req.header("authorization")));
+ const actor = gate.actor;
const isPublic = isPush ? await isRepoPublic(ref) : false;
return serviceRpc({
@@ -587,7 +620,7 @@ function readable(all: RepoSummary[], viewer: string | null): RepoSummary[] {
app.get("/", async (c) => {
const user = c.get("user");
const viewer = viewerOf(c);
- const all = await listRepos();
+ const all = (await listRepos()).filter((r) => !isProfileRepo(r.name));
const shared = viewer ? new Set(sharedWith(viewer).map((r) => `${r.owner}/${r.name}`)) : null;
return c.html(
view.repoListPage(readable(all, viewer), user, {
@@ -596,7 +629,7 @@ app.get("/", async (c) => {
);
});
-function notFound(c: any) {
+function notFound(c: Context<Env>) {
return c.html(
view.messagePage({
title: "not found",
@@ -615,8 +648,8 @@ interface ViewableRepo {
rev: string;
}
-async function viewable(c: any): Promise<ViewableRepo | null> {
- const ref = safeRef(c.req.param("owner"), c.req.param("name"));
+async function viewable(c: Context<Env>): Promise<ViewableRepo | null> {
+ const ref = refFromPath(c, "name");
if (!ref || !(await repoExists(ref))) return null;
const isPublic = await isRepoPublic(ref);
@@ -646,7 +679,7 @@ app.get("/:owner/:name/log", async (c) => {
app.get("/:owner/:name/tree", (c) => renderTree(c, ""));
app.get("/:owner/:name/tree/:path{.*}", (c) => renderTree(c, c.req.param("path")));
-async function renderTree(c: any, path: string) {
+async function renderTree(c: Context<Env>, path: string) {
const found = await viewable(c);
if (!found) return notFound(c);
const entries = await tree(found.ref, found.rev, path);
@@ -698,16 +731,16 @@ app.get("/:owner/:name/commit/:sha", async (c) => {
);
});
-async function ownedRef(c: any): Promise<RepoRef | null> {
+async function ownedRef(c: Context<Env>): Promise<RepoRef | null> {
const user = c.get("user");
if (!user) return null;
- const ref = safeRef(c.req.param("owner"), c.req.param("name"));
+ const ref = refFromPath(c, "name");
if (!ref || ref.owner !== view.ownerOf(user)) return null;
return (await repoExists(ref)) ? ref : null;
}
-async function writableRef(c: any): Promise<RepoRef | null> {
- const ref = safeRef(c.req.param("owner"), c.req.param("name"));
+async function writableRef(c: Context<Env>): Promise<RepoRef | null> {
+ const ref = refFromPath(c, "name");
if (!ref || !(await repoExists(ref))) return null;
const isPublic = await isRepoPublic(ref);
return canWrite({ ref, isPublic, viewer: viewerOf(c) }) ? ref : null;
@@ -804,6 +837,27 @@ app.post("/:owner/:name/collaborators/remove", async (c) => {
return c.redirect(`/${ref.owner}/${ref.name}/`);
});
+// The profile README, read through exactly the same access rules as any other
+// repository. A private +dough stays invisible to everyone it was not shared
+// with, so a profile page can never show content the viewer could not clone.
+async function profileReadme(
+ owner: string,
+ viewer: string | null,
+): Promise<Readme | null> {
+ const ref = safeRef(owner, PROFILE_REPO);
+ if (!ref || !(await repoExists(ref))) return null;
+ const isPublic = await isRepoPublic(ref);
+ if (!canRead({ ref, isPublic, viewer })) return null;
+ return headReadme(ref);
+}
+
+// The owner's repositories, minus the profile repo. +dough is machinery for
+// the page the visitor is already looking at, so listing it is noise; it keeps
+// its own repo page at /<owner>/+dough and is reachable from the profile.
+function ownedRepos(all: RepoSummary[], owner: string): RepoSummary[] {
+ return all.filter((r) => r.owner === owner && !isProfileRepo(r.name));
+}
+
app.get("/:owner", async (c) => {
const owner = c.req.param("owner");
if (!safeRef(owner, "x")) return notFound(c);
@@ -812,11 +866,43 @@ app.get("/:owner", async (c) => {
const viewer = viewerOf(c);
const all = await listRepos();
const owned = all.filter((r) => r.owner === owner);
- const repos = readable(owned, viewer);
+ const repos = readable(ownedRepos(all, owner), viewer);
const profile = findUserBySlug(owner);
if (!profile && owned.length === 0) return notFound(c);
- return c.html(view.profilePage({ owner, profile, repos, user }));
+
+ return c.html(
+ view.profilePage({
+ owner,
+ profile,
+ repos,
+ readme: await profileReadme(owner, viewer),
+ hasProfileRepo: owned.some((r) => isProfileRepo(r.name)),
+ isOwn: viewer === owner,
+ user,
+ }),
+ );
+});
+
+// Registered ahead of /:owner/:name. safeName() refuses "+repos" as a
+// repository name, so this route and a repo page can never contend.
+app.get(`/:owner/${PROFILE_REPOS_PATH}`, async (c) => {
+ const owner = c.req.param("owner");
+ if (!safeRef(owner, "x")) return notFound(c);
+
+ const viewer = viewerOf(c);
+ const all = await listRepos();
+ const profile = findUserBySlug(owner);
+ if (!profile && !all.some((r) => r.owner === owner)) return notFound(c);
+
+ return c.html(
+ view.reposPage({
+ owner,
+ profile,
+ repos: readable(ownedRepos(all, owner), viewer),
+ user: c.get("user"),
+ }),
+ );
});
app.get("/:owner/:name", async (c) => {
@@ -928,6 +1014,23 @@ app.post("/:owner/:name/mirrors/check", async (c) => {
return c.redirect(`/${ref.owner}/${ref.name}/`);
});
+// Recently Deleted is swept on a timer rather than only when somebody opens
+// the page, so MINIGIT_TRASH_DAYS is a retention window rather than a hint. The
+// interval is unref'd: it must never be the reason the process stays alive.
+const SWEEP_INTERVAL_MS = 6 * 60 * 60 * 1000;
+
+async function sweepTrash(): Promise<void> {
+ try {
+ const purged = await purgeAllExpired();
+ for (const gone of purged) {
+ clearRepoMetadata({ owner: gone.owner, name: gone.name });
+ console.log(`[trash] expired ${gone.owner}/${gone.name}`);
+ }
+ } catch (err) {
+ console.warn("[trash] scheduled sweep failed:", err);
+ }
+}
+
serve(
{
fetch: app.fetch,
@@ -940,6 +1043,9 @@ serve(
console.log(` static dir: ${config.staticDir}`);
console.log(` base url: ${config.baseUrl}`);
console.log(` oidc: ${oidcEnabled ? "enabled" : "disabled"}`);
+ console.log(
+ ` trash: ${config.trashDays > 0 ? `${config.trashDays}d, swept every 6h` : "kept forever"}`,
+ );
console.log(` logins: any PocketID account`);
if (oidcEnabled) {
try {
@@ -953,5 +1059,8 @@ serve(
);
}
}
+
+ void sweepTrash();
+ setInterval(() => void sweepTrash(), SWEEP_INTERVAL_MS).unref();
},
);
diff --git a/src/tokens.ts b/src/tokens.ts
index 276c075..55f39ee 100644
--- a/src/tokens.ts
+++ b/src/tokens.ts
@@ -27,6 +27,11 @@ if (!hasColumn("tokens", "owner")) {
db.exec("ALTER TABLE tokens ADD COLUMN owner TEXT");
}
+// Every git request that carries credentials looks a token up by hash, so this
+// is the hottest read in the application and the one that must not become a
+// table scan as the token count grows.
+db.exec("CREATE INDEX IF NOT EXISTS tokens_hash ON tokens (hash)");
+
function sha256(value: string): string {
return createHash("sha256").update(value).digest("hex");
}
diff --git a/src/views.ts b/src/views.ts
index 9f6c4dd..f7bd837 100644
--- a/src/views.ts
+++ b/src/views.ts
@@ -14,6 +14,7 @@ import type { CollaboratorRow } from "./access.ts";
import type { TokenRow } from "./tokens.ts";
import type { UserRow } from "./users.ts";
import type { Settings } from "./settings.ts";
+import { PROFILE_REPO, PROFILE_REPOS_PATH } from "./git.ts";
import type {
RepoSummary,
Commit,
@@ -223,36 +224,119 @@ ${createForm}
return layout({ title: config.title, user, body, path: "/" });
}
+// How many repositories the profile page shows before deferring to /+repos.
+const PROFILE_PREVIEW = 6;
+
+function ownerName(owner: string, profile: UserRow | null): string {
+ return profile ? displayName(profile) : owner;
+}
+
+function ownerHead(owner: string, profile: UserRow | null): string {
+ const handle =
+ profile?.username && profile.username !== profile.slug
+ ? profile.username
+ : null;
+
+ const known = profile
+ ? `<p class="${c.repoDesc}">@${esc(profile.slug)}${handle ? ` · ${esc(handle)}` : ""} · joined ${fmtDate(profile.created_at).slice(0, 10)}</p>`
+ : `<p class="${c.repoDesc}">@${esc(owner)} · no account on this instance</p>`;
+
+ return ` <section class="${c.profileHead}">
+ ${avatar(profile ?? { name: owner, username: null, picture: null }, "lg")}
+ <div>
+ <h1 class="${c.profileName}">${esc(ownerName(owner, profile))}</h1>
+ ${known}
+ </div>
+ </section>`;
+}
+
+// Same shape as the per-repo tabs, so an owner's pages navigate like a repo's.
+function ownerTabs(owner: string, active: "profile" | "repos"): string {
+ const tab = (id: string, label: string, glyph: string, href: string) =>
+ `<a class="${c.tab}${id === active ? " " + c.tabActive : ""}" href="${href}">${icon(glyph)}${label}</a>`;
+ return ` <nav class="${c.repoTabs}">
+ ${tab("profile", "profile", "user", `/${esc(owner)}`)}
+ ${tab("repos", "repositories", "git-branch", `/${esc(owner)}/${PROFILE_REPOS_PATH}`)}
+ </nav>`;
+}
+
export function profilePage(opts: {
owner: string;
profile: UserRow | null;
repos: RepoSummary[];
+ readme: Readme | null;
+ hasProfileRepo: boolean;
+ isOwn: boolean;
user: SessionUser | null;
}): string {
- const p = opts.profile;
- const name = p ? displayName(p) : opts.owner;
- const handle = p?.username && p.username !== p.slug ? p.username : null;
+ const name = ownerName(opts.owner, opts.profile);
+ const preview = opts.repos.slice(0, PROFILE_PREVIEW);
+ const more = opts.repos.length - preview.length;
+ const profileHref = `/${esc(opts.owner)}/${esc(PROFILE_REPO)}/`;
+
+ // The profile README is the page's headline when there is one. The three
+ // "no README" cases are only shown to the owner — a visitor has no use for
+ // them and they would read as an empty section — and they are kept distinct
+ // because the fix differs: create the repo, or push a README into it.
+ const readmeSection = opts.readme
+ ? ` <article class="${c.readme}">
+${renderMarkdown(opts.readme.text)}
+ </article>
+${opts.isOwn ? ` <p class="${c.repoDesc}"><a href="${profileHref}">${esc(PROFILE_REPO)}/${esc(opts.readme.path)}</a></p>` : ""}`
+ : !opts.isOwn
+ ? ""
+ : opts.hasProfileRepo
+ ? ` <p class="${c.cloneBox} ${c.repoDesc}">${icon("file")} <a href="${profileHref}">${esc(PROFILE_REPO)}</a> has no <code>README.md</code> yet. Push one and it shows up here.</p>`
+ : ` <form method="post" action="/new" class="${c.cloneBox} ${c.formRow}">
+ <input type="hidden" name="name" value="${esc(PROFILE_REPO)}">
+ <label class="${c.cloneLabel} ${c.withIcon}">${icon("file")}profile readme</label>
+ <span class="${c.repoDesc}">Create <code>${esc(PROFILE_REPO)}</code> and its README.md shows up here.</span>
+ <button type="submit">${icon("plus")}create</button>
+ </form>`;
- const known = p
- ? `<p class="${c.repoDesc}">@${esc(p.slug)}${handle ? ` · ${esc(handle)}` : ""} · joined ${fmtDate(p.created_at).slice(0, 10)}</p>`
- : `<p class="${c.repoDesc}">@${esc(opts.owner)} · no account on this instance</p>`;
+ const moreLink =
+ more > 0
+ ? ` <p class="${c.repoDesc}"><a href="/${esc(opts.owner)}/${PROFILE_REPOS_PATH}">all ${opts.repos.length} repositories →</a></p>`
+ : "";
- const body = ` <section class="${c.profileHead}">
- ${avatar(p ?? { name: opts.owner, username: null, picture: null }, "lg")}
- <div>
- <h1 class="${c.profileName}">${esc(name)}</h1>
- ${known}
- </div>
- </section>
+ const body = `${ownerHead(opts.owner, opts.profile)}
+${ownerTabs(opts.owner, "profile")}
+${readmeSection}
<h2 class="${c.sectionTitle}">repositories</h2>
- ${repoTable(opts.repos, { showOwner: false, empty: "nothing here yet" })}`;
+ ${repoTable(preview, { showOwner: false, empty: "nothing here yet" })}
+${moreLink}`;
return layout({
title: name,
user: opts.user,
body,
- description: `${name} (@${opts.owner}) on ${config.title}.`,
+ description: opts.readme
+ ? metaText(plainSummary(opts.readme.text))
+ : `${name} (@${opts.owner}) on ${config.title}.`,
path: `/${opts.owner}`,
+ noindex: !opts.repos.some((r) => r.isPublic) && !opts.readme,
+ });
+}
+
+export function reposPage(opts: {
+ owner: string;
+ profile: UserRow | null;
+ repos: RepoSummary[];
+ user: SessionUser | null;
+}): string {
+ const name = ownerName(opts.owner, opts.profile);
+
+ const body = `${ownerHead(opts.owner, opts.profile)}
+${ownerTabs(opts.owner, "repos")}
+ <h2 class="${c.sectionTitle}">repositories</h2>
+ ${repoTable(opts.repos, { showOwner: false, empty: "nothing here yet" })}`;
+
+ return layout({
+ title: `${name} repositories`,
+ user: opts.user,
+ body,
+ description: `Repositories owned by ${name} (@${opts.owner}) on ${config.title}.`,
+ path: `/${opts.owner}/${PROFILE_REPOS_PATH}`,
noindex: !opts.repos.some((r) => r.isPublic),
});
}
diff --git a/test/lifecycle.test.mjs b/test/lifecycle.test.mjs
index 5ef05d9..a90d9bc 100644
--- a/test/lifecycle.test.mjs
+++ b/test/lifecycle.test.mjs
@@ -42,6 +42,7 @@ const {
restoreFromTrash,
purgeFromTrash,
purgeExpired,
+ purgeAllExpired,
DELETED_META,
} = await import("../src/git.ts");
const { setCollaborator, listCollaborators, collaboratorLevel } = await import(
@@ -183,6 +184,27 @@ check("the expired entry was purged", purged.some((e) => e.name === "ancient"));
check("the fresh entry was kept", (await listTrash("alice")).some((e) => e.name === "recent"));
check("expired directory really gone", !existsSync(join(trashOf("alice"), oldEntry.entry)));
+// purgeExpired only ever sweeps the owner being looked at, so an owner who
+// never opens their own Recently Deleted page would keep expired copies for
+// ever. purgeAllExpired is what makes the retention window a real one.
+const bob = { owner: "bob", name: "forgotten" };
+await seed(bob);
+const bobEntry = await trashIt(bob, Math.floor(Date.now() / 1000) - 40 * 86400);
+const bobFresh = { owner: "bob", name: "kept" };
+await seed(bobFresh);
+await trashIt(bobFresh);
+
+const sweptAll = await purgeAllExpired();
+check(
+ "the sweep reaches an owner nobody visited",
+ sweptAll.some((e) => e.owner === "bob" && e.name === "forgotten"),
+);
+check("...and really removes it", !existsSync(join(trashOf("bob"), bobEntry.entry)));
+check(
+ "...while leaving a fresh entry alone",
+ (await listTrash("bob")).some((e) => e.name === "kept"),
+);
+
console.log("\n-- degraded entry (metadata unreadable) --");
const broken = { owner: "alice", name: "broken" };
await seed(broken);