commit
feat: add git hosting enhancements and mirror support
Add the dough-git enhancements for repository hosting, Git transport, authentication, and backup/mirror support. Implement the new Git hosting and smart HTTP functionality, repository access controls, configuration handling, notifications, URL validation, mirror management, and related tests. Add backup/mirror status handling and the associated safety checks for remote repositories and Git URL rewriting. Clean up src/ and test/ by removing inline comments while preserving file headers. The comment removal was performed through the TypeScript parser and verified against the pre-strip token streams to ensure no code was changed. Verify the complete change with typechecking, the full test suite, build, and end-to-end smoke testing.
diff --git a/.env.example b/.env.example
index ba56d66..e53e052 100644
--- a/.env.example
+++ b/.env.example
@@ -52,8 +52,42 @@ MINIGIT_PUBLIC_MARKER=minigit-public
MINIGIT_DB_PATH=
# Auto-create a bare repo on first authenticated push (set "false" to disable).
+# A name held by a repository in Recently Deleted is never auto-created over:
+# the push is refused until that copy is restored or purged.
MINIGIT_AUTO_CREATE=true
+# --- deletion + recovery -----------------------------------------------------
+# Deleting a repository moves it to <repos>/.trash/<owner>/<name>.<ts>.git
+# instead of destroying it, and its name stays reserved while it is recoverable.
+# Restore or purge it from /settings/deleted.
+#
+# The trash lives inside MINIGIT_REPOS_ROOT deliberately: same filesystem (so
+# the move is atomic), same backup volume, and a leading dot keeps it invisible
+# 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.
+MINIGIT_TRASH_DAYS=30
+
+# --- notifications and mirror status -----------------------------------------
+# Both are configured per account in the web UI at /settings, not here.
+#
+# Discord webhook — announces repositories being created and deleted, and
+# commits being pushed. Only discord.com (and its
+# canary/ptb/discordapp hostnames) are accepted. Private
+# repositories are NOT announced unless you opt in.
+#
+# Mirror status — per repository, you can record where else it is kept on
+# GitHub and Codeberg. dough-git then reports whether those
+# copies still exist and whether their refs match, using
+# `git ls-remote` only. It never pushes, fetches, repairs
+# or creates anything on a remote, and stores no
+# credentials for them: a private mirror is marked
+# `private` in the repo's `dough-links` file and skipped.
+#
+# This means the server makes outbound HTTPS requests to discord.com,
+# github.com and codeberg.org — and, by host allow-list, nowhere else.
+
# --- PocketID (OIDC) ---------------------------------------------------------
# Only needed to *view private repos in a browser*. Register this callback URL
# in PocketID: <MINIGIT_BASE_URL>/auth/callback
diff --git a/package.json b/package.json
index b8a47cb..d13f8a5 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/transport.test.mjs && node --experimental-strip-types test/markdown.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"
+ "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-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"
},
"dependencies": {
"@hono/node-server": "^1.13.7",
diff --git a/src/access.ts b/src/access.ts
index f5d802a..215f222 100644
--- a/src/access.ts
+++ b/src/access.ts
@@ -25,10 +25,8 @@ db.exec(`
);
`);
-// What an invited collaborator may do. The owner is never stored as one.
export type Level = "read" | "write";
-// The resolved answer for one viewer against one repo.
export type Access = "none" | "read" | "write";
export function isLevel(value: string): value is Level {
@@ -52,9 +50,6 @@ export function listCollaborators(ref: RepoRef): CollaboratorRow[] {
.all(ref.owner, ref.name) as unknown as CollaboratorRow[];
}
-// Add or re-level a collaborator. Inviting the owner is a no-op: they already
-// have more than any invitation could grant, and storing it would let a later
-// "remove" imply they lost access.
export function setCollaborator(
ref: RepoRef,
slug: string,
@@ -76,7 +71,6 @@ export function removeCollaborator(ref: RepoRef, slug: string): boolean {
return Number(result.changes) > 0;
}
-// Called when a repo is deleted, so its grants can't outlive it.
export function dropRepoAccess(ref: RepoRef): void {
db.prepare("DELETE FROM collaborators WHERE owner = ? AND repo = ?").run(
ref.owner,
@@ -100,8 +94,6 @@ export interface SharedRepo {
level: Level;
}
-// Repos somebody else shared with `slug`. Used to show them on the front page
-// and on that person's own profile, where they'd otherwise be invisible.
export function sharedWith(slug: string): SharedRepo[] {
const rows = db
.prepare(
@@ -122,13 +114,9 @@ export function sharedWith(slug: string): SharedRepo[] {
export interface AccessQuery {
ref: RepoRef;
isPublic: boolean;
- // The owner slug of whoever is asking, or null when nobody is signed in and
- // no token was presented.
viewer: string | null;
}
-// The single place the read/write rule is written down. Everything else — the
-// viewer routes, the git transport, the management forms — asks this.
export function accessFor(query: AccessQuery): Access {
const { ref, isPublic, viewer } = query;
diff --git a/src/auth.ts b/src/auth.ts
index 6ec8c8c..78df05d 100644
--- a/src/auth.ts
+++ b/src/auth.ts
@@ -18,8 +18,6 @@ import { verifyDbToken } from "./tokens.ts";
import { rememberUser, findUserBySub } from "./users.ts";
import { ownerSlug } from "./git.ts";
-// ---- signed values ----------------------------------------------------------
-
function b64url(input: Buffer | string): string {
return Buffer.from(input).toString("base64url");
}
@@ -30,14 +28,12 @@ function sign(payload: string): string {
.digest("base64url");
}
-// Encode an object into `payload.signature`, embedding an expiry.
export function signValue(data: object, ttlSeconds: number): string {
const body = { ...data, exp: Math.floor(Date.now() / 1000) + ttlSeconds };
const payload = b64url(JSON.stringify(body));
return `${payload}.${sign(payload)}`;
}
-// Verify and decode a signed value; returns null if tampered or expired.
export function verifyValue<T>(token: string | undefined): T | null {
if (!token) return null;
const dot = token.lastIndexOf(".");
@@ -61,25 +57,21 @@ export function verifyValue<T>(token: string | undefined): T | null {
}
}
-// ---- sessions ---------------------------------------------------------------
-
export interface SessionUser {
sub: string;
email: string | null;
name: string | null;
- username: string | null; // PocketID preferred_username
- slug: string; // owner namespace; assigned once, in users.ts
- picture: string | null; // PocketID avatar URL
+ username: string | null;
+ slug: string;
+ picture: string | null;
}
-// Sessions minted before slug/picture existed are still validly signed, so read
-// them defensively rather than logging everyone out.
export function sessionSlug(user: SessionUser): string {
return user.slug || ownerSlug(user.username ?? user.name ?? "user");
}
-const SESSION_TTL = 60 * 60 * 24 * 30; // 30 days
-const OAUTH_TTL = 60 * 10; // 10 minutes
+const SESSION_TTL = 60 * 60 * 24 * 30;
+const OAUTH_TTL = 60 * 10;
export const SESSION_COOKIE = "mg_session";
export const OAUTH_COOKIE = "mg_oauth";
@@ -92,13 +84,6 @@ export function readSession(token: string | undefined): SessionUser | null {
return verifyValue<SessionUser & { exp: number }>(token);
}
-// Re-anchor a session cookie on the user directory.
-//
-// The cookie is signed and stateless, so on its own it stays good for its whole
-// 30-day life: an account deleted from the directory would keep its access
-// until the cookie aged out. Reading the row back on every request makes the
-// removal take effect immediately, and picks up a renamed display name or a new
-// avatar for free. Returns null when the session no longer names anyone.
export function currentUser(session: SessionUser): SessionUser | null {
const row = findUserBySub(session.sub);
if (!row) return null;
@@ -113,9 +98,6 @@ export function currentUser(session: SessionUser): SessionUser | null {
};
}
-// ---- git token auth ---------------------------------------------------------
-
-// Parse an `Authorization: Basic ...` header into [user, pass].
export function parseBasicAuth(
header: string | undefined,
): [string, string] | null {
@@ -126,25 +108,11 @@ export function parseBasicAuth(
return [decoded.slice(0, idx), decoded.slice(idx + 1)];
}
-// What a set of Basic credentials is allowed to be.
-//
-// There is deliberately no instance-wide credential. Every token belongs to
-// exactly one account, so every push and every private read is attributable and
-// bounded by that account's permissions.
export type GitAuth =
- // A token minted at /tokens, acting as exactly one owner namespace.
| { kind: "user"; owner: string }
- // No credentials at all — the caller should send a Basic challenge.
| { kind: "anonymous" }
- // Credentials were presented and are not usable. `message` is written back to
- // the git client, so it has to say what to fix.
| { kind: "rejected"; message: string };
-// Resolve `Authorization: Basic ...` into what it may act as.
-//
-// The username half is no longer decorative: for an account token it must be
-// that account's owner slug. Requiring it means a push URL names who is pushing,
-// which is what makes `owner/repo` paths mean anything.
export function authenticateGit(header: string | undefined): GitAuth {
const basic = parseBasicAuth(header);
if (!basic) return { kind: "anonymous" };
@@ -164,8 +132,6 @@ export function authenticateGit(header: string | undefined): GitAuth {
};
}
- // Accept the slug itself, and also the raw username it was derived from, so
- // `https://Alex.Kim:token@host/...` still works for owner `alex-kim`.
const named =
username !== "" &&
(username === row.owner || ownerSlug(username) === row.owner);
@@ -181,23 +147,16 @@ export function authenticateGit(header: string | undefined): GitAuth {
return { kind: "user", owner: row.owner };
}
-// The owner slug a set of credentials acts as, or null when they don't act as
-// anybody. Repo-level authority lives in access.ts — this only says who.
export function gitActor(auth: GitAuth): string | null {
return auth.kind === "user" ? auth.owner : null;
}
-// ---- OIDC (PocketID) --------------------------------------------------------
-
let discovered: oidc.Configuration | null = null;
async function oidcConfig(): Promise<oidc.Configuration> {
if (!discovered) {
const { issuer, clientId, clientSecret, tokenAuth } = config.oidc;
- // Token-endpoint auth method. Empty = openid-client's default. Set
- // OIDC_TOKEN_AUTH=post for PocketID clients configured as client_secret_post,
- // or =none for a public (PKCE-only) client with no secret.
let clientAuth: oidc.ClientAuth | undefined;
switch (tokenAuth) {
case "post":
@@ -216,8 +175,6 @@ async function oidcConfig(): Promise<oidc.Configuration> {
discovered = await oidc.discovery(
new URL(issuer),
clientId,
- // When clientAuth is explicit it already carries the secret; otherwise
- // pass the secret string so openid-client uses its default method.
clientAuth ? undefined : clientSecret,
clientAuth,
);
@@ -225,8 +182,6 @@ async function oidcConfig(): Promise<oidc.Configuration> {
return discovered;
}
-// The issuer the discovery document actually advertises. Must match the `iss`
-// PocketID returns on the callback, or openid-client rejects the login.
export async function oidcIssuer(): Promise<string> {
const cfg = await oidcConfig();
return cfg.serverMetadata().issuer;
@@ -234,11 +189,9 @@ export async function oidcIssuer(): Promise<string> {
export interface AuthStart {
redirectUrl: string;
- txCookie: string; // signed cookie carrying PKCE verifier + state
+ txCookie: string;
}
-// Begin the OIDC login: returns the URL to send the browser to and a signed
-// transaction cookie to set.
export async function startLogin(): Promise<AuthStart> {
const cfg = await oidcConfig();
const verifier = oidc.randomPKCECodeVerifier();
@@ -259,8 +212,6 @@ export async function startLogin(): Promise<AuthStart> {
};
}
-// Complete the OIDC login from the callback request URL. Returns the identity,
-// or null if the transaction is invalid / the user isn't allowed.
export async function finishLogin(
currentUrl: string,
txToken: string | undefined,
@@ -291,10 +242,6 @@ export async function finishLogin(
picture: typeof claims.picture === "string" ? claims.picture : null,
};
- // Anyone PocketID vouches for is welcome: PocketID is the guest list, and
- // keeping a second one here only ever gets out of step with it. Signing in
- // earns a directory entry and with it a permanent owner slug — which is a
- // namespace of their own, not access to anybody else's.
const row = rememberUser(claimed);
return { ...claimed, slug: row.slug };
}
diff --git a/src/config.ts b/src/config.ts
index b1b46ae..e8476ec 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -18,46 +18,35 @@ export const config = {
port: Number(optional("MINIGIT_PORT", "4010")),
title: optional("MINIGIT_TITLE", "dough-git"),
- // Directory whose files are served at /static (drop your own style.css here).
staticDir: optional("MINIGIT_STATIC_DIR", "./public"),
- // Site icon. Used as the favicon and as the social-preview image, so it wants
- // to be an absolute URL that works off-site.
favicon: optional(
"MINIGIT_FAVICON",
"https://m.doughmination.gay/img/avatars/git.png",
),
- // Fallback <meta name="description"> for pages that don't derive their own.
description: optional(
"MINIGIT_DESCRIPTION",
"A minimal self-hosted git mirror.",
),
- // Browser UI colour on mobile. Matches the theme background in
- // src/styles/theme.css.ts.
themeColor: optional("MINIGIT_THEME_COLOR", "#0a0b10"),
- // Marker filename that makes a bare repo public. Absent = private.
publicMarker: optional("MINIGIT_PUBLIC_MARKER", "minigit-public"),
- // SQLite file backing the token UI. Defaults inside the repos volume so it
- // persists. Note: a non-.git file here is ignored by the repo listing.
dbPath: optional("MINIGIT_DB_PATH", "") || `${reposRoot}/dough-git.db`,
- // Auto-create a bare repo on first authenticated push (great for a backup
- // target — just `git push` and the repo appears). Set to "false" to disable.
autoCreate: optional("MINIGIT_AUTO_CREATE", "true") !== "false",
+ trashDays: Math.max(0, Number(optional("MINIGIT_TRASH_DAYS", "30")) || 0),
+
oidc: {
issuer: optional("OIDC_ISSUER", ""),
clientId: optional("OIDC_CLIENT_ID", ""),
clientSecret: optional("OIDC_CLIENT_SECRET", ""),
- // "" (default) | "basic" | "post" | "none" — token-endpoint auth method.
tokenAuth: optional("OIDC_TOKEN_AUTH", ""),
},
- // Signs session + OAuth transaction cookies. `openssl rand -hex 32`.
sessionSecret: optional("SESSION_SECRET", "dev-insecure-secret-change-me"),
} as const;
diff --git a/src/db.ts b/src/db.ts
index 19e6308..b04f09e 100644
--- a/src/db.ts
+++ b/src/db.ts
@@ -20,8 +20,6 @@ export function now(): number {
return Math.floor(Date.now() / 1000);
}
-// True if `table` already has `column` — used to apply additive migrations to
-// databases created by an older version.
export function hasColumn(table: string, column: string): boolean {
const cols = db.prepare(`PRAGMA table_info(${table})`).all() as unknown as {
name: string;
diff --git a/src/git.ts b/src/git.ts
index 32748a9..ad0224a 100644
--- a/src/git.ts
+++ b/src/git.ts
@@ -8,19 +8,25 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
-import { readdir, readFile, access, writeFile, unlink, mkdir, rm } from "node:fs/promises";
-import { join } from "node:path";
+import {
+ readdir,
+ readFile,
+ access,
+ writeFile,
+ unlink,
+ mkdir,
+ rm,
+ rename,
+} from "node:fs/promises";
+import { join, resolve, sep } from "node:path";
import { config } from "./config.ts";
+import { isMirrorKind, mirrorUrl, MIRROR_KINDS, type MirrorKind } from "./urls.ts";
const exec = promisify(execFile);
-// Separators in git's OUTPUT that we split on.
const NUL = "\x00";
const REC = "\x1e";
-// The same separators as git pretty-format escapes, used in the --format
-// argument (Node's child_process rejects literal NUL bytes in args; git expands
-// %x00/%x1e into the real bytes in its output).
const FNUL = "%x00";
const FREC = "%x1e";
@@ -32,33 +38,23 @@ async function git(repoDir: string, args: string[]): Promise<string> {
return stdout;
}
-// ---- identity ---------------------------------------------------------------
-
export interface RepoRef {
owner: string;
- name: string; // without .git
+ name: string;
}
const SEGMENT = /^[A-Za-z0-9._-]+$/;
-// A leading dot is refused outright: it covers `.` and `..` without special
-// cases, and keeps hidden names out of the repos root.
function safeSegment(s: string): boolean {
return SEGMENT.test(s) && !s.startsWith(".") && !s.includes("..");
}
-// A git object id as it may appear in a URL. Anything else — notably anything
-// starting with `-` — must never reach the git CLI as a bare argument, because
-// git would read it as an option (`--output=<file>` writes a file).
const OBJECT_ID = /^[0-9a-fA-F]{4,64}$/;
export function safeObjectId(sha: string): string | null {
return OBJECT_ID.test(sha) ? sha : null;
}
-// Validate an owner + repo name into a RepoRef. `name` may carry a `.git`
-// suffix (git clients send it); it's stripped. Returns null if either segment
-// is unsafe, so a request can never escape the repos root.
export function safeRef(owner: string, nameRaw: string): RepoRef | null {
const name = nameRaw.replace(/\.git$/, "");
if (!safeSegment(owner) || !safeSegment(name)) return null;
@@ -73,7 +69,6 @@ export function refSlug(ref: RepoRef): string {
return `${ref.owner}/${ref.name}`;
}
-// Turn a username/display name into a safe owner segment.
export function ownerSlug(raw: string): string {
const slug = raw.trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
return slug || "user";
@@ -88,8 +83,6 @@ export async function repoExists(ref: RepoRef): Promise<boolean> {
}
}
-// ---- create / delete --------------------------------------------------------
-
export async function initBareRepo(ref: RepoRef): Promise<void> {
const dir = refDir(ref);
await mkdir(dir, { recursive: true });
@@ -102,6 +95,7 @@ export interface CreateResult {
ok: boolean;
ref?: RepoRef;
error?: string;
+ reserved?: boolean;
}
export async function createRepo(
@@ -115,27 +109,233 @@ export async function createRepo(
if (await repoExists(ref)) {
return { ok: false, error: "a repo with that name already exists" };
}
+ if (await trashHasName(ref.owner, ref.name)) {
+ return {
+ ok: false,
+ error:
+ `${ref.owner}/${ref.name} is in Recently Deleted and still holds that name. ` +
+ `Restore it, or delete it permanently, from your settings.`,
+ reserved: true,
+ };
+ }
await initBareRepo(ref);
return { ok: true, ref };
}
-// Permanently delete a bare repo (guarded: must be a real repo first).
-export async function deleteRepo(ref: RepoRef): Promise<boolean> {
- if (!(await repoExists(ref))) return false;
- await rm(refDir(ref), { recursive: true, force: true });
- // Drop the owner directory too if it's now empty.
+async function pruneEmptyDir(dir: string): Promise<void> {
try {
- const ownerDir = join(config.reposRoot, ref.owner);
- if ((await readdir(ownerDir)).length === 0) {
- await rm(ownerDir, { recursive: true, force: true });
+ if ((await readdir(dir)).length === 0) {
+ await rm(dir, { recursive: true, force: true });
}
} catch {
- /* ignore */
}
+}
+
+async function pathExists(p: string): Promise<boolean> {
+ try {
+ await access(p);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+const TRASH_DIR = ".trash";
+
+export const DELETED_META = "dough-deleted.json";
+
+const TRASH_ENTRY = /^[A-Za-z0-9._-]+\.\d+\.git$/;
+
+export interface DeletedGrant {
+ slug: string;
+ level: string;
+}
+
+export interface DeletedMeta {
+ version: 1;
+ owner: string;
+ name: string;
+ deletedAt: number;
+ deletedBy: string;
+ grants: DeletedGrant[];
+}
+
+export interface TrashEntry {
+ entry: string;
+ owner: string;
+ name: string;
+ deletedAt: number;
+ deletedBy: string;
+ grants: DeletedGrant[];
+ degraded: boolean;
+}
+
+function trashRoot(): string {
+ return join(config.reposRoot, TRASH_DIR);
+}
+
+function trashOwnerDir(owner: string): string {
+ return join(trashRoot(), owner);
+}
+
+function trashEntryDir(owner: string, entry: string): string | null {
+ if (!safeSegment(owner)) return null;
+ if (entry.startsWith(".") || entry.includes("/") || entry.includes("\\")) {
+ return null;
+ }
+ if (!TRASH_ENTRY.test(entry)) return null;
+
+ const root = resolve(trashRoot());
+ const full = resolve(join(root, owner, entry));
+ if (!full.startsWith(root + sep)) return null;
+ return full;
+}
+
+function nameFromEntry(entry: string): string {
+ return entry.replace(/\.\d+\.git$/, "");
+}
+
+export async function trashRepo(
+ ref: RepoRef,
+ meta: Omit<DeletedMeta, "version" | "owner" | "name">,
+): Promise<{ ok: boolean; entry?: string; error?: string }> {
+ if (!(await repoExists(ref))) return { ok: false, error: "no such repository" };
+
+ const ownerDir = trashOwnerDir(ref.owner);
+ await mkdir(ownerDir, { recursive: true });
+
+ let stamp = meta.deletedAt;
+ let entry = `${ref.name}.${stamp}.git`;
+ while (await pathExists(join(ownerDir, entry))) {
+ stamp += 1;
+ entry = `${ref.name}.${stamp}.git`;
+ }
+
+ const full: DeletedMeta = {
+ version: 1,
+ owner: ref.owner,
+ name: ref.name,
+ deletedAt: meta.deletedAt,
+ deletedBy: meta.deletedBy,
+ grants: meta.grants,
+ };
+ await writeFile(
+ join(refDir(ref), DELETED_META),
+ JSON.stringify(full, null, 2) + "\n",
+ );
+
+ await rename(refDir(ref), join(ownerDir, entry));
+ await pruneEmptyDir(join(config.reposRoot, ref.owner));
+ return { ok: true, entry };
+}
+
+export async function listTrash(owner: string): Promise<TrashEntry[]> {
+ if (!safeSegment(owner)) return [];
+ let entries: string[];
+ try {
+ entries = await readdir(trashOwnerDir(owner));
+ } catch {
+ return [];
+ }
+
+ const out: TrashEntry[] = [];
+ for (const entry of entries) {
+ const dir = trashEntryDir(owner, entry);
+ if (!dir) continue;
+
+ const fallbackTime = Number(/\.(\d+)\.git$/.exec(entry)?.[1] ?? 0);
+ let meta: DeletedMeta | null = null;
+ try {
+ const parsed = JSON.parse(await readFile(join(dir, DELETED_META), "utf8"));
+ if (
+ parsed &&
+ typeof parsed.name === "string" &&
+ safeSegment(parsed.name) &&
+ parsed.owner === owner
+ ) {
+ meta = parsed as DeletedMeta;
+ }
+ } catch {
+ }
+
+ out.push({
+ entry,
+ owner,
+ name: meta?.name ?? nameFromEntry(entry),
+ deletedAt: meta?.deletedAt ?? fallbackTime,
+ deletedBy: meta?.deletedBy ?? "unknown",
+ grants: Array.isArray(meta?.grants) ? meta.grants : [],
+ degraded: meta === null,
+ });
+ }
+
+ out.sort((a, b) => b.deletedAt - a.deletedAt);
+ return out;
+}
+
+export async function trashHasName(owner: string, name: string): Promise<boolean> {
+ const entries = await listTrash(owner);
+ return entries.some((e) => e.name === name);
+}
+
+export interface RestoreResult {
+ ok: boolean;
+ error?: string;
+ meta?: TrashEntry;
+}
+
+export async function restoreFromTrash(
+ owner: string,
+ entry: string,
+): Promise<RestoreResult> {
+ const dir = trashEntryDir(owner, entry);
+ if (!dir || !(await pathExists(dir))) {
+ return { ok: false, error: "no such deleted repository" };
+ }
+
+ const all = await listTrash(owner);
+ const found = all.find((e) => e.entry === entry);
+ if (!found) return { ok: false, error: "no such deleted repository" };
+
+ const ref = safeRef(owner, found.name);
+ if (!ref) return { ok: false, error: "that repository's name is not usable" };
+ if (await repoExists(ref)) {
+ return {
+ ok: false,
+ error: `${owner}/${found.name} already exists. Rename or delete it first, then restore.`,
+ };
+ }
+
+ await mkdir(join(config.reposRoot, owner), { recursive: true });
+ await rename(dir, refDir(ref));
+ await unlink(join(refDir(ref), DELETED_META)).catch(() => {});
+ await pruneEmptyDir(trashOwnerDir(owner));
+ return { ok: true, meta: found };
+}
+
+export async function purgeFromTrash(
+ owner: string,
+ entry: string,
+): Promise<boolean> {
+ const dir = trashEntryDir(owner, entry);
+ if (!dir) return false;
+ if (!(await pathExists(dir))) return false;
+ await rm(dir, { recursive: true, force: true });
+ await pruneEmptyDir(trashOwnerDir(owner));
return true;
}
-// ---- visibility (filesystem marker) -----------------------------------------
+export async function purgeExpired(owner: string): Promise<TrashEntry[]> {
+ if (config.trashDays <= 0) return [];
+ const cutoff = Math.floor(Date.now() / 1000) - config.trashDays * 86400;
+ const purged: TrashEntry[] = [];
+ for (const entry of await listTrash(owner)) {
+ if (entry.degraded || entry.deletedAt <= 0) continue;
+ if (entry.deletedAt >= cutoff) continue;
+ if (await purgeFromTrash(owner, entry.entry)) purged.push(entry);
+ }
+ return purged;
+}
export async function isRepoPublic(ref: RepoRef): Promise<boolean> {
try {
@@ -152,8 +352,6 @@ export async function setRepoPublic(ref: RepoRef, isPublic: boolean): Promise<vo
else await unlink(marker).catch(() => {});
}
-// ---- listing ----------------------------------------------------------------
-
export interface RepoSummary {
owner: string;
name: string;
@@ -178,7 +376,7 @@ export async function listRepos(): Promise<RepoSummary[]> {
try {
entries = await readdir(join(config.reposRoot, owner));
} catch {
- continue; // not a directory (e.g. the sqlite db file)
+ continue;
}
for (const entry of entries) {
if (!entry.endsWith(".git")) continue;
@@ -194,7 +392,6 @@ export async function listRepos(): Promise<RepoSummary[]> {
isPublic: await isRepoPublic(ref),
});
} catch {
- /* skip invalid */
}
}
}
@@ -221,31 +418,212 @@ async function headBranch(dir: string): Promise<string> {
}
}
-// ---- description ------------------------------------------------------------
-
-// git's own one-line `description` file, which cgit and friends already read.
-// Newlines are collapsed because the format is one line by convention and the
-// whole viewer renders it as one.
const MAX_DESCRIPTION = 300;
export async function setDescription(ref: RepoRef, raw: string): Promise<void> {
const text = raw.replace(/\s+/g, " ").trim().slice(0, MAX_DESCRIPTION);
const path = join(refDir(ref), "description");
if (!text) {
- // git ships a placeholder here; restoring it is what "no description" means
- // to every other tool that reads this file.
await writeFile(path, "Unnamed repository; edit this file to name it.\n");
return;
}
await writeFile(path, `${text}\n`);
}
-// ---- refs -------------------------------------------------------------------
+const REMOTE_TIMEOUT_MS = 10_000;
+const REMOTE_MAX_BYTES = 1024 * 1024;
+
+const REMOTE_HARDENING = [
+ "-c", "protocol.allow=never",
+ "-c", "protocol.https.allow=always",
+ "-c", "credential.helper=",
+ "-c", "http.followRedirects=false",
+ "-c", "http.lowSpeedLimit=1000",
+ "-c", "http.lowSpeedTime=15",
+];
+
+const REMOTE_ENV: NodeJS.ProcessEnv = {
+ PATH: process.env.PATH ?? "/usr/bin:/bin",
+ HOME: "/nonexistent",
+ GIT_TERMINAL_PROMPT: "0",
+ GIT_ASKPASS: "/bin/true",
+ GIT_CONFIG_NOSYSTEM: "1",
+ GIT_CONFIG_GLOBAL: "/dev/null",
+ GIT_CONFIG_SYSTEM: "/dev/null",
+ LC_ALL: "C",
+};
+
+export type RemoteFailure = "denied" | "missing" | "error";
+
+export type LsRemoteResult =
+ | { ok: true; text: string }
+ | { ok: false; kind: RemoteFailure; message: string };
+
+export function classifyRemoteError(stderr: string, timedOut: boolean): {
+ kind: RemoteFailure;
+ message: string;
+} {
+ if (timedOut) return { kind: "error", message: "timed out" };
+
+ const text = stderr.trim();
+ const first =
+ text
+ .split("\n")
+ .map((l) => l.replace(/^(?:fatal|error|warning|remote):\s*/i, "").trim())
+ .filter((l) => l.length > 0)
+ .pop() ?? "unknown error";
+ const short = first.slice(0, 160);
+
+ if (/terminal prompts disabled|could not read Username|Authentication failed|403/i.test(text)) {
+ return { kind: "denied", message: short };
+ }
+ if (/repository not found|not found|404/i.test(text)) {
+ return { kind: "missing", message: short };
+ }
+ return { kind: "error", message: short };
+}
+
+export async function lsRemote(url: string): Promise<LsRemoteResult> {
+ try {
+ const { stdout } = await exec(
+ "git",
+ [...REMOTE_HARDENING, "ls-remote", "--heads", "--tags", "--", url],
+ {
+ timeout: REMOTE_TIMEOUT_MS,
+ killSignal: "SIGKILL",
+ maxBuffer: REMOTE_MAX_BYTES,
+ encoding: "utf8",
+ env: REMOTE_ENV,
+ windowsHide: true,
+ },
+ );
+ return { ok: true, text: stdout };
+ } catch (err) {
+ const e = err as { stderr?: string; killed?: boolean; signal?: string; message?: string };
+ const timedOut = e.killed === true || e.signal === "SIGKILL";
+ return {
+ ok: false,
+ ...classifyRemoteError(e.stderr ?? e.message ?? "", timedOut),
+ };
+ }
+}
+
+export async function localMirrorRefs(ref: RepoRef): Promise<Map<string, string>> {
+ const out = new Map<string, string>();
+ try {
+ const text = await git(refDir(ref), [
+ "for-each-ref",
+ "--format=%(objectname) %(refname)",
+ "refs/heads",
+ "refs/tags",
+ ]);
+ for (const line of text.split("\n")) {
+ const space = line.indexOf(" ");
+ if (space === -1) continue;
+ const sha = line.slice(0, space);
+ const name = line.slice(space + 1).trim();
+ if (safeObjectId(sha) && name) out.set(name, sha);
+ }
+ } catch {
+ }
+ return out;
+}
+
+export async function hasCommit(ref: RepoRef, sha: string): Promise<boolean> {
+ const id = safeObjectId(sha);
+ if (!id) return false;
+ try {
+ await git(refDir(ref), ["cat-file", "-e", `${id}^{commit}`]);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export async function isAncestor(
+ ref: RepoRef,
+ ancestor: string,
+ descendant: string,
+): Promise<boolean> {
+ const a = safeObjectId(ancestor);
+ const b = safeObjectId(descendant);
+ if (!a || !b) return false;
+ try {
+ await git(refDir(ref), ["merge-base", "--is-ancestor", a, b]);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+const LINKS_FILE = "dough-links";
+
+const MAX_LINKS_BYTES = 2048;
+const MAX_LINK_LINES = 16;
+
+export interface MirrorLink {
+ kind: MirrorKind;
+ url: string;
+ isPrivate: boolean;
+}
+
+export function parseLinks(text: string): MirrorLink[] {
+ const out: MirrorLink[] = [];
+ const seen = new Set<string>();
+
+ for (const raw of text.split("\n").slice(0, MAX_LINK_LINES)) {
+ const line = raw.trim();
+ if (!line || line.startsWith("#")) continue;
+
+ const parts = line.split(/\s+/);
+ const kind = (parts[0] ?? "").toLowerCase();
+ const url = parts[1] ?? "";
+ if (!isMirrorKind(kind)) continue;
+ if (seen.has(kind)) continue;
+
+ const valid = mirrorUrl(kind, url);
+ if (!valid) continue;
+
+ seen.add(kind);
+ out.push({
+ kind,
+ url: valid,
+ isPrivate: parts.slice(2).includes("private"),
+ });
+ }
+
+ out.sort((a, b) => MIRROR_KINDS.indexOf(a.kind) - MIRROR_KINDS.indexOf(b.kind));
+ return out;
+}
+
+export function serialiseLinks(links: MirrorLink[]): string {
+ return links
+ .map((l) => `${l.kind} ${l.url}${l.isPrivate ? " private" : ""}`)
+ .join("\n");
+}
+
+export async function readLinks(ref: RepoRef): Promise<MirrorLink[]> {
+ try {
+ const text = await readFile(join(refDir(ref), LINKS_FILE), "utf8");
+ return parseLinks(text.slice(0, MAX_LINKS_BYTES));
+ } catch {
+ return [];
+ }
+}
+
+export async function setLinks(ref: RepoRef, links: MirrorLink[]): Promise<void> {
+ const path = join(refDir(ref), LINKS_FILE);
+ const valid = parseLinks(serialiseLinks(links));
+ if (valid.length === 0) {
+ await unlink(path).catch(() => {});
+ return;
+ }
+ await writeFile(path, serialiseLinks(valid) + "\n");
+}
export interface RefList {
branches: string[];
tags: string[];
- // The branch HEAD points at. Always the fallback when nothing is requested.
head: string;
}
@@ -274,12 +652,6 @@ export async function listRefs(ref: RepoRef): Promise<RefList> {
};
}
-// Turn a requested revision into one that is safe to hand the git CLI.
-//
-// This is an allow-list, not a pattern check: the answer is either a ref this
-// repo actually advertises or an object id that actually resolves, and anything
-// else falls back to HEAD. That is what keeps a query string like
-// `?h=--output=/etc/cron.d/x` from ever reaching an argv slot.
export async function resolveRev(
ref: RepoRef,
requested: string | undefined,
@@ -292,7 +664,6 @@ export async function resolveRev(
if (!wanted) return fallback;
if (refs.branches.includes(wanted) || refs.tags.includes(wanted)) return wanted;
- // A full or abbreviated object id, so a commit link can be a permalink.
const sha = safeObjectId(wanted);
if (sha) {
try {
@@ -315,8 +686,6 @@ async function lastCommitTime(dir: string): Promise<number | null> {
}
}
-// ---- viewer reads -----------------------------------------------------------
-
export interface Commit {
hash: string;
author: string;
@@ -338,7 +707,48 @@ export async function log(ref: RepoRef, refspec: string, limit = 50): Promise<Co
"--",
]);
} catch {
- return []; // empty repo or bad ref
+ return [];
+ }
+ return out
+ .split(REC)
+ .map((row) => row.replace(/^\n/, ""))
+ .filter((row) => row.trim().length > 0)
+ .map((row) => {
+ const [hash, author, email, time, subject] = row.split(NUL);
+ return {
+ hash: hash ?? "",
+ author: author ?? "",
+ email: email ?? "",
+ time: Number(time ?? 0),
+ subject: subject ?? "",
+ };
+ });
+}
+
+export async function logRange(
+ ref: RepoRef,
+ from: string | null,
+ to: string,
+ limit: number,
+): Promise<Commit[]> {
+ const toId = safeObjectId(to);
+ if (!toId) return [];
+ const fromId = from ? safeObjectId(from) : null;
+ if (from && !fromId) return [];
+
+ const dir = refDir(ref);
+ const format = ["%H", "%an", "%ae", "%at", "%s"].join(FNUL);
+ let out: string;
+ try {
+ out = await git(dir, [
+ "log",
+ `--max-count=${Math.max(1, Math.floor(limit))}`,
+ `--format=${format}${FREC}`,
+ ...(fromId ? [`${fromId}..${toId}`] : [toId]),
+ "--",
+ ]);
+ } catch {
+ return [];
}
return out
.split(REC)
@@ -396,14 +806,10 @@ export async function tree(ref: RepoRef, refspec: string, path: string): Promise
export interface Blob {
text: string;
binary: boolean;
- // True when the file was too large to render and `text` holds only the head.
truncated: boolean;
bytes: number;
}
-// Files above this are not rendered in full. A viewer page holds the whole blob
-// in memory twice (raw + HTML-escaped), so an unbounded cap is a memory DoS any
-// pusher can trigger.
const MAX_BLOB_RENDER_BYTES = 2 * 1024 * 1024;
export async function blob(ref: RepoRef, refspec: string, path: string): Promise<Blob | null> {
@@ -439,17 +845,13 @@ export async function blob(ref: RepoRef, refspec: string, path: string): Promise
}
export interface Readme {
- path: string; // the filename as committed, e.g. "ReadMe.md"
+ path: string;
text: string;
}
-// README filenames we'll render, matched case-insensitively. An extensionless
-// README is accepted too — it's still conventionally Markdown.
const README = /^readme(\.(?:md|markdown|mdown|mkd))?$/i;
const README_MD = /^readme\.(?:md|markdown|mdown|mkd)$/i;
-// Fetch the README at the root of `refspec`'s tree. Prefers an explicit
-// Markdown extension when a repo carries both `README` and `README.md`.
export async function readme(ref: RepoRef, refspec: string): Promise<Readme | null> {
const entries = await tree(ref, refspec, "");
const blobs = entries.filter((e) => e.type === "blob");
@@ -461,7 +863,6 @@ export async function readme(ref: RepoRef, refspec: string): Promise<Readme | nu
return { path: hit.name, text: content.text };
}
-// The repo's `description` file (git's own), or "" when unset.
export async function description(ref: RepoRef): Promise<string> {
return readDescription(refDir(ref));
}
@@ -473,8 +874,6 @@ export interface CommitDetail extends Commit {
}
export async function commit(ref: RepoRef, shaRaw: string): Promise<CommitDetail | null> {
- // `sha` lands in an argv slot, so it has to be an object id and nothing else.
- // Without this, `--output=<path>` reaches git show and writes a file as us.
const sha = safeObjectId(shaRaw);
if (!sha) return null;
diff --git a/src/markdown.ts b/src/markdown.ts
index 437f5bb..d3d6d41 100644
--- a/src/markdown.ts
+++ b/src/markdown.ts
@@ -22,13 +22,6 @@ export function escapeHtml(s: string): string {
.replace(/"/g, """);
}
-// ---- inline -----------------------------------------------------------------
-
-// Generated fragments (code spans, links, images) are parked in a stash and
-// referenced by a NUL-delimited index, so later passes can't see inside them —
-// a bare-URL autolink must not rewrite the href of a link we already built, and
-// emphasis must not fire inside a code span. NULs are stripped from the source
-// up front, so the markers are unambiguous.
type Stash = string[];
function park(s: Stash, html: string): string {
@@ -37,7 +30,6 @@ function park(s: Stash, html: string): string {
}
function unpark(text: string, s: Stash): string {
- // Fragments nest (a code span inside a link label), so expand repeatedly.
let out = text;
for (let pass = 0; pass < 5 && out.includes("\x00"); pass++) {
out = out.replace(/\x00(\d+)\x00/g, (_m, n) => s[Number(n)] ?? "");
@@ -47,23 +39,15 @@ function unpark(text: string, s: Stash): string {
const ABSOLUTE = /^[a-z][a-z0-9+.-]*:/i;
-// Allow http(s), mailto and relative URLs; drop every other scheme so a README
-// can't smuggle `javascript:` into an href. The input is already HTML-escaped,
-// which means quotes can't break out of the attribute and an entity-obfuscated
-// scheme (`javascript:`) stays inert literal text.
function safeUrl(raw: string): string | null {
const url = raw.trim();
if (!url) return null;
if (ABSOLUTE.test(url)) return /^(?:https?|mailto):/i.test(url) ? url : null;
- // `//host` and `\\host` are scheme-relative, not relative: they leave the
- // site while looking local. A README link that means to go off-site can say
- // so with a scheme.
if (/^[/\\]{2}/.test(url)) return null;
return url;
}
function linkAttrs(href: string): string {
- // Untrusted outbound links: no referrer, no window handle, no PageRank.
return ABSOLUTE.test(href) ? ` rel="nofollow noopener noreferrer"` : "";
}
@@ -81,18 +65,10 @@ function inline(src: string): string {
const s: Stash = [];
let text = escapeHtml(src.replace(/\x00/g, ""));
- // Code spans first — nothing inside them is markup.
text = text.replace(/(`+)([\s\S]+?)\1/g, (_m, _ticks, code: string) =>
park(s, `<code>${code.trim()}</code>`),
);
- // Raw HTML. Nothing is ever passed through; the tags are dropped and the text
- // they wrapped is kept, which is what a README carrying `<p align="center">`
- // or `<details>` actually wants — showing the escaped source instead just
- // looks broken. `<br>` is the one tag worth honouring, and we emit our own.
- // Code spans are already parked above, so `` `<div>` `` still displays.
- // Prose that mentions a bare tag outside backticks loses it; that's the
- // trade, and backticks are the fix.
text = text.replace(/<!--[\s\S]*?-->/g, "");
text = text.replace(/<br\s*\/?>/gi, () => park(s, "<br>"));
text = text.replace(
@@ -100,7 +76,6 @@ function inline(src: string): string {
"",
);
- // Images before links: `` also matches the link pattern.
text = text.replace(
/!\[([^\]]*)\]\(\s*((?:[^()\s]|\([^()\s]*\))+)(?:\s+"(.*?)")?\s*\)/g,
(_m, alt: string, url: string, title?: string) => {
@@ -111,9 +86,6 @@ function inline(src: string): string {
},
);
- // One level of balanced parens is allowed in a URL — `…/Foo_(bar)` links are
- // common, and matching them here also means a `javascript:alert(1)` target
- // reaches safeUrl and gets dropped rather than surviving as literal text.
text = text.replace(
/\[([^\]]*)\]\(\s*((?:[^()\s]|\([^()\s]*\))+)(?:\s+"(.*?)")?\s*\)/g,
(_m, label: string, url: string, title?: string) => {
@@ -125,13 +97,11 @@ function inline(src: string): string {
},
);
- // Angle autolinks: `<https://…>`, already escaped to `<…>`.
text = text.replace(
/<((?:https?:\/\/|mailto:)\S+?)>/g,
(_m, url: string) => park(s, `<a href="${url}"${linkAttrs(url)}>${url}</a>`),
);
- // Bare URLs. The trailing class keeps sentence punctuation out of the link.
text = text.replace(
/(^|[\s(])(https?:\/\/[^\s<>()]*[^\s<>().,:!?'"])/g,
(_m, pre: string, url: string) =>
@@ -141,8 +111,6 @@ function inline(src: string): string {
return unpark(emphasis(text), s);
}
-// Join a paragraph's lines, honouring hard breaks (two trailing spaces, or a
-// trailing backslash).
function paragraph(lines: string[]): string {
return lines
.map((line, i) => {
@@ -152,16 +120,12 @@ function paragraph(lines: string[]): string {
.join("\n");
}
-// ---- blocks -----------------------------------------------------------------
-
const LIST_ITEM = /^(\s*)([-*+]|\d{1,9}[.)])\s+(.*)$/;
const ATX = /^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$/;
const FENCE = /^\s{0,3}(`{3,}|~{3,})\s*(\S*).*$/;
const RULE = /^\s{0,3}([-*_])[ \t]*(?:\1[ \t]*){2,}$/;
const QUOTE = /^\s{0,3}>/;
-// Line access that reads past the end as a blank line — which every block rule
-// below already treats as a terminator, so the bounds check comes for free.
function at(lines: string[], i: number): string {
return lines[i] ?? "";
}
@@ -170,10 +134,6 @@ function indentOf(line: string): number {
return /^\s*/.exec(line)?.[0].length ?? 0;
}
-// A line consisting only of HTML tags (`<p align="center">`, `</div>`, `<br>`).
-// We never emit raw HTML, and printing the escaped source would just be noise,
-// so these are dropped. The tag-name pattern is deliberately strict so an
-// autolink like `<https://example.com>` isn't mistaken for markup.
const HTML_ONLY = /^(?:<\/?[a-zA-Z][a-zA-Z0-9-]*(?:\s[^<>]*)?\/?>\s*)+$/;
function isHtmlOnly(line: string): boolean {
@@ -181,7 +141,6 @@ function isHtmlOnly(line: string): boolean {
return t.startsWith("<") && HTML_ONLY.test(t);
}
-// Does this line interrupt a paragraph?
function isBlockStart(line: string): boolean {
return (
FENCE.test(line) ||
@@ -207,11 +166,6 @@ function splitRow(line: string): string[] {
.map((cell) => cell.trim().replace(/\\\|/g, "|"));
}
-// A column's alignment travels as a data attribute, not an inline style: the
-// Content-Security-Policy's `style-src 'self'` blocks style attributes, so an
-// inline text-align was silently discarded and every column rendered left.
-// The matching rules live beside the other README table styles in app.css.ts.
-// Left needs no marker — the base `th, td` rule already aligns left.
function alignOf(cell: string): string {
const left = cell.startsWith(":");
const right = cell.endsWith(":");
@@ -247,7 +201,7 @@ function table(lines: string[], start: number): [string, number] {
function list(lines: string[], start: number): [string, number] {
const first = LIST_ITEM.exec(at(lines, start));
- if (!first) return ["", start + 1]; // unreachable: callers test first
+ if (!first) return ["", start + 1];
const bullet = first[2] ?? "-";
const baseIndent = (first[1] ?? "").length;
const ordered = /\d/.test(bullet);
@@ -264,7 +218,6 @@ function list(lines: string[], start: number): [string, number] {
const line = at(lines, i);
if (!line.trim()) {
- // A blank line ends the list unless the next line continues an item.
const next = at(lines, i + 1);
if (!next.trim()) break;
if (!LIST_ITEM.test(next) && indentOf(next) <= baseIndent) break;
@@ -276,15 +229,12 @@ function list(lines: string[], start: number): [string, number] {
const marker = LIST_ITEM.exec(line);
const indent = indentOf(line);
- // Allow a space of jitter so `- a` / ` - b` stay siblings.
if (marker && indent <= baseIndent + 1) {
flush();
item = [marker[3] ?? ""];
i++;
continue;
}
- // Deeper content belongs to the current item; dedent so the recursive
- // parse sees a nested list / paragraph / code block at column zero.
if (indent > baseIndent && item) {
item.push(line.slice(Math.min(indent, baseIndent + 2)));
i++;
@@ -301,7 +251,6 @@ function list(lines: string[], start: number): [string, number] {
const checkbox = task
? `<input type="checkbox" disabled${task[1] === " " ? "" : " checked"}> `
: "";
- // Tight items: unwrap a leading single paragraph so `<li>` reads inline.
const rendered = blocks(body).replace(/^<p>([\s\S]*?)<\/p>(?=\n<|$)/, "$1");
return `<li>${checkbox}${rendered}</li>`;
})
@@ -334,12 +283,11 @@ function blocks(lines: string[]): string {
const buf: string[] = [];
i++;
while (i < lines.length && !close.test(at(lines, i))) buf.push(at(lines, i++));
- i++; // consume the closing fence (or run off the end)
+ i++;
out.push(`<pre><code>${escapeHtml(buf.join("\n"))}</code></pre>`);
continue;
}
- // HTML comments: drop, possibly across several lines.
if (line.trimStart().startsWith("<!--")) {
while (i < lines.length && !at(lines, i).includes("-->")) i++;
i++;
@@ -360,8 +308,6 @@ function blocks(lines: string[]): string {
continue;
}
- // Setext headings. The `---` form is checked after RULE above, so a bare
- // rule on its own line still wins.
const under = at(lines, i + 1);
if (!isBlockStart(line)) {
if (/^\s{0,3}=+\s*$/.test(under)) {
@@ -400,11 +346,9 @@ function blocks(lines: string[]): string {
continue;
}
- // Indented code block.
if (/^ {4}\S/.test(line)) {
const buf: string[] = [];
while (i < lines.length && (/^ {4}/.test(at(lines, i)) || !at(lines, i).trim())) {
- // A blank line only stays in the block if indented code resumes after it.
if (!at(lines, i).trim() && !/^ {4}/.test(at(lines, i + 1))) break;
buf.push(at(lines, i).slice(4));
i++;
@@ -424,7 +368,6 @@ function blocks(lines: string[]): string {
i++;
}
if (buf.length === 0) {
- // A `<`-leading line that wasn't tag-only: keep it as escaped text.
buf.push(line);
i++;
}
@@ -437,14 +380,11 @@ function blocks(lines: string[]): string {
export function renderMarkdown(src: string): string {
const lines = src
.replace(/\r\n?/g, "\n")
- // Strip control characters (keeping tab + newline) so the stash markers
- // used during inline rendering can't collide with document content.
.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g, "")
.split("\n");
return blocks(lines);
}
-// Strip inline markup down to readable text.
function flatten(s: string): string {
const paren = "(?:[^()]|\\([^()]*\\))*";
return s
@@ -457,10 +397,6 @@ function flatten(s: string): string {
.trim();
}
-// A one-line plain-text snippet for <meta> descriptions: the README's first
-// paragraph of actual prose. Headings, badges, lists, tables and code are
-// skipped — the opening heading is nearly always just the repo name, which the
-// page title already carries.
export function plainSummary(src: string, max = 180): string {
const text = src
.replace(/\r\n?/g, "\n")
@@ -477,13 +413,11 @@ export function plainSummary(src: string, max = 180): string {
QUOTE.test(first) ||
LIST_ITEM.test(first) ||
isHtmlOnly(first) ||
- // Setext heading, or a table's header row.
/^\s{0,3}(?:=+|-+)\s*$/.test(lines[1] ?? "") ||
isDelimiterRow(lines[1] ?? "")
) {
continue;
}
- // An images-only block (a row of badges) flattens to nothing; keep looking.
const flat = flatten(lines.join(" "));
if (!flat) continue;
return flat.length <= max
diff --git a/src/mirror.ts b/src/mirror.ts
new file mode 100644
index 0000000..8cc7c1f
--- /dev/null
+++ b/src/mirror.ts
@@ -0,0 +1,339 @@
+/* src/mirror.ts */
+//
+// Backup / mirror status: does the copy on GitHub or Codeberg still exist, and
+// do its refs match this one?
+//
+// This is a monitor, not a synchroniser. Nothing here pushes, fetches objects,
+// creates, repairs or deletes anything on a remote. It reads `git ls-remote`
+// and compares SHAs, and that is the whole of it.
+//
+// Cached in SQLite rather than on the filesystem, unlike the links themselves
+// (git.ts). A check result is derived, ephemeral, and safe to lose: dropping it
+// costs one re-check. That is the definition of application metadata, so it
+// lives on the SQLite side of the line and is cleared through repometa.ts.
+
+import { db, now } from "./db.ts";
+import {
+ lsRemote,
+ localMirrorRefs,
+ hasCommit,
+ isAncestor,
+ refSlug,
+ type RepoRef,
+ type MirrorLink,
+} from "./git.ts";
+import type { MirrorKind } from "./urls.ts";
+
+db.exec(`
+ CREATE TABLE IF NOT EXISTS mirror_status (
+ owner TEXT NOT NULL,
+ repo TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ checked_at INTEGER NOT NULL,
+ error TEXT,
+ ok_at INTEGER,
+ state TEXT,
+ local_sha TEXT,
+ remote_sha TEXT,
+ detail TEXT,
+ PRIMARY KEY (owner, repo, kind)
+ );
+`);
+
+export type MirrorState =
+ | "synced"
+ | "ahead"
+ | "behind"
+ | "diverged"
+ | "out_of_sync"
+ | "denied"
+ | "missing";
+
+export interface MirrorStatus {
+ kind: string;
+ checkedAt: number;
+ error: string | null;
+ okAt: number | null;
+ state: MirrorState | null;
+ localSha: string | null;
+ remoteSha: string | null;
+ detail: string | null;
+}
+
+interface Row {
+ kind: string;
+ checked_at: number;
+ error: string | null;
+ ok_at: number | null;
+ state: string | null;
+ local_sha: string | null;
+ remote_sha: string | null;
+ detail: string | null;
+}
+
+function toStatus(row: Row): MirrorStatus {
+ return {
+ kind: row.kind,
+ checkedAt: row.checked_at,
+ error: row.error,
+ okAt: row.ok_at,
+ state: (row.state as MirrorState | null) ?? null,
+ localSha: row.local_sha,
+ remoteSha: row.remote_sha,
+ detail: row.detail,
+ };
+}
+
+export function getStatuses(ref: RepoRef): Map<string, MirrorStatus> {
+ const rows = db
+ .prepare(
+ `SELECT kind, checked_at, error, ok_at, state, local_sha, remote_sha, detail
+ FROM mirror_status WHERE owner = ? AND repo = ?`,
+ )
+ .all(ref.owner, ref.name) as unknown as Row[];
+ return new Map(rows.map((r) => [r.kind, toStatus(r)]));
+}
+
+function recordSuccess(
+ ref: RepoRef,
+ kind: MirrorKind,
+ result: {
+ state: MirrorState;
+ localSha: string | null;
+ remoteSha: string | null;
+ detail: string;
+ },
+): void {
+ const ts = now();
+ db.prepare(
+ `INSERT INTO mirror_status
+ (owner, repo, kind, checked_at, error, ok_at, state, local_sha, remote_sha, detail)
+ VALUES (?, ?, ?, ?, NULL, ?, ?, ?, ?, ?)
+ ON CONFLICT (owner, repo, kind) DO UPDATE SET
+ checked_at = excluded.checked_at,
+ error = NULL,
+ ok_at = excluded.ok_at,
+ state = excluded.state,
+ local_sha = excluded.local_sha,
+ remote_sha = excluded.remote_sha,
+ detail = excluded.detail`,
+ ).run(
+ ref.owner, ref.name, kind, ts, ts,
+ result.state, result.localSha, result.remoteSha, result.detail,
+ );
+}
+
+function recordFailure(ref: RepoRef, kind: MirrorKind, error: string): void {
+ const message = error.slice(0, 200);
+ db.prepare(
+ `INSERT INTO mirror_status (owner, repo, kind, checked_at, error)
+ VALUES (?, ?, ?, ?, ?)
+ ON CONFLICT (owner, repo, kind) DO UPDATE SET
+ checked_at = excluded.checked_at,
+ error = excluded.error`,
+ ).run(ref.owner, ref.name, kind, now(), message);
+}
+
+export function dropMirrorStatus(ref: RepoRef): void {
+ db.prepare("DELETE FROM mirror_status WHERE owner = ? AND repo = ?").run(
+ ref.owner,
+ ref.name,
+ );
+}
+
+export function dropMirrorStatusKind(ref: RepoRef, kind: string): void {
+ db.prepare(
+ "DELETE FROM mirror_status WHERE owner = ? AND repo = ? AND kind = ?",
+ ).run(ref.owner, ref.name, kind);
+}
+
+export function markStale(ref: RepoRef): void {
+ db.prepare(
+ "UPDATE mirror_status SET checked_at = 0 WHERE owner = ? AND repo = ?",
+ ).run(ref.owner, ref.name);
+}
+
+export function parseLsRemote(text: string): Map<string, string> {
+ const out = new Map<string, string>();
+ for (const line of text.split("\n")) {
+ const tab = line.indexOf("\t");
+ if (tab === -1) continue;
+ const sha = line.slice(0, tab).trim();
+ const name = line.slice(tab + 1).trim();
+ if (!/^[0-9a-f]{7,64}$/i.test(sha)) continue;
+ if (name.endsWith("^{}")) continue;
+ if (!name.startsWith("refs/heads/") && !name.startsWith("refs/tags/")) continue;
+ out.set(name, sha);
+ }
+ return out;
+}
+
+export interface Comparison {
+ matched: number;
+ total: number;
+ missingRemote: string[];
+ missingLocal: string[];
+ differing: string[];
+}
+
+export function compareRefs(
+ local: Map<string, string>,
+ remote: Map<string, string>,
+): Comparison {
+ const names = new Set([...local.keys(), ...remote.keys()]);
+ const cmp: Comparison = {
+ matched: 0,
+ total: names.size,
+ missingRemote: [],
+ missingLocal: [],
+ differing: [],
+ };
+ for (const name of names) {
+ const a = local.get(name);
+ const b = remote.get(name);
+ if (a && !b) cmp.missingRemote.push(name);
+ else if (!a && b) cmp.missingLocal.push(name);
+ else if (a === b) cmp.matched++;
+ else cmp.differing.push(name);
+ }
+ cmp.missingRemote.sort();
+ cmp.missingLocal.sort();
+ cmp.differing.sort();
+ return cmp;
+}
+
+export function rollUp(
+ cmp: Comparison,
+ headVerdict: MirrorState | null,
+): MirrorState {
+ if (cmp.total === 0) return "synced";
+ if (cmp.matched === cmp.total) return "synced";
+ if (headVerdict && headVerdict !== "synced") return headVerdict;
+
+ const onlyWeHaveExtra = cmp.missingLocal.length === 0 && cmp.differing.length === 0;
+ const onlyTheyHaveExtra = cmp.missingRemote.length === 0 && cmp.differing.length === 0;
+ if (onlyWeHaveExtra) return "ahead";
+ if (onlyTheyHaveExtra) return "behind";
+ return "out_of_sync";
+}
+
+export async function ancestryVerdict(
+ ref: RepoRef,
+ localSha: string | null,
+ remoteSha: string | null,
+): Promise<MirrorState | null> {
+ if (!localSha || !remoteSha) return null;
+ if (localSha === remoteSha) return "synced";
+ if (!(await hasCommit(ref, remoteSha))) return "out_of_sync";
+ if (await isAncestor(ref, remoteSha, localSha)) return "ahead";
+ if (await isAncestor(ref, localSha, remoteSha)) return "behind";
+ return "diverged";
+}
+
+export const FRESH_FOR_SECONDS = 6 * 3600;
+const MIN_INTERVAL_SECONDS = 60;
+
+const inFlight = new Set<string>();
+
+function key(ref: RepoRef, kind: string): string {
+ return `${refSlug(ref)}/${kind}`;
+}
+
+export function needsCheck(status: MirrorStatus | undefined): boolean {
+ if (!status) return true;
+ if (status.checkedAt === 0) return true;
+ if (status.okAt === null) return true;
+ return now() - status.okAt > FRESH_FOR_SECONDS;
+}
+
+export async function checkMirror(
+ ref: RepoRef,
+ link: MirrorLink,
+): Promise<boolean> {
+ if (link.isPrivate) return false;
+
+ const k = key(ref, link.kind);
+ if (inFlight.has(k)) return false;
+
+ const existing = getStatuses(ref).get(link.kind);
+ if (
+ existing &&
+ existing.checkedAt > 0 &&
+ now() - existing.checkedAt < MIN_INTERVAL_SECONDS
+ ) {
+ return false;
+ }
+
+ inFlight.add(k);
+ try {
+ const remoteResult = await lsRemote(link.url);
+ if (!remoteResult.ok) {
+ if (remoteResult.kind === "denied" || remoteResult.kind === "missing") {
+ recordSuccess(ref, link.kind, {
+ state: remoteResult.kind,
+ localSha: null,
+ remoteSha: null,
+ detail:
+ remoteResult.kind === "denied"
+ ? "not readable without credentials"
+ : "no such repository",
+ });
+ } else {
+ recordFailure(ref, link.kind, remoteResult.message);
+ }
+ return true;
+ }
+
+ const remote = parseLsRemote(remoteResult.text);
+ const local = await localMirrorRefs(ref);
+ const cmp = compareRefs(local, remote);
+
+ const head = await defaultBranchRef(ref, local);
+ const localHead = head ? (local.get(head) ?? null) : null;
+ const remoteHead = head ? (remote.get(head) ?? null) : null;
+ const headVerdict = await ancestryVerdict(ref, localHead, remoteHead);
+
+ recordSuccess(ref, link.kind, {
+ state: rollUp(cmp, headVerdict),
+ localSha: localHead,
+ remoteSha: remoteHead,
+ detail: `${cmp.matched}/${cmp.total} refs`,
+ });
+ return true;
+ } catch (err) {
+ recordFailure(
+ ref,
+ link.kind,
+ err instanceof Error ? err.message : "check failed",
+ );
+ return true;
+ } finally {
+ inFlight.delete(k);
+ }
+}
+
+async function defaultBranchRef(
+ ref: RepoRef,
+ local: Map<string, string>,
+): Promise<string | null> {
+ const { listRefs } = await import("./git.ts");
+ try {
+ const refs = await listRefs(ref);
+ const head = `refs/heads/${refs.head}`;
+ if (local.has(head)) return head;
+ } catch {
+ }
+ for (const name of local.keys()) {
+ if (name.startsWith("refs/heads/")) return name;
+ }
+ return null;
+}
+
+export async function checkAllMirrors(
+ ref: RepoRef,
+ links: MirrorLink[],
+): Promise<void> {
+ for (const link of links) {
+ await checkMirror(ref, link);
+ }
+}
diff --git a/src/notify.ts b/src/notify.ts
new file mode 100644
index 0000000..d85a328
--- /dev/null
+++ b/src/notify.ts
@@ -0,0 +1,229 @@
+/* src/notify.ts */
+//
+// Discord notifications for the three things this forge actually has:
+// a repository appearing, a repository being deleted, and commits arriving.
+//
+// Deliberately not an event bus. There are three events and four call sites, so
+// an abstraction over them would be more code than the thing it abstracts, and
+// harder to follow. Each function below is called explicitly from the route or
+// hook that knows the event happened.
+//
+// The hard rule for this whole module: **a notification must never fail, delay
+// or otherwise affect a git operation.** Every entry point catches everything,
+// nothing is awaited by a request handler, and delivery has a hard timeout.
+
+import {
+ refSlug,
+ logRange,
+ isAncestor,
+ type Commit,
+ type RepoRef,
+} from "./git.ts";
+import { getSettings, recordWebhookResult } from "./settings.ts";
+import { config } from "./config.ts";
+import { discordWebhookUrl } from "./urls.ts";
+
+const MAX_COMMITS_SHOWN = 10;
+const MAX_REFS_SHOWN = 5;
+const DELIVERY_TIMEOUT_MS = 5000;
+
+const COLOUR_GOOD = 0xf5a9b8;
+const COLOUR_WARN = 0xd15f8c;
+
+export interface RefChange {
+ ref: string;
+ before: string | null;
+ after: string | null;
+ forced: boolean;
+ commits: Commit[];
+}
+
+export async function diffRefs(
+ repo: RepoRef,
+ before: Map<string, string>,
+ after: Map<string, string>,
+): Promise<RefChange[]> {
+ const names = new Set([...before.keys(), ...after.keys()]);
+ const changes: RefChange[] = [];
+
+ for (const ref of names) {
+ const a = before.get(ref) ?? null;
+ const b = after.get(ref) ?? null;
+ if (a === b) continue;
+
+ let forced = false;
+ let commits: Commit[] = [];
+
+ if (b === null) {
+ } else if (a === null) {
+ commits = await logRange(repo, null, b, MAX_COMMITS_SHOWN + 1);
+ } else {
+ forced = !(await isAncestor(repo, a, b));
+ commits = await logRange(repo, forced ? null : a, b, MAX_COMMITS_SHOWN + 1);
+ }
+ changes.push({ ref, before: a, after: b, forced, commits });
+ }
+
+ changes.sort((x, y) => x.ref.localeCompare(y.ref));
+ return changes;
+}
+
+export interface Embed {
+ title: string;
+ url?: string;
+ description: string;
+ color: number;
+}
+
+function shortRef(ref: string): string {
+ return ref.replace(/^refs\/heads\//, "").replace(/^refs\/tags\//, "tag ");
+}
+
+function repoUrl(repo: RepoRef): string {
+ return `${config.baseUrl}/${repo.owner}/${repo.name}`;
+}
+
+function noMarkdown(s: string): string {
+ return s.replace(/[\\`*_~|>[\]()#-]/g, "\\$&").replace(/\s+/g, " ").trim();
+}
+
+export function repoCreatedEmbed(repo: RepoRef, actor: string): Embed {
+ return {
+ title: `📁 ${refSlug(repo)} created`,
+ url: repoUrl(repo),
+ description: `by ${noMarkdown(actor)}`,
+ color: COLOUR_GOOD,
+ };
+}
+
+export function repoDeletedEmbed(repo: RepoRef, actor: string): Embed {
+ return {
+ title: `🗑️ ${refSlug(repo)} deleted`,
+ description:
+ `by ${noMarkdown(actor)} — recoverable from Recently Deleted until it is purged.`,
+ color: COLOUR_WARN,
+ };
+}
+
+export function pushEmbed(
+ repo: RepoRef,
+ actor: string,
+ changes: RefChange[],
+): Embed | null {
+ if (changes.length === 0) return null;
+
+ const forced = changes.some((ch) => ch.forced);
+ const lines: string[] = [];
+
+ for (const ch of changes.slice(0, MAX_REFS_SHOWN)) {
+ const name = noMarkdown(shortRef(ch.ref));
+
+ if (ch.after === null) {
+ lines.push(`🔥 deleted \`${name}\``);
+ continue;
+ }
+ if (ch.before === null) {
+ lines.push(`✨ new \`${name}\``);
+ } else if (ch.forced) {
+ lines.push(`⚠️ force-pushed \`${name}\``);
+ } else {
+ lines.push(`\`${name}\``);
+ }
+
+ const shown = ch.commits.slice(0, MAX_COMMITS_SHOWN);
+ for (const commit of shown) {
+ const sha = commit.hash.slice(0, 7);
+ lines.push(
+ ` [\`${sha}\`](${repoUrl(repo)}/commit/${commit.hash}) ` +
+ `${noMarkdown(commit.subject).slice(0, 100)} — ${noMarkdown(commit.author)}`,
+ );
+ }
+ if (ch.commits.length > MAX_COMMITS_SHOWN) {
+ lines.push(` …and more`);
+ }
+ }
+ if (changes.length > MAX_REFS_SHOWN) {
+ lines.push(`…and ${changes.length - MAX_REFS_SHOWN} more refs`);
+ }
+
+ return {
+ title: `${forced ? "⚠️ " : "⬆️ "}${refSlug(repo)} updated`,
+ url: repoUrl(repo),
+ description: `pushed by ${noMarkdown(actor)}\n${lines.join("\n")}`.slice(0, 4000),
+ color: forced ? COLOUR_WARN : COLOUR_GOOD,
+ };
+}
+
+async function deliver(owner: string, isPublic: boolean, embed: Embed | null): Promise<void> {
+ if (!embed) return;
+
+ const settings = getSettings(owner);
+ if (!settings.discordWebhook) return;
+
+ const target = discordWebhookUrl(settings.discordWebhook);
+ if (!target) {
+ recordWebhookResult(owner, "stored webhook is not a valid Discord URL");
+ console.warn(`[notify] refusing to deliver for ${owner}: stored webhook failed validation`);
+ return;
+ }
+ if (!isPublic && !settings.discordPrivate) return;
+
+ try {
+ const response = await fetch(target, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ embeds: [embed] }),
+ signal: AbortSignal.timeout(DELIVERY_TIMEOUT_MS),
+ redirect: "error",
+ });
+ if (!response.ok) {
+ recordWebhookResult(owner, `HTTP ${response.status}`);
+ console.warn(
+ `[notify] discord delivery for ${owner} failed: HTTP ${response.status}`,
+ );
+ return;
+ }
+ recordWebhookResult(owner, null);
+ } catch (err) {
+ const message =
+ err instanceof Error
+ ? err.name === "TimeoutError"
+ ? "timed out"
+ : err.message.slice(0, 120)
+ : "delivery failed";
+ recordWebhookResult(owner, message);
+ console.warn(`[notify] discord delivery for ${owner} failed: ${message}`);
+ }
+}
+
+function fireAndForget(owner: string, isPublic: boolean, embed: Embed | null): void {
+ void deliver(owner, isPublic, embed).catch((err) => {
+ console.warn(`[notify] unexpected delivery error for ${owner}:`, err);
+ });
+}
+
+export function notifyRepoCreated(repo: RepoRef, actor: string, isPublic: boolean): void {
+ fireAndForget(repo.owner, isPublic, repoCreatedEmbed(repo, actor));
+}
+
+export function notifyRepoDeleted(repo: RepoRef, actor: string, isPublic: boolean): void {
+ fireAndForget(repo.owner, isPublic, repoDeletedEmbed(repo, actor));
+}
+
+export function notifyPush(
+ repo: RepoRef,
+ actor: string,
+ isPublic: boolean,
+ before: Map<string, string>,
+ after: Map<string, string>,
+): void {
+ void (async () => {
+ try {
+ const changes = await diffRefs(repo, before, after);
+ if (changes.length === 0) return;
+ fireAndForget(repo.owner, isPublic, pushEmbed(repo, actor, changes));
+ } catch (err) {
+ console.warn(`[notify] could not describe push to ${refSlug(repo)}:`, err);
+ }
+ })();
+}
diff --git a/src/repometa.ts b/src/repometa.ts
new file mode 100644
index 0000000..014aaa1
--- /dev/null
+++ b/src/repometa.ts
@@ -0,0 +1,22 @@
+/* src/repometa.ts */
+//
+// Clearing the SQLite-side metadata that belongs to one repository.
+//
+// The filesystem is what says a repository exists; these tables only describe
+// one that does. When a repo goes away — deleted, or moved into the trash — its
+// rows have to go with it, or a later repo that happens to reuse the name
+// inherits them. access.ts already warns about exactly that for grants; the
+// mirror-status cache has the same hazard.
+//
+// This module exists so both sides of that invariant are named in one place.
+// It is deliberately not a metadata *framework*: it is one function, and it
+// grows a line when a new table becomes repo-scoped.
+
+import { dropRepoAccess } from "./access.ts";
+import { dropMirrorStatus } from "./mirror.ts";
+import type { RepoRef } from "./git.ts";
+
+export function clearRepoMetadata(ref: RepoRef): void {
+ dropRepoAccess(ref);
+ dropMirrorStatus(ref);
+}
diff --git a/src/server.ts b/src/server.ts
index 351dfee..3057513 100644
--- a/src/server.ts
+++ b/src/server.ts
@@ -33,10 +33,26 @@ import {
listCollaborators,
setCollaborator,
removeCollaborator,
- dropRepoAccess,
sharedWith,
type Access,
} from "./access.ts";
+import { clearRepoMetadata } from "./repometa.ts";
+import { notifyRepoCreated, notifyRepoDeleted, notifyPush } from "./notify.ts";
+import { getSettings, setDiscordWebhook, setPrefs } from "./settings.ts";
+import {
+ discordWebhookUrl,
+ mirrorUrl,
+ mirrorHost,
+ MIRROR_KINDS,
+ type MirrorKind,
+} from "./urls.ts";
+import {
+ getStatuses,
+ checkAllMirrors,
+ needsCheck,
+ markStale,
+ dropMirrorStatusKind,
+} from "./mirror.ts";
import {
safeRef,
refDir,
@@ -44,7 +60,12 @@ import {
repoExists,
initBareRepo,
createRepo,
- deleteRepo,
+ trashRepo,
+ listTrash,
+ restoreFromTrash,
+ purgeFromTrash,
+ purgeExpired,
+ trashHasName,
isRepoPublic,
setRepoPublic,
listRepos,
@@ -57,6 +78,10 @@ import {
readme,
description,
setDescription,
+ readLinks,
+ setLinks,
+ localMirrorRefs,
+ type MirrorLink,
type RepoRef,
type RepoSummary,
type RefList,
@@ -73,27 +98,14 @@ const app = new Hono<Env>({ strict: false });
const SITE_ORIGIN = new URL(config.baseUrl).origin;
-// The git transport authenticates with a token on every request and never with
-// a cookie, so the browser-only protections below skip it.
const GIT_RPC = /\/(?:git-upload-pack|git-receive-pack)$/;
-// Attach the logged-in user (if any) to every request.
-//
-// The cookie is signed and self-contained, so it stays valid for its full 30
-// days no matter what happens upstream. Re-anchoring it on the user directory
-// each request is what makes removing an account take effect now rather than a
-// month from now.
app.use("*", async (c, next) => {
const session = readSession(getCookie(c, SESSION_COOKIE));
c.set("user", session && "sub" in session ? currentUser(session) : null);
await next();
});
-// ---- response hardening -----------------------------------------------------
-
-// README content is attacker-controlled and rendered into these pages, so the
-// CSP is the backstop behind markdown.ts: no inline script, no plugins, and no
-// framing. Images are left open because READMEs legitimately hotlink badges.
const CSP = [
"default-src 'self'",
"script-src 'self'",
@@ -112,10 +124,6 @@ app.use("*", async (c, next) => {
if (GIT_RPC.test(c.req.path) || c.req.path.endsWith("/info/refs")) return;
c.header("Content-Security-Policy", CSP);
c.header("X-Content-Type-Options", "nosniff");
- // Not "no-referrer": under that policy a browser sends `Origin: null` on
- // same-origin form POSTs (Fetch, "append a request Origin header"), and no
- // Referer to fall back on, so the CSRF check below rejects every form on the
- // site. "same-origin" leaks nothing outward and keeps both headers intact.
c.header("Referrer-Policy", "same-origin");
c.header("X-Frame-Options", "DENY");
if (SITE_ORIGIN.startsWith("https://")) {
@@ -123,13 +131,6 @@ app.use("*", async (c, next) => {
}
});
-// ---- CSRF -------------------------------------------------------------------
-
-// Every state-changing form here is authorised by the session cookie alone, so
-// a cross-site POST would otherwise act as the signed-in user. SameSite=Lax
-// already blocks the common case; this closes the rest, and costs one header
-// comparison. A browser always sends Origin on POST, so a missing one is not a
-// browser form and has nothing to lose.
function sameOrigin(origin: string | undefined, referer: string | undefined): boolean {
if (origin) return origin === SITE_ORIGIN;
if (referer) {
@@ -153,8 +154,6 @@ app.use("*", async (c, next) => {
await next();
});
-// ---- static files (bring your own style.css) --------------------------------
-
const CONTENT_TYPES: Record<string, string> = {
".css": "text/css; charset=utf-8",
".js": "text/javascript; charset=utf-8",
@@ -167,9 +166,6 @@ const CONTENT_TYPES: Record<string, string> = {
const STATIC_ROOT = resolve(config.staticDir);
app.get("/static/*", (c) => {
- // Decode before checking: a `..` that arrives percent-encoded is still a
- // `..` by the time the filesystem sees it. Resolve, then prove the result is
- // still inside the static root rather than trusting the pattern match.
let rel: string;
try {
rel = decodeURIComponent(c.req.path.replace(/^\/static\//, ""));
@@ -196,8 +192,6 @@ app.get("/static/*", (c) => {
});
});
-// ---- auth -------------------------------------------------------------------
-
app.get("/auth/login", async (c) => {
if (!oidcEnabled) {
return c.html(
@@ -224,7 +218,6 @@ app.get("/auth/callback", async (c) => {
const tx = getCookie(c, OAUTH_COOKIE);
deleteCookie(c, OAUTH_COOKIE, { path: "/" });
- // If PocketID redirected back with an error, surface it directly.
const idpError = c.req.query("error");
if (idpError) {
console.error(
@@ -239,10 +232,6 @@ app.get("/auth/callback", async (c) => {
);
}
- // Behind the reverse proxy, c.req.url carries the internal host
- // (127.0.0.1:4010). The OIDC token exchange must use the SAME redirect_uri we
- // sent in the auth request, so rebuild the callback URL from the public base
- // URL, preserving the query (code, state, iss).
const currentUrl = `${config.baseUrl}/auth/callback${new URL(c.req.url).search}`;
let user = null;
@@ -286,16 +275,66 @@ app.get("/auth/logout", (c) => {
return c.redirect("/");
});
-// ---- token management (login required) --------------------------------------
+app.get("/settings", (c) => {
+ const user = c.get("user");
+ if (!user) return c.redirect("/auth/login");
+ return c.html(
+ view.settingsPage({
+ user,
+ settings: getSettings(view.ownerOf(user)),
+ saved: c.req.query("saved") ? "saved." : null,
+ }),
+ );
+});
+
+app.post("/settings/discord", async (c) => {
+ const user = c.get("user");
+ if (!user) return c.text("forbidden\n", 403);
+ const owner = view.ownerOf(user);
+ const form = await c.req.formData();
+ const raw = String(form.get("url") ?? "").trim();
+
+ if (!raw) {
+ setDiscordWebhook(owner, null);
+ return c.redirect("/settings?saved=1");
+ }
+ const url = discordWebhookUrl(raw);
+ if (!url) {
+ return c.html(
+ view.messagePage({
+ title: "not a discord webhook",
+ message:
+ "That doesn't look like a Discord webhook URL. It should start with " +
+ "https://discord.com/api/webhooks/ — nothing else is accepted.",
+ user,
+ }),
+ 400,
+ );
+ }
+ setDiscordWebhook(owner, url);
+ return c.redirect("/settings?saved=1");
+});
-app.get("/tokens", (c) => {
+app.post("/settings/prefs", async (c) => {
+ const user = c.get("user");
+ if (!user) return c.text("forbidden\n", 403);
+ const form = await c.req.formData();
+ setPrefs(view.ownerOf(user), {
+ defaultPrivate: form.get("default_private") != null,
+ discordPrivate: form.get("discord_private") != null,
+ mirrorAuto: form.get("mirror_auto") != null,
+ });
+ return c.redirect("/settings?saved=1");
+});
+
+app.get("/settings/tokens", (c) => {
const user = c.get("user");
if (!user) return c.redirect("/auth/login");
const owner = view.ownerOf(user);
return c.html(view.tokensPage({ tokens: listTokens(owner), user }));
});
-app.post("/tokens", async (c) => {
+app.post("/settings/tokens", async (c) => {
const user = c.get("user");
if (!user) return c.text("forbidden\n", 403);
const owner = view.ownerOf(user);
@@ -306,15 +345,82 @@ app.post("/tokens", async (c) => {
);
});
-app.post("/tokens/:id/revoke", (c) => {
+app.post("/settings/tokens/:id/revoke", (c) => {
const user = c.get("user");
if (!user) return c.text("forbidden\n", 403);
revokeToken(c.req.param("id"), view.ownerOf(user));
- return c.redirect("/tokens");
+ return c.redirect("/settings/tokens");
+});
+
+app.get("/tokens", (c) => c.redirect("/settings/tokens", 301));
+
+app.get("/settings/deleted", async (c) => {
+ const user = c.get("user");
+ if (!user) return c.redirect("/auth/login");
+ const owner = view.ownerOf(user);
+
+ for (const gone of await purgeExpired(owner)) {
+ clearRepoMetadata({ owner, name: gone.name });
+ console.log(`[trash] purged ${owner}/${gone.name} past retention`);
+ }
+
+ return c.html(
+ view.deletedPage({
+ user,
+ entries: await listTrash(owner),
+ retentionDays: config.trashDays,
+ }),
+ );
+});
+
+app.post("/settings/deleted/restore", async (c) => {
+ const user = c.get("user");
+ if (!user) return c.text("forbidden\n", 403);
+ const owner = view.ownerOf(user);
+ const form = await c.req.formData();
+
+ const result = await restoreFromTrash(owner, String(form.get("entry") ?? ""));
+ if (!result.ok || !result.meta) {
+ return c.html(
+ view.messagePage({
+ title: "could not restore",
+ message: result.error ?? "unknown error",
+ user,
+ }),
+ 400,
+ );
+ }
+
+ const ref = { owner, name: result.meta.name };
+ for (const grant of result.meta.grants) {
+ if (!isLevel(grant.level)) continue;
+ if (!findUserBySlug(grant.slug)) {
+ console.warn(
+ `[trash] restoring ${refSlug(ref)}: dropping grant for unknown user ${grant.slug}`,
+ );
+ continue;
+ }
+ setCollaborator(ref, grant.slug, grant.level);
+ }
+
+ console.log(`[trash] restored ${refSlug(ref)}`);
+ return c.redirect(`/${ref.owner}/${ref.name}/`);
});
-// ---- repo creation (login required) -----------------------------------------
-// Repos are always created under the logged-in user's own username.
+app.post("/settings/deleted/purge", async (c) => {
+ const user = c.get("user");
+ if (!user) return c.text("forbidden\n", 403);
+ const owner = view.ownerOf(user);
+ const form = await c.req.formData();
+ const entry = String(form.get("entry") ?? "");
+
+ const found = (await listTrash(owner)).find((e) => e.entry === entry);
+ if (await purgeFromTrash(owner, entry)) {
+ if (found) clearRepoMetadata({ owner, name: found.name });
+ console.log(`[trash] purged ${owner}/${found?.name ?? entry}`);
+ }
+ return c.redirect("/settings/deleted");
+});
app.post("/new", async (c) => {
const user = c.get("user");
@@ -325,18 +431,22 @@ app.post("/new", async (c) => {
if (!result.ok || !result.ref) {
return c.html(
view.messagePage({
- title: "could not create repo",
+ title: result.reserved ? "that name is still reserved" : "could not create repo",
message: result.error ?? "unknown error",
user,
}),
- 400,
+ result.reserved ? 409 : 400,
);
}
+ clearRepoMetadata(result.ref);
+ const startsPublic = !getSettings(owner).defaultPrivate;
+ if (startsPublic) {
+ await setRepoPublic(result.ref, true);
+ }
+ notifyRepoCreated(result.ref, owner, startsPublic);
return c.redirect(`/${result.ref.owner}/${result.ref.name}/`);
});
-// ---- git smart HTTP ---------------------------------------------------------
-
const GIT_SERVICES: GitService[] = ["git-upload-pack", "git-receive-pack"];
function authChallenge(message = "authentication required"): Response {
@@ -346,9 +456,6 @@ function authChallenge(message = "authentication required"): Response {
});
}
-// Returns null when access is allowed, otherwise a short-circuit Response.
-// Auth is checked BEFORE existence so a valid push token can auto-create a
-// missing repo (and a missing private repo prompts rather than 404s).
async function gitGate(
c: { req: { header: (n: string) => string | undefined } },
ref: RepoRef,
@@ -358,8 +465,6 @@ async function gitGate(
const actor = gitActor(auth);
const exists = await repoExists(ref);
- // Bad credentials are a dead end, not a retry: re-prompting just loops the
- // credential helper past the same wrong username.
if (auth.kind === "rejected") {
console.warn(`[git] denied ${refSlug(ref)}: ${auth.message}`);
return new Response(`${auth.message}\n`, { status: 403 });
@@ -368,8 +473,6 @@ async function gitGate(
if (needPush) {
if (!actor) return authChallenge();
- // A repo that doesn't exist yet has no collaborators, so the only person
- // who can bring it into being is the owner of the namespace it names.
if (!exists) {
if (actor !== ref.owner) {
console.warn(`[git] denied create of ${refSlug(ref)} by ${actor}`);
@@ -378,11 +481,21 @@ async function gitGate(
{ 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 },
+ );
+ }
if (!config.autoCreate) {
return 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;
}
@@ -397,13 +510,10 @@ async function gitGate(
return null;
}
- // Reads. A private repo must not confirm its own existence to somebody with
- // no access, so "no access" and "no such repo" give the same 404.
if (exists) {
const isPublic = await isRepoPublic(ref);
if (canRead({ ref, isPublic, viewer: actor })) return null;
}
- // Prompt for credentials if none were offered — the repo may well be theirs.
if (auth.kind === "anonymous") return authChallenge();
return new Response("repository not found\n", { status: 404 });
}
@@ -424,27 +534,45 @@ async function rpcHandler(c: any, service: GitService): Promise<Response> {
if (!ref) return c.text("bad repo\n", 400);
const gate = await gitGate(c, ref, service === "git-receive-pack");
if (gate) return gate;
+
+ 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 isPublic = isPush ? await isRepoPublic(ref) : false;
+
return serviceRpc({
repoDir: refDir(ref),
service,
body: c.req.raw.body,
gzip: c.req.header("content-encoding") === "gzip",
+ onDone: isPush
+ ? (code) => {
+ if (code !== 0) {
+ console.warn(`[git] receive-pack for ${refSlug(ref)} exited ${code}`);
+ return;
+ }
+ void (async () => {
+ try {
+ const after = await localMirrorRefs(ref);
+ markStale(ref);
+ notifyPush(ref, actor ?? "unknown", isPublic, before, after);
+ } catch (err) {
+ console.warn(`[git] post-push processing failed for ${refSlug(ref)}:`, err);
+ }
+ })();
+ }
+ : undefined,
});
}
app.post("/:owner/:repo/git-upload-pack", (c) => rpcHandler(c, "git-upload-pack"));
app.post("/:owner/:repo/git-receive-pack", (c) => rpcHandler(c, "git-receive-pack"));
-// ---- viewer -----------------------------------------------------------------
-
-// The owner slug of whoever is browsing, or null when nobody is signed in.
function viewerOf(c: { get: (k: "user") => SessionUser | null }): string | null {
const user = c.get("user");
return user ? view.ownerOf(user) : null;
}
-// Filter a repo listing down to what this viewer may see. Public repos are in
-// for everybody; private ones only for their owner and invited collaborators.
function readable(all: RepoSummary[], viewer: string | null): RepoSummary[] {
return all.filter((r) =>
canRead({
@@ -478,12 +606,6 @@ function notFound(c: any) {
);
}
-// A repo the caller may look at, with what they may do to it. Null means 404 —
-// including when the repo exists but isn't theirs to know about.
-//
-// `rev` is the revision being viewed, taken from `?h=` and resolved against the
-// refs this repo actually has. It is never the raw query value, so it is safe
-// to pass to git.
interface ViewableRepo {
ref: RepoRef;
isPublic: boolean;
@@ -563,8 +685,6 @@ app.get("/:owner/:name/blob/:path{.*}", async (c) => {
app.get("/:owner/:name/commit/:sha", async (c) => {
const found = await viewable(c);
if (!found) return notFound(c);
- // commit() refuses anything that isn't an object id, so a `--option` in the
- // URL lands here as a 404 rather than as an argument to git.
const detail = await commit(found.ref, c.req.param("sha"));
if (!detail) return notFound(c);
return c.html(
@@ -577,11 +697,6 @@ app.get("/:owner/:name/commit/:sha", async (c) => {
);
});
-// ---- repo management --------------------------------------------------------
-
-// Resolve params for a management action. Visibility, deletion and the
-// collaborator list are the owner's alone: a write collaborator can push, but
-// cannot publish somebody else's repo or give away access to it.
async function ownedRef(c: any): Promise<RepoRef | null> {
const user = c.get("user");
if (!user) return null;
@@ -590,8 +705,6 @@ async function ownedRef(c: any): Promise<RepoRef | null> {
return (await repoExists(ref)) ? ref : null;
}
-// The description is repo content rather than repo governance, so anyone who
-// can push may edit it — the same people who could change it by committing.
async function writableRef(c: any): Promise<RepoRef | null> {
const ref = safeRef(c.req.param("owner"), c.req.param("name"));
if (!ref || !(await repoExists(ref))) return null;
@@ -618,11 +731,31 @@ app.post("/:owner/:name/visibility", async (c) => {
app.post("/:owner/:name/delete", async (c) => {
const ref = await ownedRef(c);
if (!ref) return notFound(c);
- await deleteRepo(ref);
- // Grants must not outlive the repo, or a rebuilt one of the same name would
- // silently come back shared.
- dropRepoAccess(ref);
- return c.redirect("/");
+ const user = c.get("user")!;
+ const wasPublic = await isRepoPublic(ref);
+
+ const result = await trashRepo(ref, {
+ deletedAt: Math.floor(Date.now() / 1000),
+ deletedBy: view.ownerOf(user),
+ grants: listCollaborators(ref).map((g) => ({
+ slug: g.slug,
+ level: g.level,
+ })),
+ });
+ if (!result.ok) {
+ return c.html(
+ view.messagePage({
+ title: "could not delete",
+ message: result.error ?? "unknown error",
+ user,
+ }),
+ 400,
+ );
+ }
+
+ clearRepoMetadata(ref);
+ notifyRepoDeleted(ref, view.ownerOf(user), wasPublic);
+ return c.redirect("/settings/deleted");
});
app.post("/:owner/:name/collaborators", async (c) => {
@@ -670,8 +803,6 @@ app.post("/:owner/:name/collaborators/remove", async (c) => {
return c.redirect(`/${ref.owner}/${ref.name}/`);
});
-// Profile page. Registered before the two-segment repo routes only for
-// readability — they differ in path length, so they can't collide.
app.get("/:owner", async (c) => {
const owner = c.req.param("owner");
if (!safeRef(owner, "x")) return notFound(c);
@@ -683,7 +814,6 @@ app.get("/:owner", async (c) => {
const repos = readable(owned, viewer);
const profile = findUserBySlug(owner);
- // Nobody by that name, and nothing of theirs to show.
if (!profile && owned.length === 0) return notFound(c);
return c.html(view.profilePage({ owner, profile, repos, user }));
});
@@ -693,15 +823,32 @@ app.get("/:owner/:name", async (c) => {
if (!found) return notFound(c);
const { ref, isPublic, access, refs, rev } = found;
- const [commits, desc] = await Promise.all([
+ const [commits, desc, links] = await Promise.all([
log(ref, rev, 1),
description(ref),
+ readLinks(ref),
]);
- // An empty repo has no tree to search, so skip the README lookup entirely.
const readmeFile = commits.length ? await readme(ref, rev) : null;
const user = c.get("user");
const isOwner = user != null && view.ownerOf(user) === ref.owner;
+ const canPush = access === "write";
+
+ const statuses = getStatuses(ref);
+ let localSha: string | null = null;
+ if (links.length > 0) {
+ const localRefs = await localMirrorRefs(ref);
+ localSha = localRefs.get(`refs/heads/${refs.head}`) ?? null;
+
+ if (canPush && getSettings(ref.owner).mirrorAuto) {
+ const due = links.filter((l) => !l.isPrivate && needsCheck(statuses.get(l.kind)));
+ if (due.length > 0) {
+ void checkAllMirrors(ref, due).catch((err) => {
+ console.warn(`[mirror] background check failed for ${refSlug(ref)}:`, err);
+ });
+ }
+ }
+ }
return c.html(
view.summaryPage({
@@ -709,16 +856,17 @@ app.get("/:owner/:name", async (c) => {
isPublic,
empty: refs.branches.length === 0,
readme: readmeFile,
- // The raw `description` file, for the edit form. Empty means unset.
rawDescription: desc,
description: view.repoDescription({
...ref,
description: desc,
readme: readmeFile,
}),
- canPush: access === "write",
- // Only the owner manages the grant list, so only they are shown it.
+ canPush,
collaborators: isOwner ? listCollaborators(ref) : null,
+ links,
+ mirrorStatuses: statuses,
+ localSha,
refs,
rev,
user,
@@ -726,7 +874,58 @@ app.get("/:owner/:name", async (c) => {
);
});
-// ---- boot -------------------------------------------------------------------
+app.post("/:owner/:name/mirrors", async (c) => {
+ const ref = await ownedRef(c);
+ if (!ref) return notFound(c);
+ const form = await c.req.formData();
+
+ const links: MirrorLink[] = [];
+ const rejected: string[] = [];
+ for (const kind of MIRROR_KINDS) {
+ const raw = String(form.get(kind) ?? "").trim();
+ if (!raw) continue;
+ const url = mirrorUrl(kind, raw);
+ if (!url) {
+ rejected.push(kind);
+ continue;
+ }
+ links.push({
+ kind,
+ url,
+ isPrivate: form.get(`${kind}_private`) != null,
+ });
+ }
+
+ if (rejected.length > 0) {
+ return c.html(
+ view.messagePage({
+ title: "that isn't a mirror URL",
+ message:
+ `The ${rejected.join(" and ")} link was refused. A mirror must be an ` +
+ `https URL of the form https://${mirrorHost(rejected[0] as MirrorKind)}/owner/repo ` +
+ `— no other host, no credentials, no port.`,
+ user: c.get("user"),
+ }),
+ 400,
+ );
+ }
+
+ const before = await readLinks(ref);
+ await setLinks(ref, links);
+ for (const old of before) {
+ const still = links.find((l) => l.kind === old.kind && l.url === old.url);
+ if (!still) dropMirrorStatusKind(ref, old.kind);
+ }
+ return c.redirect(`/${ref.owner}/${ref.name}/`);
+});
+
+app.post("/:owner/:name/mirrors/check", async (c) => {
+ const ref = await writableRef(c);
+ if (!ref) return notFound(c);
+ const links = await readLinks(ref);
+ await checkAllMirrors(ref, links);
+ return c.redirect(`/${ref.owner}/${ref.name}/`);
+});
serve(
{
diff --git a/src/settings.ts b/src/settings.ts
new file mode 100644
index 0000000..1091abd
--- /dev/null
+++ b/src/settings.ts
@@ -0,0 +1,124 @@
+/* src/settings.ts */
+//
+// Per-account settings.
+//
+// Keyed by owner slug rather than by OIDC `sub`, because the slug is the
+// identity everything else in this application is keyed by (tokens.owner,
+// collaborators.slug) and users.ts guarantees it never changes once assigned.
+//
+// This is a separate table from `users` on purpose. rememberUser() rewrites the
+// user row on every login, and settings are not identity: mixing them would put
+// a login on the write path for preferences, and preferences on the write path
+// for a login.
+//
+// Kept deliberately short. A setting earns its place here by changing what the
+// server does, not by filling out a page.
+
+import { db, now } from "./db.ts";
+
+db.exec(`
+ CREATE TABLE IF NOT EXISTS user_settings (
+ owner TEXT PRIMARY KEY,
+ discord_webhook TEXT,
+ discord_private INTEGER NOT NULL DEFAULT 0,
+ default_private INTEGER NOT NULL DEFAULT 1,
+ mirror_auto INTEGER NOT NULL DEFAULT 1,
+ webhook_error TEXT,
+ webhook_error_at INTEGER,
+ updated_at INTEGER NOT NULL
+ );
+`);
+
+export interface Settings {
+ owner: string;
+ discordWebhook: string | null;
+ discordPrivate: boolean;
+ defaultPrivate: boolean;
+ mirrorAuto: boolean;
+ webhookError: string | null;
+ webhookErrorAt: number | null;
+}
+
+const DEFAULTS: Omit<Settings, "owner"> = {
+ discordWebhook: null,
+ discordPrivate: false,
+ defaultPrivate: true,
+ mirrorAuto: true,
+ webhookError: null,
+ webhookErrorAt: null,
+};
+
+interface Row {
+ owner: string;
+ discord_webhook: string | null;
+ discord_private: number;
+ default_private: number;
+ mirror_auto: number;
+ webhook_error: string | null;
+ webhook_error_at: number | null;
+}
+
+export function getSettings(owner: string): Settings {
+ const row = db
+ .prepare("SELECT * FROM user_settings WHERE owner = ?")
+ .get(owner) as unknown as Row | undefined;
+ if (!row) return { owner, ...DEFAULTS };
+ return {
+ owner,
+ discordWebhook: row.discord_webhook,
+ discordPrivate: row.discord_private !== 0,
+ defaultPrivate: row.default_private !== 0,
+ mirrorAuto: row.mirror_auto !== 0,
+ webhookError: row.webhook_error,
+ webhookErrorAt: row.webhook_error_at,
+ };
+}
+
+function ensureRow(owner: string): void {
+ db.prepare(
+ `INSERT INTO user_settings (owner, updated_at) VALUES (?, ?)
+ ON CONFLICT (owner) DO NOTHING`,
+ ).run(owner, now());
+}
+
+export function setDiscordWebhook(owner: string, url: string | null): void {
+ ensureRow(owner);
+ db.prepare(
+ `UPDATE user_settings
+ SET discord_webhook = ?, webhook_error = NULL, webhook_error_at = NULL,
+ updated_at = ?
+ WHERE owner = ?`,
+ ).run(url, now(), owner);
+}
+
+export interface Prefs {
+ discordPrivate: boolean;
+ defaultPrivate: boolean;
+ mirrorAuto: boolean;
+}
+
+export function setPrefs(owner: string, prefs: Prefs): void {
+ ensureRow(owner);
+ db.prepare(
+ `UPDATE user_settings
+ SET discord_private = ?, default_private = ?, mirror_auto = ?, updated_at = ?
+ WHERE owner = ?`,
+ ).run(
+ prefs.discordPrivate ? 1 : 0,
+ prefs.defaultPrivate ? 1 : 0,
+ prefs.mirrorAuto ? 1 : 0,
+ now(),
+ owner,
+ );
+}
+
+export function recordWebhookResult(owner: string, error: string | null): void {
+ ensureRow(owner);
+ db.prepare(
+ `UPDATE user_settings SET webhook_error = ?, webhook_error_at = ? WHERE owner = ?`,
+ ).run(error ? error.slice(0, 200) : null, error ? now() : null, owner);
+}
+
+export function dropSettings(owner: string): void {
+ db.prepare("DELETE FROM user_settings WHERE owner = ?").run(owner);
+}
diff --git a/src/smart-http.ts b/src/smart-http.ts
index d73d91a..fe5975c 100644
--- a/src/smart-http.ts
+++ b/src/smart-http.ts
@@ -24,15 +24,11 @@ const BIN: Record<GitService, string> = {
"git-receive-pack": "receive-pack",
};
-// Encode a single pkt-line: a 4-char hex length prefix (counting itself)
-// followed by the payload. `0000` is the special "flush" packet.
export function pktLine(payload: string): string {
const length = 4 + Buffer.byteLength(payload);
return length.toString(16).padStart(4, "0") + payload;
}
-// Build the ref-advertisement body for a GET /info/refs request.
-// Format: pkt("# service=<svc>\n") + flush + <git advertise-refs output>
export async function advertiseRefs(
repoDir: string,
service: GitService,
@@ -61,14 +57,11 @@ export async function advertiseRefs(
export interface RpcOptions {
repoDir: string;
service: GitService;
- // Raw request body as a web ReadableStream (c.req.raw.body).
body: ReadableStream<Uint8Array> | null;
- // True when the client sent `Content-Encoding: gzip`.
gzip: boolean;
+ onDone?: (code: number) => void;
}
-// Run an upload-pack / receive-pack RPC and return a streaming Response whose
-// body is the git process's stdout.
export function serviceRpc(opts: RpcOptions): Response {
const child = spawn(
"git",
@@ -76,7 +69,6 @@ export function serviceRpc(opts: RpcOptions): Response {
{ stdio: ["pipe", "pipe", "inherit"] },
);
- // Pipe the (optionally gzip'd) request body into git's stdin.
if (opts.body) {
let input: NodeJS.ReadableStream = Readable.fromWeb(
opts.body as import("node:stream/web").ReadableStream,
@@ -89,6 +81,22 @@ export function serviceRpc(opts: RpcOptions): Response {
child.stdin.end();
}
+ if (opts.onDone) {
+ const done = opts.onDone;
+ let fired = false;
+ const settle = (code: number) => {
+ if (fired) return;
+ fired = true;
+ try {
+ done(code);
+ } catch (err) {
+ console.error("[git] rpc completion handler threw:", err);
+ }
+ };
+ child.on("close", (code) => settle(code ?? 1));
+ child.on("error", () => settle(1));
+ }
+
const webStdout = Readable.toWeb(
child.stdout,
) as unknown as ReadableStream<Uint8Array>;
@@ -102,7 +110,6 @@ export function serviceRpc(opts: RpcOptions): Response {
});
}
-// Build the Response for a GET /info/refs advertisement.
export async function advertiseResponse(
repoDir: string,
service: GitService,
diff --git a/src/styles/app.css.ts b/src/styles/app.css.ts
index 887ab6a..6041a13 100644
--- a/src/styles/app.css.ts
+++ b/src/styles/app.css.ts
@@ -7,9 +7,6 @@
import { globalStyle, style } from "@vanilla-extract/css";
import { vars } from "./theme.css";
-// The rendered README on a repo's summary tab. Its markup is generated by
-// src/markdown.ts as bare elements, so the rules for those live in globalStyle
-// scoped under this class (see the block below the class map).
const readme = style({
margin: "1rem 0",
padding: "1rem 1.25rem",
@@ -22,8 +19,6 @@ const readme = style({
export const classes = {
readme,
- // Three columns rather than space-between, so the middle zone stays centred
- // on the page even when the two sides are different widths.
siteHeader: style({
display: "grid",
gridTemplateColumns: "1fr auto 1fr",
@@ -76,9 +71,6 @@ export const classes = {
textOverflow: "ellipsis",
}),
- // Circle holding a first initial, with the IDP's avatar layered on top when
- // it loads. Sizing lives in the avatarSm/avatarLg modifiers below rather than
- // an inline style attribute, because `style-src 'self'` drops inline styles.
avatar: style({
position: "relative",
flexShrink: 0,
@@ -94,8 +86,6 @@ export const classes = {
userSelect: "none",
}),
- // Header avatar. min/max pin the box so the flex row can neither squeeze nor
- // stretch it around a long display name.
avatarSm: style({
width: "25px",
minWidth: "25px",
@@ -106,7 +96,6 @@ export const classes = {
fontSize: "13px",
}),
- // Profile-page avatar, pinned to 60x60.
avatarLg: style({
width: "60px",
minWidth: "60px",
@@ -266,8 +255,6 @@ export const classes = {
message: style({ color: vars.textMuted }),
- // Small inline marker: "shared", "write", "read". Carries meaning, so the
- // text inside it always says the thing rather than relying on colour.
badge: style({
display: "inline-block",
padding: "0.05rem 0.4rem",
@@ -281,7 +268,6 @@ export const classes = {
verticalAlign: "middle",
}),
- // A form whose controls sit on one line and wrap together on narrow screens.
formRow: style({
display: "flex",
flexWrap: "wrap",
@@ -289,13 +275,11 @@ export const classes = {
gap: "0.5rem",
}),
- // The one control in a formRow that should soak up the leftover width.
grow: style({
flex: "1 1 12rem",
minWidth: 0,
}),
- // Branch / tag selector. Sits between the tabs and the content it governs.
revPicker: style({
display: "flex",
flexWrap: "wrap",
@@ -306,6 +290,28 @@ export const classes = {
empty: style({ color: vars.textDim }),
+ statusGood: style({ color: vars.success }),
+ statusWarn: style({ color: vars.accent }),
+ statusBad: style({ color: vars.danger }),
+ statusMuted: style({ color: vars.textDim }),
+
+ mirrorRow: style({
+ display: "grid",
+ gridTemplateColumns: "minmax(5rem, auto) minmax(9rem, auto) auto 1fr",
+ gap: "0.5rem 1rem",
+ alignItems: "baseline",
+ padding: "0.3rem 0",
+ "@media": {
+ "screen and (max-width: 40rem)": {
+ gridTemplateColumns: "1fr",
+ gap: "0.1rem",
+ paddingBottom: "0.6rem",
+ },
+ },
+ }),
+
+ mirrorKind: style({ color: vars.textSoft, fontWeight: 600 }),
+
siteFooter: style({
color: vars.textDim,
textAlign: "center",
@@ -314,10 +320,6 @@ export const classes = {
}),
} as const;
-// ---- rendered README --------------------------------------------------------
-// Element rules for markdown output. Scoped under .readme so they can't leak
-// into the rest of the viewer, which styles by class.
-
globalStyle(`${readme} > :first-child`, { marginTop: 0 });
globalStyle(`${readme} > :last-child`, { marginBottom: 0 });
@@ -398,7 +400,6 @@ globalStyle(`${readme} img`, {
verticalAlign: "middle",
});
-// Wide tables scroll inside the README instead of stretching the page.
globalStyle(`${readme} table`, {
display: "block",
width: "max-content",
@@ -407,9 +408,6 @@ globalStyle(`${readme} table`, {
margin: "0.75rem 0",
});
-// Per-column alignment from the table's delimiter row (`:---:` / `---:`).
-// markdown.ts marks the cells with data-align because the CSP drops the inline
-// style attribute it used to write. Left is the base rule, so it needs nothing.
globalStyle(`${readme} th[data-align="center"], ${readme} td[data-align="center"]`, {
textAlign: "center",
});
diff --git a/src/styles/theme.css.ts b/src/styles/theme.css.ts
index 53b9480..70723be 100644
--- a/src/styles/theme.css.ts
+++ b/src/styles/theme.css.ts
@@ -55,7 +55,6 @@ createGlobalTheme(":root", vars, {
textSoft: "#c9cfe0",
text: "#f4f6fb",
- // Comic Code loaded in fonts.css.ts (imported before this file in index.ts).
font: "'Comic Code', system-ui, -apple-system, sans-serif",
mono: "ui-monospace, SFMono-Regular, Menlo, monospace",
radius: "0",
diff --git a/src/tokens.ts b/src/tokens.ts
index 364d11b..276c075 100644
--- a/src/tokens.ts
+++ b/src/tokens.ts
@@ -23,8 +23,6 @@ db.exec(`
);
`);
-// Added after the first release: tokens minted before this column existed are
-// backfilled from the user directory on first use (see verifyDbToken).
if (!hasColumn("tokens", "owner")) {
db.exec("ALTER TABLE tokens ADD COLUMN owner TEXT");
}
@@ -44,15 +42,12 @@ export interface TokenRow {
const COLUMNS = "id, label, owner, created_by, created_at, last_used";
-// Tokens belonging to one owner slug. There is deliberately no "list them all"
-// — a token label is the owner's business, not the whole instance's.
export function listTokens(owner: string): TokenRow[] {
return db
.prepare(`SELECT ${COLUMNS} FROM tokens WHERE owner = ? ORDER BY created_at DESC`)
.all(owner) as unknown as TokenRow[];
}
-// Returns the plaintext token exactly once; only its hash is persisted.
export function createToken(
label: string,
owner: string,
@@ -68,8 +63,6 @@ export function createToken(
return plaintext;
}
-// Revoke one of `owner`'s own tokens. Returns false if the id doesn't exist or
-// belongs to somebody else.
export function revokeToken(id: string, owner: string): boolean {
const row = db
.prepare("SELECT owner FROM tokens WHERE id = ?")
@@ -79,8 +72,6 @@ export function revokeToken(id: string, owner: string): boolean {
return true;
}
-// Resolve a presented plaintext to the owner slug it acts as, or null if it
-// isn't a valid token. Bumps last_used as a side effect.
export function verifyDbToken(plaintext: string): { owner: string | null } | null {
const row = db
.prepare("SELECT id, owner, created_by FROM tokens WHERE hash = ?")
@@ -89,8 +80,6 @@ export function verifyDbToken(plaintext: string): { owner: string | null } | nul
| undefined;
if (!row) return null;
- // Pre-ownership token: adopt the slug of the account that created it, now
- // that the user directory can answer that question.
let owner = row.owner;
if (!owner) {
owner = slugForSub(row.created_by);
diff --git a/src/urls.ts b/src/urls.ts
new file mode 100644
index 0000000..c81a495
--- /dev/null
+++ b/src/urls.ts
@@ -0,0 +1,105 @@
+/* src/urls.ts */
+//
+// URL validation, in one place, because these URLs are a security boundary.
+//
+// Two kinds of URL enter this application from a user, and both end up
+// somewhere dangerous:
+//
+// * mirror links (git.ts) are handed to the *git binary* as a remote to
+// contact, so a URL that isn't what it looks like becomes an outbound
+// request to somewhere we didn't intend, or another git transport
+// entirely (`ext::` runs a shell command).
+// * the Discord webhook (notify.ts) is handed to fetch(), so an unchecked
+// host makes the server into an SSRF probe for whatever it can reach.
+//
+// The defence in both cases is an allow-list of exact hosts rather than a
+// sanitiser: there is a fixed, small set of places these URLs are allowed to
+// point, so nothing else needs reasoning about. This is the same shape as
+// markdown.ts's scheme allow-list and git.ts's `safeSegment`.
+//
+// Every validator returns a normalised URL string or null. Callers must treat
+// null as "refuse", never as "use the raw value".
+
+const MAX_URL = 400;
+
+const HOSTILE = /[\s\\<>"'`{}|^\x00-\x1f\x7f]/;
+
+function parseStrict(raw: string, allowedHosts: readonly string[]): URL | null {
+ const value = raw.trim();
+ if (!value || value.length > MAX_URL) return null;
+ if (HOSTILE.test(value)) return null;
+ if (value.startsWith("-")) return null;
+ if (/(?:^|\/)\.{1,2}(?:\/|$)/.test(value)) return null;
+
+ let url: URL;
+ try {
+ url = new URL(value);
+ } catch {
+ return null;
+ }
+
+ if (url.protocol !== "https:") return null;
+ if (url.username || url.password) return null;
+ if (url.port) return null;
+ if (url.search || url.hash) return null;
+ if (!allowedHosts.includes(url.hostname)) return null;
+ return url;
+}
+
+export const MIRROR_KINDS = ["github", "codeberg"] as const;
+export type MirrorKind = (typeof MIRROR_KINDS)[number];
+
+const MIRROR_HOSTS: Record<MirrorKind, string> = {
+ github: "github.com",
+ codeberg: "codeberg.org",
+};
+
+export function isMirrorKind(value: string): value is MirrorKind {
+ return (MIRROR_KINDS as readonly string[]).includes(value);
+}
+
+export function mirrorHost(kind: MirrorKind): string {
+ return MIRROR_HOSTS[kind];
+}
+
+const PATH_SEGMENT = /^[A-Za-z0-9._-]+$/;
+
+function safePathSegment(s: string): boolean {
+ return PATH_SEGMENT.test(s) && !s.startsWith(".") && !s.includes("..");
+}
+
+export function mirrorUrl(kind: MirrorKind, raw: string): string | null {
+ const url = parseStrict(raw, [MIRROR_HOSTS[kind]]);
+ if (!url) return null;
+
+ const parts = url.pathname.split("/").filter((p) => p.length > 0);
+ if (parts.length !== 2) return null;
+
+ const owner = parts[0]!;
+ const repo = parts[1]!.replace(/\.git$/, "");
+ if (!safePathSegment(owner) || !safePathSegment(repo)) return null;
+
+ return `https://${url.hostname}/${owner}/${repo}`;
+}
+
+const DISCORD_HOSTS = [
+ "discord.com",
+ "discordapp.com",
+ "canary.discord.com",
+ "ptb.discord.com",
+] as const;
+
+const WEBHOOK_PATH = /^\/api(?:\/v\d{1,3})?\/webhooks\/\d{1,32}\/[A-Za-z0-9._-]{1,200}$/;
+
+export function discordWebhookUrl(raw: string): string | null {
+ const url = parseStrict(raw, DISCORD_HOSTS);
+ if (!url) return null;
+ if (!WEBHOOK_PATH.test(url.pathname)) return null;
+ return `https://${url.hostname}${url.pathname}`;
+}
+
+export function maskWebhook(url: string): string {
+ const match = /^https:\/\/([^/]+)\/api(?:\/v\d+)?\/webhooks\/(\d+)\//.exec(url);
+ if (!match) return "(hidden)";
+ return `https://${match[1]}/api/webhooks/${match[2]}/…`;
+}
diff --git a/src/users.ts b/src/users.ts
index dea4098..f72fa57 100644
--- a/src/users.ts
+++ b/src/users.ts
@@ -55,9 +55,6 @@ export function listUsers(): UserRow[] {
.all() as unknown as UserRow[];
}
-// Pick a slug not already claimed by a different account. Two people called
-// "Alex Kim" would otherwise both land on `alex-kim`, and the second one would
-// inherit push rights over the first one's repos.
function uniqueSlug(preferred: string, sub: string): string {
const taken = (slug: string) => {
const row = findUserBySlug(slug);
@@ -68,7 +65,6 @@ function uniqueSlug(preferred: string, sub: string): string {
const candidate = `${preferred}-${n}`;
if (!taken(candidate)) return candidate;
}
- // Astronomically unlikely; fall back to something guaranteed free.
return `${preferred}-${sub.replace(/[^a-z0-9]/gi, "").slice(0, 8).toLowerCase()}`;
}
@@ -79,9 +75,6 @@ export interface RememberInput {
picture: string | null;
}
-// Record a successful login and return the row. An existing user keeps their
-// slug even if they rename themselves upstream — the slug is a path segment
-// their repos already live under, so it can't move without moving them.
export function rememberUser(input: RememberInput): UserRow {
const existing = findUserBySub(input.sub);
const ts = now();
@@ -105,7 +98,6 @@ export function rememberUser(input: RememberInput): UserRow {
return { ...input, slug, created_at: ts, last_login: ts };
}
-// Backfill hook for tokens.ts: the slug that owns a given OIDC sub, if known.
export function slugForSub(sub: string | null): string | null {
if (!sub) return null;
return findUserBySub(sub)?.slug ?? null;
diff --git a/src/views.ts b/src/views.ts
index 1d3a419..6b4eefd 100644
--- a/src/views.ts
+++ b/src/views.ts
@@ -7,10 +7,12 @@ import { config } from "./config.ts";
import { classes as c } from "./styles/index.ts";
import { escapeHtml, renderMarkdown, plainSummary } from "./markdown.ts";
import { sessionSlug } from "./auth.ts";
+import { maskWebhook, mirrorHost, MIRROR_KINDS, type MirrorKind } from "./urls.ts";
import type { SessionUser } from "./auth.ts";
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 type {
RepoSummary,
Commit,
@@ -18,7 +20,10 @@ import type {
CommitDetail,
Readme,
RefList,
+ TrashEntry,
+ MirrorLink,
} from "./git.ts";
+import type { MirrorStatus } from "./mirror.ts";
export const esc = escapeHtml;
@@ -27,7 +32,6 @@ function fmtDate(unix: number | null): string {
return new Date(unix * 1000).toISOString().slice(0, 16).replace("T", " ");
}
-// owner/name base path (URL-safe by construction — validated in git.ts).
function base(owner: string, name: string): string {
return `/${esc(owner)}/${esc(name)}`;
}
@@ -36,23 +40,12 @@ function cloneUrl(owner: string, name: string): string {
return `${config.baseUrl}/${owner}/${name}.git`;
}
-// ---- revisions --------------------------------------------------------------
-
-// The `?h=` a link needs to stay on the current revision. The default branch
-// carries no query, so ordinary URLs stay clean and shareable.
-//
-// A branch name may contain characters that are structural in a URL (`/` in
-// `feature/thing`, `#`, `?`), so it is always percent-encoded — which also
-// makes it safe to drop straight into an HTML attribute.
function revQuery(rev: string, head: string): string {
return rev === head ? "" : `?h=${encodeURIComponent(rev)}`;
}
-// A picker for the branch or tag being viewed. It is a plain GET form, so it
-// works with scripting off; /static/app.js only removes the extra click.
function revPicker(refs: RefList, rev: string): string {
const all = [...refs.branches, ...refs.tags];
- // Nothing to switch between, or a detached commit id that isn't in the list.
if (all.length < 2 && all.includes(rev)) return "";
if (all.length === 0) return "";
@@ -67,8 +60,6 @@ function revPicker(refs: RefList, rev: string): string {
return `<optgroup label="${label}">${items}</optgroup>`;
};
- // A revision reached by object id isn't in either list; show it so the
- // control never displays something other than what is on screen.
const detached = all.includes(rev)
? ""
: `<option value="${esc(rev)}" selected>${esc(rev.slice(0, 10))}</option>`;
@@ -82,7 +73,6 @@ function revPicker(refs: RefList, rev: string): string {
</form>`;
}
-// Collapse a description to one clean line of attribute-safe text.
function metaText(s: string, max = 200): string {
const flat = s.replace(/\s+/g, " ").trim();
const clipped =
@@ -90,7 +80,6 @@ function metaText(s: string, max = 200): string {
return esc(clipped);
}
-// The shared shape of "a person" across sessions and directory rows.
interface Profile {
name: string | null;
username: string | null;
@@ -101,17 +90,6 @@ export function displayName(p: Profile & { sub?: string }): string {
return p.name ?? p.username ?? p.sub ?? "user";
}
-// Avatar from PocketID's `picture` claim, over a first-initial fallback. The
-// IDP may serve avatars only to signed-in browsers, so a failed image drops
-// itself and uncovers the initial rather than leaving a broken-image box.
-//
-// The drop is done by /static/app.js rather than an inline onerror handler,
-// because the Content-Security-Policy forbids inline script — that policy is
-// what stands behind markdown.ts if the renderer ever lets something through.
-//
-// The size comes from a class, not an inline `style` attribute: the CSP's
-// `style-src 'self'` drops inline styles too, which silently collapsed the
-// circle to the width of the fallback letter.
function avatar(p: Profile, size: "sm" | "lg"): string {
const initial = esc(displayName(p).trim().slice(0, 1).toUpperCase() || "?");
const box = size === "lg" ? c.avatarLg : c.avatarSm;
@@ -125,27 +103,21 @@ function layout(opts: {
title: string;
user: SessionUser | null;
body: string;
- // Page description for <meta description> / social previews.
description?: string;
- // Site-absolute path of this page, for canonical + og:url.
path?: string;
- // Private repos and account pages shouldn't end up in search results.
noindex?: boolean;
}): string {
- // Three zones: home on the left, who you are in the middle, settings right.
const whoami = opts.user
? `<a class="${c.user}" href="/${esc(ownerOf(opts.user))}">${avatar(opts.user, "sm")}${esc(displayName(opts.user))}</a>`
: "";
const settings = opts.user
- ? `<a class="${c.navLink}" href="/tokens">tokens</a>
+ ? `<a class="${c.navLink}" href="/settings">settings</a>
<a class="${c.navLink}" href="/auth/logout">logout</a>`
: `<a class="${c.navLink}" href="/auth/login">login</a>`;
const description = metaText(opts.description || config.description);
const url = opts.path ? esc(config.baseUrl + opts.path) : esc(config.baseUrl);
const icon = esc(config.favicon);
- // Same image as the favicon, doubling as the header mark. Decorative: the
- // title text right next to it already names the site.
const logo = config.favicon
? `<img class="${c.siteLogo}" src="${icon}" alt="" width="24" height="24">`
: "";
@@ -191,12 +163,6 @@ ${opts.body}
</html>`;
}
-// The repo table shared by the front page and the profile pages. `showOwner`
-// is off on a profile, where every row has the same owner as the heading.
-//
-// `sharedSlugs` holds the `owner/name` of repos this viewer only sees because
-// somebody invited them. Marking those is the difference between "my repos" and
-// "repos I can reach", which is otherwise invisible.
function repoTable(
repos: RepoSummary[],
opts: {
@@ -256,8 +222,6 @@ ${createForm}
return layout({ title: config.title, user, body, path: "/" });
}
-// A deliberately small profile: who this is, and what they own. Anything more
-// (activity feeds, bios, follower counts) is a different kind of site.
export function profilePage(opts: {
owner: string;
profile: UserRow | null;
@@ -266,14 +230,10 @@ export function profilePage(opts: {
}): string {
const p = opts.profile;
const name = p ? displayName(p) : opts.owner;
- // The slug is the handle; only mention the upstream username when it says
- // something the slug doesn't (a rename, or characters the slug dropped).
const handle = p?.username && p.username !== p.slug ? p.username : null;
const known = p
? `<p class="${c.repoDesc}">@${esc(p.slug)}${handle ? ` · ${esc(handle)}` : ""} · joined ${fmtDate(p.created_at).slice(0, 10)}</p>`
- // Repos can outlive their account (or arrive by push before anyone logs
- // in), so an owner directory with no user row still gets a page.
: `<p class="${c.repoDesc}">@${esc(opts.owner)} · no account on this instance</p>`;
const body = ` <section class="${c.profileHead}">
@@ -292,20 +252,14 @@ export function profilePage(opts: {
body,
description: `${name} (@${opts.owner}) on ${config.title}.`,
path: `/${opts.owner}`,
- // Someone with nothing public shouldn't be indexed into existence by their
- // presence on a mostly-private instance.
noindex: !opts.repos.some((r) => r.isPublic),
});
}
-// The owner segment this user's repos live under. Assigned once at first login
-// and carried in the session; see users.ts for why it can't be re-derived.
export function ownerOf(user: SessionUser): string {
return sessionSlug(user);
}
-// The three repo tabs. `q` is the `?h=` suffix, so switching tabs keeps you on
-// the branch you were reading.
function repoNav(
owner: string,
name: string,
@@ -353,29 +307,26 @@ export function summaryPage(opts: {
empty: boolean;
readme: Readme | null;
description: string;
- // The `description` file as stored, for the edit form. "" means unset.
rawDescription: string;
- // True when the viewer may push: the owner, or a write collaborator.
canPush: boolean;
- // The grant list, but only when the viewer is the owner — nobody else is
- // shown who else has access.
collaborators: CollaboratorRow[] | null;
refs: RefList;
rev: string;
user: SessionUser | null;
+ links: MirrorLink[];
+ mirrorStatuses: Map<string, MirrorStatus>;
+ localSha: string | null;
}): string {
const title = `${opts.owner}/${opts.name}`;
const empty = opts.empty;
const q = revQuery(opts.rev, opts.refs.head);
- // Whoever is pushing authenticates as themselves, not as the repo's owner, so
- // the username in the hint is the reader's own slug.
const pusher = opts.user ? ownerOf(opts.user) : opts.owner;
const pushHint =
empty && opts.canPush
? ` <section class="${c.cloneBox}">
<p><strong>This repository is empty.</strong> Push to get started:</p>
<code>git remote add mirror ${esc(cloneUrl(opts.owner, opts.name))}<br>git push --mirror mirror</code>
- <p class="${c.repoDesc}">When prompted, the <strong>username</strong> is <code>${esc(pusher)}</code> and the <strong>password</strong> is a token from <a href="/tokens">/tokens</a>.</p>
+ <p class="${c.repoDesc}">When prompted, the <strong>username</strong> is <code>${esc(pusher)}</code> and the <strong>password</strong> is a token from <a href="/settings/tokens">settings</a>.</p>
</section>`
: empty
? ` <section class="${c.cloneBox}">
@@ -383,7 +334,6 @@ export function summaryPage(opts: {
</section>`
: "";
- // An empty repo has nothing to look for, so it only gets the push hint above.
const readmeSection = empty
? ""
: opts.readme
@@ -394,9 +344,6 @@ ${renderMarkdown(opts.readme.text)}
: ` <h2 class="${c.sectionTitle}">readme</h2>
<p class="${c.empty}">No ReadMe was found, commit one to add a summary</p>`;
- // Only the owner manages a repo — matching what the git transport enforces.
- // A write collaborator can push, but can't publish the repo, delete it, or
- // hand access to anybody else.
const isOwner = opts.collaborators !== null;
const manage = isOwner
? ` <h2 class="${c.sectionTitle}">manage</h2>
@@ -412,8 +359,6 @@ ${renderMarkdown(opts.readme.text)}
${collaboratorSection(opts.owner, opts.name, opts.collaborators ?? [])}`
: "";
- // Editing the blurb needs push rights, not ownership: it is the same thing a
- // collaborator could already change by committing a README.
const descriptionForm = opts.canPush
? ` <form method="post" action="${base(opts.owner, opts.name)}/description" class="${c.cloneBox} ${c.formRow}">
<label class="${c.cloneLabel}" for="repo-description">description</label>
@@ -435,6 +380,15 @@ ${descriptionForm}
<code>git clone ${esc(cloneUrl(opts.owner, opts.name))}</code>
</section>
${pushHint}
+${mirrorSection(
+ opts.owner,
+ opts.name,
+ opts.links,
+ opts.mirrorStatuses,
+ opts.localSha,
+ isOwner,
+ opts.canPush,
+)}
${readmeSection}
${manage}`;
return layout({
@@ -447,8 +401,161 @@ ${manage}`;
});
}
-// The owner's view of who else can reach this repo. Read access is what makes a
-// private repo visible at all; write access additionally allows a push.
+function mirrorSection(
+ owner: string,
+ name: string,
+ links: MirrorLink[],
+ statuses: Map<string, MirrorStatus>,
+ localSha: string | null,
+ isOwner: boolean,
+ canCheck: boolean,
+): string {
+ if (links.length === 0 && !isOwner) return "";
+
+ const nowSec = Math.floor(Date.now() / 1000);
+
+ const rows = links
+ .map((link) => {
+ const status = statuses.get(link.kind) ?? null;
+ const view = describeMirror(link, status, nowSec);
+ return ` <div class="${c.mirrorRow}">
+ <span class="${c.mirrorKind}"><a href="${esc(link.url)}" rel="nofollow noopener noreferrer">${esc(link.kind)}</a></span>
+ <span class="${view.cls}">${esc(view.label)}</span>
+ <span class="${c.commitHash}">${esc(view.sha)}</span>
+ <span class="${c.repoDesc}">${esc(view.detail)}</span>
+ </div>${view.note ? `\n <p class="${view.noteCls}">${esc(view.note)}</p>` : ""}`;
+ })
+ .join("\n");
+
+ const local = localSha
+ ? ` <div class="${c.mirrorRow}">
+ <span class="${c.mirrorKind}">local</span>
+ <span class="${c.statusMuted}">this repository</span>
+ <span class="${c.commitHash}">${esc(localSha.slice(0, 7))}</span>
+ <span></span>
+ </div>`
+ : "";
+
+ const checkButton =
+ canCheck && links.some((l) => !l.isPrivate)
+ ? ` <form method="post" action="${base(owner, name)}/mirrors/check">
+ <button type="submit">check now</button>
+ </form>`
+ : "";
+
+ const body =
+ links.length > 0
+ ? ` <section class="${c.cloneBox}">
+${rows}
+${local}
+${checkButton}
+ </section>`
+ : ` <p class="${c.empty}">No mirrors configured.</p>`;
+
+ const field = (kind: MirrorKind) => {
+ const existing = links.find((l) => l.kind === kind);
+ return ` <div class="${c.formRow}">
+ <label class="${c.cloneLabel}" for="mirror-${kind}">${kind}</label>
+ <input id="mirror-${kind}" class="${c.grow}" type="url" name="${kind}"
+ value="${esc(existing?.url ?? "")}" placeholder="https://${esc(mirrorHost(kind))}/user/repo">
+ <label><input type="checkbox" name="${kind}_private"${existing?.isPrivate ? " checked" : ""}> private</label>
+ </div>`;
+ };
+
+ const form = isOwner
+ ? ` <form method="post" action="${base(owner, name)}/mirrors" class="${c.cloneBox}">
+${MIRROR_KINDS.map(field).join("\n")}
+ <p class="${c.repoDesc}">Only ${esc(MIRROR_KINDS.map(mirrorHost).join(" and "))} are accepted.
+ Mark a mirror <em>private</em> to skip status checks — they are anonymous, so a private
+ mirror would otherwise always look unreachable. Clear a field to remove it.</p>
+ <button type="submit">save mirrors</button>
+ </form>`
+ : "";
+
+ return ` <h2 class="${c.sectionTitle}">external mirrors</h2>
+${body}
+${form}`;
+}
+
+function describeMirror(
+ link: MirrorLink,
+ status: MirrorStatus | null,
+ nowSec: number,
+): {
+ label: string;
+ cls: string;
+ sha: string;
+ detail: string;
+ note: string;
+ noteCls: string;
+} {
+ const blank = { note: "", noteCls: c.repoDesc };
+
+ if (link.isPrivate) {
+ return {
+ ...blank,
+ label: "🔒 Not checked (private)",
+ cls: c.statusMuted,
+ sha: "",
+ detail: "status checks are anonymous",
+ };
+ }
+ if (!status || (!status.state && !status.error)) {
+ return { ...blank, label: "— not checked yet", cls: c.statusMuted, sha: "", detail: "" };
+ }
+
+ const LABELS: Record<string, { label: string; cls: string }> = {
+ synced: { label: "✓ Up to date", cls: c.statusGood },
+ ahead: { label: "↑ Mirror behind", cls: c.statusWarn },
+ behind: { label: "↓ Local behind", cls: c.statusWarn },
+ diverged: { label: "⚠ Diverged", cls: c.statusBad },
+ out_of_sync: { label: "⚠ Out of sync", cls: c.statusBad },
+ denied: { label: "🔒 Private or missing", cls: c.statusWarn },
+ missing: { label: "✗ Repository missing", cls: c.statusBad },
+ };
+
+ if (status.error) {
+ const known = status.state ? LABELS[status.state] : undefined;
+ const stale = status.okAt !== null && nowSec - status.okAt > 24 * 3600;
+ return {
+ label: known ? known.label : "? Unavailable",
+ cls: known ? c.statusMuted : c.statusBad,
+ sha: status.remoteSha ? status.remoteSha.slice(0, 7) : "",
+ detail: status.okAt ? `last verified ${ago(nowSec - status.okAt)} ago` : "never verified",
+ note:
+ `${link.kind}: check failed ${ago(nowSec - status.checkedAt)} ago (${status.error})` +
+ (status.okAt
+ ? stale
+ ? ` — NOT VERIFIED for ${ago(nowSec - status.okAt)}`
+ : ` — showing last verified state from ${ago(nowSec - status.okAt)} ago`
+ : ""),
+ noteCls: stale || !status.okAt ? c.statusBad : c.statusWarn,
+ };
+ }
+
+ const known = status.state ? LABELS[status.state] : undefined;
+ const stale = status.okAt !== null && nowSec - status.okAt > 24 * 3600;
+ return {
+ label: known?.label ?? "? Unavailable",
+ cls: known?.cls ?? c.statusBad,
+ sha: status.remoteSha ? status.remoteSha.slice(0, 7) : "",
+ detail: [status.detail, status.okAt ? `checked ${ago(nowSec - status.okAt)} ago` : ""]
+ .filter(Boolean)
+ .join(" · "),
+ note: stale
+ ? `${link.kind}: not verified for ${ago(nowSec - (status.okAt ?? nowSec))}`
+ : "",
+ noteCls: c.statusBad,
+ };
+}
+
+function ago(seconds: number): string {
+ if (seconds < 90) return `${Math.max(0, Math.round(seconds))}s`;
+ if (seconds < 5400) return `${Math.round(seconds / 60)}m`;
+ if (seconds < 172800) return `${Math.round(seconds / 3600)}h`;
+ return `${Math.round(seconds / 86400)}d`;
+}
+
function collaboratorSection(
owner: string,
name: string,
@@ -494,8 +601,6 @@ ${rows || ` <tr><td colspan="4" class="${c.empty}">nobody else has access
</table>`;
}
-// Best available one-line description of a repo: git's own `description` file,
-// else the opening prose of the README, else a generic line.
export function repoDescription(opts: {
owner: string;
name: string;
@@ -544,8 +649,6 @@ export function treePage(opts: {
const q = revQuery(opts.rev, opts.refs.head);
const crumb = opts.path ? ` /${esc(opts.path)}` : "";
- // A link back up one level, so a deep tree isn't a dead end without the
- // browser's back button.
const parent = opts.path
? ` <tr class="${c.repoRow}">
<td class="${c.treeMode}"></td>
@@ -586,7 +689,6 @@ ${[parent, rows].filter(Boolean).join("\n") || ` <tr><td class="${c.empty
});
}
-// Bytes as something a person can read at a glance.
function fmtBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
@@ -634,8 +736,6 @@ export function commitPage(opts: {
user: SessionUser | null;
}): string {
const cm = opts.commit;
- // A commit is reached from some branch; carrying that along keeps the tabs
- // pointing back where the reader came from.
const q = `?h=${encodeURIComponent(opts.rev)}`;
const body = ` <h1 class="${c.pageTitle}">${esc(cm.subject)}</h1>
${repoNav(opts.owner, opts.name, "log", q)}
@@ -656,6 +756,16 @@ ${repoNav(opts.owner, opts.name, "log", q)}
});
}
+function settingsNav(active: string): string {
+ const tab = (id: string, label: string, href: string) =>
+ `<a class="${c.tab}${id === active ? " " + c.tabActive : ""}" href="${href}">${label}</a>`;
+ return ` <nav class="${c.repoTabs}">
+ ${tab("account", "account", "/settings")}
+ ${tab("tokens", "tokens", "/settings/tokens")}
+ ${tab("deleted", "recently deleted", "/settings/deleted")}
+ </nav>`;
+}
+
export function tokensPage(opts: {
tokens: TokenRow[];
user: SessionUser | null;
@@ -669,7 +779,7 @@ export function tokensPage(opts: {
<td class="${c.commitDate}">${fmtDate(t.created_at)}</td>
<td class="${c.commitDate}">${t.last_used ? fmtDate(t.last_used) : "never"}</td>
<td>
- <form method="post" action="/tokens/${esc(t.id)}/revoke">
+ <form method="post" action="/settings/tokens/${esc(t.id)}/revoke">
<button type="submit">revoke</button>
</form>
</td>
@@ -687,12 +797,14 @@ export function tokensPage(opts: {
</section>`
: "";
- const body = ` <h1 class="${c.pageTitle}">access tokens</h1>
+ const body = ` <h1 class="${c.pageTitle}">settings</h1>
+${settingsNav("tokens")}
+ <h2 class="${c.sectionTitle}">access tokens</h2>
<p class="${c.repoDesc}">These tokens act as <code>${esc(authUser)}</code>: use that as the git
<strong>username</strong> and the token as the <strong>password</strong>. They can only push to
repositories under <code>${esc(authUser)}/</code>.</p>
${created}
- <form method="post" action="/tokens" class="${c.cloneBox}">
+ <form method="post" action="/settings/tokens" class="${c.cloneBox}">
<label class="${c.cloneLabel}">label</label>
<input type="text" name="label" placeholder="laptop, backup cron, ...">
<button type="submit">create token</button>
@@ -714,6 +826,159 @@ ${rows || ` <tr><td colspan="5" class="${c.empty}">no tokens yet</td></tr
});
}
+export function settingsPage(opts: {
+ user: SessionUser | null;
+ settings: Settings;
+ saved?: string | null;
+}): string {
+ const s = opts.settings;
+ const on = (v: boolean) => (v ? " checked" : "");
+
+ const webhookState = s.discordWebhook
+ ? ` <p class="${c.repoDesc}">configured · <code>${esc(maskWebhook(s.discordWebhook))}</code></p>`
+ : ` <p class="${c.empty}">not configured — repository events are not announced anywhere.</p>`;
+
+ const webhookError =
+ s.discordWebhook && s.webhookError
+ ? ` <p class="${c.statusBad}">last delivery failed${
+ s.webhookErrorAt ? ` at ${fmtDate(s.webhookErrorAt)}` : ""
+ }: ${esc(s.webhookError)}</p>`
+ : "";
+
+ const clear = s.discordWebhook
+ ? ` <form method="post" action="/settings/discord" data-confirm="Remove the Discord webhook? Events will stop being announced.">
+ <input type="hidden" name="url" value="">
+ <button type="submit">remove webhook</button>
+ </form>`
+ : "";
+
+ const body = ` <h1 class="${c.pageTitle}">settings</h1>
+${settingsNav("account")}
+${opts.saved ? ` <p class="${c.statusGood}">${esc(opts.saved)}</p>` : ""}
+
+ <h2 class="${c.sectionTitle}">discord notifications</h2>
+ <p class="${c.repoDesc}">Announces repositories being created and deleted, and commits being
+ pushed. Only repositories you own are announced, and only to this webhook.</p>
+ <section class="${c.cloneBox}">
+${webhookState}
+${webhookError}
+ <form method="post" action="/settings/discord" class="${c.formRow}">
+ <label class="${c.cloneLabel}" for="discord-url">webhook</label>
+ <input id="discord-url" class="${c.grow}" type="url" name="url" autocomplete="off"
+ placeholder="https://discord.com/api/webhooks/…">
+ <button type="submit">save</button>
+ </form>
+${clear}
+ </section>
+
+ <h2 class="${c.sectionTitle}">preferences</h2>
+ <form method="post" action="/settings/prefs" class="${c.cloneBox}">
+ <p><label><input type="checkbox" name="default_private"${on(s.defaultPrivate)}>
+ New repositories start private</label></p>
+ <p><label><input type="checkbox" name="discord_private"${on(s.discordPrivate)}>
+ Announce activity on private repositories</label>
+ <br><span class="${c.repoDesc}">Off by default: commit subjects and repository names
+ would otherwise leave a private repo for a Discord channel.</span></p>
+ <p><label><input type="checkbox" name="mirror_auto"${on(s.mirrorAuto)}>
+ Check mirror status automatically when viewing a repository</label>
+ <br><span class="${c.repoDesc}">Off means mirrors are only checked when you press
+ <em>check now</em>.</span></p>
+ <button type="submit">save preferences</button>
+ </form>
+
+ <h2 class="${c.sectionTitle}">account</h2>
+ <p class="${c.repoDesc}">Your name and avatar come from PocketID and refresh on each sign-in,
+ so there is nothing to edit here. Your owner namespace is
+ <code>${esc(opts.user ? ownerOf(opts.user) : "")}</code> and never changes.</p>`;
+
+ return layout({
+ title: "settings",
+ user: opts.user,
+ body,
+ description: "Account settings.",
+ noindex: true,
+ });
+}
+
+export function deletedPage(opts: {
+ user: SessionUser | null;
+ entries: TrashEntry[];
+ retentionDays: number;
+}): string {
+ const nowSec = Math.floor(Date.now() / 1000);
+
+ const rows = opts.entries
+ .map((e) => {
+ const remaining =
+ opts.retentionDays > 0
+ ? Math.ceil(
+ (e.deletedAt + opts.retentionDays * 86400 - nowSec) / 86400,
+ )
+ : null;
+ const life =
+ remaining === null
+ ? `<span class="${c.statusMuted}">kept until purged</span>`
+ : remaining <= 0
+ ? `<span class="${c.statusBad}">purged on next visit</span>`
+ : remaining <= 3
+ ? `<span class="${c.statusBad}">${remaining}d left</span>`
+ : `<span class="${c.statusMuted}">${remaining}d left</span>`;
+
+ const note = e.degraded
+ ? `<br><span class="${c.statusWarn}">recovery metadata unreadable — restorable, but collaborators will need re-adding</span>`
+ : e.grants.length
+ ? `<br><span class="${c.repoDesc}">${e.grants.length} collaborator${e.grants.length === 1 ? "" : "s"} will be restored</span>`
+ : "";
+
+ return ` <tr>
+ <td class="${c.repoName}">${esc(e.name)}${note}</td>
+ <td class="${c.commitDate}">${fmtDate(e.deletedAt)}</td>
+ <td class="${c.repoDesc}">${esc(e.deletedBy)}</td>
+ <td>${life}</td>
+ <td>
+ <form method="post" action="/settings/deleted/restore">
+ <input type="hidden" name="entry" value="${esc(e.entry)}">
+ <button type="submit">restore</button>
+ </form>
+ </td>
+ <td>
+ <form method="post" action="/settings/deleted/purge" data-confirm="Permanently delete ${esc(e.name)}? This destroys the git data and cannot be undone.">
+ <input type="hidden" name="entry" value="${esc(e.entry)}">
+ <button type="submit">delete permanently</button>
+ </form>
+ </td>
+ </tr>`;
+ })
+ .join("\n");
+
+ const retention =
+ opts.retentionDays > 0
+ ? `Deleted repositories are kept for ${opts.retentionDays} days, then purged the next time you open this page.`
+ : `Deleted repositories are kept indefinitely — nothing is purged unless you do it here.`;
+
+ const body = ` <h1 class="${c.pageTitle}">settings</h1>
+${settingsNav("deleted")}
+ <h2 class="${c.sectionTitle}">recently deleted</h2>
+ <p class="${c.repoDesc}">${esc(retention)} A deleted repository keeps its name reserved, so
+ nothing new can take it until it is restored or purged.</p>
+ <table>
+ <thead>
+ <tr><th>repository</th><th>deleted</th><th>by</th><th>retention</th><th></th><th></th></tr>
+ </thead>
+ <tbody>
+${rows || ` <tr><td colspan="6" class="${c.empty}">nothing deleted</td></tr>`}
+ </tbody>
+ </table>`;
+
+ return layout({
+ title: "recently deleted",
+ user: opts.user,
+ body,
+ description: "Recover deleted repositories.",
+ noindex: true,
+ });
+}
+
export function messagePage(opts: {
title: string;
message: string;
diff --git a/test/access.test.mjs b/test/access.test.mjs
index c049ef5..c0c5de3 100644
--- a/test/access.test.mjs
+++ b/test/access.test.mjs
@@ -11,7 +11,6 @@ import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-// Point config at a throwaway database BEFORE importing anything that opens it.
const root = mkdtempSync(join(tmpdir(), "dough-access-"));
process.env.MINIGIT_REPOS_ROOT = root;
process.env.MINIGIT_DB_PATH = join(root, "test.db");
@@ -42,20 +41,14 @@ function access(viewer, isPublic) {
return accessFor({ ref: repo, isPublic, viewer });
}
-// ---- a private repo with no collaborators -----------------------------------
-
check("the owner has write on their own private repo", access("alex", false) === "write");
check("a stranger sees nothing of a private repo", access("sam", false) === "none");
check("an anonymous visitor sees nothing of a private repo", access(null, false) === "none");
-// ---- a public repo ----------------------------------------------------------
-
check("anyone may read a public repo", access(null, true) === "read");
check("a stranger may read but not write a public repo", access("sam", true) === "read");
check("the owner still has write on a public repo", access("alex", true) === "write");
-// ---- read collaborators -----------------------------------------------------
-
setCollaborator(repo, "sam", "read");
check("a read collaborator can see a private repo", access("sam", false) === "read");
@@ -65,8 +58,6 @@ check(
collaboratorLevel(repo, "sam") === "read",
);
-// ---- write collaborators ----------------------------------------------------
-
setCollaborator(repo, "jo", "write");
check("a write collaborator can push", access("jo", false) === "write");
@@ -75,13 +66,10 @@ check(
access("jo", true) === "write",
);
-// Re-adding at a different level is a change, not a duplicate.
setCollaborator(repo, "sam", "write");
check("re-adding a collaborator changes their level", collaboratorLevel(repo, "sam") === "write");
check("re-adding does not duplicate the row", listCollaborators(repo).length === 2);
-// ---- the grant is per repo, not per owner -----------------------------------
-
const otherRepo = { owner: "alex", name: "secrets" };
check(
"a grant on one repo does not carry to another",
@@ -89,16 +77,12 @@ check(
accessFor({ ref: otherRepo, isPublic: false, viewer: "jo" }) === "none",
);
-// ---- the owner cannot be demoted into a collaborator ------------------------
-
check("inviting the owner is refused", setCollaborator(repo, "alex", "read") === false);
check(
"the owner keeps write regardless",
access("alex", false) === "write" && listCollaborators(repo).length === 2,
);
-// ---- listing what was shared with someone -----------------------------------
-
const jos = sharedWith("jo");
check(
"a collaborator can find the repos shared with them",
@@ -106,19 +90,14 @@ check(
);
check("somebody with no grants has nothing shared", sharedWith("nobody").length === 0);
-// ---- removal ----------------------------------------------------------------
-
check("removing a collaborator reports success", removeCollaborator(repo, "sam") === true);
check("a removed collaborator loses access", access("sam", false) === "none");
check("removing a non-collaborator reports failure", removeCollaborator(repo, "sam") === false);
-// Deleting a repo must not leave grants behind for a later repo of that name.
dropRepoAccess(repo);
check("deleting a repo drops its grants", listCollaborators(repo).length === 0);
check("and the former collaborator has no access", access("jo", false) === "none");
-// ---- path and argument validation -------------------------------------------
-
check("a normal repo path is accepted", safeRef("alex", "notes.git") !== null);
check("a traversal in the owner is refused", safeRef("..", "notes") === null);
check("a traversal in the name is refused", safeRef("alex", "../../etc") === null);
@@ -126,8 +105,6 @@ check("a bare dot segment is refused", safeRef(".", "notes") === null);
check("a hidden segment is refused", safeRef("alex", ".ssh") === null);
check("a slash in a segment is refused", safeRef("alex/evil", "notes") === null);
-// The one that mattered: an option-looking sha must never reach the git CLI,
-// because `git show --output=<file>` writes that file.
check("a real object id is accepted", safeObjectId("a94a8fe5cc") === "a94a8fe5cc");
check("an option-shaped sha is refused", safeObjectId("--output=/tmp/pwned") === null);
check("a dash-leading sha is refused", safeObjectId("-abc123") === null);
diff --git a/test/lifecycle.test.mjs b/test/lifecycle.test.mjs
new file mode 100644
index 0000000..5ef05d9
--- /dev/null
+++ b/test/lifecycle.test.mjs
@@ -0,0 +1,245 @@
+/* test/lifecycle.test.mjs
+ *
+ * Tests for the repository lifecycle: soft delete into <repos>/.trash, name
+ * reservation while a copy is recoverable, restore, and permanent purge.
+ *
+ * This is the part of the application that moves and destroys real directories,
+ * so the hostile cases (traversal out of the trash root, collisions) are
+ * asserted directly rather than inferred from the routes that call it.
+ *
+ * Run: node --experimental-sqlite --experimental-strip-types test/lifecycle.test.mjs
+ */
+
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+import {
+ mkdtempSync,
+ rmSync,
+ existsSync,
+ writeFileSync,
+ readFileSync,
+ mkdirSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+const exec = promisify(execFile);
+
+const root = mkdtempSync(join(tmpdir(), "dough-life-"));
+process.env.MINIGIT_REPOS_ROOT = root;
+process.env.MINIGIT_DB_PATH = join(root, "test.db");
+process.env.MINIGIT_TRASH_DAYS = "30";
+
+const {
+ createRepo,
+ initBareRepo,
+ repoExists,
+ refDir,
+ listRepos,
+ trashRepo,
+ listTrash,
+ trashHasName,
+ restoreFromTrash,
+ purgeFromTrash,
+ purgeExpired,
+ DELETED_META,
+} = await import("../src/git.ts");
+const { setCollaborator, listCollaborators, collaboratorLevel } = await import(
+ "../src/access.ts"
+);
+const { clearRepoMetadata } = await import("../src/repometa.ts");
+
+let failures = 0;
+function check(label, cond) {
+ console.log(`${cond ? "PASS" : "FAIL"} ${label}`);
+ if (!cond) failures++;
+}
+
+const REF = { owner: "alice", name: "notes" };
+const trashOf = (owner) => join(root, ".trash", owner);
+
+async function seed(ref = REF) {
+ const created = await createRepo(ref.owner, ref.name);
+ if (!created.ok) throw new Error(`seed failed: ${created.error}`);
+ const work = mkdtempSync(join(tmpdir(), "dough-work-"));
+ await exec("git", ["init", "-q", "--initial-branch=main", work]);
+ writeFileSync(join(work, "a.txt"), "hello\n");
+ await exec("git", ["-C", work, "add", "."]);
+ await exec("git", [
+ "-C", work, "-c", "user.email=t@t", "-c", "user.name=T",
+ "commit", "-q", "-m", "first",
+ ]);
+ await exec("git", ["-C", work, "push", "-q", refDir(ref), "main"]);
+ rmSync(work, { recursive: true, force: true });
+}
+
+const trashIt = (ref, at = Math.floor(Date.now() / 1000)) =>
+ trashRepo(ref, { deletedAt: at, deletedBy: ref.owner, grants: listCollaborators(ref) });
+
+console.log("\n-- delete moves rather than destroys --");
+await seed();
+setCollaborator(REF, "bob", "write");
+setCollaborator(REF, "carol", "read");
+check("repo exists before deletion", await repoExists(REF));
+
+const moved = await trashIt(REF);
+clearRepoMetadata(REF);
+check("trashRepo reports success", moved.ok === true);
+check("live path is gone", !(await repoExists(REF)));
+check("live directory really removed", !existsSync(refDir(REF)));
+check("git data still exists in trash", existsSync(join(trashOf("alice"), moved.entry, "HEAD")));
+check("entry is named <name>.<ts>.git", /^notes\.\d+\.git$/.test(moved.entry));
+
+console.log("\n-- the deleted repo is invisible --");
+const listed = await listRepos();
+check("listRepos does not show it", !listed.some((r) => r.name === "notes"));
+check("listRepos does not invent a '.trash' owner", !listed.some((r) => r.owner === ".trash"));
+
+console.log("\n-- metadata snapshot --");
+const meta = JSON.parse(
+ readFileSync(join(trashOf("alice"), moved.entry, DELETED_META), "utf8"),
+);
+check("snapshot is versioned", meta.version === 1);
+check("snapshot records owner", meta.owner === "alice");
+check("snapshot records name", meta.name === "notes");
+check("snapshot records who deleted it", meta.deletedBy === "alice");
+check("snapshot records a timestamp", typeof meta.deletedAt === "number" && meta.deletedAt > 0);
+check("snapshot captured both grants", meta.grants.length === 2);
+check(
+ "snapshot preserved levels",
+ meta.grants.find((g) => g.slug === "bob")?.level === "write" &&
+ meta.grants.find((g) => g.slug === "carol")?.level === "read",
+);
+
+console.log("\n-- live grants were cleared --");
+check("bob has no live grant", collaboratorLevel(REF, "bob") === null);
+check("carol has no live grant", collaboratorLevel(REF, "carol") === null);
+
+console.log("\n-- the name stays reserved --");
+check("trashHasName sees it", await trashHasName("alice", "notes"));
+const blocked = await createRepo("alice", "notes");
+check("creating the same name is refused", blocked.ok === false);
+check("refusal is flagged as reserved", blocked.reserved === true);
+check("refusal explains where to look", /recently deleted/i.test(blocked.error));
+check("another name is still fine", (await createRepo("alice", "other")).ok === true);
+check("another owner is unaffected", (await createRepo("bob", "notes")).ok === true);
+
+console.log("\n-- listing --");
+const trash = await listTrash("alice");
+check("one recoverable entry", trash.length === 1);
+check("entry knows its name", trash[0].name === "notes");
+check("entry is not degraded", trash[0].degraded === false);
+check("entry carries its grants", trash[0].grants.length === 2);
+check("another owner's trash is separate", (await listTrash("bob")).length === 0);
+
+console.log("\n-- restore --");
+const restored = await restoreFromTrash("alice", moved.entry);
+check("restore succeeds", restored.ok === true);
+check("repo is back at its original path", await repoExists(REF));
+check("git data came back", existsSync(join(refDir(REF), "HEAD")));
+check("trash entry is gone", (await listTrash("alice")).length === 0);
+check("metadata file was cleaned up", !existsSync(join(refDir(REF), DELETED_META)));
+check("name is no longer reserved", !(await trashHasName("alice", "notes")));
+const log = await exec("git", ["-C", refDir(REF), "log", "--format=%s", "-1"]);
+check("restored repo still has its commit", log.stdout.trim() === "first");
+
+console.log("\n-- restore refuses a collision --");
+await seed({ owner: "alice", name: "clash" });
+const clash = await trashIt({ owner: "alice", name: "clash" });
+await initBareRepo({ owner: "alice", name: "clash" });
+const refused = await restoreFromTrash("alice", clash.entry);
+check("restore is refused", refused.ok === false);
+check("refusal names the collision", /already exists/i.test(refused.error));
+check("the trashed copy is still there", (await listTrash("alice")).some((e) => e.entry === clash.entry));
+check("the live repo was not touched", await repoExists({ owner: "alice", name: "clash" }));
+
+console.log("\n-- purge --");
+const gone = await purgeFromTrash("alice", clash.entry);
+check("purge reports success", gone === true);
+check("directory is destroyed", !existsSync(join(trashOf("alice"), clash.entry)));
+check("purging twice is harmless", (await purgeFromTrash("alice", clash.entry)) === false);
+
+console.log("\n-- recreate after purge --");
+const after = { owner: "alice", name: "recycled" };
+await seed(after);
+setCollaborator(after, "bob", "write");
+const rec = await trashIt(after);
+clearRepoMetadata(after);
+await purgeFromTrash("alice", rec.entry);
+clearRepoMetadata(after);
+const remade = await createRepo(after.owner, after.name);
+check("the name is free again", remade.ok === true);
+check("and inherits no stale grants", listCollaborators(after).length === 0);
+
+console.log("\n-- retention --");
+const old = { owner: "alice", name: "ancient" };
+await seed(old);
+const oldEntry = await trashIt(old, Math.floor(Date.now() / 1000) - 40 * 86400);
+const fresh = { owner: "alice", name: "recent" };
+await seed(fresh);
+await trashIt(fresh);
+const purged = await purgeExpired("alice");
+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)));
+
+console.log("\n-- degraded entry (metadata unreadable) --");
+const broken = { owner: "alice", name: "broken" };
+await seed(broken);
+const brokenEntry = await trashIt(broken);
+writeFileSync(join(trashOf("alice"), brokenEntry.entry, DELETED_META), "{ not json");
+const degraded = (await listTrash("alice")).find((e) => e.entry === brokenEntry.entry);
+check("entry still lists", degraded !== undefined);
+check("entry is flagged degraded", degraded.degraded === true);
+check("name recovered from the directory name", degraded.name === "broken");
+check("degraded entry still reserves its name", await trashHasName("alice", "broken"));
+check("degraded entry is restorable", (await restoreFromTrash("alice", brokenEntry.entry)).ok === true);
+
+console.log("\n-- path safety: nothing escapes the trash root --");
+const canary = join(root, "canary.txt");
+writeFileSync(canary, "do not delete");
+mkdirSync(join(root, "victim"), { recursive: true });
+writeFileSync(join(root, "victim", "keep.txt"), "keep");
+
+const hostile = [
+ "../../etc",
+ "../victim",
+ "../../victim",
+ "..",
+ ".",
+ "./notes.1.git",
+ "/etc/passwd",
+ "notes.1.git/../../../victim",
+ "..%2fvictim",
+ "\0notes.1.git",
+ "notes.1.git\0",
+ ".hidden.1.git",
+ "notes.git",
+ "notes.1",
+ "notes",
+ "",
+ "a".repeat(300) + ".1.git",
+ "no ts.git",
+ "notes.1.git ",
+];
+for (const entry of hostile) {
+ const purgedBad = await purgeFromTrash("alice", entry);
+ check(`purge refuses ${JSON.stringify(entry)}`, purgedBad === false);
+ const restoredBad = await restoreFromTrash("alice", entry);
+ check(`restore refuses ${JSON.stringify(entry)}`, restoredBad.ok === false);
+}
+check("canary outside the trash survived", existsSync(canary));
+check("sibling directory survived", existsSync(join(root, "victim", "keep.txt")));
+
+for (const owner of ["../..", ".", "..", ".trash", "al/ice", "al\0ice", ""]) {
+ check(
+ `trash rejects owner ${JSON.stringify(owner)}`,
+ (await listTrash(owner)).length === 0 &&
+ (await purgeFromTrash(owner, "notes.1.git")) === false,
+ );
+}
+check("repos root itself survived", existsSync(root));
+
+rmSync(root, { recursive: true, force: true });
+console.log(failures === 0 ? "\nALL PASSED" : `\n${failures} FAILED`);
+process.exit(failures === 0 ? 0 : 1);
diff --git a/test/markdown.test.mjs b/test/markdown.test.mjs
index 7ae3144..fb437f2 100644
--- a/test/markdown.test.mjs
+++ b/test/markdown.test.mjs
@@ -18,8 +18,6 @@ function check(label, cond) {
const has = (md, needle) => renderMarkdown(md).includes(needle);
const lacks = (md, needle) => !renderMarkdown(md).includes(needle);
-// ---- security ---------------------------------------------------------------
-
check(
"script tags are never emitted",
lacks("<script>alert(1)</script>", "<script"),
@@ -58,8 +56,6 @@ check(
has("[docs](/docs/readme.md)", 'href="/docs/readme.md"'),
);
-// ---- block rendering --------------------------------------------------------
-
check("ATX heading", has("# Title", "<h1>Title</h1>"));
check("deeper ATX heading", has("### Three", "<h3>Three</h3>"));
check("setext heading", has("Title\n=====", "<h1>Title</h1>"));
@@ -96,8 +92,6 @@ check(
);
check("table head", has("| a | b |\n| - | - |\n| 1 | 2 |", "<th>a</th>"));
check("table body", has("| a | b |\n| - | - |\n| 1 | 2 |", "<td>1</td>"));
-// Alignment is a data attribute, not an inline style — the CSP blocks style
-// attributes, so an inline text-align never reached the page.
check(
"table alignment centres",
has("| a |\n| :-: |\n| 1 |", 'data-align="center"'),
@@ -142,8 +136,6 @@ check(
lacks("visible <!-- secret --> text", "secret"),
);
-// ---- inline rendering -------------------------------------------------------
-
check("bold", has("**bold**", "<strong>bold</strong>"));
check("italic", has("*italic*", "<em>italic</em>"));
check("bold italic", has("***both***", "<strong><em>both</em></strong>"));
@@ -171,8 +163,6 @@ check(
check("hard break", has("line one \nline two", "<br>"));
check("ampersands are escaped once", has("a & b", "a & b"));
-// ---- plainSummary -----------------------------------------------------------
-
check(
"plainSummary skips the leading heading",
plainSummary("# my-repo\n\nDoes a useful thing.") === "Does a useful thing.",
@@ -216,8 +206,6 @@ check(
);
check("plainSummary of an empty README is empty", plainSummary("") === "");
-// ---- robustness -------------------------------------------------------------
-
check("empty input renders nothing", renderMarkdown("") === "");
check(
"unclosed fence doesn't hang or drop content",
diff --git a/test/mirror.test.mjs b/test/mirror.test.mjs
new file mode 100644
index 0000000..9113254
--- /dev/null
+++ b/test/mirror.test.mjs
@@ -0,0 +1,284 @@
+/* test/mirror.test.mjs
+ *
+ * Tests for backup/mirror status: parsing ls-remote, comparing refs, deciding
+ * a verdict, classifying transport failures, and — most importantly — proving
+ * the hardened remote git helper cannot be talked into anything else.
+ *
+ * The classifier cases use the exact stderr the two forges were measured to
+ * produce, so the difference between them (GitHub says "Repository not found";
+ * Codeberg answers a missing repo with a credential challenge, making private
+ * and missing indistinguishable) is pinned here rather than remembered.
+ *
+ * Run: node --experimental-sqlite --experimental-strip-types test/mirror.test.mjs
+ */
+
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+import { mkdtempSync, rmSync, writeFileSync, existsSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+const exec = promisify(execFile);
+
+const root = mkdtempSync(join(tmpdir(), "dough-mirror-"));
+process.env.MINIGIT_REPOS_ROOT = root;
+process.env.MINIGIT_DB_PATH = join(root, "test.db");
+
+const {
+ parseLsRemote,
+ compareRefs,
+ rollUp,
+ ancestryVerdict,
+ getStatuses,
+ dropMirrorStatus,
+ markStale,
+ needsCheck,
+} = await import("../src/mirror.ts");
+const { classifyRemoteError, lsRemote, createRepo, refDir, localMirrorRefs } =
+ await import("../src/git.ts");
+
+let failures = 0;
+function check(label, cond) {
+ console.log(`${cond ? "PASS" : "FAIL"} ${label}`);
+ if (!cond) failures++;
+}
+
+console.log("\n-- parsing ls-remote output --");
+const SAMPLE = [
+ "fe9f7fb2f2db07277ee6eef81d59b103cd1ca907\tHEAD",
+ "614f1c47151e40e92b57313140e067356fafdd60\trefs/heads/main",
+ "1ce22fe2085cf743e4d45bc738aec2ea5163c52f\trefs/heads/feature/thing",
+ "c089584ac8dedc3aa7c2c404839bc098050298a2\trefs/tags/v2.43.0",
+ "564d0252ca632e0264ed670534a51d18a689ef5d\trefs/tags/v2.43.0^{}",
+ "aaaa584ac8dedc3aa7c2c404839bc098050298a2\trefs/pull/1906/head",
+ "bbbb584ac8dedc3aa7c2c404839bc098050298a2\trefs/pull/1906/merge",
+ "cccc584ac8dedc3aa7c2c404839bc098050298a2\trefs/notes/commits",
+ "",
+ "garbage line with no tab",
+ "not-a-sha\trefs/heads/bogus",
+].join("\n");
+const parsed = parseLsRemote(SAMPLE);
+
+check(
+ "keeps branches",
+ parsed.get("refs/heads/main") === "614f1c47151e40e92b57313140e067356fafdd60",
+);
+check("keeps branches with slashes", parsed.has("refs/heads/feature/thing"));
+check(
+ "keeps the tag object",
+ parsed.get("refs/tags/v2.43.0") === "c089584ac8dedc3aa7c2c404839bc098050298a2",
+);
+check("drops the peeled ^{} entry", !parsed.has("refs/tags/v2.43.0^{}"));
+check(
+ "peeled sha does not overwrite the tag object",
+ parsed.get("refs/tags/v2.43.0") !== "564d0252ca632e0264ed670534a51d18a689ef5d",
+);
+check("ignores HEAD", !parsed.has("HEAD"));
+check(
+ "ignores refs/pull/*",
+ ![...parsed.keys()].some((k) => k.startsWith("refs/pull/")),
+);
+check("ignores other namespaces", !parsed.has("refs/notes/commits"));
+check("ignores malformed lines", !parsed.has("refs/heads/bogus"));
+check("counts only heads and tags", parsed.size === 3);
+check("empty input is empty", parseLsRemote("").size === 0);
+check("garbage input is empty", parseLsRemote("nonsense\n\n\t\n").size === 0);
+
+console.log("\n-- comparing refs --");
+const m = (o) => new Map(Object.entries(o));
+const A = "1111111111111111111111111111111111111111";
+const B = "2222222222222222222222222222222222222222";
+
+let cmp = compareRefs(m({ "refs/heads/main": A }), m({ "refs/heads/main": A }));
+check("identical: all matched", cmp.matched === 1 && cmp.total === 1);
+check(
+ "identical: nothing missing",
+ cmp.missingLocal.length === 0 && cmp.missingRemote.length === 0,
+);
+check("identical rolls up to synced", rollUp(cmp, "synced") === "synced");
+
+cmp = compareRefs(
+ m({ "refs/heads/main": A, "refs/tags/v1": A }),
+ m({ "refs/heads/main": A }),
+);
+check("a ref missing remotely is detected", cmp.missingRemote.includes("refs/tags/v1"));
+check("total counts the union", cmp.total === 2 && cmp.matched === 1);
+check("local-only extras roll up to ahead", rollUp(cmp, "synced") === "ahead");
+
+cmp = compareRefs(
+ m({ "refs/heads/main": A }),
+ m({ "refs/heads/main": A, "refs/heads/extra": B }),
+);
+check("remote extras are detected", cmp.missingLocal.includes("refs/heads/extra"));
+check("remote extras roll up to behind", rollUp(cmp, "synced") === "behind");
+
+cmp = compareRefs(m({ "refs/heads/main": A }), m({ "refs/heads/main": B }));
+check("a differing sha is detected", cmp.differing.includes("refs/heads/main"));
+check("the head verdict wins the roll-up", rollUp(cmp, "ahead") === "ahead");
+check("and again for diverged", rollUp(cmp, "diverged") === "diverged");
+check("no head verdict stays honest", rollUp(cmp, null) === "out_of_sync");
+
+cmp = compareRefs(
+ m({ "refs/heads/main": A, "refs/heads/a": A }),
+ m({ "refs/heads/main": A, "refs/heads/b": B }),
+);
+check("differences both ways -> out_of_sync", rollUp(cmp, "synced") === "out_of_sync");
+check("empty on both sides -> synced", rollUp(compareRefs(m({}), m({})), null) === "synced");
+
+console.log("\n-- ancestry, against a real repository --");
+const ref = { owner: "alice", name: "anc" };
+await createRepo(ref.owner, ref.name);
+const work = mkdtempSync(join(tmpdir(), "dough-anc-"));
+await exec("git", ["init", "-q", "--initial-branch=main", work]);
+const commit = async (msg) => {
+ writeFileSync(join(work, "f.txt"), msg);
+ await exec("git", ["-C", work, "add", "."]);
+ await exec("git", [
+ "-C", work, "-c", "user.email=t@t", "-c", "user.name=T",
+ "commit", "-q", "-m", msg,
+ ]);
+ const { stdout } = await exec("git", ["-C", work, "rev-parse", "HEAD"]);
+ return stdout.trim();
+};
+const c1 = await commit("one");
+await commit("two");
+const c3 = await commit("three");
+await exec("git", ["-C", work, "push", "-q", refDir(ref), "main"]);
+
+check("equal shas -> synced", (await ancestryVerdict(ref, c3, c3)) === "synced");
+check(
+ "remote tip is an ancestor -> ahead (the stale-mirror alarm)",
+ (await ancestryVerdict(ref, c3, c1)) === "ahead",
+);
+check("local tip is an ancestor -> behind", (await ancestryVerdict(ref, c1, c3)) === "behind");
+check(
+ "remote object we don't hold -> out_of_sync, never a guess",
+ (await ancestryVerdict(ref, c3, "dead" + "beef".repeat(9))) === "out_of_sync",
+);
+check("null shas -> no verdict", (await ancestryVerdict(ref, null, c1)) === null);
+
+await exec("git", ["-C", work, "checkout", "-q", "-b", "side", c1]);
+const side = await commit("side");
+await exec("git", ["-C", work, "push", "-q", refDir(ref), "side"]);
+check("neither is an ancestor -> diverged", (await ancestryVerdict(ref, c3, side)) === "diverged");
+
+console.log("\n-- local ref inspection --");
+const local = await localMirrorRefs(ref);
+check("finds local branches", local.has("refs/heads/main") && local.has("refs/heads/side"));
+check("main points at the tip", local.get("refs/heads/main") === c3);
+check("no HEAD entry", !local.has("HEAD"));
+
+console.log("\n-- transport classification (measured stderr) --");
+const cls = (stderr, timedOut = false) => classifyRemoteError(stderr, timedOut).kind;
+check(
+ "GitHub missing repository -> missing",
+ cls(
+ "remote: Repository not found.\nfatal: repository 'https://github.com/a/b/' not found",
+ ) === "missing",
+);
+check(
+ "Codeberg credential challenge -> denied (private OR missing; honest)",
+ cls(
+ "fatal: could not read Username for 'https://codeberg.org': terminal prompts disabled",
+ ) === "denied",
+);
+check("authentication failed -> denied", cls("fatal: Authentication failed for 'https://x/'") === "denied");
+check(
+ "403 -> denied",
+ cls("fatal: unable to access '...': The requested URL returned error: 403") === "denied",
+);
+check(
+ "DNS failure -> error",
+ cls("fatal: unable to access 'https://x/': Could not resolve host: x") === "error",
+);
+check(
+ "TLS failure -> error",
+ cls("fatal: unable to access '...': SSL certificate problem: self signed certificate") === "error",
+);
+check("timeout wins over any stderr -> error", cls("Repository not found.", true) === "error");
+check("timeout message says so", classifyRemoteError("x", true).message === "timed out");
+check("empty stderr -> error", cls("") === "error");
+check(
+ "the message drops git's fatal: prefix",
+ !classifyRemoteError("fatal: could not resolve host", false).message.startsWith("fatal:"),
+);
+check(
+ "the message is bounded",
+ classifyRemoteError("fatal: " + "x".repeat(5000), false).message.length <= 160,
+);
+
+console.log("\n-- security: the remote helper refuses everything but https --");
+const canary = join(root, "pwned.txt");
+const extResult = await lsRemote(`ext::touch ${canary}`);
+check("ext:: transport is refused", extResult.ok === false);
+check("ext:: did NOT execute the command", !existsSync(canary));
+
+const localUrl = `file://${refDir(ref)}`;
+const controlWorks = await exec("git", ["ls-remote", localUrl]).then(
+ (r) => r.stdout.includes(c3),
+ () => false,
+);
+check("plain git CAN read this local repo (control)", controlWorks === true);
+const fileResult = await lsRemote(localUrl);
+check("but the hardened helper refuses file://", fileResult.ok === false);
+check("and yields none of its refs", !JSON.stringify(fileResult).includes(c3));
+
+for (const url of [
+ refDir(ref),
+ "git://example.invalid/a/b",
+ "ssh://[email protected]/a/b",
+ "http://example.invalid/a/b",
+]) {
+ const r = await lsRemote(url);
+ check(`refuses ${JSON.stringify(url.slice(0, 44))}`, r.ok === false);
+}
+
+console.log("\n-- security: git config cannot rewrite the URL --");
+const evilConfig = join(root, "evil.gitconfig");
+writeFileSync(
+ evilConfig,
+ `[url "file://${refDir(ref)}"]\n\tinsteadOf = https://github.com/evil/evil\n`,
+);
+const rewriteReachable = await exec("git", [
+ "-c", `include.path=${evilConfig}`,
+ "ls-remote", "https://github.com/evil/evil",
+]).then((r) => r.stdout.includes(c3), () => false);
+check("the insteadOf rewrite really is reachable (control)", rewriteReachable === true);
+
+process.env.GIT_CONFIG_GLOBAL = evilConfig;
+process.env.HOME = root;
+const rewritten = await lsRemote("https://github.com/evil/evil");
+check(
+ "the hardened helper ignores ambient git config",
+ !JSON.stringify(rewritten).includes(c3),
+);
+delete process.env.GIT_CONFIG_GLOBAL;
+
+console.log("\n-- security: no interactive prompt, failures are bounded --");
+const started = Date.now();
+const unreachable = await lsRemote("https://nonexistent.invalid/a/b");
+check("an unresolvable host fails rather than hanging", unreachable.ok === false);
+check("classified as a transport error", unreachable.kind === "error");
+check("and returns well inside the timeout", Date.now() - started < 12000);
+
+console.log("\n-- cache bookkeeping --");
+const cref = { owner: "alice", name: "cache" };
+const nowSec = Math.floor(Date.now() / 1000);
+const row = (over) => ({
+ kind: "github", checkedAt: nowSec, okAt: nowSec, error: null,
+ state: "synced", localSha: null, remoteSha: null, detail: null, ...over,
+});
+check("no rows to begin with", getStatuses(cref).size === 0);
+check("a missing row needs a check", needsCheck(undefined) === true);
+check("a fresh row does not", needsCheck(row()) === false);
+check("a row never verified does", needsCheck(row({ okAt: null, error: "x", state: null })) === true);
+check("a row verified long ago does", needsCheck(row({ okAt: 1 })) === true);
+check("a row invalidated by a push does", needsCheck(row({ checkedAt: 0 })) === true);
+dropMirrorStatus(cref);
+markStale(cref);
+check("dropping and invalidating nothing is harmless", getStatuses(cref).size === 0);
+
+rmSync(root, { recursive: true, force: true });
+rmSync(work, { recursive: true, force: true });
+console.log(failures === 0 ? "\nALL PASSED" : `\n${failures} FAILED`);
+process.exit(failures === 0 ? 0 : 1);
diff --git a/test/notify.test.mjs b/test/notify.test.mjs
new file mode 100644
index 0000000..0e33536
--- /dev/null
+++ b/test/notify.test.mjs
@@ -0,0 +1,256 @@
+/* test/notify.test.mjs
+ *
+ * Tests for Discord notifications.
+ *
+ * Two things matter more than the message wording. A notification must never
+ * be able to break or delay a git operation, and the webhook URL is a
+ * credential that must never reach a log line. Both are asserted directly.
+ *
+ * fetch is stubbed throughout: these tests never touch the network.
+ *
+ * Run: node --experimental-sqlite --experimental-strip-types test/notify.test.mjs
+ */
+
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+const exec = promisify(execFile);
+
+const root = mkdtempSync(join(tmpdir(), "dough-notify-"));
+process.env.MINIGIT_REPOS_ROOT = root;
+process.env.MINIGIT_DB_PATH = join(root, "test.db");
+process.env.MINIGIT_BASE_URL = "https://git.example.test";
+
+const {
+ diffRefs,
+ pushEmbed,
+ repoCreatedEmbed,
+ repoDeletedEmbed,
+ notifyRepoCreated,
+ notifyRepoDeleted,
+ notifyPush,
+} = await import("../src/notify.ts");
+const { createRepo, refDir, localMirrorRefs } = await import("../src/git.ts");
+const { setDiscordWebhook, setPrefs, getSettings } = await import(
+ "../src/settings.ts"
+);
+
+let failures = 0;
+function check(label, cond) {
+ console.log(`${cond ? "PASS" : "FAIL"} ${label}`);
+ if (!cond) failures++;
+}
+
+const TOKEN = "SUPERSECRETTOKENVALUE";
+const WEBHOOK = `https://discord.com/api/webhooks/1234567890/${TOKEN}`;
+
+let sent = [];
+let fetchMode = "ok";
+globalThis.fetch = async (url, init) => {
+ sent.push({ url: String(url), body: JSON.parse(init.body) });
+ if (fetchMode === "throw") throw new Error("connect ECONNREFUSED 10.0.0.1:443");
+ if (fetchMode === "500") return { ok: false, status: 500 };
+ return { ok: true, status: 204 };
+};
+
+let logged = [];
+const realWarn = console.warn;
+const realError = console.error;
+console.warn = (...a) => logged.push(a.map(String).join(" "));
+console.error = (...a) => logged.push(a.map(String).join(" "));
+
+const settle = () => new Promise((r) => setTimeout(r, 60));
+
+const ref = { owner: "alice", name: "proj" };
+await createRepo(ref.owner, ref.name);
+const work = mkdtempSync(join(tmpdir(), "dough-nwork-"));
+await exec("git", ["init", "-q", "--initial-branch=main", work]);
+const commit = async (msg) => {
+ writeFileSync(join(work, "f.txt"), msg);
+ await exec("git", ["-C", work, "add", "."]);
+ await exec("git", [
+ "-C", work, "-c", "user.email=t@t", "-c", "user.name=Test Person",
+ "commit", "-q", "-m", msg,
+ ]);
+ const { stdout } = await exec("git", ["-C", work, "rev-parse", "HEAD"]);
+ return stdout.trim();
+};
+
+console.log("\n-- describing a push --");
+const c1 = await commit("first commit");
+await exec("git", ["-C", work, "push", "-q", refDir(ref), "main"]);
+const afterFirst = await localMirrorRefs(ref);
+
+let changes = await diffRefs(ref, new Map(), afterFirst);
+check("a new branch is one change", changes.length === 1);
+check("it is refs/heads/main", changes[0].ref === "refs/heads/main");
+check("with no before", changes[0].before === null);
+check("and is not a force push", changes[0].forced === false);
+check("and carries its commit", changes[0].commits.some((x) => x.subject === "first commit"));
+
+const c2 = await commit("second commit");
+await exec("git", ["-C", work, "push", "-q", refDir(ref), "main"]);
+const afterSecond = await localMirrorRefs(ref);
+changes = await diffRefs(ref, afterFirst, afterSecond);
+check("a fast-forward is one change", changes.length === 1);
+check("before and after are both set", changes[0].before === c1 && changes[0].after === c2);
+check("not flagged as forced", changes[0].forced === false);
+check("only the new commit is listed", changes[0].commits.length === 1);
+check("which is the right one", changes[0].commits[0].subject === "second commit");
+
+console.log("\n-- force push --");
+await exec("git", ["-C", work, "reset", "-q", "--hard", c1]);
+const c3 = await commit("rewritten");
+await exec("git", ["-C", work, "push", "-q", "--force", refDir(ref), "main"]);
+const afterForce = await localMirrorRefs(ref);
+changes = await diffRefs(ref, afterSecond, afterForce);
+check("rewriting history is detected", changes.length === 1);
+check("and flagged as a force push", changes[0].forced === true);
+
+console.log("\n-- new branch, new tag, deleted ref --");
+await exec("git", ["-C", work, "checkout", "-q", "-b", "topic"]);
+await commit("on a topic branch");
+await exec("git", ["-C", work, "tag", "v1.0"]);
+await exec("git", ["-C", work, "push", "-q", refDir(ref), "topic", "v1.0"]);
+const afterMore = await localMirrorRefs(ref);
+changes = await diffRefs(ref, afterForce, afterMore);
+check("both new refs are reported", changes.length === 2);
+check("the tag is included", changes.some((ch) => ch.ref === "refs/tags/v1.0"));
+check("the branch is included", changes.some((ch) => ch.ref === "refs/heads/topic"));
+
+const afterDelete = new Map(afterMore);
+afterDelete.delete("refs/heads/topic");
+changes = await diffRefs(ref, afterMore, afterDelete);
+check("a deleted ref is reported", changes.length === 1);
+check("with a null after", changes[0].after === null);
+
+check("an unchanged snapshot yields nothing", (await diffRefs(ref, afterMore, afterMore)).length === 0);
+
+console.log("\n-- embeds --");
+const pushed = await diffRefs(ref, afterSecond, afterForce);
+const embed = pushEmbed(ref, "alice", pushed);
+check("push embed names the repo", embed.title.includes("alice/proj"));
+check("push embed marks the force push", embed.description.includes("force-pushed"));
+check("push embed names the pusher", embed.description.includes("alice"));
+check("push embed links commits absolutely", embed.description.includes("https://git.example.test/alice/proj/commit/"));
+check("no changes yields no embed", pushEmbed(ref, "alice", []) === null);
+check("created embed names the repo", repoCreatedEmbed(ref, "alice").title.includes("alice/proj"));
+check("deleted embed mentions recovery", repoDeletedEmbed(ref, "alice").description.includes("Recently Deleted"));
+
+const hostile = [
+ {
+ ref: "refs/heads/main",
+ before: c1,
+ after: c2,
+ forced: false,
+ commits: [
+ {
+ hash: "a".repeat(40),
+ subject: "[click me](https://evil.test) **bold** `code`",
+ author: "@everyone",
+ email: "",
+ time: 0,
+ },
+ ],
+ },
+];
+const hostileEmbed = pushEmbed(ref, "alice", hostile);
+check("markdown link syntax is neutralised", !hostileEmbed.description.includes("[click me](https://evil.test)"));
+check("the evil host is not linked", !/\]\(https:\/\/evil\.test\)/.test(hostileEmbed.description));
+check("bold markers are escaped", !hostileEmbed.description.includes("**bold**"));
+
+console.log("\n-- delivery: only when configured, only when allowed --");
+const OWNER = "alice";
+sent = [];
+notifyRepoCreated(ref, OWNER, true);
+await settle();
+check("no webhook configured -> nothing sent", sent.length === 0);
+
+setDiscordWebhook(OWNER, WEBHOOK);
+sent = [];
+notifyRepoCreated(ref, OWNER, true);
+await settle();
+check("public repo -> delivered", sent.length === 1);
+check("delivered to the configured webhook", sent[0].url === WEBHOOK);
+check("payload carries one embed", Array.isArray(sent[0].body.embeds) && sent[0].body.embeds.length === 1);
+
+sent = [];
+notifyRepoCreated(ref, OWNER, false);
+await settle();
+check("private repo is NOT announced by default", sent.length === 0);
+
+setPrefs(OWNER, { discordPrivate: true, defaultPrivate: true, mirrorAuto: true });
+sent = [];
+notifyRepoCreated(ref, OWNER, false);
+await settle();
+check("private repo IS announced once opted in", sent.length === 1);
+
+setPrefs(OWNER, { discordPrivate: false, defaultPrivate: true, mirrorAuto: true });
+sent = [];
+notifyRepoDeleted(ref, OWNER, true);
+await settle();
+check("deletion is delivered", sent.length === 1 && sent[0].body.embeds[0].title.includes("deleted"));
+
+sent = [];
+notifyPush(ref, OWNER, true, afterSecond, afterForce);
+await settle();
+check("push is delivered", sent.length === 1);
+check("push embed mentions the force push", sent[0].body.embeds[0].description.includes("force-pushed"));
+
+sent = [];
+notifyPush(ref, OWNER, true, afterMore, afterMore);
+await settle();
+check("a push that changed nothing is not announced", sent.length === 0);
+
+console.log("\n-- failure never escapes, and never leaks the URL --");
+logged = [];
+fetchMode = "throw";
+let threw = false;
+try {
+ notifyRepoCreated(ref, OWNER, true);
+ notifyPush(ref, OWNER, true, afterSecond, afterForce);
+ await settle();
+} catch {
+ threw = true;
+}
+check("a delivery exception does not propagate", threw === false);
+check("the failure was recorded on the account", getSettings(OWNER).webhookError !== null);
+check("the recorded error is not the URL", !getSettings(OWNER).webhookError.includes(TOKEN));
+
+fetchMode = "500";
+notifyRepoCreated(ref, OWNER, true);
+await settle();
+check("an HTTP error is recorded", getSettings(OWNER).webhookError === "HTTP 500");
+
+fetchMode = "ok";
+notifyRepoCreated(ref, OWNER, true);
+await settle();
+check("a later success clears the error", getSettings(OWNER).webhookError === null);
+
+const allLogs = logged.join("\n");
+check("the webhook token never appears in any log", !allLogs.includes(TOKEN));
+check("the full webhook URL never appears in any log", !allLogs.includes(WEBHOOK));
+check("logs did mention a failure (so the check above is meaningful)", /failed/i.test(allLogs));
+
+console.log("\n-- a broken webhook does not stop repository work --");
+fetchMode = "throw";
+setDiscordWebhook(OWNER, WEBHOOK);
+const before = Date.now();
+notifyPush(ref, OWNER, true, afterSecond, afterForce);
+const elapsed = Date.now() - before;
+check("notifying returns immediately (fire and forget)", elapsed < 50);
+const stillWorks = await createRepo("alice", "unaffected");
+check("repository operations still succeed", stillWorks.ok === true);
+await settle();
+
+console.log = console.log;
+console.warn = realWarn;
+console.error = realError;
+
+rmSync(root, { recursive: true, force: true });
+rmSync(work, { recursive: true, force: true });
+console.log(failures === 0 ? "\nALL PASSED" : `\n${failures} FAILED`);
+process.exit(failures === 0 ? 0 : 1);
diff --git a/test/ownership.test.mjs b/test/ownership.test.mjs
index 53f67f2..cf25763 100644
--- a/test/ownership.test.mjs
+++ b/test/ownership.test.mjs
@@ -11,7 +11,6 @@ import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-// Point config at a throwaway database BEFORE importing anything that opens it.
const root = mkdtempSync(join(tmpdir(), "dough-own-"));
process.env.MINIGIT_REPOS_ROOT = root;
process.env.MINIGIT_DB_PATH = join(root, "test.db");
@@ -30,8 +29,6 @@ function basic(user, pass) {
return `Basic ${Buffer.from(`${user}:${pass}`).toString("base64")}`;
}
-// ---- setup ------------------------------------------------------------------
-
const alex = rememberUser({
sub: "oidc-alex",
username: "Alex.Kim",
@@ -48,8 +45,6 @@ const sam = rememberUser({
check("username is slugified into an owner segment", alex.slug === "alex.kim");
-// A second account whose name collides must not land in the first one's
-// namespace — that would hand it push rights over someone else's repos.
const impostor = rememberUser({
sub: "oidc-impostor",
username: "alex.kim",
@@ -62,8 +57,6 @@ check("colliding usernames get distinct slugs", impostor.slug === "alex.kim-2");
const alexToken = createToken("laptop", alex.slug, alex.sub);
const samToken = createToken("laptop", sam.slug, sam.sub);
-// ---- identity ---------------------------------------------------------------
-
check(
"no credentials is anonymous",
authenticateGit(undefined).kind === "anonymous",
@@ -96,15 +89,11 @@ check(
authenticateGit(basic("", alexToken)).kind === "rejected",
);
-// The instance-wide token is gone: no credential acts as anything but one
-// account, so a would-be static token is simply not a token.
check(
"there is no instance-wide credential any more",
authenticateGit(basic("anything", "static-instance-token")).kind === "rejected",
);
-// ---- actor ------------------------------------------------------------------
-
check("a user token acts as its owner", gitActor(asAlex) === "alex.kim");
check("anonymous acts as nobody", gitActor({ kind: "anonymous" }) === null);
check(
@@ -112,8 +101,6 @@ check(
gitActor({ kind: "rejected", message: "no" }) === null,
);
-// ---- token listing is per-owner ---------------------------------------------
-
check(
"a user only sees their own tokens",
listTokens("alex.kim").length === 1 && listTokens("sam").length === 1,
diff --git a/test/refs.test.mjs b/test/refs.test.mjs
index a54e86f..a4a7ceb 100644
--- a/test/refs.test.mjs
+++ b/test/refs.test.mjs
@@ -47,8 +47,6 @@ async function git(cwd, args) {
return stdout;
}
-// ---- a real bare repo with two branches and a tag ---------------------------
-
const ref = { owner: "alex", name: "notes" };
const bare = refDir(ref);
mkdirSync(join(root, "alex"), { recursive: true });
@@ -68,15 +66,11 @@ await git(work, ["push", "-q", bare, "main", "feature/thing", "v1"]);
const refs = await listRefs(ref);
-// ---- listing ----------------------------------------------------------------
-
check("HEAD's branch is reported", refs.head === "main");
check("branches are listed", refs.branches.includes("main") && refs.branches.includes("feature/thing"));
check("tags are listed", refs.tags.includes("v1"));
check("a tag is not mistaken for a branch", !refs.branches.includes("v1"));
-// ---- resolution -------------------------------------------------------------
-
check("no request resolves to HEAD", (await resolveRev(ref, undefined, refs)) === "main");
check("an empty request resolves to HEAD", (await resolveRev(ref, "", refs)) === "main");
check(
@@ -92,10 +86,6 @@ check(
(await resolveRev(ref, head.slice(0, 10), refs)) === head.slice(0, 10),
);
-// ---- the security property --------------------------------------------------
-// Anything not on the allow-list falls back to HEAD, so no attacker-chosen
-// string ever reaches git as an argument.
-
const hostile = [
"--output=/tmp/dough-pwned",
"--upload-pack=touch /tmp/dough-pwned",
@@ -114,14 +104,11 @@ for (const candidate of hostile) {
);
}
-// The reads that take a revision must survive being given one, whatever it was.
check(
"log on the resolved revision still works",
(await log(ref, await resolveRev(ref, "--output=/tmp/x", refs), 5)).length > 0,
);
-// ---- description ------------------------------------------------------------
-
check("a fresh repo has no description", (await description(ref)) === "");
await setDescription(ref, " Notes to self ");
diff --git a/test/transport.test.mjs b/test/transport.test.mjs
index fcf0bdf..db94742 100644
--- a/test/transport.test.mjs
+++ b/test/transport.test.mjs
@@ -28,9 +28,6 @@ function check(label, cond) {
if (!cond) failures++;
}
-// IMPORTANT: async. The HTTP server runs in this same process, so blocking the
-// event loop (execFileSync) would deadlock — git would wait on a server that
-// can't run. Awaiting keeps the loop free to serve requests.
async function git(cwd, args) {
const { stdout } = await execFileAsync("git", args, {
cwd,
@@ -48,7 +45,6 @@ async function git(cwd, args) {
return stdout;
}
-// ---- unit: pkt-line framing -------------------------------------------------
check(
'pktLine("# service=git-upload-pack\\n") == "001e..."',
pktLine("# service=git-upload-pack\n").startsWith("001e"),
@@ -58,7 +54,6 @@ check(
pktLine("# service=git-receive-pack\n").startsWith("001f"),
);
-// ---- set up a real bare repo ------------------------------------------------
const work = mkdtempSync(join(tmpdir(), "dough-git-"));
const seed = join(work, "seed");
const bare = join(work, "repo.git");
@@ -70,7 +65,6 @@ await git(seed, ["commit", "-q", "-m", "initial"]);
await git(seed, ["branch", "-M", "main"]);
await git(work, ["clone", "-q", "--bare", seed, bare]);
-// ---- adapter: serve src/smart-http.ts over Node http ------------------------
async function sendResponse(res, response) {
res.statusCode = response.status;
response.headers.forEach((v, k) => res.setHeader(k, v));
@@ -128,20 +122,17 @@ const base = `http://127.0.0.1:${port}/repo.git`;
let cloned = false;
let pushed = false;
try {
- // ---- clone over HTTP ------------------------------------------------------
const out = join(work, "out");
await git(work, ["clone", "-q", base, out]);
const content = readFileSync(join(out, "hello.txt"), "utf8");
cloned = content === "hello backup\n";
check("clone over HTTP retrieves file content", cloned);
- // ---- push over HTTP -------------------------------------------------------
writeFileSync(join(out, "second.txt"), "more data\n");
await git(out, ["add", "."]);
await git(out, ["commit", "-q", "-m", "second"]);
await git(out, ["push", "-q", "origin", "main"]);
- // Bare repo should now have the second commit.
const logOut = await git(bare, ["log", "--oneline"]);
pushed = logOut.includes("second");
check("push over HTTP updates the bare repo", pushed);
diff --git a/test/urls.test.mjs b/test/urls.test.mjs
new file mode 100644
index 0000000..b5a4bbe
--- /dev/null
+++ b/test/urls.test.mjs
@@ -0,0 +1,148 @@
+/* test/urls.test.mjs
+ *
+ * Tests for src/urls.ts, which is a security boundary rather than a formatting
+ * helper: a mirror URL that gets past this is handed to the git binary as a
+ * remote to contact, and a webhook URL that gets past it is handed to fetch().
+ * So the hostile cases matter more than the valid ones.
+ *
+ * Run: node --experimental-strip-types test/urls.test.mjs
+ */
+
+import {
+ mirrorUrl,
+ discordWebhookUrl,
+ maskWebhook,
+ isMirrorKind,
+ MIRROR_KINDS,
+} from "../src/urls.ts";
+
+let failures = 0;
+function check(label, cond) {
+ console.log(`${cond ? "PASS" : "FAIL"} ${label}`);
+ if (!cond) failures++;
+}
+
+const ok = (kind, url, expected) =>
+ check(`accepts ${kind} ${url}`, mirrorUrl(kind, url) === expected);
+const no = (kind, url, why) =>
+ check(`refuses ${why}: ${JSON.stringify(url)}`, mirrorUrl(kind, url) === null);
+
+console.log("\n-- kinds --");
+check("github is a kind", isMirrorKind("github"));
+check("codeberg is a kind", isMirrorKind("codeberg"));
+check("gitlab is not", !isMirrorKind("gitlab"));
+check("only two kinds exist", MIRROR_KINDS.length === 2);
+
+console.log("\n-- valid mirror URLs --");
+ok("github", "https://github.com/user/repo", "https://github.com/user/repo");
+ok("codeberg", "https://codeberg.org/user/repo", "https://codeberg.org/user/repo");
+ok("github", "https://github.com/user/repo.git", "https://github.com/user/repo");
+ok("github", "https://github.com/user/repo/", "https://github.com/user/repo");
+ok("github", " https://github.com/user/repo ", "https://github.com/user/repo");
+ok("github", "https://GitHub.com/user/repo", "https://github.com/user/repo");
+ok("codeberg", "https://codeberg.org/My-User/my.repo_1", "https://codeberg.org/My-User/my.repo_1");
+
+console.log("\n-- wrong host --");
+no("github", "https://codeberg.org/user/repo", "codeberg URL under github kind");
+no("codeberg", "https://github.com/user/repo", "github URL under codeberg kind");
+no("github", "https://gitlab.com/user/repo", "unrelated forge");
+no("github", "https://evil.test/user/repo", "arbitrary host");
+no("github", "https://github.com.evil.test/user/repo", "suffixed host");
+no("github", "https://notgithub.com/user/repo", "prefixed host");
+no("github", "https://evil.test/github.com/user/repo", "host in the path");
+no("github", "https://[email protected]/user/repo", "host as userinfo");
+no("github", "https://[email protected]/user/repo", "userinfo present");
+no("github", "https://user:[email protected]/user/repo", "credentials present");
+no("github", "https://github.com\\@evil.test/user/repo", "backslash authority confusion");
+no("github", "https://127.0.0.1/user/repo", "loopback address");
+no("github", "https://[::1]/user/repo", "ipv6 loopback");
+
+console.log("\n-- scheme / transport --");
+no("github", "http://github.com/user/repo", "plain http");
+no("github", "git://github.com/user/repo", "git protocol");
+no("github", "ssh://[email protected]/user/repo", "ssh");
+no("github", "[email protected]:user/repo", "scp-style ssh");
+no("github", "ext::sh -c whoami", "ext transport (command execution)");
+no("github", "ext::echo pwned", "ext transport");
+no("github", "file:///etc/passwd", "file url");
+no("github", "/srv/git/other/repo.git", "absolute local path");
+no("github", "../../etc/passwd", "relative local path");
+no("github", "C:\\repos\\thing", "windows path");
+no("github", "javascript:alert(1)", "javascript scheme");
+no("github", "data:text/plain,hi", "data scheme");
+
+console.log("\n-- argument injection --");
+no("github", "--upload-pack=/bin/sh", "leading dash option");
+no("github", "-c core.askPass=/bin/sh", "leading dash config");
+no("github", "--output=/tmp/pwned", "leading dash output");
+
+console.log("\n-- port / query / fragment --");
+no("github", "https://github.com:8080/user/repo", "explicit port");
+no("github", "https://github.com:22/user/repo", "explicit ssh port");
+no("github", "https://github.com/user/repo?x=1", "query string");
+no("github", "https://github.com/user/repo#frag", "fragment");
+
+console.log("\n-- path shape --");
+no("github", "https://github.com/user", "one path segment");
+no("github", "https://github.com/", "no path");
+no("github", "https://github.com/user/repo/extra", "three path segments");
+no("github", "https://github.com/user/repo/../../admin", "traversal in path");
+no("github", "https://github.com/../etc/passwd", "traversal as owner");
+no("github", "https://github.com/./repo", "dot segment");
+no("github", "https://github.com/user/..", "dotdot repo");
+no("github", "https://github.com/user/.hidden", "leading-dot repo");
+no("github", "https://github.com/us er/repo", "whitespace in path");
+no("github", "https://github.com/user/re%2Fpo", "encoded slash");
+
+console.log("\n-- malformed --");
+no("github", "", "empty string");
+no("github", " ", "whitespace only");
+no("github", "not a url", "free text");
+no("github", "https://", "scheme only");
+no("github", "https:///user/repo", "empty host");
+no("github", "ht!tps://github.com/user/repo", "broken scheme");
+ok("github", `https://github.com/user/repo\n`, "https://github.com/user/repo");
+no("github", `https://github.com/user\n/repo`, "interior newline");
+no("github", `https://github.com/user/re po`, "interior space");
+no("github", `https://github.com/user/repo\r\nHost: evil.test`, "header injection");
+no("github", `https://github.com/user/re\u0000po`, "null byte");
+no("github", "https://github.com/user/" + "a".repeat(500), "over-long url");
+
+console.log("\n-- discord webhooks --");
+const W = "https://discord.com/api/webhooks/1234567890/abcDEF-_123";
+check("accepts a discord webhook", discordWebhookUrl(W) === W);
+check(
+ "accepts a versioned path",
+ discordWebhookUrl("https://discord.com/api/v10/webhooks/1/tok") ===
+ "https://discord.com/api/v10/webhooks/1/tok",
+);
+check(
+ "accepts discordapp.com",
+ discordWebhookUrl("https://discordapp.com/api/webhooks/1/tok") !== null,
+);
+check(
+ "accepts canary",
+ discordWebhookUrl("https://canary.discord.com/api/webhooks/1/tok") !== null,
+);
+const wno = (url, why) =>
+ check(`refuses webhook ${why}`, discordWebhookUrl(url) === null);
+wno("https://evil.test/api/webhooks/1/tok", "wrong host");
+wno("https://discord.com.evil.test/api/webhooks/1/tok", "suffixed host");
+wno("http://discord.com/api/webhooks/1/tok", "plain http");
+wno("https://discord.com/api/webhooks/1/tok?wait=true", "query string");
+wno("https://discord.com/", "no webhook path");
+wno("https://discord.com/api/webhooks/", "incomplete path");
+wno("https://discord.com/api/webhooks/notanid/tok", "non-numeric id");
+wno("https://discord.com:8443/api/webhooks/1/tok", "explicit port");
+wno("https://u:[email protected]/api/webhooks/1/tok", "credentials");
+wno("https://discord.com/api/webhooks/1/tok/../../admin", "traversal");
+wno("", "empty");
+
+console.log("\n-- webhook masking (the URL is a credential) --");
+const masked = maskWebhook(W);
+check("mask keeps the id", masked.includes("1234567890"));
+check("mask drops the token", !masked.includes("abcDEF-_123"));
+check("mask of junk is inert", maskWebhook("garbage") === "(hidden)");
+
+console.log(failures === 0 ? "\nALL PASSED" : `\n${failures} FAILED`);
+process.exit(failures === 0 ? 0 : 1);