commit
ooooo
diff --git a/public/app.js b/public/app.js
index 62d4ba5..327069d 100644
--- a/public/app.js
+++ b/public/app.js
@@ -1,13 +1,7 @@
/* public/app.js
- *
- * The whole client-side script. Two behaviours, both progressive: the page is
- * complete without this file, and the Content-Security-Policy forbids inline
- * script, so anything of this kind has to live here.
+ * LICENCED DASL-1.0 (c) Clove Twilight
*/
-// PocketID may serve an avatar only to a signed-in browser. When the image
-// fails, remove it so the first-initial circle underneath shows through
-// instead of a broken-image box. `error` doesn't bubble, so listen in capture.
document.addEventListener(
"error",
function (event) {
@@ -19,8 +13,6 @@ document.addEventListener(
true,
);
-// Confirm destructive submits. The button carries its own prompt text, which
-// keeps the wording next to the thing it destroys.
document.addEventListener("submit", function (event) {
var form = event.target;
if (!(form instanceof HTMLFormElement)) return;
@@ -31,8 +23,6 @@ document.addEventListener("submit", function (event) {
}
});
-// Submit on change, for selects that are the whole form. The submit button
-// stays in the markup, so the control still works with scripting off.
document.addEventListener("change", function (event) {
var control = event.target;
if (control instanceof HTMLSelectElement && control.hasAttribute("data-autosubmit")) {
diff --git a/scripts/build.mjs b/scripts/build.mjs
index 9df3abc..a1dcacf 100644
--- a/scripts/build.mjs
+++ b/scripts/build.mjs
@@ -1,10 +1,6 @@
-// Build step. Vanilla Extract needs a bundler to turn .css.ts into static CSS,
-// so we run esbuild with the vanilla-extract plugin. It bundles the server to
-// dist/server.js and, as a side effect of the styles being imported, emits the
-// extracted stylesheet to dist/server.css — which we copy to public/style.css
-// (served at /static/style.css).
-//
-// Run with plain Node: npm run build
+/* scripts/build.mjs
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
import { build } from "esbuild";
import { vanillaExtractPlugin } from "@vanilla-extract/esbuild-plugin";
@@ -16,12 +12,7 @@ await build({
platform: "node",
format: "esm",
target: "node22",
- // Keep runtime deps (hono, openid-client, @hono/node-server) external so they
- // resolve from node_modules at run time; only our own code + .css.ts is bundled.
packages: "external",
- // url(/static/...) references in the .css.ts (cursors, etc.) are resolved by
- // the app's static handler at run time, not on disk at build time — leave them
- // untouched instead of trying (and failing) to bundle them.
external: ["/static/*"],
outdir: "dist",
minify: true,
@@ -29,7 +20,6 @@ await build({
plugins: [vanillaExtractPlugin()],
});
-// Surface the compiled CSS where the static handler serves it.
mkdirSync("public", { recursive: true });
if (existsSync("dist/server.css")) {
copyFileSync("dist/server.css", "public/style.css");
diff --git a/src/access.ts b/src/access.ts
index bf8c0a1..5cacdfc 100644
--- a/src/access.ts
+++ b/src/access.ts
@@ -1,15 +1,6 @@
-/* src/access.ts */
-//
-// Who may read and write a repository.
-//
-// Two things decide it. The filesystem marker (git.ts) says whether a repo is
-// world-readable, and this table says who else — beyond the owner — was invited
-// in. The owner always has write; nobody else gets write without being named
-// here; and a private repo is invisible to everyone who isn't.
-//
-// Every entry addresses a repo by `owner/name` rather than by a row id, because
-// that is the identity the filesystem already uses. Deleting a repo drops its
-// rows (see dropRepoAccess), so a later repo of the same name starts clean.
+/* src/access.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
import { db, now } from "./db.ts";
import type { RepoRef } from "./git.ts";
@@ -25,9 +16,6 @@ db.exec(`
);
`);
-// The primary key answers "who may touch this repo", which is the question the
-// transport asks. sharedWith() asks the mirror image — "which repos may this
-// person touch" — on every repo listing, and that one needs its own index.
db.exec("CREATE INDEX IF NOT EXISTS collaborators_slug ON collaborators (slug)");
export type Level = "read" | "write";
diff --git a/src/auth.ts b/src/auth.ts
index 78df05d..b978983 100644
--- a/src/auth.ts
+++ b/src/auth.ts
@@ -1,15 +1,6 @@
-/* src/auth.ts */
-//
-// Authentication.
-//
-// * Browser login -> PocketID (OIDC). The resulting identity is stored in a
-// stateless, HMAC-signed session cookie; the account itself is recorded in
-// the user directory (users.ts) so its owner slug is stable.
-// * git clone/pull/push -> HTTP Basic auth. The password is a token; the
-// username is the owner slug the token belongs to.
-//
-// Session and OAuth-transaction state live entirely in signed cookies, so there
-// is no server-side session store.
+/* src/auth.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
import { createHmac, timingSafeEqual } from "node:crypto";
import * as oidc from "openid-client";
diff --git a/src/config.ts b/src/config.ts
index e8476ec..9c6af33 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -1,9 +1,6 @@
-/* src/config.ts */
-//
-// Central configuration. Everything comes from environment variables. Repo
-// visibility is a filesystem marker plus a collaborator table, git auth is
-// per-user tokens minted in the browser, and browser sessions are stateless
-// signed cookies over a SQLite user directory.
+/* src/config.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
function optional(name: string, fallback: string): string {
return process.env[name] ?? fallback;
diff --git a/src/db.ts b/src/db.ts
index b04f09e..ea58d06 100644
--- a/src/db.ts
+++ b/src/db.ts
@@ -1,10 +1,6 @@
-/* src/db.ts */
-//
-// The one SQLite handle, shared by the users, tokens and collaborators tables.
-//
-// Uses Node's built-in `node:sqlite` (run with --experimental-sqlite), so there
-// is no native module to compile. Both tables are small and only ever touched
-// on login, token management, and git auth, so synchronous access is fine.
+/* src/db.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
import { DatabaseSync } from "node:sqlite";
import { mkdirSync } from "node:fs";
diff --git a/src/git.ts b/src/git.ts
index 3ca7c7c..e5da8eb 100644
--- a/src/git.ts
+++ b/src/git.ts
@@ -1,10 +1,6 @@
-/* src/git.ts */
-//
-// Read-only helpers for the web viewer + repo management. Everything here shells
-// out to the git CLI against bare repositories under config.reposRoot.
-//
-// Repos are namespaced GitHub-style: <reposRoot>/<owner>/<name>.git, addressed
-// as `owner/name`. A RepoRef carries that identity through the whole module.
+/* src/git.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
import { execFile } from "node:child_process";
import { promisify } from "node:util";
@@ -49,24 +45,8 @@ function safeSegment(s: string): boolean {
return SEGMENT.test(s) && !s.startsWith(".") && !s.includes("..");
}
-// The "+" namespace.
-//
-// A leading "+" marks a name the forge owns rather than the user. It buys two
-// things at once: route segments like /:owner/+repos can never collide with a
-// real repository, and the profile repo cannot be created by accident or
-// squatted by someone typing a plausible name.
-//
-// Exactly one "+" name is a real repository — PROFILE_REPO, whose README is
-// rendered on its owner's profile page. Every other "+" name is refused
-// everywhere a name is accepted, so `git push` cannot conjure one and neither
-// can the create form. "+" is not allowed anywhere else in a name, which keeps
-// the prefix a namespace marker rather than a character.
export const PROFILE_REPO = "+dough";
-// The owner-level repositories page lives at /<owner>/+repos. It is a route,
-// not a repository, and it is deliberately spelled with the reserved prefix:
-// safeName() refuses every "+" name but PROFILE_REPO, so no repository can ever
-// exist that would answer to this URL.
export const PROFILE_REPOS_PATH = "+repos";
const NAME_SEGMENT = /^[A-Za-z0-9._+-]+$/;
@@ -370,12 +350,6 @@ export async function purgeExpired(owner: string): Promise<TrashEntry[]> {
return purged;
}
-// Retention across every owner.
-//
-// purgeExpired() only sweeps the owner whose page is being rendered, which
-// makes MINIGIT_TRASH_DAYS a promise that is only kept for people who happen to
-// visit. This is the sweep the server runs on a timer so the retention window
-// means what it says.
export async function purgeAllExpired(): Promise<TrashEntry[]> {
if (config.trashDays <= 0) return [];
@@ -418,6 +392,43 @@ export interface RepoSummary {
isPublic: boolean;
}
+const LIST_CONCURRENCY = 16;
+
+async function mapLimit<T, R>(
+ items: T[],
+ limit: number,
+ fn: (item: T) => Promise<R>,
+): Promise<R[]> {
+ const out = new Array<R>(items.length);
+ let next = 0;
+
+ const worker = async (): Promise<void> => {
+ for (let i = next++; i < items.length; i = next++) {
+ out[i] = await fn(items[i]!);
+ }
+ };
+
+ await Promise.all(
+ Array.from({ length: Math.min(limit, items.length) }, worker),
+ );
+ return out;
+}
+
+async function summarise(ref: RepoRef): Promise<RepoSummary | null> {
+ const dir = refDir(ref);
+ try {
+ const [description, head, lastCommit, isPublic] = await Promise.all([
+ readDescription(dir),
+ headBranch(dir),
+ lastCommitTime(dir),
+ isRepoPublic(ref),
+ ]);
+ return { owner: ref.owner, name: ref.name, description, head, lastCommit, isPublic };
+ } catch {
+ return null;
+ }
+}
+
export async function listRepos(): Promise<RepoSummary[]> {
let owners: string[];
try {
@@ -426,7 +437,7 @@ export async function listRepos(): Promise<RepoSummary[]> {
return [];
}
- const repos: RepoSummary[] = [];
+ const refs: RepoRef[] = [];
for (const owner of owners) {
if (!safeSegment(owner)) continue;
let entries: string[];
@@ -439,22 +450,14 @@ export async function listRepos(): Promise<RepoSummary[]> {
if (!entry.endsWith(".git")) continue;
const name = entry.replace(/\.git$/, "");
if (!safeName(name)) continue;
- const ref: RepoRef = { owner, name };
- const dir = refDir(ref);
- try {
- repos.push({
- owner,
- name: ref.name,
- description: await readDescription(dir),
- head: await headBranch(dir),
- lastCommit: await lastCommitTime(dir),
- isPublic: await isRepoPublic(ref),
- });
- } catch {
- }
+ refs.push({ owner, name });
}
}
+ const repos = (await mapLimit(refs, LIST_CONCURRENCY, summarise)).filter(
+ (r): r is RepoSummary => r !== null,
+ );
+
repos.sort((a, b) => (b.lastCommit ?? 0) - (a.lastCommit ?? 0));
return repos;
}
@@ -922,10 +925,6 @@ export async function readme(ref: RepoRef, refspec: string): Promise<Readme | nu
return { path: hit.name, text: content.text };
}
-// The README at a repo's default branch, for callers that want it without
-// caring which revision they are on. tree() already swallows a bad refspec and
-// returns nothing, so an empty repo, a dangling HEAD and a repo with no README
-// all arrive here as the same null.
export async function headReadme(ref: RepoRef): Promise<Readme | null> {
const refs = await listRefs(ref);
if (refs.branches.length === 0) return null;
diff --git a/src/icons.ts b/src/icons.ts
index ed64aaa..6015bac 100644
--- a/src/icons.ts
+++ b/src/icons.ts
@@ -1,9 +1,9 @@
-/* src/icons.ts */
+/* src/icons.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
-// Icons are read from the installed pixelarticons package (MIT); none copied in.
import { getIconSvg } from "pixelarticons";
-// Parsed icon source, cached so each file is read once per process.
const cache = new Map<string, { viewBox: string; body: string }>();
function parse(name: string): { viewBox: string; body: string } {
@@ -30,7 +30,6 @@ function parse(name: string): { viewBox: string; body: string } {
return parsed;
}
-// Render one pixelarticons icon (kebab-case name) as an inline SVG string.
export function icon(name: string, size = 16): string {
const { viewBox, body } = parse(name);
return `<svg class="icon" viewBox="${viewBox}" width="${size}" height="${size}" aria-hidden="true">${body}</svg>`;
diff --git a/src/markdown.ts b/src/markdown.ts
index 72c3973..fef4b5b 100644
--- a/src/markdown.ts
+++ b/src/markdown.ts
@@ -1,18 +1,6 @@
-/* src/markdown.ts */
-//
-// A small, deliberately safe Markdown renderer for repository READMEs.
-//
-// Why hand-rolled rather than a library: README content is attacker-controlled
-// — anyone who can push, on a repo that may be public — so this renderer is
-// escape-first. Every character is HTML-escaped before any markup is produced,
-// raw HTML from the source is never passed through, and link/image URLs go
-// through a scheme allowlist. Injection is impossible by construction instead
-// of depending on a sanitiser staying in step with a parser.
-//
-// Covers the README subset: ATX/setext headings, fenced and indented code,
-// blockquotes, nested and task lists, GFM tables, rules, images, links,
-// autolinks, emphasis, inline code, hard line breaks. Raw HTML blocks are
-// dropped rather than shown as escaped source.
+/* src/markdown.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
import { icon } from "./icons.ts";
@@ -24,6 +12,13 @@ export function escapeHtml(s: string): string {
.replace(/"/g, """);
}
+const MAX_LABEL = 400;
+const MAX_URL_PARTS = 500;
+const MAX_ATTRS = 400;
+const MAX_COMMENT = 1000;
+const MAX_NEST = 24;
+const MAX_RENDER_CHARS = 256 * 1024;
+
type Stash = string[];
function park(s: Stash, html: string): string {
@@ -53,6 +48,208 @@ function linkAttrs(href: string): string {
return ABSOLUTE.test(href) ? ` rel="nofollow noopener noreferrer"` : "";
}
+const VOID_HTML = new Set(["br", "hr", "img", "source", "wbr"]);
+
+const HTML_ATTRS: Record<string, readonly string[]> = {
+ a: ["href", "title"],
+ img: ["src", "alt", "title", "width", "height", "align"],
+ picture: [],
+ source: ["src", "srcset", "media", "type"],
+ div: ["align"],
+ p: ["align"],
+ span: [],
+ center: [],
+ h1: ["align"],
+ h2: ["align"],
+ h3: ["align"],
+ h4: ["align"],
+ h5: ["align"],
+ h6: ["align"],
+ table: ["align"],
+ thead: [],
+ tbody: [],
+ tfoot: [],
+ tr: [],
+ th: ["align", "colspan", "rowspan"],
+ td: ["align", "colspan", "rowspan"],
+ ul: [],
+ ol: ["start"],
+ li: [],
+ dl: [],
+ dt: [],
+ dd: [],
+ blockquote: ["cite"],
+ pre: [],
+ code: [],
+ kbd: [],
+ samp: [],
+ b: [],
+ strong: [],
+ i: [],
+ em: [],
+ u: [],
+ s: [],
+ del: [],
+ ins: [],
+ mark: [],
+ sub: [],
+ sup: [],
+ small: [],
+ br: [],
+ hr: [],
+ wbr: [],
+ details: ["open"],
+ summary: [],
+ figure: [],
+ figcaption: [],
+};
+
+const RAW_TEXT = /^\s{0,3}<(script|style|textarea)(?=[\s/>])/i;
+
+const RAW_TEXT_INLINE = new RegExp(
+ `<(script|style|textarea)(?:(?!>)[\\s\\S]){0,${MAX_ATTRS}}?>` +
+ `(?:(?!</)[\\s\\S]){0,${MAX_RENDER_CHARS}}?</\\1\\s*>`,
+ "gi",
+);
+
+const ALIGN_VALUE = /^(?:left|center|right|justify)$/i;
+const DIMENSION_VALUE = /^\d{1,4}(?:%|px)?$/i;
+const COUNT_VALUE = /^\d{1,4}$/;
+const MEDIA_VALUE = /^[a-zA-Z0-9 ()\-:,.]{1,100}$/;
+const MIME_VALUE = /^[a-zA-Z0-9.+-]{1,40}\/[a-zA-Z0-9.+-]{1,40}$/;
+
+const HTML_TAG = new RegExp(
+ `<(/?)([a-zA-Z][a-zA-Z0-9]{0,14})` +
+ `((?:\\s(?:(?!>)[\\s\\S]){0,${MAX_ATTRS}}?)?)\\s*/?>`,
+ "g",
+);
+
+const HTML_ATTR = new RegExp(
+ `([a-zA-Z][a-zA-Z0-9-]{0,19})` +
+ `(?:\\s*=\\s*(?:"((?:(?!")[\\s\\S]){0,${MAX_LABEL}})"` +
+ `|'([^']{0,${MAX_LABEL}})'` +
+ `|([^\\s&]{1,${MAX_LABEL}})))?`,
+ "g",
+);
+
+function srcsetValue(raw: string): string | null {
+ const parts = raw.split(",").map((c) => c.trim()).filter(Boolean);
+ if (parts.length === 0 || parts.length > 16) return null;
+ const rebuilt: string[] = [];
+ for (const part of parts) {
+ const [url, ...rest] = part.split(/\s+/);
+ const safe = url ? safeUrl(url) : null;
+ if (!safe) return null;
+ if (rest.length > 1) return null;
+ if (rest.length === 1 && !/^\d{1,4}(?:w|x)$/.test(rest[0]!)) return null;
+ rebuilt.push(rest.length ? `${safe} ${rest[0]}` : safe);
+ }
+ return rebuilt.join(", ");
+}
+
+function attrValue(name: string, raw: string | undefined): string | null {
+ switch (name) {
+ case "href":
+ case "src":
+ case "cite":
+ return raw === undefined ? null : safeUrl(raw);
+ case "srcset":
+ return raw === undefined ? null : srcsetValue(raw);
+ case "align":
+ return raw !== undefined && ALIGN_VALUE.test(raw) ? raw.toLowerCase() : null;
+ case "width":
+ case "height":
+ return raw !== undefined && DIMENSION_VALUE.test(raw) ? raw : null;
+ case "colspan":
+ case "rowspan":
+ case "start":
+ return raw !== undefined && COUNT_VALUE.test(raw) ? raw : null;
+ case "media":
+ return raw !== undefined && MEDIA_VALUE.test(raw) ? raw : null;
+ case "type":
+ return raw !== undefined && MIME_VALUE.test(raw) ? raw : null;
+ case "alt":
+ case "title":
+ return raw ?? "";
+ case "open":
+ return "";
+ default:
+ return null;
+ }
+}
+
+function rebuildTag(closing: string, rawName: string, rawAttrs: string): string {
+ const name = rawName.toLowerCase();
+ const allowed = HTML_ATTRS[name];
+ if (!allowed) return "";
+ if (closing) return VOID_HTML.has(name) ? "" : `\x01</${name}>\x02`;
+
+ let out = `<${name}`;
+ let href = "";
+ HTML_ATTR.lastIndex = 0;
+ let m: RegExpExecArray | null;
+ while ((m = HTML_ATTR.exec(rawAttrs)) !== null) {
+ if (m[0] === "") {
+ HTML_ATTR.lastIndex++;
+ continue;
+ }
+ const attr = m[1]!.toLowerCase();
+ if (!allowed.includes(attr)) continue;
+ const value = attrValue(attr, m[2] ?? m[3] ?? m[4]);
+ if (value === null) continue;
+ if (attr === "href") href = value;
+ out += attr === "open" ? " open" : ` ${attr}="${value}"`;
+ }
+
+ if (name === "a" && href) out += linkAttrs(href);
+ if (name === "img") out += ' loading="lazy"';
+
+ return `\x01${out}>\x02`;
+}
+
+function balanceHtml(html: string): string {
+ const open: string[] = [];
+ let out = "";
+ let i = 0;
+
+ while (i < html.length) {
+ const start = html.indexOf("\x01", i);
+ if (start === -1) {
+ out += html.slice(i);
+ break;
+ }
+ const end = html.indexOf("\x02", start);
+ if (end === -1) {
+ out += html.slice(i);
+ break;
+ }
+
+ out += html.slice(i, start);
+ const tag = html.slice(start + 1, end);
+ i = end + 1;
+
+ const name = /^<\/?([a-z0-9]+)/.exec(tag)?.[1] ?? "";
+ if (VOID_HTML.has(name)) {
+ out += tag;
+ continue;
+ }
+ if (!tag.startsWith("</")) {
+ open.push(name);
+ out += tag;
+ continue;
+ }
+
+ const depth = open.lastIndexOf(name);
+ if (depth === -1) continue;
+ for (let d = open.length - 1; d > depth; d--) out += `</${open[d]}>`;
+ out += tag;
+ open.length = depth;
+ }
+
+ while (open.length > 0) out += `</${open.pop()}>`;
+ return out;
+}
+
function emphasis(t: string): string {
return t
.replace(/\*\*\*(\S[\s\S]*?\S|\S)\*\*\*/g, "<strong><em>$1</em></strong>")
@@ -63,6 +260,15 @@ function emphasis(t: string): string {
.replace(/~~(\S[\s\S]*?\S|\S)~~/g, "<del>$1</del>");
}
+function LINK_RE(bang: string): RegExp {
+ return new RegExp(
+ `${bang}\\[([^\\]]{0,${MAX_LABEL}})\\]` +
+ `\\(\\s*((?:[^()\\s]|\\([^()\\s]*\\)){1,${MAX_URL_PARTS}})` +
+ `(?:\\s+"(.{0,${MAX_LABEL}}?)")?\\s*\\)`,
+ "g",
+ );
+}
+
function inline(src: string): string {
const s: Stash = [];
let text = escapeHtml(src.replace(/\x00/g, ""));
@@ -71,15 +277,17 @@ function inline(src: string): string {
park(s, `<code>${code.trim()}</code>`),
);
- text = text.replace(/<!--[\s\S]*?-->/g, "");
- text = text.replace(/<br\s*\/?>/gi, () => park(s, "<br>"));
- text = text.replace(
- /<\/?[a-zA-Z][a-zA-Z0-9-]*(?:\s(?:(?!>)[\s\S])*?)?\/?>/g,
- "",
- );
+ text = text.replace(new RegExp(`<!--[\\s\\S]{0,${MAX_COMMENT}}?-->`, "g"), "");
+ text = text.replace(RAW_TEXT_INLINE, "");
+
+ HTML_TAG.lastIndex = 0;
+ text = text.replace(HTML_TAG, (_m, closing: string, name: string, attrs: string) => {
+ const tag = rebuildTag(closing, name, attrs);
+ return tag ? park(s, tag) : "";
+ });
text = text.replace(
- /!\[([^\]]*)\]\(\s*((?:[^()\s]|\([^()\s]*\))+)(?:\s+"(.*?)")?\s*\)/g,
+ LINK_RE("!"),
(_m, alt: string, url: string, title?: string) => {
const src = safeUrl(url);
if (!src) return alt;
@@ -89,7 +297,7 @@ function inline(src: string): string {
);
text = text.replace(
- /\[([^\]]*)\]\(\s*((?:[^()\s]|\([^()\s]*\))+)(?:\s+"(.*?)")?\s*\)/g,
+ LINK_RE(""),
(_m, label: string, url: string, title?: string) => {
const inner = emphasis(label);
const href = safeUrl(url);
@@ -100,7 +308,7 @@ function inline(src: string): string {
);
text = text.replace(
- /<((?:https?:\/\/|mailto:)\S+?)>/g,
+ new RegExp(`<((?:https?://|mailto:)\\S{1,${MAX_URL_PARTS}}?)>`, "g"),
(_m, url: string) => park(s, `<a href="${url}"${linkAttrs(url)}>${url}</a>`),
);
@@ -128,10 +336,8 @@ const FENCE = /^\s{0,3}(`{3,}|~{3,})\s*(\S*).*$/;
const RULE = /^\s{0,3}([-*_])[ \t]*(?:\1[ \t]*){2,}$/;
const QUOTE = /^\s{0,3}>/;
-// GitHub alert marker: the whole first line of a blockquote, nothing else.
const ALERT = /^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*$/i;
-// Pixel icon per alert kind (names from the pixelarticons set).
const ALERT_ICON: Record<string, string> = {
note: "info-box",
tip: "lightbulb",
@@ -140,11 +346,11 @@ const ALERT_ICON: Record<string, string> = {
caution: "square-alert",
};
-function alertBlock(kind: string, body: string[]): string {
+function alertBlock(kind: string, body: string[], depth: number): string {
const key = kind.toLowerCase();
const label = key.charAt(0).toUpperCase() + key.slice(1);
const glyph = icon(ALERT_ICON[key] ?? "info-box");
- const inner = blocks(body);
+ const inner = blocks(body, depth + 1);
const title = `<p class="md-alert-title">${glyph}${label}</p>`;
return `<div class="md-alert md-alert-${key}">\n${title}\n${inner}\n</div>`;
}
@@ -157,11 +363,19 @@ function indentOf(line: string): number {
return /^\s*/.exec(line)?.[0].length ?? 0;
}
-const HTML_ONLY = /^(?:<\/?[a-zA-Z][a-zA-Z0-9-]*(?:\s[^<>]*)?\/?>\s*)+$/;
+const BLOCK_HTML = new Set([
+ "div", "p", "center", "h1", "h2", "h3", "h4", "h5", "h6",
+ "table", "thead", "tbody", "tfoot", "tr", "th", "td",
+ "ul", "ol", "li", "dl", "dt", "dd",
+ "blockquote", "pre", "details", "summary",
+ "figure", "figcaption", "picture", "source", "hr",
+]);
+
+const BLOCK_HTML_START = /^\s{0,3}<(\/?)([a-zA-Z][a-zA-Z0-9]{0,14})(?=[\s/>])/;
function isHtmlOnly(line: string): boolean {
- const t = line.trim();
- return t.startsWith("<") && HTML_ONLY.test(t);
+ const m = BLOCK_HTML_START.exec(line);
+ return m !== null && BLOCK_HTML.has(m[2]!.toLowerCase());
}
function isBlockStart(line: string): boolean {
@@ -171,6 +385,7 @@ function isBlockStart(line: string): boolean {
ATX.test(line) ||
QUOTE.test(line) ||
LIST_ITEM.test(line) ||
+ RAW_TEXT.test(line) ||
isHtmlOnly(line) ||
line.trimStart().startsWith("<!--")
);
@@ -222,7 +437,7 @@ function table(lines: string[], start: number): [string, number] {
];
}
-function list(lines: string[], start: number): [string, number] {
+function list(lines: string[], start: number, depth: number): [string, number] {
const first = LIST_ITEM.exec(at(lines, start));
if (!first) return ["", start + 1];
const bullet = first[2] ?? "-";
@@ -274,7 +489,7 @@ function list(lines: string[], start: number): [string, number] {
const checkbox = task
? `<input type="checkbox" disabled${task[1] === " " ? "" : " checked"}> `
: "";
- const rendered = blocks(body).replace(/^<p>([\s\S]*?)<\/p>(?=\n<|$)/, "$1");
+ const rendered = blocks(body, depth + 1).replace(/^<p>([\s\S]*?)<\/p>(?=\n<|$)/, "$1");
return `<li>${checkbox}${rendered}</li>`;
})
.join("\n");
@@ -287,7 +502,12 @@ function list(lines: string[], start: number): [string, number] {
return [`<${tag}${startAttr}>\n${html}\n</${tag}>`, i];
}
-function blocks(lines: string[]): string {
+function blocks(lines: string[], depth = 0): string {
+ if (depth > MAX_NEST) {
+ const text = lines.filter((l) => l.trim()).join("\n");
+ return text ? `<p>${paragraph(text.split("\n"))}</p>` : "";
+ }
+
const out: string[] = [];
let i = 0;
@@ -354,11 +574,11 @@ function blocks(lines: string[]): string {
const marker = ALERT.exec(buf[0] ?? "");
if (marker) {
- out.push(alertBlock(marker[1] ?? "", buf.slice(1)));
+ out.push(alertBlock(marker[1] ?? "", buf.slice(1), depth));
continue;
}
- out.push(`<blockquote>\n${blocks(buf)}\n</blockquote>`);
+ out.push(`<blockquote>\n${blocks(buf, depth + 1)}\n</blockquote>`);
continue;
}
@@ -370,7 +590,7 @@ function blocks(lines: string[]): string {
}
if (LIST_ITEM.test(line)) {
- const [html, next] = list(lines, i);
+ const [html, next] = list(lines, i, depth);
out.push(html);
i = next;
continue;
@@ -387,11 +607,26 @@ function blocks(lines: string[]): string {
continue;
}
- if (isHtmlOnly(line)) {
+ const rawText = RAW_TEXT.exec(line);
+ if (rawText && !line.toLowerCase().includes(`</${rawText[1]!.toLowerCase()}`)) {
+ const closer = `</${rawText[1]!.toLowerCase()}`;
+ i++;
+ while (i < lines.length && !at(lines, i).toLowerCase().includes(closer)) i++;
i++;
continue;
}
+ if (isHtmlOnly(line)) {
+ const buf: string[] = [];
+ while (i < lines.length && at(lines, i).trim()) {
+ buf.push(inline(at(lines, i).trim()));
+ i++;
+ }
+ const html = buf.join("\n");
+ if (html.trim()) out.push(html);
+ continue;
+ }
+
const buf: string[] = [];
while (i < lines.length && at(lines, i).trim() && !isBlockStart(at(lines, i))) {
buf.push(at(lines, i));
@@ -408,18 +643,26 @@ function blocks(lines: string[]): string {
}
export function renderMarkdown(src: string): string {
- const lines = src
+ const oversize = src.length > MAX_RENDER_CHARS;
+ const lines = (oversize ? src.slice(0, MAX_RENDER_CHARS) : src)
.replace(/\r\n?/g, "\n")
.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g, "")
.split("\n");
- return blocks(lines);
+
+ if (oversize) lines.pop();
+
+ const html = balanceHtml(blocks(lines));
+ return oversize
+ ? `${html}\n<p><em>This document was truncated for display.</em></p>`
+ : html;
}
function flatten(s: string): string {
- const paren = "(?:[^()]|\\([^()]*\\))*";
+ const paren = `(?:[^()]|\\([^()]*\\)){0,${MAX_URL_PARTS}}`;
+ const label = `[^\\]]{0,${MAX_LABEL}}`;
return s
- .replace(new RegExp(`!\\[[^\\]]*\\]\\(${paren}\\)`, "g"), " ")
- .replace(new RegExp(`\\[([^\\]]*)\\]\\(${paren}\\)`, "g"), "$1")
+ .replace(new RegExp(`!\\[${label}\\]\\(${paren}\\)`, "g"), " ")
+ .replace(new RegExp(`\\[(${label})\\]\\(${paren}\\)`, "g"), "$1")
.replace(/<[^<>]*>/g, " ")
.replace(/[*_`~]/g, "")
.replace(/\\([\\`*_{}[\]()#+\-.!])/g, "$1")
@@ -429,9 +672,10 @@ function flatten(s: string): string {
export function plainSummary(src: string, max = 180): string {
const text = src
+ .slice(0, MAX_RENDER_CHARS)
.replace(/\r\n?/g, "\n")
.replace(/```[\s\S]*?(?:```|$)/g, "\n\n")
- .replace(/<!--[\s\S]*?-->/g, " ");
+ .replace(new RegExp(`<!--[\\s\\S]{0,${MAX_COMMENT}}?-->`, "g"), " ");
for (const block of text.split(/\n\s*\n/)) {
const lines = block.split("\n").filter((l) => l.trim());
diff --git a/src/mirror.ts b/src/mirror.ts
index 8cc7c1f..5958979 100644
--- a/src/mirror.ts
+++ b/src/mirror.ts
@@ -1,16 +1,6 @@
-/* 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.
+/* src/mirror.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
import { db, now } from "./db.ts";
import {
diff --git a/src/notify.ts b/src/notify.ts
index d85a328..15adb6d 100644
--- a/src/notify.ts
+++ b/src/notify.ts
@@ -1,16 +1,6 @@
-/* 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.
+/* src/notify.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
import {
refSlug,
diff --git a/src/repometa.ts b/src/repometa.ts
index 014aaa1..cfbe50b 100644
--- a/src/repometa.ts
+++ b/src/repometa.ts
@@ -1,16 +1,6 @@
-/* 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.
+/* src/repometa.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
import { dropRepoAccess } from "./access.ts";
import { dropMirrorStatus } from "./mirror.ts";
diff --git a/src/server.ts b/src/server.ts
index 5359c38..9e15b60 100644
--- a/src/server.ts
+++ b/src/server.ts
@@ -1,7 +1,6 @@
-/* src/server.ts */
-//
-// HTTP entrypoint: wires the git smart-HTTP transport and the read-only viewer
-// onto one Hono app. Run with `npm start`.
+/* src/server.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
import { Hono, type Context } from "hono";
import { getCookie, setCookie, deleteCookie } from "hono/cookie";
@@ -454,10 +453,6 @@ app.post("/new", async (c) => {
return c.redirect(`/${result.ref.owner}/${result.ref.name}/`);
});
-// Route params are typed as possibly-absent on a generic Context. These routes
-// always define them, but reading them through one helper keeps that assumption
-// in a single place instead of scattering casts, and gives a missing param the
-// same "no such repo" answer as an unsafe one.
function refFromPath(c: Context<Env>, nameParam: "name" | "repo"): RepoRef | null {
const owner = c.req.param("owner");
const name = c.req.param(nameParam);
@@ -474,10 +469,6 @@ function authChallenge(message = "authentication required"): Response {
});
}
-// The outcome of the transport gate. It carries the actor as well as the
-// verdict because verifying a token is a hash lookup *and* a `last_used`
-// write: re-deriving the actor afterwards would bill every clone and push for
-// two of each, and leave two places that could disagree about who is pushing.
interface GitGate {
response: Response | null;
actor: string | null;
@@ -837,9 +828,6 @@ app.post("/:owner/:name/collaborators/remove", async (c) => {
return c.redirect(`/${ref.owner}/${ref.name}/`);
});
-// The profile README, read through exactly the same access rules as any other
-// repository. A private +dough stays invisible to everyone it was not shared
-// with, so a profile page can never show content the viewer could not clone.
async function profileReadme(
owner: string,
viewer: string | null,
@@ -851,9 +839,6 @@ async function profileReadme(
return headReadme(ref);
}
-// The owner's repositories, minus the profile repo. +dough is machinery for
-// the page the visitor is already looking at, so listing it is noise; it keeps
-// its own repo page at /<owner>/+dough and is reachable from the profile.
function ownedRepos(all: RepoSummary[], owner: string): RepoSummary[] {
return all.filter((r) => r.owner === owner && !isProfileRepo(r.name));
}
@@ -884,8 +869,6 @@ app.get("/:owner", async (c) => {
);
});
-// Registered ahead of /:owner/:name. safeName() refuses "+repos" as a
-// repository name, so this route and a repo page can never contend.
app.get(`/:owner/${PROFILE_REPOS_PATH}`, async (c) => {
const owner = c.req.param("owner");
if (!safeRef(owner, "x")) return notFound(c);
@@ -906,6 +889,10 @@ app.get(`/:owner/${PROFILE_REPOS_PATH}`, async (c) => {
});
app.get("/:owner/:name", async (c) => {
+ if (c.req.param("name") === PROFILE_REPOS_PATH) {
+ return c.redirect(`/${c.req.param("owner")}/${PROFILE_REPOS_PATH}`, 301);
+ }
+
const found = await viewable(c);
if (!found) return notFound(c);
const { ref, isPublic, access, refs, rev } = found;
@@ -1014,9 +1001,6 @@ app.post("/:owner/:name/mirrors/check", async (c) => {
return c.redirect(`/${ref.owner}/${ref.name}/`);
});
-// Recently Deleted is swept on a timer rather than only when somebody opens
-// the page, so MINIGIT_TRASH_DAYS is a retention window rather than a hint. The
-// interval is unref'd: it must never be the reason the process stays alive.
const SWEEP_INTERVAL_MS = 6 * 60 * 60 * 1000;
async function sweepTrash(): Promise<void> {
diff --git a/src/settings.ts b/src/settings.ts
index 1091abd..fb173b7 100644
--- a/src/settings.ts
+++ b/src/settings.ts
@@ -1,18 +1,6 @@
-/* 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.
+/* src/settings.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
import { db, now } from "./db.ts";
diff --git a/src/smart-http.ts b/src/smart-http.ts
index fe5975c..921c6af 100644
--- a/src/smart-http.ts
+++ b/src/smart-http.ts
@@ -1,17 +1,6 @@
-/* src/smart-http.ts */
-//
-// Git "smart HTTP" transport.
-//
-// This implements the two request shapes a git client makes when cloning,
-// fetching, or pushing over HTTP:
-//
-// GET /<repo>/info/refs?service=git-upload-pack -> ref advertisement
-// POST /<repo>/git-upload-pack -> fetch / clone
-// POST /<repo>/git-receive-pack -> push
-//
-// We shell out to the real `git upload-pack` / `git receive-pack` binaries in
-// `--stateless-rpc` mode, which is exactly what git's own http-backend does.
-// Auth/authorization is handled by the caller (server.ts) before we get here.
+/* src/smart-http.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
import { spawn } from "node:child_process";
import { Readable } from "node:stream";
diff --git a/src/styles/app.css.ts b/src/styles/app.css.ts
index 30cf23a..829f827 100644
--- a/src/styles/app.css.ts
+++ b/src/styles/app.css.ts
@@ -1,7 +1,5 @@
-/* src/styles/app.css.ts
- *
- * Component classes. Each is a generated, scoped class name (zero runtime).
- * Imported as a single `classes` object by the HTML views.
+/* src/styles/app.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
*/
import { globalStyle, style } from "@vanilla-extract/css";
@@ -19,8 +17,6 @@ const readme = style({
export const classes = {
readme,
- // Icon-then-label. Used anywhere an icon() sits next to text and needs to
- // ride the text baseline with consistent spacing rather than a literal space.
withIcon: style({
display: "inline-flex",
alignItems: "center",
@@ -396,7 +392,6 @@ globalStyle(`${readme} blockquote`, {
color: vars.textMuted,
});
-// GitHub-style alerts: one accent colour per kind.
const alertColor = {
note: "#4493f8",
tip: "#3fb950",
@@ -475,7 +470,6 @@ globalStyle(`${readme} th[data-align="right"], ${readme} td[data-align="right"]`
globalStyle(`${readme} del`, { color: vars.textDim });
-// Inline pixel icons: crispEdges keeps the pixel grid sharp at any size.
globalStyle(".icon", {
display: "inline-block",
verticalAlign: "middle",
diff --git a/src/styles/fonts.css.ts b/src/styles/fonts.css.ts
index 70aa7ae..906a3b1 100644
--- a/src/styles/fonts.css.ts
+++ b/src/styles/fonts.css.ts
@@ -1,14 +1,9 @@
-/* Comic Code — the same paid display face used across the other doughmination
- * sites (see the personal site's fonts.css.ts). Applied to the `font` token
- * (UI chrome: nav, headers, labels) — `mono` stays a real monospace stack in
- * theme.css.ts since dough-git aligns commit hashes, file sizes and tree
- * listings in columns, which Comic Code's metrics aren't built for.
+/* src/styles/fonts.css.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
*/
import { globalFontFace } from "@vanilla-extract/css";
-// Exported so the server can name this origin in font-src. A CSP of 'self'
-// alone blocks every face below, and the page silently falls back to system-ui.
export const FONT_ORIGIN = "https://m.doughmination.gay";
const CDN = `${FONT_ORIGIN}/f`;
diff --git a/src/styles/global.css.ts b/src/styles/global.css.ts
index 5859228..6b52f4d 100644
--- a/src/styles/global.css.ts
+++ b/src/styles/global.css.ts
@@ -1,6 +1,5 @@
-/* Global element styling — the parts that must target bare elements (html,
- * body, a, table, pre) rather than a generated class, so they live in
- * globalStyle exactly like the personal site's base.css.ts.
+/* src/styles/global.css.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
*/
import { globalStyle } from "@vanilla-extract/css";
@@ -30,11 +29,6 @@ globalStyle("a", {
globalStyle("a:hover", { textDecoration: "underline" });
-// Self-hosted pixel cursor (dark art only, since dough-git is always dark).
-// The PNGs are pixelarticons' free cursors, downloaded from
-// https://pixelarticons.com/free/cursors/ and committed to public/cursors/ —
-// they are NOT part of the pixelarticons npm package that src/icons.ts reads,
-// so they have to travel with the repo. The trailing numbers are the hotspot.
globalStyle("a, button", {
cursor: "url('/static/cursors/pointer-dark.png') 12 1, pointer",
});
@@ -69,14 +63,6 @@ globalStyle("pre", {
overflowX: "auto",
});
-/* Form controls. Native buttons/inputs come with their own light-mode chrome
- * (system font, rounded corners, grey gradient) which reads as foreign against
- * the dark theme, so restyle them onto the same bordered-box idiom the `tab`
- * and `badge` classes use.
- */
-
-// Text-ish inputs only — a checkbox gets its own treatment below, since border
-// and background on one replace the box itself rather than framing it.
const FIELDS = [
'input[type="text"]',
'input[type="url"]',
@@ -90,7 +76,6 @@ const FIELDS = [
const CONTROLS = ["button", ...FIELDS];
-/** sel(["button", "select"], ":hover") => "button:hover, select:hover" */
const sel = (sels: string[], suffix = "") =>
sels.map((s) => s + suffix).join(", ");
@@ -104,8 +89,6 @@ globalStyle(sel(CONTROLS), {
});
globalStyle("button", {
- // Buttons are always [icon, label], so centre them as a row rather than
- // relying on the SVG's inline baseline.
display: "inline-flex",
alignItems: "center",
gap: "0.35rem",
@@ -130,7 +113,6 @@ globalStyle(sel(FIELDS, "::placeholder"), { color: vars.textFaint });
globalStyle(sel(FIELDS, ":hover"), { borderColor: vars.textFaint });
-// One focus treatment across the set, so tabbing through a form is consistent.
globalStyle(sel(CONTROLS, ":focus-visible"), {
outline: `1px solid ${vars.accent}`,
outlineOffset: "1px",
diff --git a/src/styles/index.ts b/src/styles/index.ts
index 1884e40..8df3035 100644
--- a/src/styles/index.ts
+++ b/src/styles/index.ts
@@ -1,6 +1,6 @@
-// Style entrypoint. Importing this pulls in the theme + global rules (side
-// effects) and exposes the component class names. The esbuild + vanilla-extract
-// build turns all of this into one static CSS file at compile time.
+/* src/styles/index.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
import "./fonts.css.ts";
import "./theme.css.ts";
diff --git a/src/styles/theme.css.ts b/src/styles/theme.css.ts
index 70723be..2b583e3 100644
--- a/src/styles/theme.css.ts
+++ b/src/styles/theme.css.ts
@@ -1,9 +1,5 @@
-/* Design tokens for dough-git.
- *
- * Same shape as the personal site's themes.css.ts: a global theme *contract*
- * maps token names to literal CSS custom properties (surfaceHi => var(--
- * surface-hi)), and createGlobalTheme binds them on :root. Palette is the site's
- * pink dark-trans theme so dough-git reads as part of the same family.
+/* src/styles/theme.css.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
*/
import {
diff --git a/src/tokens.ts b/src/tokens.ts
index 55f39ee..f48107e 100644
--- a/src/tokens.ts
+++ b/src/tokens.ts
@@ -1,12 +1,6 @@
-/* src/tokens.ts */
-//
-// SQLite-backed git access tokens, managed from the browser.
-//
-// Only token *hashes* are stored; the plaintext is shown once at creation.
-// Every token is bound to the owner slug of whoever minted it, which is what
-// lets the transport refuse a push into somebody else's namespace. There is no
-// instance-wide credential: a token is always somebody in particular, and what
-// that somebody may reach is decided in access.ts.
+/* src/tokens.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
import { randomBytes, createHash } from "node:crypto";
import { db, now, hasColumn } from "./db.ts";
@@ -27,9 +21,6 @@ if (!hasColumn("tokens", "owner")) {
db.exec("ALTER TABLE tokens ADD COLUMN owner TEXT");
}
-// Every git request that carries credentials looks a token up by hash, so this
-// is the hottest read in the application and the one that must not become a
-// table scan as the token count grows.
db.exec("CREATE INDEX IF NOT EXISTS tokens_hash ON tokens (hash)");
function sha256(value: string): string {
diff --git a/src/urls.ts b/src/urls.ts
index ef76b49..8921130 100644
--- a/src/urls.ts
+++ b/src/urls.ts
@@ -1,34 +1,11 @@
-/* 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".
+/* src/urls.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
const MAX_URL = 400;
const HOSTILE = /[\s\\<>"'`{}|^\x00-\x1f\x7f]/;
-// allowedParams names the query parameters a caller is willing to consider.
-// It is deliberately opt-in and empty by default, so every existing caller
-// keeps the blanket "no query string" rule. Naming a parameter here only gets
-// it past this gate — the caller still has to validate the value and rebuild
-// the query itself, so nothing user-controlled is passed through verbatim.
function parseStrict(
raw: string,
allowedHosts: readonly string[],
@@ -57,8 +34,6 @@ function parseStrict(
const seen = new Set<string>();
for (const key of url.searchParams.keys()) {
if (!allowedParams.includes(key)) return null;
- // A repeated key is ambiguous rather than useful; refuse instead of
- // silently picking one of the values.
if (seen.has(key)) return null;
seen.add(key);
}
@@ -112,12 +87,6 @@ const DISCORD_HOSTS = [
const WEBHOOK_PATH = /^\/api(?:\/v\d{1,3})?\/webhooks\/\d{1,32}\/[A-Za-z0-9._-]{1,200}$/;
-// The two Discord webhook parameters worth honouring, each pinned to the exact
-// shape its value may take. thread_id posts into an existing thread rather than
-// the parent channel; wait=true makes Discord answer 200 + the created message
-// instead of a bare 204, so a delivery that Discord rejects is reported as a
-// failure rather than passing silently. Both stay inside notify.ts's
-// `response.ok` check, which spans the whole 2xx range.
const WEBHOOK_PARAMS: Record<string, RegExp> = {
thread_id: /^\d{1,32}$/,
wait: /^(?:true|false)$/,
@@ -130,9 +99,6 @@ export function discordWebhookUrl(raw: string): string | null {
if (!url) return null;
if (!WEBHOOK_PATH.test(url.pathname)) return null;
- // Rebuild the query from validated values in a fixed order rather than
- // reusing url.search, so the stored URL is canonical and nothing the user
- // typed reaches fetch() unexamined.
const params = new URLSearchParams();
for (const name of WEBHOOK_PARAM_NAMES) {
const value = url.searchParams.get(name);
diff --git a/src/users.ts b/src/users.ts
index f72fa57..3220b36 100644
--- a/src/users.ts
+++ b/src/users.ts
@@ -1,16 +1,6 @@
-/* src/users.ts */
-//
-// The user directory: everyone who has ever signed in via PocketID.
-//
-// This exists for two reasons. Repos are namespaced by an owner *slug*, so the
-// mapping from OIDC `sub` to slug has to be stable and unique — deriving it
-// fresh on every login would let two accounts collide into one namespace and
-// push to each other's repos. And the profile pages need a name and avatar for
-// an owner even when that person isn't the one browsing.
-//
-// Nothing here is authoritative for access control on its own: the slug stored
-// here is what a session and a token are bound to, and git.ts still owns what a
-// safe path segment looks like.
+/* src/users.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
import { db, now } from "./db.ts";
import { ownerSlug } from "./git.ts";
diff --git a/src/views.ts b/src/views.ts
index f7bd837..ae6596e 100644
--- a/src/views.ts
+++ b/src/views.ts
@@ -1,7 +1,6 @@
-/* src/views.ts */
-//
-// HTML rendering. Class names come from the compiled Vanilla Extract styles
-// (src/styles). Repos are addressed GitHub-style as owner/name throughout.
+/* src/views.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
import { config } from "./config.ts";
import { classes as c } from "./styles/index.ts";
@@ -224,7 +223,6 @@ ${createForm}
return layout({ title: config.title, user, body, path: "/" });
}
-// How many repositories the profile page shows before deferring to /+repos.
const PROFILE_PREVIEW = 6;
function ownerName(owner: string, profile: UserRow | null): string {
@@ -250,7 +248,6 @@ function ownerHead(owner: string, profile: UserRow | null): string {
</section>`;
}
-// Same shape as the per-repo tabs, so an owner's pages navigate like a repo's.
function ownerTabs(owner: string, active: "profile" | "repos"): string {
const tab = (id: string, label: string, glyph: string, href: string) =>
`<a class="${c.tab}${id === active ? " " + c.tabActive : ""}" href="${href}">${icon(glyph)}${label}</a>`;
@@ -274,10 +271,6 @@ export function profilePage(opts: {
const more = opts.repos.length - preview.length;
const profileHref = `/${esc(opts.owner)}/${esc(PROFILE_REPO)}/`;
- // The profile README is the page's headline when there is one. The three
- // "no README" cases are only shown to the owner — a visitor has no use for
- // them and they would read as an empty section — and they are kept distinct
- // because the fix differs: create the repo, or push a README into it.
const readmeSection = opts.readme
? ` <article class="${c.readme}">
${renderMarkdown(opts.readme.text)}
diff --git a/test/access.test.mjs b/test/access.test.mjs
index c0c5de3..b26e1fb 100644
--- a/test/access.test.mjs
+++ b/test/access.test.mjs
@@ -1,10 +1,5 @@
/* test/access.test.mjs
- *
- * Tests for who may read and write a repository. This is the rule that makes
- * "private" mean something on a multi-user instance, so each case is asserted
- * directly rather than inferred from the routes that call it.
- *
- * Run: node --experimental-sqlite --experimental-strip-types test/access.test.mjs
+ * LICENCED DASL-1.0 (c) Clove Twilight
*/
import { mkdtempSync, rmSync } from "node:fs";
diff --git a/test/icons.test.mjs b/test/icons.test.mjs
index f52dd1f..59dfb38 100644
--- a/test/icons.test.mjs
+++ b/test/icons.test.mjs
@@ -1,7 +1,6 @@
-/* test/icons.test.mjs */
-
-// Pins the contract views.ts relies on from icon().
-// Run: node --experimental-strip-types test/icons.test.mjs
+/* test/icons.test.mjs
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
import { icon } from "../src/icons.ts";
@@ -11,7 +10,6 @@ function check(label, cond) {
if (!cond) failures++;
}
-// The pixelarticons names dough-git actually uses.
const names = [
"git-branch",
"git-commit",
diff --git a/test/lifecycle.test.mjs b/test/lifecycle.test.mjs
index a90d9bc..86e871f 100644
--- a/test/lifecycle.test.mjs
+++ b/test/lifecycle.test.mjs
@@ -1,13 +1,5 @@
/* 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
+ * LICENCED DASL-1.0 (c) Clove Twilight
*/
import { execFile } from "node:child_process";
@@ -184,9 +176,6 @@ check("the expired entry was purged", purged.some((e) => e.name === "ancient"));
check("the fresh entry was kept", (await listTrash("alice")).some((e) => e.name === "recent"));
check("expired directory really gone", !existsSync(join(trashOf("alice"), oldEntry.entry)));
-// purgeExpired only ever sweeps the owner being looked at, so an owner who
-// never opens their own Recently Deleted page would keep expired copies for
-// ever. purgeAllExpired is what makes the retention window a real one.
const bob = { owner: "bob", name: "forgotten" };
await seed(bob);
const bobEntry = await trashIt(bob, Math.floor(Date.now() / 1000) - 40 * 86400);
diff --git a/test/markdown.test.mjs b/test/markdown.test.mjs
index 8a22663..19068c2 100644
--- a/test/markdown.test.mjs
+++ b/test/markdown.test.mjs
@@ -1,11 +1,6 @@
-// Tests for the README Markdown renderer.
-//
-// The security cases matter most: README content comes from anyone who can
-// push, and renders on pages that may be public, so the escape-first contract
-// in src/markdown.ts (no raw HTML through, scheme allowlist on URLs) is the
-// thing most worth pinning down.
-//
-// Run: node --experimental-strip-types test/markdown.test.mjs
+/* test/markdown.test.mjs
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
import { renderMarkdown, plainSummary } from "../src/markdown.ts";
@@ -277,5 +272,95 @@ check(
lacks("\x000\x00 text", "\x00"),
);
+console.log("\n-- resource bounds (unbounded scans used to be quadratic) --");
+
+function timed(label, src, budgetMs) {
+ const t = process.hrtime.bigint();
+ let threw = null;
+ try {
+ renderMarkdown(src);
+ } catch (err) {
+ threw = err;
+ }
+ const ms = Number(process.hrtime.bigint() - t) / 1e6;
+ check(`${label} (${ms.toFixed(0)}ms, budget ${budgetMs}ms)`, threw === null && ms < budgetMs);
+}
+
+timed("200k unclosed [ does not go quadratic", "[".repeat(200_000), 3000);
+timed("200k unclosed ", 'href="https://example.com"'));
+check("images still render", has("", '<img src="https://example.com/i.png"'));
+check("link titles still render", has('[x](https://a.com "t")', 'title="t"'));
+
+console.log("\n-- allowlisted html renders --");
+
+check("centered div", has('<div align="center">x</div>', '<div align="center">'));
+check("img with dimensions", has('<img src="l.png" width="200" height="9">', '<img src="l.png" width="200" height="9" loading="lazy">'));
+check("img is not wrapped in a stray p", lacks('<div align="center">\n<img src="l.png">\n</div>', "<p>"));
+check("centered heading is not wrapped in p", has('<h1 align="center">P</h1>', '<h1 align="center">P</h1>') && lacks('<h1 align="center">P</h1>', "<p>"));
+check("anchor round-trips with rel", has('<a href="https://x.com">t</a>', '<a href="https://x.com" rel="nofollow noopener noreferrer">t</a>'));
+check("details and summary", has("<details>\n<summary>s</summary>\n</details>", "<details>") && has("<details>\n<summary>s</summary>\n</details>", "<summary>s</summary>"));
+check("markdown inside a details block still renders", has("<details>\n<summary>s</summary>\n\n**b**\n\n</details>", "<strong>b</strong>"));
+check("picture and source", has('<picture>\n<source media="(prefers-color-scheme: dark)" srcset="d.png">\n</picture>', '<source media="(prefers-color-scheme: dark)" srcset="d.png">'));
+check("inline kbd stays inline", has("press <kbd>C</kbd>", "<p>press <kbd>C</kbd></p>"));
+check("html table", has('<table><tr><td align="right">1</td></tr></table>', '<td align="right">1</td>'));
+check("center", has("<center>c</center>", "<center>c</center>"));
+check("br and hr", has("a<br>b", "a<br>b") && has("<hr>", "<hr>"));
+check("backticked tag is still code, not markup", has("use `<div>` here", "<code><div></code>"));
+
+console.log("\n-- the allowlist is an allowlist --");
+
+check("iframe is dropped", lacks('<iframe src="https://e.com"></iframe>', "<iframe"));
+check("form and input are dropped", lacks('<form><input name="p"></form>', "<input"));
+check("style tag is dropped", lacks("<style>body{}</style>", "<style"));
+check("svg is dropped", lacks("<svg onload=alert(1)></svg>", "<svg"));
+check("base is dropped", lacks('<base href="//e.com/">', "<base"));
+check("event handlers never survive", lacks('<div onclick="alert(1)">x</div>', "onclick") && lacks("<img src=x onerror=alert(1)>", "onerror"));
+check("style attribute never survives", lacks('<div style="x:url(javascript:1)">x</div>', "style="));
+check("target never survives", lacks('<a href="https://x.com" target="_blank">t</a>', "target"));
+check("class and id never survive", lacks('<div class="c" id="i">x</div>', "class=") && lacks('<div class="c" id="i">x</div>', "id="));
+check("javascript: href is dropped, text kept", lacks('<a href="javascript:alert(1)">t</a>', "javascript:") && has('<a href="javascript:alert(1)">t</a>', "t"));
+check("data: src is dropped", lacks('<img src="data:text/html;base64,PHN2Zz4=">', "data:"));
+check("protocol-relative src is dropped", lacks('<img src="//evil.com/x.png">', "evil.com"));
+check("javascript: in srcset is dropped", lacks('<source srcset="javascript:alert(1)">', "javascript:"));
+check("one bad srcset candidate drops the attribute", lacks('<source srcset="a.png 1x, javascript:alert(1) 2x">', "javascript:"));
+check("align only takes known values", lacks('<div align="center\" onclick=\"alert(1)">x</div>', "onclick"));
+check("an unknown attribute is dropped", lacks('<div data-x="1">y</div>', "data-x"));
+
+check("script content is dropped, not shown as text", has("<script>alert(2)</script>ok", "<p>ok</p>"));
+check("style content is dropped", has("<style>body{x}</style>ok", "<p>ok</p>"));
+check("a multi-line script block is dropped whole", lacks("a\n<script>\nalert(1)\n</script>\nb", "alert"));
+check("an unclosed script swallows nothing after it", has("a\n<script>\nalert(1)", "<p>a</p>"));
+check("a mid-line script is dropped, surrounds kept", has("hi <script>alert(1)</script> there", "hi") && lacks("hi <script>alert(1)</script> there", "alert"));
+check("fenced code still shows tags literally", has("```\n<script>x</script>\n```", "<script>x</script>"));
+check("inline code still shows tags literally", has("use `<script>` here", "<code><script></code>"));
+
+console.log("\n-- html is balanced, so a readme cannot escape its container --");
+
+check("an unclosed tag is closed", has('<div align="center">', "</div>"));
+check("unclosed nesting closes inside out", has("<div><span><b>", "<div><span><b></b></span></div>"));
+check("a stray closing tag is dropped", lacks("</div>", "</div>"));
+check("a stray page tag is dropped entirely", lacks("</article></body>", "</article>") && lacks("</article></body>", "</body>"));
+check("closers cannot outnumber openers", has("<div>a</div></div></div>", "<div>a</div>") && lacks("<div>a</div></div></div>", "</div></div>"));
+check("the internal tag markers never reach output", lacks("<div>x</div>", "\u0001") && lacks("<div>x</div>", "\u0002"));
+check("a forged marker in source is inert", lacks("\u0001<script>alert(1)</script>\u0002", "<script"));
+
console.log(failures === 0 ? "\nALL PASSED" : `\n${failures} FAILED`);
process.exit(failures === 0 ? 0 : 1);
diff --git a/test/mirror.test.mjs b/test/mirror.test.mjs
index 9113254..4715d32 100644
--- a/test/mirror.test.mjs
+++ b/test/mirror.test.mjs
@@ -1,15 +1,5 @@
/* 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
+ * LICENCED DASL-1.0 (c) Clove Twilight
*/
import { execFile } from "node:child_process";
diff --git a/test/notify.test.mjs b/test/notify.test.mjs
index 0e33536..46ff5d2 100644
--- a/test/notify.test.mjs
+++ b/test/notify.test.mjs
@@ -1,14 +1,5 @@
/* 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
+ * LICENCED DASL-1.0 (c) Clove Twilight
*/
import { execFile } from "node:child_process";
diff --git a/test/ownership.test.mjs b/test/ownership.test.mjs
index cf25763..df75bba 100644
--- a/test/ownership.test.mjs
+++ b/test/ownership.test.mjs
@@ -1,10 +1,5 @@
/* test/ownership.test.mjs
- *
- * Tests for per-user token ownership: who a token acts as. This is the rule
- * that keeps one account out of another's namespace, so it's worth pinning down
- * directly rather than only through the transport.
- *
- * Run: node --experimental-sqlite --experimental-strip-types test/ownership.test.mjs
+ * LICENCED DASL-1.0 (c) Clove Twilight
*/
import { mkdtempSync, rmSync } from "node:fs";
diff --git a/test/profile.test.mjs b/test/profile.test.mjs
index fad5168..e789c80 100644
--- a/test/profile.test.mjs
+++ b/test/profile.test.mjs
@@ -1,15 +1,5 @@
/* test/profile.test.mjs
- *
- * Tests for the "+" namespace and the profile README that rides on it.
- *
- * The load-bearing case is the first group. A leading "+" is what keeps the
- * route /<owner>/+repos from ever colliding with a repository, so the rule
- * "every + name is refused except the one profile repo" is a routing invariant
- * and not a cosmetic one: the moment safeRef accepts +repos, a repository can
- * shadow that page. The rest checks that a name the forge does accept survives
- * everything a normal repository survives — listing, trash, restore.
- *
- * Run: node --experimental-strip-types test/profile.test.mjs
+ * LICENCED DASL-1.0 (c) Clove Twilight
*/
import { execFile } from "node:child_process";
@@ -61,8 +51,6 @@ async function git(cwd, args) {
return stdout;
}
-// -- the "+" namespace --------------------------------------------------------
-
console.log("-- the + namespace is reserved, with exactly one exception --");
check("the profile repo is accepted", safeRef("clove", PROFILE_REPO) !== null);
@@ -85,13 +73,10 @@ check(
);
check("an owner may not use the + prefix", safeRef(PROFILE_REPO, "x") === null);
-// The pre-existing guarantees have to still hold.
check("still refuses traversal", safeRef("clove", "../etc") === null);
check("still refuses a dotfile name", safeRef("clove", ".ssh") === null);
check("still accepts an ordinary name", safeRef("clove", "my-repo.v2") !== null);
-// -- headReadme ---------------------------------------------------------------
-
console.log("\n-- the profile readme is read at HEAD --");
const created = await createRepo("clove", PROFILE_REPO);
@@ -112,8 +97,6 @@ const found = await headReadme(ref);
check("the readme is found at HEAD", found?.path === "README.md");
check("...with its text", found?.text.includes("profile text."));
-// A repo with commits but no README is the case the profile page reports
-// differently from a missing repo, so it must come back as null, not throw.
const plain = await createRepo("clove", "plain");
check("a second repo is created", plain.ok === true);
await git(work, ["push", "-q", refDir({ owner: "clove", name: "plain" }), "main:main"]);
@@ -125,20 +108,14 @@ check(
(await headReadme({ owner: "clove", name: "plain" })) === null,
);
-// -- listing ------------------------------------------------------------------
-
console.log("\n-- listing ignores names the forge would refuse --");
-// A directory can be created by hand; listRepos must not surface one whose
-// name safeRef would reject, or the UI would link to a page that 404s.
mkdirSync(join(root, "clove", "+bogus.git"), { recursive: true });
const listed = (await listRepos()).map((r) => r.name).sort();
check("the profile repo is listed by git.ts", listed.includes(PROFILE_REPO));
check("a stray + directory is not", !listed.includes("+bogus"));
check("ordinary repos are", listed.includes("plain"));
-// -- trash round-trip ---------------------------------------------------------
-
console.log("\n-- the profile repo trashes and restores like any other --");
const trashed = await trashRepo(ref, {
diff --git a/test/refs.test.mjs b/test/refs.test.mjs
index a4a7ceb..869645f 100644
--- a/test/refs.test.mjs
+++ b/test/refs.test.mjs
@@ -1,13 +1,5 @@
/* test/refs.test.mjs
- *
- * Tests for revision resolution and the repo description, against a real bare
- * repository with real branches and tags.
- *
- * The load-bearing case is the last group: `?h=` is attacker-supplied and ends
- * up in a git argv slot, so resolveRev has to be an allow-list rather than a
- * pattern check.
- *
- * Run: node --experimental-strip-types test/refs.test.mjs
+ * LICENCED DASL-1.0 (c) Clove Twilight
*/
import { execFile } from "node:child_process";
diff --git a/test/transport.test.mjs b/test/transport.test.mjs
index db94742..e697aa4 100644
--- a/test/transport.test.mjs
+++ b/test/transport.test.mjs
@@ -1,11 +1,6 @@
-// End-to-end test of the git smart-HTTP transport.
-//
-// Stands up a tiny Node HTTP server backed by src/smart-http.ts, seeds a real
-// bare repo, then uses the *actual git client* to clone from it and push to it,
-// asserting the round trip works. This validates the trickiest part of the
-// project (pkt-line framing + upload-pack/receive-pack RPC) against real git.
-//
-// Run: node --experimental-strip-types test/transport.test.mjs
+/* test/transport.test.mjs
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
import { createServer } from "node:http";
import { Readable } from "node:stream";
diff --git a/test/urls.test.mjs b/test/urls.test.mjs
index 89a6e48..b1baf26 100644
--- a/test/urls.test.mjs
+++ b/test/urls.test.mjs
@@ -1,11 +1,5 @@
/* 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
+ * LICENCED DASL-1.0 (c) Clove Twilight
*/
import {
@@ -80,8 +74,6 @@ 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");
-// The webhook validator opts into thread_id and wait; mirrors opt into
-// nothing, so those names must be just as dead here as any other.
no("github", "https://github.com/user/repo?thread_id=17", "an opted-in webhook parameter");
no("github", "https://github.com/user/repo?wait=true", "a webhook boolean");
no("github", "https://github.com/user/repo#frag", "fragment");
@@ -133,8 +125,6 @@ check(
discordWebhookUrl("https://ptb.discord.com/api/webhooks/1/tok") !== null,
);
-// thread_id and wait are the only query parameters allowed through, and only
-// with these exact value shapes. Anything else must still be refused outright.
check("accepts thread_id", discordWebhookUrl(`${W}?thread_id=17`) === `${W}?thread_id=17`);
check("accepts wait=true", discordWebhookUrl(`${W}?wait=true`) === `${W}?wait=true`);
check("accepts wait=false", discordWebhookUrl(`${W}?wait=false`) === `${W}?wait=false`);