2ca58cd86939
resolve the Kepr review findings: request cuts, abuse limits, resumable work and counter hygiene (v3.2.7)
- time
- 2026-11-17 00:31 UTC · 1 week ago
- machine
- Junes-MacBook-Pro.local
- agent
- deepseek/deepseek-flash
- session
- review findings
- parent
- 82287e051d2e
↓ kepr-2ca58cd8.tar.gzatlas at this save
files changed38 files
package.json+1 −1public/css/kepr.css+3 −1public/js/kepr.js+46 −8scripts/budget.ts+1 −2scripts/import-kepr2.ts+0 −206src/admin/backups.ts+2 −3src/admin/console.ts+10 −4src/admin/issues.ts+5 −1src/admin/rename.ts+15 −3src/admin/repos.ts+2 −1src/admin/store.ts+2 −0src/bucket/sync.ts+15 −10src/bucket/worker.ts+3 −0src/issues/followers.ts+14 −4src/issues/pages.ts+25 −3src/issues/spam.ts+17 −4src/issues/store.ts+10 −9src/main.ts+2 −1src/mirror/remote.ts+20 −21src/mirror/store.ts+2 −0src/pages/atlas.ts+125 −22src/pages/front.ts+20 −2src/pages/markdown.ts+8 −0src/pages/repo.ts+14 −8src/releases/releases.ts+42 −0src/releases/routes.ts+1 −1src/server/backup.ts+24 −25src/server/client.ts+8 −3src/server/db.ts+1 −0src/server/totp.ts+2 −1src/tarball/archive.ts+4 −2src/tarball/tar.ts+39 −1tests/client.test.ts+39 −0tests/fixtures/kepr2/schema.sql+0 −715tests/follow.test.ts+18 −0tests/import.test.ts+0 −367tests/issues.test.ts+26 −0tests/releases.test.ts+58 −1package.json+1 −1
@@ -1,6 +1,6 @@11 {22 "name": "kepr",3- "version": "3.2.6",3+ "version": "3.2.7",44 "private": true,55 "type": "module",66 "scripts": {public/css/kepr.css+3 −1
@@ -1858,7 +1858,9 @@18581858 .issue-post-actions a {18591859 color: var(--text-faint);18601860 }1861-.issue-post:hover .issue-post-actions a {1861+/* :where() flattens this to (0,1,1): still after `.issue-post-actions a`, so on hover the1862+ colour wins by order rather than by outranking every later `a` rule in the sheet. */1863+:where(.issue-post:hover) .issue-post-actions a {18621864 color: var(--text-muted);18631865 }18641866 .issue-post-actions a:hover,public/js/kepr.js+46 −8
@@ -497,37 +497,75 @@497497 });498498 }499499 const panels = new Map();500- const panelFor = (path) => {500+ // Each panel is fetched once per row and kept; a hover's fetch is dropped when the pointer leaves501+ // the row, so crossing rows asks only for the one the pointer stops on.502+ const panelFor = (path, signal) => {501503 if (!panels.has(path)) {502504 const query = new URLSearchParams({ path });503505 if (root.dataset.at) query.set("at", root.dataset.at);504- const text = fetch(`/${root.dataset.repo}/atlas/panel?${query}`)506+ const text = fetch(`/${root.dataset.repo}/atlas/panel?${query}`, { signal })505507 .then((response) => (response.ok ? response.text() : Promise.reject()))506508 .catch(() => {507509 panels.delete(path);508- return "";510+ return null;509511 });510512 panels.set(path, text);511513 }512514 return panels.get(path).then((text) => {515+ if (text === null) return null;513516 const template = document.createElement("template");514517 template.innerHTML = text;515518 return template.content;516519 });517520 };518521 let selected = null;519- const show = async (row) => {522+ const select = (row) => {523+ if (selected === row) return;520524 selected?.classList.remove("selected");521525 selected = row;522526 row.classList.add("selected");523- const content = await panelFor(row.dataset.path ?? `${row.parentElement.dataset.path}/`);524- if (selected === row) panel.replaceChildren(content);525527 };528+ const show = async (row, signal) => {529+ select(row);530+ const content = await panelFor(531+ row.dataset.path ?? `${row.parentElement.dataset.path}/`,532+ signal,533+ );534+ if (content && selected === row) panel.replaceChildren(content);535+ };536+ // A hover waits this long for the pointer to settle before it fetches.537+ const HOVER = 100;538+ let hovered = null;539+ let pending = 0;540+ let running = null;541+ const cancel = () => {542+ clearTimeout(pending);543+ pending = 0;544+ running?.abort();545+ running = null;546+ };547+ const leave = (row) => {548+ if (hovered !== row) return;549+ hovered = null;550+ cancel();551+ };526552 for (const row of root.querySelectorAll(".atlas-row")) {527553 row.addEventListener("pointerenter", (event) => {528- if (event.pointerType === "mouse") show(row);554+ if (event.pointerType !== "mouse") return;555+ cancel();556+ hovered = row;557+ select(row);558+ pending = setTimeout(() => {559+ running = new AbortController();560+ show(row, running.signal);561+ }, HOVER);529562 });530- row.addEventListener("focus", () => show(row));563+ row.addEventListener("pointerleave", () => leave(row));564+ row.addEventListener("focus", () => {565+ cancel();566+ hovered = null;567+ show(row);568+ });531569 }532570 // A map link in a panel jumps to its row, opening the folders above it.533571 const jump = (path) => {scripts/budget.ts+1 −2
@@ -4,7 +4,7 @@44 55 // Prefixes are matched in order, so the specific files come before the directories.66 const TS_AREAS: [string, string[], number][] = [7- ["bucket", ["src/bucket/"], 1245],7+ ["bucket", ["src/bucket/"], 1250],88 ["mirror", ["src/mirror/"], 1100],99 ["describe", ["src/describe/"], 530],1010 ["pages", ["src/pages/"], 2565],@@ -12,7 +12,6 @@1212 ["tarball", ["src/tarball/"], 300],1313 ["issues", ["src/issues/"], 1700],1414 ["admin", ["src/admin/"], 2800],15- ["import-kepr2", ["scripts/import-kepr2.ts"], 300],1615 ["server", ["src/server/", "src/main.ts", "scripts/budget.ts"], 2040],1716 ];1817 const ASSET_AREAS: [string, string, number][] = [scripts/import-kepr2.ts+0 −206
@@ -1,206 +0,0 @@1-// One-time Kepr 2 import (§28), deleted after cutover; the only bucket writer.2-// --dry-run writes nothing.3-import { dirname, join } from "node:path";4-import { blake3 } from "@noble/hashes/blake3.js";5-import { bytesToHex } from "@noble/hashes/utils.js";6-import { SQL } from "bun";7-import { openBucket } from "../src/bucket/reader.ts";8-import { checkRelease } from "../src/bucket/repo.ts";9-import { compareVersions } from "../src/releases/releases.ts";10-import { openKeprDb } from "../src/server/db.ts";11-12-type Row = Record<string, string | number | null>;13-const env = (name: string) => process.env[name] ?? "";14-const dry = process.argv.includes("--dry-run");15-const pg = new SQL(env("KEPR2_DATABASE_URL"));16-const kepr = openKeprDb(env("KEPR_DATA"));17-const folder = env("KOH_FOLDER");18-const VARS = "ENDPOINT BUCKET REGION ACCESS_KEY_ID SECRET_ACCESS_KEY".split(" ");19-const [endpoint, name, region, accessKeyId, secretAccessKey] = VARS.map((v) => env(`KOH_S3_${v}`));20-const s3 = { endpoint, region, accessKeyId, secretAccessKey };21-const bucket = openBucket(folder ? { kind: "folder", path: folder } : { kind: "s3", name, ...s3 });22-/** put_if_absent (§9.1); throws when `key` holds other bytes. */23-async function put(key: string, body: string | Uint8Array): Promise<void> {24- const bytes = typeof body === "string" ? new TextEncoder().encode(body) : body;25- const had = (await bucket.get(key)) ?? (dry ? null : await write(key, bytes));26- console.log(had ? "have" : dry ? "would put" : "put", key);27- if (had && !Bun.deepEquals(had, bytes)) throw new Error(`${key} holds other bytes`);28-}29-// Bun's S3 client can't write conditionally, so a presigned PUT does;30-// a 412 returns the racer's bytes.31-async function write(key: string, bytes: Uint8Array): Promise<Uint8Array | null> {32- if (folder) return Bun.write(join(folder, key), bytes).then(() => null);33- const url = new Bun.S3Client({ ...s3, bucket: name }).presign(key, { method: "PUT" });34- const res = await fetch(url, { method: "PUT", body: bytes, headers: { "If-None-Match": "*" } });35- if (res.ok || res.status === 412) return res.ok ? null : bucket.get(key);36- throw new Error(`put ${key}: ${res.status}`);37-}38-function insert(table: string, row: Row, tail: string): number | null {39- const cols = Object.keys(row);40- const sql = `INSERT INTO ${table} (${cols})41- VALUES (${cols.map((c) => `$${c}`)})42- ${tail}43- RETURNING rowid AS id`;44- const id = kepr.query<{ id: number }, [Row]>(sql).get(row)?.id ?? null;45- console.log(table, JSON.stringify(row).slice(0, 80), id ? "set" : "have");46- return id;47-}48-const errors: string[] = [],49- writes: [string, string | Uint8Array][] = [];50-kepr.run("BEGIN");51-const upsert = "ON CONFLICT DO UPDATE SET public = excluded.public, category = excluded.category";52-for (const repo of await pg<Row[]>`53- SELECT54- name,55- (private = 0)::int AS public,56- trim(split_part(COALESCE(categories, ''), ',', 1)) AS category57- FROM repos`) {58- insert("repos", repo, upsert);59-}60-// Kepr 2's four statuses become two (Phase 5); "enhancement" is an idea.61-// Kepr 2 wrote the operator's replies as "operator" (NULL before accounts);62-// a third account's reply has no author kind here.63-for (const { replies, ...i } of await pg<(Row & { replies: Row[] })[]>`64- SELECT65- i.repo,66- i.number,67- i.title,68- i.description AS body,69- CASE WHEN i.type IN ('bug', 'question') THEN i.type ELSE 'idea' END AS type,70- COALESCE(i.filed_ver, '') AS version,71- COALESCE(NULLIF(i.reporter_name, ''), '@' || a.username, '') AS reporter_name,72- COALESCE(NULLIF(i.contact_email, ''), i.contact, '') AS contact_email,73- i.filed_at,74- CASE75- WHEN i.status IN ('resolved', 'wontfix', 'closed') THEN 'closed'76- ELSE 'open'77- END AS status,78- CASE79- WHEN i.closed_save ~ '^[0-9a-f]{12}$' THEN i.closed_save80- ELSE ''81- END AS fixed_in,82- CASE83- WHEN i.status IN ('resolved', 'wontfix', 'closed') THEN COALESCE(i.closed_at, i.filed_at)84- END AS closed_at,85- (86- SELECT COALESCE(87- json_agg(88- json_build_object(89- 'author',90- CASE91- WHEN e.account_id IS NULL92- OR e.account_id = 'operator'93- OR o.tier = 'operator'94- THEN 'operator'95- WHEN e.account_id = i.account_id THEN 'reporter'96- END,97- 'body', e.body,98- 'created_at', e.created_at99- )100- ORDER BY e.created_at, e.id101- ),102- '[]'103- )104- FROM issue_entries e105- LEFT JOIN accounts o ON o.id = e.account_id106- WHERE e.issue_id = i.id107- AND e.entry_type = 'reply'108- AND e.body IS NOT NULL109- ) AS replies110- FROM issues i111- LEFT JOIN accounts a ON a.id = i.account_id112- ORDER BY i.repo, i.number`) {113- const id = insert("issues", i, "ON CONFLICT DO NOTHING");114- if (replies.some((r) => !r.author)) errors.push(`${i.repo}#${i.number}: third-party reply`);115- else {116- for (const r of id ? replies : []) {117- const name = r.author === "reporter" ? i.reporter_name : "";118- insert("issue_entries", { issue_id: id, ...r, name }, "");119- }120- }121-}122-// Kepr 2 counted Nix fetches as installs (kept 90 days).123-// Its archive downloads have no home in Kepr 3.124-for (const count of await pg<Row[]>`125- SELECT126- repo_id AS repo,127- COUNT(*) AS count128- FROM engagement_events129- WHERE event_type = 'nix_install'130- AND repo_id IS NOT NULL131- GROUP BY repo_id`) {132- insert("installs", count, "ON CONFLICT DO NOTHING");133-}134-// Only what Kepr 2 served: successful and partial builds, a file stored as135-// the repo's name as <repo>-<platform>, older uploads named by platform;136-// builds off hid a repo's. Save, notes: newest build's.137-type Release = { repo: string; version: string; hidden: boolean; record: Row; stored: string[] };138-const newest = new Map<string, string>();139-for (const { repo, version, hidden, record, stored } of await pg<Release[]>`140- SELECT141- a.repo_id AS repo,142- a.version,143- bool_or(r.builds_enabled = 0) AS hidden,144- json_agg(145- concat_ws(146- '/',147- 'releases',148- a.repo_id,149- a.version,150- a.platform,151- a.filename152- )153- ORDER BY a.platform154- ) AS stored,155- json_build_object(156- 'format', 1,157- 'repo', a.repo_id,158- 'version', a.version,159- 'save', (array_agg(b.save_id ORDER BY b.started_at DESC))[1],160- 'published_at', max(COALESCE(b.finished_at, a.built_at)),161- 'machine', 'kepr2',162- 'notes', COALESCE((array_agg(b.release_notes ORDER BY b.started_at DESC))[1], ''),163- 'files',164- json_agg(165- json_build_object(166- 'platform', a.platform,167- 'name',168- CASE169- WHEN a.filename = a.repo_id THEN a.repo_id || '-' || a.platform170- ELSE a.filename171- END,172- 'size', a.size_bytes,173- 'blake3', a.blake3,174- 'sha256', a.sha256175- )176- ORDER BY a.platform177- )178- ) AS record179- FROM release_artifacts a180- JOIN build_runs b ON b.id = a.build_run181- JOIN repos r ON r.name = a.repo_id182- WHERE b.status IN ('success', 'partial')183- GROUP BY a.repo_id, a.version184- ORDER BY a.repo_id, a.version`) {185- const prefix = `${repo}/releases/${version}`;186- try {187- for (const [n, f] of checkRelease(repo, version, record).files.entries()) {188- const path = join(env("KEPR2_DATA"), stored[n] ?? "");189- const file = Bun.file(path);190- const bytes = await ((await file.exists()) ? file : Bun.file(dirname(path))).bytes();191- if (bytesToHex(blake3(bytes)) !== f.blake3) throw new Error(`${f.platform}: hash mismatch`);192- writes.push([`${prefix}/${f.platform}/${f.name}`, bytes]);193- }194- writes.push([`${prefix}/release.json`, JSON.stringify(record)]);195- if (hidden) insert("release_settings", { repo, version, hidden: 1 }, "ON CONFLICT DO NOTHING");196- if (compareVersions(version, newest.get(repo) ?? "") > 0) newest.set(repo, version);197- } catch (error) {198- errors.push(`${prefix}: ${error instanceof Error ? error.message : error}`);199- }200-}201-// Fail before any write (kepr.db is not yet written); writes never overwrite, so a re-run finishes one.202-if (errors.length > 0) throw new Error(`not imported, nothing written:\n${errors.join("\n")}`);203-for (const [repo, version] of newest) writes.push([`${repo}/releases/latest`, version]);204-for (const [key, body] of writes) await put(key, body);205-kepr.run(dry ? "ROLLBACK" : "END");206-await pg.close();src/admin/backups.ts+2 −3
@@ -8,7 +8,6 @@88 backups,99 backupTarball,1010 checkBackupBucket,11- makeBackup,1211 offsiteBackups,1312 } from "../server/backup.ts";1413 import { type BackupBucket, saveConfig } from "../server/config.ts";@@ -139,14 +138,14 @@139138 app.get("/admin/backup", (c) => {140139 const backup = backupTarball(ctx.dataDir, c.req.query("name"));141140 if (!backup) return c.notFound();142- return c.body(backup.bytes, 200, {141+ return c.body(backup.stream, 200, {143142 "Content-Type": "application/gzip",144143 "Content-Disposition": `attachment; filename="kepr-backup-${backup.name}.tar.gz"`,145144 });146145 });147146 148147 app.post("/admin/backup", async (c) => {149- const failure = attemptBackup(ctx.kepr, () => makeBackup(ctx.kepr, ctx.dataDir));148+ const failure = await attemptBackup(ctx.kepr, () => ctx.syncer.backup(ctx.dataDir, "now"));150149 if (failure)151150 return c.html(await backupsPage(c, ctx, { error: `The backup failed: ${failure}` }), 500);152151 const upload = await attemptUpload(ctx.kepr, ctx.dataDir, ctx.config.backup);src/admin/console.ts+10 −4
@@ -100,9 +100,16 @@100100 }101101 102102 // ponytail: counted once per process by walking the source, since there is no build step.103-let runningLines: number | null = null;104-async function sourceLines(): Promise<number> {105- if (runningLines !== null) return runningLines;103+let runningLines: Promise<number> | null = null;104+function sourceLines(): Promise<number> {105+ // Cache the promise, not the value: concurrent first requests share one walk.106+ runningLines ??= countLines().catch((error) => {107+ runningLines = null;108+ throw error;109+ });110+ return runningLines;111+}112+async function countLines(): Promise<number> {106113 let total = 0;107114 const root = `${import.meta.dir}/../..`;108115 for await (const path of new Bun.Glob("{src,scripts}/**/*.ts").scan(root)) {@@ -110,7 +117,6 @@110117 const text = await Bun.file(`${root}/${path}`).text();111118 total += text.split("\n").length - (text.endsWith("\n") ? 1 : 0);112119 }113- runningLines = total;114120 return total;115121 }116122 src/admin/issues.ts+5 −1
@@ -16,6 +16,7 @@1616 operatorEntries,1717 operatorIssue,1818 operatorIssues,19+ operatorMatch,1920 replyAddresses,2021 reporterBlocked,2122 setClosed,@@ -64,9 +65,12 @@6465 const repo = repos.find((name) => name === c.req.query("repo")) ?? "";6566 const type = ISSUE_TYPES.find((t) => t === c.req.query("type")) ?? "";6667 const words = (c.req.query("q") ?? "").trim();68+ // One read of every issue, so each tab's count and the list come from the same result.69+ const all = operatorIssues(ctx.kepr);6770 const narrowed = (f: OperatorFilter) =>68- operatorIssues(ctx.kepr, f).filter(71+ all.filter(6972 (issue) =>73+ operatorMatch[f](issue) &&7074 (!repo || issue.repo === repo) &&7175 (!type || issue.type === type) &&7276 `${issue.title}\n${issue.body}`.toLowerCase().includes(words.toLowerCase()),src/admin/rename.ts+15 −3
@@ -3,6 +3,7 @@33 import { type Bucket, inTurn, KEPR_PREFIX } from "../bucket/reader.ts";44 import type { SyncTarget } from "../bucket/sync.ts";55 import { closeMirror } from "../mirror/store.ts";6+import { keepState, setting } from "../server/db.ts";67 import { RESERVED_NAMES } from "../server/reserved.ts";78 import { dropTarballs } from "../tarball/cache.ts";89 import type { AdminContext } from "./console.ts";@@ -28,6 +29,8 @@2829 if (!NEW_NAME.test(to)) return "a new name is lowercase letters, digits, '.', '_' and '-'.";2930 if (RESERVED_NAMES.has(to)) return `"${to}" is one of Kepr's own addresses.`;3031 if (renames.has(from)) return `it is already being renamed to ${renames.get(from)}.`;32+ // A retry of the rename a restart interrupted finishes that copy; its name is not taken.33+ if ((setting(ctx.kepr, "rename_pending") ?? "").startsWith(`${from}\n${to}\n`)) return null;3134 if (findRepo(ctx.kepr, to) || (await ctx.sync.bucket.list(`${to}/`)).length > 0) {3235 return `"${to}" is taken.`;3336 }@@ -38,8 +41,8 @@3841 * Renames a repo in the background (§30, 2026-10-01), with syncs held so none sees it half moved.3942 * Every key is copied to the new name, `head` last, again until the old `head` stops moving; then4043 * `.kepr/renamed/<old>` tells Koh the new name, Kepr's rows, mirror and hidden paths move, and the41- * old keys go. A machine offering to the old name meanwhile loses nothing: its saves are its own,42- * and its next offer follows the marker.44+ * old keys go. Its progress sits in settings, so a retry after a restart finishes the copy; a45+ * machine offering to the old name meanwhile keeps its saves, and follows the marker.4346 */4447 export function renameRepo(ctx: AdminContext, from: string, to: string): void {4548 renames.set(from, to);@@ -51,11 +54,17 @@5154 }5255 5356 async function move({ bucket, kepr, mirrorDir }: SyncTarget, from: string, to: string) {57+ // The record is `old name, new name, 1 once head has moved`: what a retry after a restart reads.58+ const [savedFrom, savedTo, savedHead] = (setting(kepr, "rename_pending") ?? "").split("\n");59+ let moved = savedFrom === from && savedTo === to && savedHead === "1";60+ keepState(kepr, "rename_pending", `${from}\n${to}\n${moved ? "1" : "0"}`);5461 const copied = new Set<string>();5562 let head: string | null = null;5663 for (let pass = 0; ; pass++) {5764 const now = await text(bucket, `${from}/head`);58- if (now === null) throw new Error(`${from} has no head in the bucket.`);65+ // `head` is copied last, so a missing old one leaves only the removal of the old keys.66+ if (now === null && !moved) throw new Error(`${from} has no head in the bucket.`);67+ if (now === null) break;5968 if (now === head) break;6069 if (pass === 5) throw new Error(`${from} kept moving while it was copied; try again.`);6170 const keys = (await bucket.list(`${from}/`)).filter(@@ -64,6 +73,8 @@6473 await inTurn(keys, AT_ONCE, (key) => bucket.copy(key, `${to}/${key.slice(from.length + 1)}`));6574 for (const key of keys) copied.add(key);6675 await bucket.copy(`${from}/head`, `${to}/head`);76+ moved = true;77+ keepState(kepr, "rename_pending", `${from}\n${to}\n${moved ? "1" : "0"}`);6778 head = now;6879 }6980 await bucket.put(@@ -84,6 +95,7 @@8495 if (existsSync(path)) renameSync(path, join(mirrorDir, `${to}.db${suffix}`));8596 }8697 await inTurn(await bucket.list(`${from}/`), AT_ONCE, (key) => bucket.removeRenamed(key));98+ keepState(kepr, "rename_pending", null);8799 }88100 89101 async function text(bucket: Bucket, key: string): Promise<string | null> {src/admin/repos.ts+2 −1
@@ -45,7 +45,8 @@4545 });4646 4747 app.post("/admin/sync", async (c) => {48- await ctx.syncer.syncAll();48+ // Handed to the sync's own thread: a pass over every repo cannot wait behind a proxy timeout.49+ await ctx.syncer.syncSoon();4950 return c.redirect("/admin/repos", 303);5051 });5152 src/admin/store.ts+2 −0
@@ -56,6 +56,8 @@5656 /** Moves a renamed repo's settings, texts, issues and counts to its new name, and records it. */5757 export function moveRepoRows(db: Database, from: string, to: string): void {5858 db.transaction(() => {59+ // A sync after a crash may have registered the new name already, from the copied `head`.60+ db.query("DELETE FROM repos WHERE name = ?").run(to);5961 for (const [table, column] of REPO_COLUMNS) {6062 db.query(`UPDATE ${table} SET ${column} = ? WHERE ${column} = ?`).run(to, from);6163 }src/bucket/sync.ts+15 −10
@@ -11,6 +11,7 @@1111 type StoredObject,1212 storeObjects,1313 } from "../mirror/store.ts";14+import { backupWhen } from "../server/backup.ts";1415 import type { BucketSource } from "../server/config.ts";1516 import {1617 hiddenPaths,@@ -72,7 +73,7 @@7273 7374 let running: Promise<void> | null = null;7475 75-/** Syncs every repo in the bucket; the admin console's "sync now" calls this too. Never overlaps itself. */76+/** Syncs every repo in the bucket. Never overlaps itself. */7677 export function syncAll(target: SyncTarget): Promise<void> {7778 return running ?? holdSync(() => syncEach(target));7879 }@@ -92,21 +93,24 @@9293 }9394 9495 /**95- * What the app asks of the sync: one now, syncs held off while some work runs, a changed hidden96- * list applied, new bucket settings followed. Mirrors have one writer, the sync, so hidden lists go97- * through it too.96+ * What the app asks of the sync: a pass and wait for it, a pass posted and answered at once,97+ * syncs held off while work runs, hidden lists applied, bucket settings followed, a backup made98+ * where it cannot stall a request. Mirrors have one writer; in this thread a posted pass has run.9899 */99100 export type Syncer = {100101 syncAll(): Promise<void>;102+ syncSoon(): Promise<void>;101103 hold(work: () => Promise<void>): Promise<void>;102104 applyHidden(repos: string[]): Promise<void>;103105 setBucket(source: BucketSource): void;106+ backup(dataDir: string, when: "due" | "now"): Promise<void>;104107 };105108 106109 /** The sync in this thread, as the worker and the tests run it. */107110 export function localSyncer(target: SyncTarget): Syncer {108111 return {109112 syncAll: () => syncAll(target),113+ syncSoon: () => syncAll(target),110114 hold: holdSync,111115 applyHidden: async (repos) => {112116 for (const asked of repos) {@@ -117,6 +121,7 @@117121 }118122 },119123 setBucket: (source) => Object.assign(target.bucket, openBucket(source)),124+ backup: async (dataDir, when) => void backupWhen(target.kepr, dataDir, when),120125 };121126 }122127 @@ -125,6 +130,7 @@125130 | { kind: "start"; dataDir: string; source: BucketSource }126131 | { kind: "sync" | "hold" | "release"; id: number }127132 | { kind: "hidden"; id: number; repos: string[] }133+ | { kind: "backup"; id: number; dataDir: string; when: "due" | "now" }128134 | { kind: "bucket"; source: BucketSource };129135 export type SyncReply = { kind: "done"; id: number; error?: string };130136 @@ -156,11 +162,11 @@156162 waiting.set(id, { resolve: () => resolve(id), reject });157163 send(request(id));158164 });165+ const once = async (request: (id: number) => SyncRequest) => void (await ask(request));159166 send({ kind: "start", dataDir, source });160167 return {161- syncAll: async () => {162- await ask((id) => ({ kind: "sync", id }));163- },168+ syncAll: () => once((id) => ({ kind: "sync", id })),169+ syncSoon: () => Promise.resolve(send({ kind: "sync", id: next++ })),164170 async hold(work) {165171 const id = await ask((id) => ({ kind: "hold", id }));166172 try {@@ -169,10 +175,9 @@169175 send({ kind: "release", id });170176 }171177 },172- applyHidden: async (repos) => {173- await ask((id) => ({ kind: "hidden", id, repos }));174- },178+ applyHidden: (repos) => once((id) => ({ kind: "hidden", id, repos })),175179 setBucket: (source) => send({ kind: "bucket", source }),180+ backup: (dataDir, when) => once((id) => ({ kind: "backup", id, dataDir, when })),176181 };177182 }178183 src/bucket/worker.ts+3 −0
@@ -60,5 +60,8 @@6060 );6161 case "bucket":6262 return syncer.setBucket(data.source);63+ case "backup":64+ // On this thread, so the VACUUM and its copy never hold up a request.65+ return void settle(data.id, syncer.backup(data.dataDir, data.when));6366 }6467 });src/issues/followers.ts+14 −4
@@ -10,9 +10,17 @@1010 return address.length <= 254 && EMAIL.test(address);1111 }1212 13+// §23: how long an address that never confirms holds its row. Past it a request for the same14+// address takes the row over, so a lost email can be asked for again and an address someone else15+// typed first is not held forever. Inside it a repeat sends nothing, so the form cannot be used to16+// flood an inbox. Only unconfirmed rows are ever taken over.17+const UNCONFIRMED_LIFE = 86_400;18+1319 /**1420 * Asks an address to follow an issue (§23). A new one is sent one confirmation email and nothing15- * more until it is confirmed; one already asked is sent nothing. True when a confirmation went out.21+ * more until it is confirmed; one already asked within the last day is sent nothing, and one asked22+ * longer ago than that is asked again. A confirmed follower is left as it is. True when a23+ * confirmation went out.1624 */1725 export function follow(1826 kepr: Database,@@ -25,13 +33,15 @@2533 ): boolean {2634 const address = email.toLowerCase();2735 const row = kepr28- .query<{ id: number }, [number, string, string, number]>(36+ .query<{ id: number }, [number, string, string, number, number]>(2937 `INSERT INTO issue_followers (issue_id, email, ip_hash, created_at)3038 VALUES (?, ?, ?, ?)31-ON CONFLICT (issue_id, email) DO NOTHING39+ON CONFLICT (issue_id, email) DO UPDATE40+SET ip_hash = excluded.ip_hash, created_at = excluded.created_at41+WHERE confirmed = 0 AND created_at <= ?3242 RETURNING id`,3343 )34- .get(issue.id, address, ipHash, now);44+ .get(issue.id, address, ipHash, now, now - UNCONFIRMED_LIFE);3545 if (!row) return false;3646 // Only a request that mails something counts, and it is logged here rather than in the follower3747 // rows, so stopping the emails cannot free the hour's allowance (§23).src/issues/pages.ts+25 −3
@@ -118,8 +118,11 @@118118 const repo = openPublicRepo(ctx, c.req.param("repo"));119119 if (!repo) return notFound(c, ctx);120120 const status = c.req.query("status") === "closed" ? "closed" : "open";121+ const wanted = Math.max(1, Number.parseInt(c.req.query("page") ?? "1", 10) || 1);121122 cacheFor(c, false);122- return c.html(listPage(ctx, repo, status, c.req.query("q") ?? "", c.req.query("type") ?? ""));123+ return c.html(124+ listPage(ctx, repo, status, c.req.query("q") ?? "", c.req.query("type") ?? "", wanted),125+ );123126 });124127 125128 app.get("/:repo/issues/new", (c) => {@@ -456,21 +459,36 @@456459 <a href="/${repo}/issues${closed ? "?status=closed" : ""}">back to issues</a></p>`;457460 }458461 462+// Fifty rows is a page a reader can scan, and keeps an old issue one link away.463+const ISSUES_PER_PAGE = 50;464+459465 function listPage(460466 ctx: PageContext,461467 repo: PublicRepo,462468 status: "open" | "closed",463469 query: string,464470 type: string,471+ requested: number,465472 ): string {466473 const name = repo.settings.name;467474 const counts = issueCounts(ctx.kepr, name);468475 const filter = ISSUE_TYPES.includes(type as IssueType) ? type : "";469- const issues = listIssues(ctx.kepr, name, status).filter(476+ // ponytail: a repo's whole visible list is filtered then sliced in memory; push the filter and477+ // LIMIT into SQL if one repo ever holds more issues than a request should read.478+ const matched = listIssues(ctx.kepr, name, status).filter(470479 (issue) =>471480 (!filter || issue.type === filter) &&472481 issue.title.toLowerCase().includes(query.trim().toLowerCase()),473482 );483+ const pages = Math.max(1, Math.ceil(matched.length / ISSUES_PER_PAGE));484+ const current = Math.min(Math.max(1, requested), pages);485+ const issues = matched.slice((current - 1) * ISSUES_PER_PAGE, current * ISSUES_PER_PAGE);486+ // Page 1 keeps today's URL, so a short list reads exactly as it did.487+ const pageHref = (n: number) => {488+ const params = new URLSearchParams({ status, q: query, type: filter });489+ if (n > 1) params.set("page", String(n));490+ return `/${name}/issues?${params.toString()}`;491+ };474492 const tab = (which: "open" | "closed") =>475493 html`<a class="issues-tab${which === status ? " active" : ""}"476494 href="/${name}/issues${which === "closed" ? "?status=closed" : ""}">@@ -509,7 +527,11 @@509527 )510528 : html`<p class="muted mono save-empty">${query || filter ? "no matching issues" : `no ${status} issues`}</p>`511529 }512-</section>`,530+</section>531+${532+ pages > 1 &&533+ html`<p class="pager mono">${current > 1 && html`<a href="${pageHref(current - 1)}">← newer</a>`}<span class="muted">page ${current} of ${pages}</span>${current < pages && html`<a class="pager-older" href="${pageHref(current + 1)}">older →</a>`}</p>`534+}`,513535 });514536 }515537 src/issues/spam.ts+17 −4
@@ -14,12 +14,25 @@1414 const FORM_COOKIE = "kepr_form";1515 const HEX = /^[0-9a-f]{32,64}$/;1616 17+// Read once per database: every IP hash, form stamp and follower token used to take the write lock18+// to re-store the same key (§23). Keyed by database so a process with several keeps them apart.19+const secrets = new WeakMap<Database, string>();20+1721 /** One random key, made on first use and kept in kepr.db, for the IP hash and the form stamps. */1822 function secret(db: Database): string {19- db.query("INSERT OR IGNORE INTO settings (key, value) VALUES ('issue_secret', ?)").run(20- randomBytes(32).toString("hex"),21- );22- return setting(db, "issue_secret") as string;23+ const cached = secrets.get(db);24+ if (cached !== undefined) return cached;25+ const stored = setting(db, "issue_secret");26+ if (stored !== null) {27+ secrets.set(db, stored);28+ return stored;29+ }30+ const fresh = randomBytes(32).toString("hex");31+ db.query("INSERT OR IGNORE INTO settings (key, value) VALUES ('issue_secret', ?)").run(fresh);32+ // Another process may have got there first; whatever the row holds is the key all of them share.33+ const value = setting(db, "issue_secret") ?? fresh;34+ secrets.set(db, value);35+ return value;2336 }2437 2538 function mac(db: Database, message: string): string {src/issues/store.ts+10 −9
@@ -230,23 +230,24 @@230230 ), 'reporter') = 'reporter'`;231231 const OPERATOR_COLUMNS = `${PUBLIC_COLUMNS}, repo, hidden, contact_email,232232 ${REPORTER_SPOKE_LAST} AS awaiting`;233-const OPERATOR_WHERE: Record<OperatorFilter, string> = {234- open: "hidden = 0 AND status = 'open'",235- awaiting: `hidden = 0 AND status = 'open' AND ${REPORTER_SPOKE_LAST}`,236- closed: "hidden = 0 AND status = 'closed'",237- hidden: "hidden = 1",233+/** Each console tab's test, so a single read of every issue answers every tab. */234+export const operatorMatch: Record<OperatorFilter, (issue: OperatorIssue) => boolean> = {235+ open: (issue) => !issue.hidden && issue.status === "open",236+ awaiting: (issue) => !issue.hidden && issue.status === "open" && issue.awaiting === 1,237+ closed: (issue) => !issue.hidden && issue.status === "closed",238+ hidden: (issue) => issue.hidden === 1,238239 };239240 240-/** Every repo's issues under one console tab, private repos' included, newest first. */241-export function operatorIssues(db: Database, filter: OperatorFilter): OperatorIssue[] {242- return db241+/** Every repo's issues, private repos' included, newest first; no filter reads them all at once. */242+export function operatorIssues(db: Database, filter?: OperatorFilter): OperatorIssue[] {243+ const issues = db243244 .query<OperatorIssue, []>(244245 `SELECT ${OPERATOR_COLUMNS}245246 FROM issues246-WHERE ${OPERATOR_WHERE[filter]}247247 ORDER BY filed_at DESC, id DESC`,248248 )249249 .all();250+ return filter ? issues.filter(operatorMatch[filter]) : issues;250251 }251252 252253 export function operatorIssue(db: Database, repo: string, number: number): OperatorIssue | null {src/main.ts+2 −1
@@ -20,12 +20,13 @@2020 const kepr = openKeprDb(config.dataDir);2121 // One bucket for the sync loop and the app, so settings saved in the console reach both.2222 const bucket = openBucket(config.bucket);23- startBackupLoop(kepr, config);2423 startMailLoop(kepr, config);2524 const mirrorDir = join(config.dataDir, "mirror");2625 openMirrors(mirrorDir);2726 // The first visitor after a new save would otherwise wait a second or two on a big repo.2827 const syncer = startSyncWorker(config.dataDir, config.bucket);28+ // A backup vacuums and copies on the sync's thread, so it never stalls a request.29+ startBackupLoop(kepr, config, () => syncer.backup(config.dataDir, "due"));2930 startStorageLoop({ bucket, kepr, mirrorDir });3031 return createApp(config, kepr, bucket, CONFIG_FILE, syncer).fetch;3132 }src/mirror/remote.ts+20 −21
@@ -1,4 +1,4 @@1-import type { Database } from "bun:sqlite";1+import { Database } from "bun:sqlite";22 import type { Context, Hono } from "hono";33 import { type EventRecord, SAVE_ID, type SaveFile, type SaveRecord } from "../bucket/repo.ts";44 import { openPublicRepo, type PageContext } from "../pages/layout.ts";@@ -117,14 +117,13 @@117117 // Koh lists `<repo>/saves` and `<repo>/objects` as well as its events: a steal walks the chain118118 // it is given here, and fetches every object those saves name. Both lists follow the mirror, so119119 // neither is cached.120+ const listIds = (c: Context, mirror: Database, table: "saves" | "events"): Response => {121+ const ids = mirror.query<{ id: string }, []>(`SELECT id FROM ${table} ORDER BY id`).all();122+ return text(c, ids.length > 0 ? `${ids.map((row) => row.id).join("\n")}\n` : "", NO_CACHE);123+ };124+120125 app.get("/:repo/koh/saves", (c) =>121- serve(c, c.req.param("repo"), (mirror) => {122- const ids = mirror123- .query<{ id: string }, []>("SELECT id FROM saves ORDER BY id")124- .all()125- .map((row) => row.id);126- return text(c, ids.length > 0 ? `${ids.join("\n")}\n` : "", NO_CACHE);127- }),126+ serve(c, c.req.param("repo"), (mirror) => listIds(c, mirror, "saves")),128127 );129128 130129 app.get("/:repo/koh/objects", (c) =>@@ -142,13 +141,7 @@142141 );143142 144143 app.get("/:repo/koh/events", (c) =>145- serve(c, c.req.param("repo"), (mirror) => {146- const ids = mirror147- .query<{ id: string }, []>("SELECT id FROM events ORDER BY id")148- .all()149- .map((row) => row.id);150- return text(c, ids.length > 0 ? `${ids.join("\n")}\n` : "", NO_CACHE);151- }),144+ serve(c, c.req.param("repo"), (mirror) => listIds(c, mirror, "events")),152145 );153146 154147 app.get("/:repo/koh/events/:id", (c) =>@@ -195,28 +188,34 @@195188 yield encoder.encode(`${key} ${bytes.length}\n`);196189 yield bytes;197190 }198- // `prepare`, never the cached `query`: two bundles streaming at once would share one cursor and199- // split the rows between them.200- const saves = mirror.prepare<SaveRow, []>(`SELECT ${SAVE_COLUMNS} FROM saves`);201- const events = mirror.prepare<EventRow, []>(`SELECT ${EVENT_COLUMNS} FROM events`);202- const objects = mirror.prepare<{ hash: string; data: Uint8Array }, []>(191+ // One snapshot on a connection of its own: a strip landing mid-stream must not leave a save192+ // naming an object this read omits, and a second steal must not nest in this one's transaction.193+ const reader = new Database(mirror.filename, { strict: true, readonly: true });194+ const saves = reader.prepare<SaveRow, []>(`SELECT ${SAVE_COLUMNS} FROM saves`);195+ const events = reader.prepare<EventRow, []>(`SELECT ${EVENT_COLUMNS} FROM events`);196+ const objects = reader.prepare<{ hash: string; data: Uint8Array }, []>(203197 `SELECT hash, data FROM objects o204198 WHERE EXISTS (SELECT 1 FROM save_files f WHERE f.hash = o.hash)`,205199 );206200 try {201+ reader.run("BEGIN DEFERRED");207202 for (const row of saves.iterate()) {208- yield* entry(`saves/${row.id}`, encoder.encode(saveRecord(mirror, row)));203+ yield* entry(`saves/${row.id}`, encoder.encode(saveRecord(reader, row)));209204 }210205 for (const row of events.iterate()) {211206 yield* entry(`events/${row.id}`, encoder.encode(eventRecord(row)));212207 }213208 for (const row of objects.iterate()) yield* entry(`objects/${row.hash}`, row.data);209+ reader.run("COMMIT");214210 // A connection cut between two entries would otherwise pass for the whole repo.215211 yield encoder.encode("end 0\n");216212 } finally {217213 saves.finalize();218214 events.finalize();219215 objects.finalize();216+ // A client that hangs up mid-stream would otherwise leave the snapshot open.217+ if (reader.inTransaction) reader.run("ROLLBACK");218+ reader.close();220219 }221220 }222221 src/mirror/store.ts+2 −0
@@ -188,6 +188,8 @@188188 "The mirror is disposable: delete it and the next sync rebuilds it from the bucket.",189189 );190190 }191+ // A panel reads one path's touches; without this index every hover scans them (§21.5).192+ db.run("CREATE INDEX IF NOT EXISTS touches_path ON touches(path, n)");191193 // Mirrors counted under an older rule are recounted now, not at the next save.192194 if (mirrorState(db, "head") && mirrorState(db, "stats_rule") !== STATS_RULE) refreshStats(db);193195 open.set(path, db);src/pages/atlas.ts+125 −22
@@ -1,6 +1,13 @@1+import type { Database } from "bun:sqlite";12 import { describeFolder, firstSentence } from "../describe/describe.ts";23 import { isTestPath, type Outline, repoIndex, resolveImports } from "../describe/links.ts";3-import { filesWithFacts, fileTouches, type Save, type Touches } from "../mirror/queries.ts";4+import {5+ filesWithFacts,6+ fileTouches,7+ type Save,8+ type Touches,9+ tarballGeneration,10+} from "../mirror/queries.ts";411 import { type Html, html } from "./html.ts";512 import {613 formatDate,@@ -35,6 +42,9 @@3542 /** Each file's resolved imports, and who imports each file or `folder/`. */3643 type Links = { imports: Map<string, string[]>; usedBy: Map<string, string[]> };3744 45+/** The fields resolving imports reads, from the tree or straight from the mirror's facts. */46+type Linked = { path: string; outline: Outline | null };47+3848 type View = { repo: string; at: string | null; links: Links };3949 4050 // A panel lists this many names or links, then says how many more.@@ -43,11 +53,19 @@4353 /** The tree at one save with each file's facts and the links between files. */4454 type AtlasModel = { root: AtlasFolder; links: Links; count: number };4555 46-// Built per request from what each save recorded as it landed (touches and facts), so nothing is47-// kept between requests. In one read snapshot: the sync's thread can change the mirror between any48-// two statements.49-function atlasModel(repo: PublicRepo, saveId: string): AtlasModel {50- return repo.mirror.transaction(() => buildAtlasModel(repo, saveId))();56+// Linking needs every file's outline, so a save's links are worked out once and kept for its57+// panels: a hover then reads its own row alone. `tarballGeneration` names what a landed sync can58+// change behind a save (strips, hidden paths, a cleared mirror).59+const linkCache = new Map<string, Links>();60+61+function linksFor(repo: PublicRepo, saveId: string, read: () => Linked[]): Links {62+ const key = `${repo.settings.name}\n${saveId}\n${tarballGeneration(repo.mirror)}`;63+ const found = linkCache.get(key);64+ if (found) return found;65+ const links = linksOf(read());66+ if (linkCache.size > 3) linkCache.clear();67+ linkCache.set(key, links);68+ return links;5169 }5270 5371 function buildAtlasModel(repo: PublicRepo, saveId: string): AtlasModel {@@ -80,7 +98,7 @@8098 saves: touches.byPath.get(entry.path) ?? [],8199 });82100 }83- return { root, links: linksOf(allFiles(root)), count: entries.length };101+ return { root, links: linksFor(repo, saveId, () => entries), count: entries.length };84102 }85103 86104 /**@@ -90,7 +108,8 @@90108 * to view it at instead, its rows fetched from `atlasPickerRows` when first opened.91109 */92110 export function atlasSection(repo: PublicRepo, saveId: string, at: string | null): Html {93- const model = atlasModel(repo, saveId);111+ // In one read snapshot: the sync's thread can change the mirror between any two statements.112+ const model = repo.mirror.transaction(() => buildAtlasModel(repo, saveId))();94113 const view = { repo: repo.settings.name, at, links: model.links };95114 return html`<section class="repo-section" id="atlas">96115 <details class="repo-section-toggle" open>@@ -113,6 +132,43 @@113132 </section>`;114133 }115134 135+type PanelRow = { path: string; size: number; lines: number | null; description: string | null };136+137+// A panel's own reads: one row's facts, and the saves that touched it or (for a folder) anything138+// under it. Everything else the panel needs comes from the links, which are kept (linksFor).139+const FILE_SQL = `SELECT f.path, o.size, x.lines, x.description, x.outline140+ FROM save_files f141+ JOIN objects o ON o.hash = f.hash142+ LEFT JOIN facts x ON x.hash = f.hash AND x.path = f.path143+ WHERE f.save_id = ? AND f.path = ? AND f.path != '.kohignore'`;144+const FOLDER_SQL = `SELECT f.path, o.size, x.lines, x.description145+ FROM save_files f146+ JOIN objects o ON o.hash = f.hash147+ LEFT JOIN facts x ON x.hash = f.hash AND x.path = f.path148+ WHERE f.save_id = ? AND f.path >= ? AND f.path < ? AND f.path != '.kohignore'149+ ORDER BY f.path`;150+151+// The saves that touched a path, or (with `under`) anything under a folder, oldest first.152+function pathTouches(db: Database, saveId: string, path: string, under: boolean): Save[] {153+ const scope = under ? "path >= ? AND path < ?" : "path = ?";154+ const params = under ? [saveId, `${path}/`, `${path}0`] : [saveId, path];155+ return db156+ .query<Save, string[]>(157+ `SELECT id, COALESCE(parent, '') AS parent, message, created_at, machine,158+ COALESCE(agent, '') AS agent, COALESCE(session, '') AS session,159+ is_checkpoint = 1 AS is_checkpoint160+ FROM saves161+ WHERE is_checkpoint = 0162+ AND rowid IN (163+ SELECT n FROM touches164+ WHERE n <= (SELECT rowid FROM saves WHERE id = ?) AND ${scope}165+ )166+ ORDER BY rowid`,167+ )168+ .all(...params)169+ .map((row) => ({ ...row, is_checkpoint: Boolean(row.is_checkpoint) }));170+}171+116172 /** One row's detail panel: a file's, or a folder's when `path` ends in a slash; null if absent. */117173 export function atlasPanel(118174 repo: PublicRepo,@@ -120,17 +176,65 @@120176 at: string | null,121177 path: string,122178 ): Html | null {123- const model = atlasModel(repo, saveId);124- const view = { repo: repo.settings.name, at, links: model.links };125- const parts = path.replace(/\/$/, "").split("/");126- let folder: AtlasFolder | undefined = model.root;127- for (const name of path.endsWith("/") ? parts : parts.slice(0, -1)) {128- folder = folder?.folders.find((f) => f.name === name);129- }130- if (!folder) return null;131- if (path.endsWith("/")) return folderPanel(folder, view);132- const file = folder.files.find((f) => f.path === path);133- return file ? filePanel(file, view) : null;179+ const folder = path.endsWith("/");180+ const dir = folder ? path.slice(0, -1) : path;181+ return repo.mirror.transaction((): Html | null => {182+ const rows = folder183+ ? repo.mirror184+ .query<PanelRow, [string, string, string]>(FOLDER_SQL)185+ .all(saveId, `${dir}/`, `${dir}0`)186+ : [];187+ const row = folder188+ ? null189+ : (repo.mirror190+ .query<PanelRow & { outline: string | null }, [string, string]>(FILE_SQL)191+ .get(saveId, dir) ?? null);192+ if (folder ? rows.length === 0 : row === null) return null;193+ const view = {194+ repo: repo.settings.name,195+ at,196+ links: linksFor(repo, saveId, () =>197+ filesWithFacts(repo.mirror, saveId).filter((entry) => entry.path !== ".kohignore"),198+ ),199+ };200+ if (rows.length > 0) {201+ const files = rows.map(202+ (entry): AtlasFile => ({203+ name: entry.path.split("/").pop() as string,204+ path: entry.path,205+ size: entry.size,206+ lines: entry.lines,207+ description: entry.description,208+ outline: null,209+ saves: [],210+ }),211+ );212+ return folderPanel(213+ {214+ name: dir.split("/").pop() as string,215+ path: dir,216+ folders: [],217+ files: files.filter((file) => !file.path.slice(dir.length + 1).includes("/")),218+ saves: pathTouches(repo.mirror, saveId, dir, true),219+ },220+ files,221+ view,222+ );223+ }224+ if (row === null) return null;225+ return filePanel(226+ {227+ name: dir.split("/").pop() as string,228+ path: dir,229+ size: row.size,230+ lines: row.lines,231+ description: row.description,232+ outline: row.outline === null ? null : (JSON.parse(row.outline) as Outline),233+ saves: pathTouches(repo.mirror, saveId, dir, false),234+ },235+ view,236+ );237+ })();134238 }135239 136240 // Kepr 2's "explore through time". Its rows arrive when first opened (kepr.js): a big repo's@@ -227,7 +331,7 @@227331 return more > 0 ? [...items.slice(0, LISTED), html`+${more} more`] : items;228332 }229333 230-function linksOf(files: AtlasFile[]): Links {334+function linksOf(files: Linked[]): Links {231335 const index = repoIndex(files.map((file) => file.path));232336 const imports = new Map<string, string[]>();233337 const usedBy = new Map<string, string[]>();@@ -254,8 +358,7 @@254358 </details>`;255359 }256360 257-function folderPanel(folder: AtlasFolder, view: View): Html {258- const files = allFiles(folder);361+function folderPanel(folder: AtlasFolder, files: AtlasFile[], view: View): Html {259362 const size = files.reduce((sum, f) => sum + f.size, 0);260363 const lines = files.reduce((sum, f) => sum + (f.lines ?? 0), 0);261364 return panel(src/pages/front.ts+20 −2
@@ -1,5 +1,5 @@11 import type { Hono } from "hono";2-import { knownObjects, languageLines } from "../mirror/queries.ts";2+import { headId, knownObjects, languageLines, tarballGeneration } from "../mirror/queries.ts";33 import { setting } from "../server/db.ts";44 import { type Html, html } from "./html.ts";55 import { cacheFor, type PageContext, page, plural } from "./layout.ts";@@ -15,7 +15,7 @@1515 const library = publicLibrary(ctx);1616 const tagline = setting(ctx.kepr, "tagline") ?? "";1717 // §21.1: distinct objects across every public repo's real saves.18- const known = new Set(library.flatMap((repo) => knownObjects(repo.mirror))).size;18+ const known = knownThings(library);1919 const latest = library2020 .filter((repo) => repo.stats.updated !== null)2121 .sort((a, b) => (b.stats.updated ?? 0) - (a.stats.updated ?? 0))@@ -60,6 +60,24 @@6060 }),6161 );6262 });63+}64+65+// §21.1's "things": the union of every public repo's objects, which only a sync changes. The key66+// names each mirror's head and what rewrites an older save (strips, hidden paths, a cleared67+// mirror), so a landed sync counts again and no request scans every object.68+let counted: { key: string; count: number } | null = null;69+70+function knownThings(library: LibraryRepo[]): number {71+ const key = library72+ .map(73+ (repo) =>74+ `${repo.settings.name}\n${headId(repo.mirror) ?? ""}\n${tarballGeneration(repo.mirror)}`,75+ )76+ .join("\n");77+ if (counted?.key === key) return counted.count;78+ const count = new Set(library.flatMap((repo) => knownObjects(repo.mirror))).size;79+ counted = { key, count };80+ return count;6381 }6482 6583 // Rows of recent save messages drifting at different depths; the motion is CSS, and stops undersrc/pages/markdown.ts+8 −0
@@ -52,6 +52,14 @@5252 const image = md.renderer.rules.image;5353 md.renderer.rules.image = (tokens, idx, options, env, self) => {5454 const token = tokens[idx] as (typeof tokens)[number];55+ // An issue's picture would be fetched from the reader's browser, counting a download or56+ // calling home, so a comment shows its alt text instead (§25).57+ if (env?.comment) {58+ const alt = md.utils.escapeHtml(token.content);59+ if (alt) return alt;60+ const src = md.utils.escapeHtml(String(token.attrGet("src") ?? ""));61+ return `<a href="${src}" rel="nofollow ugc noopener">${src}</a>`;62+ }5563 const words = String(token.attrGet("title") ?? "")5664 .split(/\s+/)5765 .filter(Boolean);src/pages/repo.ts+14 −8
@@ -50,7 +50,10 @@5050 if (at !== undefined && !atSave) return notFound(c, ctx);5151 const pageNumber = Math.max(1, Number.parseInt(c.req.query("page") ?? "1", 10) || 1);5252 const name = repo.settings.name;53- const intro = repoIntro(repo);53+ // §21.4: the README, inflated once for both the intro and the details.54+ const readme =55+ !repo.settings.description || !repo.settings.details ? readmeAtHead(repo.mirror) : null;56+ const intro = repoIntro(repo, readme);5457 cacheFor(c, false);5558 return c.html(5659 page(ctx, {@@ -59,7 +62,7 @@5962 path: `/${name}`,6063 body: html`${header(ctx, repo, intro?.html ?? null)}6164 ${headId(repo.mirror) && sections(repo, pageNumber, atSave?.id ?? null)}62-${details(repoDetails(repo))}`,65+${details(repoDetails(repo, readme))}`,6366 }),6467 );6568 });@@ -103,21 +106,24 @@103106 * The repo's description, as markup and as plain text: the operator's own, or else the README's104107 * first paragraph (§21.4).105108 */106-export function repoIntro(repo: PublicRepo): { html: Html; text: string } | null {109+export function repoIntro(110+ repo: PublicRepo,111+ readme?: string | null,112+): { html: Html; text: string } | null {107113 const { name, description } = repo.settings;108114 if (description)109115 return renderParagraph(description, { repo: name, dir: "", at: null, own: true });110- const readme = readmeAtHead(repo.mirror);111- const paragraph = readme === null ? null : describeFile("README.md", readme);116+ const text = readme === undefined ? readmeAtHead(repo.mirror) : readme;117+ const paragraph = text === null ? null : describeFile("README.md", text);112118 return paragraph === null ? null : renderParagraph(paragraph, { repo: name, dir: "", at: null });113119 }114120 115121 /** The details section: the operator's own Markdown, or else the rendered README. */116-export function repoDetails(repo: PublicRepo): Html | null {122+export function repoDetails(repo: PublicRepo, readme?: string | null): Html | null {117123 const { name, details } = repo.settings;118124 if (details) return renderMarkdown(details, { repo: name, dir: "", at: null, own: true });119- const readme = readmeAtHead(repo.mirror);120- return readme === null ? null : renderMarkdown(readme, { repo: name, dir: "", at: null });125+ const text = readme === undefined ? readmeAtHead(repo.mirror) : readme;126+ return text === null ? null : renderMarkdown(text, { repo: name, dir: "", at: null });121127 }122128 123129 export function readmeAtHead(mirror: PublicRepo["mirror"]): string | null {src/releases/releases.ts+42 −0
@@ -1,4 +1,5 @@11 import type { Database } from "bun:sqlite";2+import type { Context } from "hono";23 import type { Bucket } from "../bucket/reader.ts";34 import {45 checkRelease,@@ -8,6 +9,7 @@89 } from "../bucket/repo.ts";910 import { releaseRecords } from "../mirror/queries.ts";1011 import { forgetRelease, replaceRelease } from "../mirror/store.ts";12+import { clientIp } from "../server/client.ts";1113 1214 /** A release as the public sees it: its notes are the operator's override when one is set (§24). */1315 export type Release = {@@ -73,17 +75,57 @@7375 7476 const DAYS_KEPT = 400;7577 const DAY_MS = 24 * 60 * 60 * 1000;78+const HOUR_MS = 60 * 60 * 1000;7679 7780 /** A UTC day as `download_days` keys it. */7881 export const utcDay = (ms: number): string => new Date(ms).toISOString().slice(0, 10);7982 83+/**84+ * User agents that fetch a release link to describe it, never to install it (2026-11-16): the link85+ * previews in Slack, Discord, Telegram, WhatsApp, iMessage/Facebook and Twitter, and the search86+ * crawlers. A bare `curl` is not here: `install.sh` downloads with it, and that is a person.87+ */88+const PREVIEW_AGENT =89+ /bot|crawler|spider|scraper|slack|discord|telegram|whatsapp|facebookexternalhit|imessage|preview/i;90+91+// When each client last counted for one file, by `<client>|<repo>|<version>|<platform>`. In memory92+// on purpose: a restart at worst counts an hour's reloads again, and no backup carries it.93+const lastCounted = new Map<string, number>();94+95+/** Whether this client's ask for a file counts now: one per client per file per hour. */96+function firstAsk(key: string, now: number): boolean {97+ const at = lastCounted.get(key);98+ // A timestamp ahead of now means the clock stepped back, and it blocks nothing: a fake clock99+ // in a test must not hold a count off for as long as it stays behind the entry.100+ if (at !== undefined && at <= now && at > now - HOUR_MS) return false;101+ lastCounted.set(key, now);102+ // Bounded: past a few thousand clients an hour, the stale entries of other files are swept.103+ if (lastCounted.size > 4096) {104+ for (const [other, when] of lastCounted) {105+ if (when <= now - HOUR_MS) lastCounted.delete(other);106+ }107+ }108+ return true;109+}110+111+/**112+ * Counts one download (§22.2), unless the request isn't a person asking for the file: a HEAD113+ * fetches nothing, a preview fetch only describes the link (2026-11-16), and the same client114+ * asking again within the hour is a reload. What is served never changes, only the count.115+ */80116 export function countDownload(117+ c: Context,81118 kepr: Database,82119 repo: string,83120 version: string,84121 platform: string,85122 ): void {86123 const now = Date.now();124+ if (c.req.method === "HEAD" || PREVIEW_AGENT.test(c.req.header("User-Agent") ?? "")) return;125+ const client = clientIp(c);126+ // An address no runtime gave (a bare test request) can't tell clients apart, so it counts127+ // every time rather than collapsing every client into one.128+ if (client && !firstAsk(`${client}|${repo}|${version}|${platform}`, now)) return;87129 kepr.transaction(() => {88130 kepr89131 .query(src/releases/routes.ts+1 −1
@@ -30,7 +30,7 @@3030 };3131 // Counted before the redirect (§22.2); Kepr never streams a release file itself.3232 const download = (c: Context, repo: string, version: string, file: ReleaseFile) => {33- countDownload(ctx.kepr, repo, version, file.platform);33+ countDownload(c, ctx.kepr, repo, version, file.platform);3434 const key = `${repo}/releases/${version}/${file.platform}/${file.name}`;3535 c.header("Cache-Control", "no-store");3636 return c.redirect(bucket.downloadUrl(key, file.name, releaseContentType(file.name)), 302);src/server/backup.ts+24 −25
@@ -1,16 +1,7 @@11 import { Database } from "bun:sqlite";2-import {3- cpSync,4- existsSync,5- mkdirSync,6- readdirSync,7- readFileSync,8- renameSync,9- rmSync,10- statSync,11-} from "node:fs";2+import { cpSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync } from "node:fs";123 import { join, relative } from "node:path";13-import { buildTarball } from "../tarball/tar.ts";4+import { streamTarball } from "../tarball/tar.ts";145 import type { BackupBucket, Config } from "./config.ts";156 import { notify, setting } from "./db.ts";167 @@ -69,13 +60,23 @@6960 return newest && newest > stamp(now - DAY_MS) ? null : makeBackup(kepr, dataDir, now);7061 }7162 63+/** Makes the backup a request asks for: one now, or the one that is due. */64+export function backupWhen(kepr: Database, dataDir: string, when: "due" | "now"): string | null {65+ return when === "due" ? backupIfDue(kepr, dataDir) : makeBackup(kepr, dataDir);66+}67+7268 /**7369 * Daily backups: checked at startup and every hour, so a restart never skips a day, and an upload74- * to the backup bucket that failed is retried. `config` is the live one the console edits.70+ * to the backup bucket that failed is retried. `config` is the live one the console edits, and71+ * `make` builds the backup, on the sync's thread when the app has one.7572 */76-export function startBackupLoop(kepr: Database, config: Config): void {77- const tick = () => {78- attemptBackup(kepr, () => backupIfDue(kepr, config.dataDir));73+export function startBackupLoop(74+ kepr: Database,75+ config: Config,76+ make: () => unknown = () => backupWhen(kepr, config.dataDir, "due"),77+): void {78+ const tick = async () => {79+ await attemptBackup(kepr, make);7980 attemptUpload(kepr, config.dataDir, config.backup).catch((error) =>8081 console.error(`kepr: backup upload failed: ${error}`),8182 );@@ -88,9 +89,9 @@8889 * One backup attempt. A failure is kept for the console until a backup succeeds (§24), and only a8990 * backup that starts failing is told, not every hourly retry. Returns the failure, or null.9091 */91-export function attemptBackup(kepr: Database, make: () => unknown): string | null {92+export async function attemptBackup(kepr: Database, make: () => unknown): Promise<string | null> {9293 try {93- make();94+ await make();9495 kepr.query("DELETE FROM settings WHERE key = 'backup_error'").run();9596 return null;9697 } catch (error) {@@ -168,7 +169,8 @@168169 const tarball = backupTarball(dataDir, newest);169170 if (!tarball) return null;170171 const client = backupClient(bucket);171- await client.write(offsiteKey(newest), tarball.bytes, { type: "application/gzip" });172+ const body = new Response(tarball.stream);173+ await client.write(offsiteKey(newest), body, { type: "application/gzip" });172174 for (const old of (await offsiteBackups(bucket)).slice(0, -KEEP)) {173175 await client.delete(offsiteKey(old.name));174176 }@@ -199,20 +201,17 @@199201 200202 /**201203 * A kept backup as a `.tar.gz` for the console's downloads (§24), the newest when no name is202- * given; null when there is no such backup.204+ * given; null when there is no such backup. The archive is streamed, never held whole.203205 */204206 export function backupTarball(205207 dataDir: string,206208 wanted?: string,207-): { name: string; bytes: Uint8Array<ArrayBuffer> } | null {209+): { name: string; stream: ReadableStream<Uint8Array> } | null {208210 const kept = backups(dataDir);209211 // Only a name from the list, so a request can never reach outside data/backups/.210212 const name = wanted === undefined ? kept.at(-1) : kept.find((known) => known === wanted);211213 if (!name) return null;212- const files = backupFiles(dataDir, name).map((file) => ({213- path: file.path,214- bytes: readFileSync(file.full),215- }));214+ const files = backupFiles(dataDir, name);216215 // Owner-only once unpacked: kepr.db holds reporters' contact emails.217- return { name, bytes: buildTarball(`kepr-backup-${name}`, files, 0o600) };216+ return { name, stream: streamTarball(`kepr-backup-${name}`, files, 0o600) };218217 }src/server/client.ts+8 −3
@@ -1,17 +1,22 @@1+import { isIP } from "node:net";12 import type { Context } from "hono";23 34 const LOOPBACK = /^(127\.|::1$|::ffff:127\.)/;45 56 /**67 * The client's address, for rate limits. The socket peer, unless the peer is loopback: then it is7- * a reverse proxy on the same host (HAProxy in production), and the address is the8- * rightmost `X-Forwarded-For` entry, the one that proxy appended. Anything to its left came from9- * the client and could be forged, so it is never trusted.8+ * a reverse proxy on the same host (HAProxy, or Cloudflare's edge), and the address is9+ * `CF-Connecting-IP`, which Cloudflare sets to the visitor, or else the rightmost10+ * `X-Forwarded-For` entry, the one that proxy appended. Anything to its left came from the client11+ * and could be forged, so it is never trusted.1012 */1113 export function clientIp(c: Context): string {1214 // Bun passes its server as the env; a test passes a stand-in with the same method.1315 const server = c.env as { requestIP?: (request: Request) => { address: string } | null };1416 const peer = server?.requestIP?.(c.req.raw)?.address ?? "";1517 if (!LOOPBACK.test(peer)) return peer;18+ // Behind Cloudflare, XFF ends at the edge, so every visitor would share one bucket.19+ const cf = c.req.header("cf-connecting-ip")?.trim() ?? "";20+ if (isIP(cf)) return cf;1621 return c.req.header("x-forwarded-for")?.split(",").at(-1)?.trim() || peer;1722 }src/server/db.ts+1 −0
@@ -240,6 +240,7 @@240240 const db = new Database(join(dataDir, "kepr.db"), { strict: true });241241 db.run("PRAGMA journal_mode = WAL");242242 db.run("PRAGMA busy_timeout = 5000");243+ db.run("PRAGMA foreign_keys = ON");243244 db.run(SCHEMA);244245 // Every name below comes from the two lists above, never from input.245246 const has = (table: string, column: string) =>src/server/totp.ts+2 −1
@@ -59,7 +59,8 @@5959 const counter = Buffer.alloc(8);6060 counter.writeBigUInt64BE(BigInt(step));6161 const mac = createHmac("sha1", key).update(counter).digest();62- const offset = mac[mac.length - 1]! & 0x0f;62+ // readUInt8 bounds-checks for us: a digest always has 20 bytes, offsets 0-15 of it always read.63+ const offset = mac.readUInt8(mac.length - 1) & 0x0f;6364 const value = mac.readUInt32BE(offset) & 0x7fffffff;6465 return String(value % 10 ** DIGITS).padStart(DIGITS, "0");6566 }src/tarball/archive.ts+4 −2
@@ -33,8 +33,10 @@3333 }3434 const bytes = await cachedTarball(bucket, repo.mirror, name, save.id);3535 if (!bytes) return notFound(c, ctx);36- // §22.2: a Nix fetch is an install. Only the tarball itself counts, not the redirects to it.37- if (c.req.header("User-Agent")?.includes("nix/")) countInstall(ctx.kepr, name);36+ // §22.2: a Nix fetch is an install. Only the tarball itself counts, not the redirects to37+ // it, and a HEAD fetches nothing.38+ const agent = c.req.header("User-Agent") ?? "";39+ if (c.req.method !== "HEAD" && agent.includes("nix/")) countInstall(ctx.kepr, name);3840 c.header("Content-Type", "application/gzip");3941 c.header("Content-Disposition", `attachment; filename="${name}-${save.id.slice(0, 8)}.tar.gz"`);4042 c.header("Cache-Control", TARBALL_CACHE);src/tarball/tar.ts+39 −1
@@ -56,9 +56,47 @@5656 return gzip;5757 }5858 59+/**60+ * `buildTarball`'s archive of files on disk, gzipped as it is made: a backup holds kepr.db and its61+ * attachments, which grow past what is worth holding in memory twice.62+ */63+export function streamTarball(64+ root: string,65+ files: { path: string; full: string }[],66+ mode: number,67+): ReadableStream<Uint8Array> {68+ const entries = files69+ .filter((file) => file.path !== "" && !isStripped(file.path))70+ .map((file) => ({ ...file, name: encoder.encode(`${root}/${file.path}`) }))71+ .sort((a, b) => Buffer.compare(a.name, b.name));72+ const gzip = new CompressionStream("gzip");73+ void (async () => {74+ const writer = gzip.writable.getWriter();75+ try {76+ await writer.write(header(encoder.encode(root), 0, true));77+ for (const entry of entries) {78+ const file = Bun.file(entry.full);79+ await writer.write(header(entry.name, file.size, false, mode));80+ for await (const chunk of file.stream()) await writer.write(chunk);81+ await writer.write(new Uint8Array((BLOCK - (file.size % BLOCK)) % BLOCK));82+ }83+ await writer.write(new Uint8Array(2 * BLOCK));84+ await writer.close();85+ } catch (error) {86+ await writer.abort(error);87+ }88+ })();89+ return gzip.readable;90+}91+5992 // A POSIX ustar header, as Kepr 2's `tarWriteHeader`: names over 99 bytes (98 for a directory, which6093 // needs its trailing slash) split at a '/' into the 155-byte prefix field, never truncated.61-function header(name: Uint8Array, size: number, isDir: boolean, mode = 0o644): Uint8Array {94+function header(95+ name: Uint8Array,96+ size: number,97+ isDir: boolean,98+ mode = 0o644,99+): Uint8Array<ArrayBuffer> {62100 const h = new Uint8Array(BLOCK);63101 const maxName = isDir ? 98 : 99;64102 let base = name;tests/client.test.ts+39 −0
@@ -0,0 +1,39 @@1+import { expect, test } from "bun:test";2+import { Hono } from "hono";3+import { clientIp } from "../src/server/client.ts";4+5+const app = new Hono();6+app.get("/", (c) => c.text(clientIp(c)));7+8+const ip = async (peer: string, headers: Record<string, string>) =>9+ (await app.request("/", { headers }, { requestIP: () => ({ address: peer }) })).text();10+11+test("Cloudflare's CF-Connecting-IP wins over the edge address in X-Forwarded-For", async () => {12+ expect(13+ await ip("127.0.0.1", {14+ "cf-connecting-ip": "198.51.100.20",15+ "x-forwarded-for": "198.51.100.20, 172.68.1.1",16+ }),17+ ).toBe("198.51.100.20");18+ expect(await ip("::1", { "cf-connecting-ip": "2001:db8::7" })).toBe("2001:db8::7");19+});20+21+test("an invalid CF-Connecting-IP falls back to the rightmost X-Forwarded-For entry", async () => {22+ for (const cf of ["not-an-address", "198.51.100.300", "203.0.113.9:1234"]) {23+ expect(24+ await ip("127.0.0.1", {25+ "cf-connecting-ip": cf,26+ "x-forwarded-for": "10.9.9.9, 198.51.100.21",27+ }),28+ ).toBe("198.51.100.21");29+ }30+});31+32+test("a non-loopback peer ignores both headers", async () => {33+ expect(34+ await ip("203.0.113.9", {35+ "cf-connecting-ip": "198.51.100.20",36+ "x-forwarded-for": "198.51.100.20",37+ }),38+ ).toBe("203.0.113.9");39+});tests/fixtures/kepr2/schema.sql+0 −715
@@ -1,715 +0,0 @@1--- Kepr Postgres schema — version 1.2---3--- A faithful translation of the cumulative SQLite schema (migrations 1..39,4--- as materialised by db.applyAll) into idiomatic Postgres. It is NOT derived5--- from prose: it was produced from `.schema` of a database with all 396--- migrations applied, so every column, constraint, CHECK, and index matches7--- what the live SQLite database actually holds.8---9--- Translation rules (chosen for an exact, value-preserving migration):10--- * SQLite INTEGER -> BIGINT (SQLite ints are 64-bit; size_bytes11--- and byte counts exceed int32)12--- * SQLite REAL -> DOUBLE PRECISION13--- * SQLite TEXT -> TEXT14--- * Integer 0/1 booleans are KEPT as BIGINT 0/1 — not converted to BOOLEAN —15--- so the migration is a verbatim value copy and db.zig reads them exactly16--- as it does today (i64, != 0 == true).17--- * INTEGER PRIMARY KEY AUTOINCREMENT -> BIGINT GENERATED BY DEFAULT AS18--- IDENTITY (BY DEFAULT, not ALWAYS, so the migration tool can insert the19--- existing ids; the sequence is advanced past MAX(id) after bulk load).20--- * All timestamps remain Unix epoch seconds (BIGINT), unconverted.21---22--- Foreign keys are declared as in SQLite. SQLite did not enforce them at23--- runtime, so the one-time migration tool loads with24--- `SET session_replication_role = replica` to bypass FK/trigger checks, then25--- the constraints guard all subsequently-written data.26-27-BEGIN;28-29-CREATE TABLE schema_version (30- version INTEGER NOT NULL31-);32-INSERT INTO schema_version (version) VALUES (1);33-34--- ── Repositories and saves ───────────────────────────────────────────35-36-CREATE TABLE repos (37- name TEXT PRIMARY KEY,38- created_at BIGINT NOT NULL,39- description TEXT,40- languages TEXT DEFAULT '',41- details TEXT,42- categories TEXT DEFAULT '',43- count_extensions TEXT DEFAULT '',44- contributor_handle TEXT,45- issues_enabled BIGINT NOT NULL DEFAULT 1,46- languages_cloud TEXT,47- project_id TEXT,48- trusted BIGINT NOT NULL DEFAULT 0,49- trust_computed_at BIGINT,50- private BIGINT NOT NULL DEFAULT 0,51- builds_enabled BIGINT NOT NULL DEFAULT 1,52- display_languages TEXT53-);54-55-CREATE TABLE saves (56- id TEXT NOT NULL,57- repo TEXT NOT NULL REFERENCES repos(name) ON UPDATE CASCADE,58- lane TEXT NOT NULL CHECK (lane IN ('main','dev')),59- message TEXT NOT NULL,60- timestamp BIGINT NOT NULL,61- size_bytes BIGINT NOT NULL,62- parent_id TEXT,63- is_checkpoint BIGINT NOT NULL DEFAULT 0,64- checksum TEXT NOT NULL,65- manifest_path TEXT NOT NULL,66- file_count BIGINT NOT NULL DEFAULT 0,67- line_count BIGINT NOT NULL DEFAULT 0,68- session TEXT,69- agent TEXT,70- PRIMARY KEY (id, repo)71-);72-CREATE INDEX saves_repo_lane_ts ON saves(repo, lane, timestamp);73-74-CREATE TABLE object_refs (75- hex_hash TEXT NOT NULL,76- save_id TEXT NOT NULL,77- repo TEXT NOT NULL,78- PRIMARY KEY (hex_hash, save_id, repo)79-);80-CREATE INDEX object_refs_hash ON object_refs(hex_hash);81-82--- Reserved advisory-lock id: Postgres advisory locks (pg_advisory_xact_lock /83--- pg_advisory_xact_lock_shared) are a single flat bigint namespace per84--- cluster, not scoped to any table, but the id kepr reserves here exists to85--- protect this table specifically. storage GC's sweep (storage_admin.gc)86--- holds it exclusive around deciding which objects/ files are unreferenced;87--- every offer-complete transaction that promotes rows into object_refs88--- (src/web/api.zig: handleComplete, acceptPending) takes it89--- shared first, so a commit that references an object already on disk can90--- never race a concurrent sweep into deleting that object (review F12,91--- decision D3). Shared holders never block each other. See92--- db_mod.STORAGE_GC_ADVISORY_LOCK_ID in src/db.zig for the actual id and the93--- lockGcExclusive/lockGcShared helpers — if kepr ever reserves another94--- advisory-lock id, pick a value nowhere near this one and document it here95--- too.96-97--- Content-addressed cache of a countable file's line count, keyed by its98--- Blake3 hash. A hash's line count never changes, so once computed it never99--- needs decompressing again on a later save that re-references the same100--- unchanged file.101-CREATE TABLE object_line_counts (102- hex_hash TEXT PRIMARY KEY,103- lines BIGINT NOT NULL104-);105-106--- Operator-purged paths: the server-side equivalent of .kohignore (which kepr107--- strips from manifests, so it cannot be edited server-side). A path here was108--- stripped from every save's manifest by an operator; future offers that109--- re-introduce it are filtered on ingest. Matches a file exactly or as a dir.110-CREATE TABLE repo_purged_paths (111- repo_id TEXT NOT NULL REFERENCES repos(name) ON UPDATE CASCADE,112- path TEXT NOT NULL,113- purged_at BIGINT NOT NULL,114- PRIMARY KEY (repo_id, path)115-);116-117-CREATE TABLE offer_tokens (118- offer_id TEXT PRIMARY KEY,119- repo TEXT NOT NULL,120- manifest_id TEXT NOT NULL,121- missing TEXT NOT NULL,122- manifest TEXT NOT NULL,123- key_type TEXT NOT NULL CHECK (key_type IN ('operator','contributor')),124- expires_at BIGINT NOT NULL,125- -- Account id that negotiated this token; complete must be performed by the126- -- same account (§8.9). NULL only for tokens predating protocol 2.0.127- negotiated_account TEXT128-);129-130-CREATE TABLE pending_offers (131- offer_id TEXT PRIMARY KEY,132- repo TEXT NOT NULL,133- manifest_id TEXT NOT NULL,134- manifest TEXT NOT NULL,135- contributor TEXT,136- submitted_at BIGINT NOT NULL,137- status TEXT NOT NULL DEFAULT 'pending'138- CHECK (status IN ('draft','pending','accepted','declined')),139- reviewed_at BIGINT,140- review_note TEXT,141- agent_verdict TEXT,142- agent_status TEXT DEFAULT 'pending'143- CHECK (agent_status IN ('pending','running','complete','failed','unavailable')),144- findings_json TEXT,145- scan_status TEXT CHECK (scan_status IN ('ok','failed')),146- -- Contributor's human-readable note to the reviewer (separate from save147- -- messages); 'draft' status holds an offer out of the review queue until148- -- the contributor promotes it.149- description TEXT150-);151-152-CREATE TABLE pending_offer_identity_quarantine (153- offer_id TEXT PRIMARY KEY REFERENCES pending_offers(offer_id) ON DELETE CASCADE,154- legacy_fingerprint TEXT NOT NULL,155- reason TEXT NOT NULL,156- recorded_at BIGINT NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW())::BIGINT157-);158-CREATE INDEX pending_offer_identity_quarantine_fp159- ON pending_offer_identity_quarantine(legacy_fingerprint);160-161-CREATE TABLE steals (162- id TEXT PRIMARY KEY,163- repo TEXT NOT NULL REFERENCES repos(name) ON UPDATE CASCADE,164- timestamp BIGINT NOT NULL165-);166-CREATE INDEX steals_repo_ts ON steals(repo, timestamp);167-168-CREATE TABLE storage_snapshots (169- date TEXT PRIMARY KEY,170- total_bytes BIGINT NOT NULL,171- object_count BIGINT NOT NULL,172- repo_count BIGINT NOT NULL,173- save_count BIGINT NOT NULL,174- languages TEXT,175- first_received BIGINT176-);177-178-CREATE TABLE instance_images (179- filename TEXT PRIMARY KEY,180- created_at BIGINT NOT NULL,181- size_bytes BIGINT NOT NULL,182- checksum TEXT NOT NULL,183- repo_count BIGINT NOT NULL,184- save_count BIGINT NOT NULL,185- kepr_version TEXT NOT NULL186-);187-188-CREATE TABLE diff_cache (189- repo TEXT NOT NULL,190- save_id TEXT NOT NULL,191- diff_json TEXT NOT NULL,192- computed_at BIGINT NOT NULL,193- PRIMARY KEY (repo, save_id)194-);195-196-CREATE TABLE ops_credentials (197- key TEXT PRIMARY KEY,198- value TEXT NOT NULL199-);200-201--- ── Contributor handles ──────────────────────────────────────────────202-203-CREATE TABLE handles (204- id TEXT PRIMARY KEY,205- handle TEXT UNIQUE NOT NULL,206- created_at BIGINT NOT NULL,207- recovery_hash TEXT NOT NULL208-);209-210--- ── Assets, dependencies, builds, releases ───────────────────────────211-212-CREATE TABLE repo_assets (213- id TEXT PRIMARY KEY,214- repo_id TEXT NOT NULL REFERENCES repos(name) ON UPDATE CASCADE,215- filename TEXT NOT NULL,216- mime_type TEXT NOT NULL,217- size_bytes BIGINT NOT NULL,218- uploaded_at BIGINT NOT NULL219-);220-221-CREATE TABLE repo_dependencies (222- from_repo TEXT NOT NULL REFERENCES repos(name) ON UPDATE CASCADE,223- to_repo TEXT NOT NULL REFERENCES repos(name) ON UPDATE CASCADE,224- first_stolen_at BIGINT NOT NULL,225- last_stolen_at BIGINT NOT NULL,226- PRIMARY KEY (from_repo, to_repo)227-);228-229-CREATE TABLE build_runs (230- id TEXT PRIMARY KEY,231- repo_id TEXT NOT NULL REFERENCES repos(name) ON UPDATE CASCADE,232- save_id TEXT NOT NULL,233- version TEXT NOT NULL,234- trigger TEXT NOT NULL,235- status TEXT NOT NULL,236- started_at BIGINT NOT NULL,237- finished_at BIGINT,238- log TEXT,239- release_notes TEXT,240- platform_results TEXT NOT NULL DEFAULT '{}',241- duration_ms BIGINT,242- lane TEXT NOT NULL DEFAULT 'main'243-);244-245-CREATE TABLE release_artifacts (246- id TEXT PRIMARY KEY,247- build_run TEXT NOT NULL REFERENCES build_runs(id),248- repo_id TEXT NOT NULL REFERENCES repos(name) ON UPDATE CASCADE,249- version TEXT NOT NULL,250- platform TEXT NOT NULL,251- filename TEXT NOT NULL,252- size_bytes BIGINT NOT NULL,253- sha256 TEXT NOT NULL,254- blake3 TEXT NOT NULL,255- signature TEXT NOT NULL DEFAULT '',256- built_at BIGINT NOT NULL257-);258-CREATE UNIQUE INDEX release_artifacts_repo_version_platform259- ON release_artifacts (repo_id, version, platform);260-261--- ── Issues ───────────────────────────────────────────────────────────262-263-CREATE TABLE issues (264- id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,265- repo TEXT NOT NULL REFERENCES repos(name) ON UPDATE CASCADE,266- title TEXT NOT NULL,267- description TEXT NOT NULL,268- contact TEXT,269- filed_at BIGINT NOT NULL,270- filed_save TEXT NOT NULL,271- filed_ver TEXT,272- status TEXT NOT NULL DEFAULT 'open',273- closed_at BIGINT,274- closed_save TEXT,275- ip_hash TEXT,276- number BIGINT NOT NULL DEFAULT 0,277- type TEXT NOT NULL DEFAULT 'bug',278- severity TEXT,279- face_id TEXT,280- resolution_face TEXT,281- account_id TEXT,282- contact_email TEXT,283- updated_at BIGINT NOT NULL DEFAULT 0,284- reporter_name TEXT285-);286-CREATE UNIQUE INDEX issues_repo_number ON issues(repo, number);287-CREATE INDEX issues_repo_status_created288- ON issues(repo, status, filed_at DESC);289-CREATE INDEX issues_repo_type_status_created290- ON issues(repo, type, status, filed_at DESC);291-292-CREATE TABLE issue_notes (293- id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,294- issue_id BIGINT NOT NULL REFERENCES issues(id),295- body TEXT NOT NULL,296- posted_at BIGINT NOT NULL,297- is_op BIGINT NOT NULL DEFAULT 0298-);299-300-CREATE TABLE issue_entries (301- id TEXT PRIMARY KEY,302- issue_id BIGINT NOT NULL REFERENCES issues(id) ON DELETE CASCADE,303- account_id TEXT,304- entry_type TEXT NOT NULL CHECK (entry_type IN ('reply','status_change','face_linked')),305- body TEXT,306- created_at BIGINT NOT NULL307-);308-CREATE INDEX issue_entries_issue ON issue_entries(issue_id, created_at);309-310-CREATE TABLE issue_attachments (311- id TEXT PRIMARY KEY,312- issue_id BIGINT REFERENCES issues(id) ON DELETE CASCADE,313- repo_id TEXT NOT NULL REFERENCES repos(name) ON UPDATE CASCADE,314- filename TEXT NOT NULL,315- mime_type TEXT NOT NULL,316- size_bytes BIGINT NOT NULL,317- path TEXT NOT NULL,318- tmp_token TEXT,319- tmp_expires BIGINT,320- created_at BIGINT NOT NULL321-);322-CREATE INDEX issue_attachments_issue ON issue_attachments(issue_id, created_at);323-CREATE INDEX issue_attachments_repo ON issue_attachments(repo_id, created_at);324-325--- ── Caches and challenges ────────────────────────────────────────────326-327-CREATE TABLE graph_cache (328- repo TEXT NOT NULL,329- head_save_id TEXT NOT NULL,330- json TEXT NOT NULL,331- computed_at BIGINT NOT NULL,332- PRIMARY KEY (repo, head_save_id)333-);334-335-CREATE TABLE archive_cache (336- repo_id TEXT NOT NULL REFERENCES repos(name) ON UPDATE CASCADE,337- save_id TEXT NOT NULL,338- path TEXT NOT NULL,339- size_bytes BIGINT NOT NULL,340- created_at BIGINT NOT NULL,341- -- Vestigial: live archive nar hashes are kept in archive_hashes now. The342- -- column still exists in the SQLite source schema, so it is mirrored here so343- -- the one-time SQLite→Postgres migration (which copies every source column344- -- via PRAGMA table_info) does not fail on a missing target column.345- nar_hash TEXT,346- PRIMARY KEY (repo_id, save_id)347-);348-349-CREATE TABLE archive_hashes (350- repo_id TEXT NOT NULL REFERENCES repos(name) ON UPDATE CASCADE,351- save_id TEXT NOT NULL,352- blake3 TEXT NOT NULL,353- sha256 TEXT NOT NULL,354- nar_hash TEXT,355- computed_at BIGINT NOT NULL,356- PRIMARY KEY (repo_id, save_id)357-);358-359-CREATE TABLE pow_challenges (360- id TEXT PRIMARY KEY,361- nonce TEXT NOT NULL,362- difficulty BIGINT NOT NULL DEFAULT 4,363- created_at BIGINT NOT NULL,364- expires_at BIGINT NOT NULL,365- used BIGINT NOT NULL DEFAULT 0366-);367-368--- ── Accounts, sessions, auth ─────────────────────────────────────────369-370-CREATE TABLE accounts (371- id TEXT PRIMARY KEY,372- username TEXT NOT NULL UNIQUE,373- bio TEXT,374- location TEXT,375- website TEXT,376- email TEXT,377- recovery_hash TEXT NOT NULL,378- created_at BIGINT NOT NULL,379- tier TEXT NOT NULL DEFAULT 'contributor'380- CHECK (tier IN ('operator', 'team', 'contributor')),381- -- Operator web-login credentials (bcrypt password + base32 TOTP secret).382- -- NULL until the operator enrols at /login; only the operator-tier row uses them.383- password_hash TEXT,384- totp_secret TEXT,385- notif_offer_accepted BIGINT NOT NULL DEFAULT 1,386- notif_offer_rejected BIGINT NOT NULL DEFAULT 1,387- notif_issue_response BIGINT NOT NULL DEFAULT 1,388- notif_issue_resolved BIGINT NOT NULL DEFAULT 1,389- notif_issue_status BIGINT NOT NULL DEFAULT 1390-);391-CREATE INDEX accounts_username ON accounts(username);392--- Partial unique: one account per non-null email, enforced at the database393--- so the join handler's check-then-act can't lose a race under concurrent394--- registrations (review F4). Existing databases get this via db.zig's395--- ensureUniqueEmailIndex idempotent migration instead, which must detect396--- pre-existing duplicates first (D4).397-CREATE UNIQUE INDEX accounts_email_unique ON accounts(email) WHERE email IS NOT NULL;398-399--- ── Internal tickets ─────────────────────────────────────────────────400--- Operator/team-only ticket tracker. created_by/assigned_to reference401--- accounts(id) (TEXT, not the int ids the original brief assumed).402--- resolving_save_id is a plain TEXT column with no FK: saves has a403--- composite PRIMARY KEY (id, repo), so a single-column FK to saves(id)404--- is not expressible; integrity is enforced in the application layer.405-406-CREATE TABLE tickets (407- id BIGINT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,408- title TEXT NOT NULL,409- body TEXT NOT NULL DEFAULT '',410- state TEXT NOT NULL DEFAULT 'open'411- CHECK (state IN ('open', 'in_progress', 'closed')),412- repo TEXT REFERENCES repos(name) ON UPDATE CASCADE ON DELETE SET NULL,413- resolving_save_id TEXT,414- created_by TEXT NOT NULL REFERENCES accounts(id),415- assigned_to TEXT REFERENCES accounts(id) ON DELETE SET NULL,416- created_at BIGINT NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW())::BIGINT,417- updated_at BIGINT NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW())::BIGINT,418- closed_at BIGINT419-);420-CREATE INDEX tickets_state ON tickets(state, created_at DESC);421-CREATE INDEX tickets_repo ON tickets(repo);422-CREATE INDEX tickets_assigned ON tickets(assigned_to);423-CREATE INDEX tickets_created_by ON tickets(created_by);424-425-CREATE TABLE ticket_attachments (426- id TEXT PRIMARY KEY,427- ticket_id BIGINT REFERENCES tickets(id) ON DELETE CASCADE,428- repo_id TEXT REFERENCES repos(name) ON UPDATE CASCADE,429- filename TEXT NOT NULL,430- mime_type TEXT NOT NULL,431- size_bytes BIGINT NOT NULL,432- path TEXT NOT NULL,433- created_at BIGINT NOT NULL434-);435-CREATE INDEX ticket_attachments_ticket ON ticket_attachments(ticket_id, created_at);436-CREATE INDEX ticket_attachments_repo ON ticket_attachments(repo_id, created_at);437-438--- ── Collaboration layer + notifications ──────────────────────────────439--- author/account columns reference accounts(id) (TEXT). Comment ids are440--- BIGINT identity to match the project convention (the brief assumed441--- SQLite-era INTEGER identity). save_comments carries both save_id and442--- repo so a composite FK to saves(id, repo) is expressible; the other443--- save-keyed tables hold only save_id (plain TEXT, no FK — saves has a444--- composite PK) and rely on application-layer integrity. Boolean-ish445--- columns are BIGINT 0/1 to match the existing schema (accounts.notif_*,446--- repos.*), since the pg shim binds/reads integers, not SQL BOOLEAN.447-448-CREATE TABLE save_comments (449- id BIGINT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,450- save_id TEXT NOT NULL,451- repo TEXT NOT NULL REFERENCES repos(name) ON UPDATE CASCADE ON DELETE CASCADE,452- author_account_id TEXT NOT NULL REFERENCES accounts(id),453- body TEXT NOT NULL,454- created_at BIGINT NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW())::BIGINT,455- updated_at BIGINT NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW())::BIGINT,456- edited BIGINT NOT NULL DEFAULT 0,457- FOREIGN KEY (save_id, repo) REFERENCES saves(id, repo) ON DELETE CASCADE458-);459-CREATE INDEX save_comments_save_id ON save_comments(save_id, created_at);460-CREATE INDEX save_comments_repo ON save_comments(repo, created_at DESC);461-CREATE INDEX save_comments_author ON save_comments(author_account_id);462-463-CREATE TABLE save_acknowledgements (464- save_id TEXT NOT NULL,465- account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,466- kind TEXT NOT NULL DEFAULT 'ack'467- CHECK (kind IN ('ack', 'flag')),468- created_at BIGINT NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW())::BIGINT,469- PRIMARY KEY (save_id, account_id)470-);471-CREATE INDEX save_acks_save_id ON save_acknowledgements(save_id);472-473-CREATE TABLE draft_comments (474- id BIGINT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,475- offer_id TEXT NOT NULL REFERENCES pending_offers(offer_id) ON DELETE CASCADE,476- author_account_id TEXT NOT NULL REFERENCES accounts(id),477- body TEXT NOT NULL,478- created_at BIGINT NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW())::BIGINT479-);480-CREATE INDEX draft_comments_offer ON draft_comments(offer_id, created_at);481-482-CREATE TABLE notifications (483- id BIGINT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,484- account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,485- kind TEXT NOT NULL CHECK (kind IN (486- 'save_comment', 'save_comment_reply', 'save_mention', 'save_ack',487- 'save_flag', 'contribution_accepted', 'contribution_declined',488- 'contribution_pending', 'draft_comment', 'issue_filed', 'issue_reply',489- 'issue_response', 'issue_resolved', 'issue_status',490- 'ticket_assigned', 'ticket_state_changed', 'team_promoted',491- 'milestone_saves', 'milestone_downloads', 'milestone_first_steal',492- 'milestone_first_contributor', 'milestone_trusted'493- )),494- payload_json TEXT NOT NULL DEFAULT '{}',495- preview TEXT NOT NULL DEFAULT '',496- href TEXT NOT NULL DEFAULT '/',497- read BIGINT NOT NULL DEFAULT 0,498- created_at BIGINT NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW())::BIGINT,499- read_at BIGINT500-);501-CREATE INDEX notifications_account_unread ON notifications(account_id, read, created_at DESC);502-CREATE INDEX notifications_account_all ON notifications(account_id, created_at DESC);503-CREATE INDEX notifications_created_at ON notifications(created_at DESC);504-505-CREATE TABLE notification_preferences (506- account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,507- kind TEXT NOT NULL,508- in_app BIGINT NOT NULL DEFAULT 1,509- email BIGINT NOT NULL DEFAULT 0,510- PRIMARY KEY (account_id, kind)511-);512-513-CREATE TABLE notification_category_prefs (514- account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,515- category TEXT NOT NULL CHECK (category IN (516- 'contributions', 'discussion', 'issues', 'tickets', 'milestones'517- )),518- in_app BIGINT NOT NULL DEFAULT 1,519- email BIGINT NOT NULL DEFAULT 0,520- PRIMARY KEY (account_id, category)521-);522-523-CREATE TABLE sessions (524- id TEXT PRIMARY KEY,525- account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,526- created_at BIGINT NOT NULL,527- expires_at BIGINT NOT NULL,528- last_used BIGINT NOT NULL,529- user_agent TEXT530-);531-CREATE INDEX sessions_account ON sessions(account_id);532-CREATE INDEX sessions_expiry ON sessions(expires_at);533-534-CREATE TABLE account_recovery_codes (535- id TEXT PRIMARY KEY,536- account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,537- code_hash TEXT NOT NULL,538- created_at BIGINT NOT NULL,539- expires_at BIGINT NOT NULL,540- used BIGINT NOT NULL DEFAULT 0541-);542-CREATE INDEX account_recovery_codes_account ON account_recovery_codes(account_id, expires_at);543-544--- ── Health, safety, trust ────────────────────────────────────────────545-546-CREATE TABLE repo_health (547- repo_id TEXT PRIMARY KEY REFERENCES repos(name) ON UPDATE CASCADE,548- save_id TEXT NOT NULL,549- computed_at BIGINT NOT NULL,550- secrets_status TEXT NOT NULL DEFAULT 'clean',551- secrets_detail TEXT,552- deps_status TEXT NOT NULL DEFAULT 'none',553- deps_detail TEXT,554- builds_status TEXT NOT NULL DEFAULT 'none',555- builds_detail TEXT,556- agents_status TEXT NOT NULL DEFAULT 'none',557- agents_detail TEXT,558- license_status TEXT NOT NULL DEFAULT 'none',559- license_detail TEXT,560- trust_status TEXT NOT NULL DEFAULT 'clean',561- trust_detail TEXT,562- collapsed_html TEXT NOT NULL DEFAULT ''563-);564-565-CREATE TABLE secret_scan_results (566- id TEXT PRIMARY KEY,567- repo_id TEXT NOT NULL REFERENCES repos(name) ON UPDATE CASCADE,568- save_id TEXT NOT NULL,569- file_path TEXT NOT NULL,570- line_number BIGINT,571- pattern TEXT NOT NULL,572- entropy DOUBLE PRECISION,573- severity TEXT NOT NULL,574- status TEXT NOT NULL,575- detected_at BIGINT NOT NULL576-);577-CREATE INDEX secret_scan_results_repo_save578- ON secret_scan_results(repo_id, save_id, detected_at DESC);579-580-CREATE TABLE secret_false_positives (581- repo_id TEXT NOT NULL,582- file_path TEXT NOT NULL,583- marked_at BIGINT NOT NULL,584- PRIMARY KEY (repo_id, file_path)585-);586-587-CREATE TABLE code_finding_false_positives (588- repo_id TEXT NOT NULL,589- code TEXT NOT NULL,590- path TEXT NOT NULL,591- marked_at BIGINT NOT NULL,592- PRIMARY KEY (repo_id, code, path)593-);594-595--- Operator-dismissed safety findings. A suppressed finding is filtered from596--- the public repo page and the admin panel; the dismissed list remains597--- visible and reversible. Keyed by (repo_id, file_path, rule, fingerprint)598--- so a suppression only matches when the same content fires the same rule.599-CREATE TABLE safety_suppressions (600- id TEXT PRIMARY KEY,601- repo_id TEXT NOT NULL REFERENCES repos(name) ON UPDATE CASCADE ON DELETE CASCADE,602- file_path TEXT NOT NULL,603- rule TEXT NOT NULL,604- fingerprint TEXT NOT NULL,605- dismissed_at BIGINT NOT NULL,606- dismissed_by TEXT NOT NULL REFERENCES accounts(id),607- note TEXT608-);609-CREATE INDEX safety_suppressions_repo ON safety_suppressions(repo_id, file_path, rule);610-611-CREATE TABLE dep_advisories (612- id TEXT PRIMARY KEY,613- repo_id TEXT NOT NULL REFERENCES repos(name) ON UPDATE CASCADE,614- save_id TEXT NOT NULL,615- dep_name TEXT NOT NULL,616- dep_version TEXT NOT NULL,617- cve_id TEXT,618- severity TEXT NOT NULL,619- summary TEXT NOT NULL,620- fix_version TEXT,621- detected_at BIGINT NOT NULL622-);623-CREATE INDEX dep_advisories_repo_save624- ON dep_advisories(repo_id, save_id, detected_at DESC);625-626-CREATE TABLE binary_sizes (627- id TEXT PRIMARY KEY,628- repo_id TEXT NOT NULL REFERENCES repos(name) ON UPDATE CASCADE,629- save_id TEXT NOT NULL,630- platform TEXT NOT NULL,631- size_bytes BIGINT NOT NULL,632- built_at BIGINT NOT NULL633-);634-CREATE INDEX binary_sizes_repo_save635- ON binary_sizes(repo_id, save_id, built_at DESC);636-637-CREATE TABLE trust_results (638- repo_id TEXT PRIMARY KEY REFERENCES repos(name) ON UPDATE CASCADE,639- save_id TEXT NOT NULL,640- trusted BIGINT NOT NULL,641- secrets_clean BIGINT NOT NULL,642- no_binary_blobs BIGINT NOT NULL,643- build_scripts_clean BIGINT NOT NULL,644- no_trojan_source BIGINT NOT NULL,645- supply_chain_stable BIGINT NOT NULL,646- licenses_compatible BIGINT NOT NULL,647- has_attribution BIGINT NOT NULL,648- detail_json TEXT NOT NULL DEFAULT '{}',649- computed_at BIGINT NOT NULL650-);651-652--- ── Engagement and notifications ─────────────────────────────────────653-654-CREATE TABLE engagement_events (655- id TEXT PRIMARY KEY,656- event_type TEXT NOT NULL,657- repo_id TEXT,658- save_id TEXT,659- platform TEXT,660- occurred_at BIGINT NOT NULL661-);662-CREATE INDEX eng_repo_type ON engagement_events(repo_id, event_type, occurred_at DESC);663-CREATE INDEX eng_type_time ON engagement_events(event_type, occurred_at DESC);664-665-CREATE TABLE notification_queue (666- id TEXT PRIMARY KEY,667- account_id TEXT,668- type TEXT NOT NULL,669- payload TEXT NOT NULL,670- status TEXT NOT NULL DEFAULT 'pending',671- attempts BIGINT NOT NULL DEFAULT 0,672- next_retry BIGINT,673- created_at BIGINT NOT NULL,674- sent_at BIGINT675-);676-CREATE INDEX notification_queue_pending677- ON notification_queue(status, next_retry);678-679--- ┌─────────────────────────────────────────────────────────────────┐680--- │ JOB QUEUE — Postgres-native, SELECT FOR UPDATE SKIP LOCKED. │681--- │ New in the Postgres architecture; has no SQLite predecessor. │682--- └─────────────────────────────────────────────────────────────────┘683-684-CREATE TABLE jobs (685- id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,686- kind TEXT NOT NULL,687- payload_json TEXT NOT NULL DEFAULT '{}',688- status TEXT NOT NULL DEFAULT 'pending'689- CHECK (status IN ('pending','running','done','failed')),690- -- Only one pending/running job per (kind, dedup_key) — collapses the691- -- thundering herd of a 1000-save offer into one job of each kind per repo.692- dedup_key TEXT,693- priority BIGINT NOT NULL DEFAULT 5,694- attempts BIGINT NOT NULL DEFAULT 0,695- max_attempts BIGINT NOT NULL DEFAULT 3,696- created_at BIGINT NOT NULL,697- started_at BIGINT,698- completed_at BIGINT,699- error_text TEXT,700- run_after BIGINT NOT NULL DEFAULT 0701-);702-703--- Worker poll path: lowest priority then oldest, pending only.704-CREATE INDEX jobs_pending ON jobs(priority, created_at)705- WHERE status = 'pending';706-707--- Deduplication: enforce one live job per (kind, dedup_key).708-CREATE UNIQUE INDEX jobs_dedup ON jobs(kind, dedup_key)709- WHERE status IN ('pending','running') AND dedup_key IS NOT NULL;710-711--- Cleanup scan for pruning finished jobs.712-CREATE INDEX jobs_completed_at ON jobs(completed_at)713- WHERE status IN ('done','failed');714-715-COMMIT;tests/follow.test.ts+18 −0
@@ -264,4 +264,22 @@264264 expect(page).toContain("x".repeat(20_000));265265 expect(page).not.toContain("TAIL-MARK");266266 });267+268+ test("an unanswered confirmation expires and can be asked for again", async () => {269+ const reader = new Browser(inst.app, "198.51.100.90");270+ const ask = () =>271+ send(reader, "/app/issues/1/follow", { email: "[email protected]" }, "/app/issues/1");272+ await ask();273+ expect(queued("[email protected]")).toHaveLength(1);274+ // Inside the day, a duplicate request sends nothing.275+ await ask();276+ expect(queued("[email protected]")).toHaveLength(1);277+ tick(24 * 60 * 60 + 60);278+ await ask();279+ expect(queued("[email protected]")).toHaveLength(2);280+ const rows = inst.kepr281+ .query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM issue_followers WHERE email = ?")282+ .get("[email protected]")?.n;283+ expect(rows).toBe(1);284+ });267285 });tests/import.test.ts+0 −367
@@ -1,367 +0,0 @@1-import { afterAll, beforeAll, expect, test } from "bun:test";2-import { mkdir, mkdtemp, readdir, writeFile } from "node:fs/promises";3-import { tmpdir } from "node:os";4-import { join } from "node:path";5-import { blake3 } from "@noble/hashes/blake3.js";6-import { bytesToHex } from "@noble/hashes/utils.js";7-import { SQL } from "bun";8-import { instance } from "./browser.ts";9-import { makeRepos } from "./fixture.ts";10-11-// A throwaway Postgres holding Kepr 2's schema and a few synthetic rows, stopped after the tests.12-const SCRIPT = join(import.meta.dir, "../scripts/import-kepr2.ts");13-const root = await mkdtemp(join(tmpdir(), "kepr-import-"));14-const pgDir = join(root, "pg");15-const kepr2Data = join(root, "kepr2");16-let url = "";17-let bucketDir = "";18-let save = "";19-20-const hex = (bytes: Uint8Array) => bytesToHex(blake3(bytes));21-const sha = (bytes: Uint8Array) => new Bun.CryptoHasher("sha256").update(bytes).digest("hex");22-const bytesOf = (text: string) => new TextEncoder().encode(text);23-const run = (cmd: string[]) => {24- const out = Bun.spawnSync(cmd, { cwd: root, env: { PATH: process.env.PATH, LC_ALL: "C" } });25- if (out.exitCode !== 0) throw new Error(`${cmd.join(" ")}: ${out.stderr.toString()}`);26-};27-28-const artifact = (29- id: string,30- run: string,31- repo: string,32- version: string,33- platform: string,34- name: string,35- bytes: Uint8Array,36- b3 = hex(bytes),37-) =>38- `('${id}', '${run}', '${repo}', '${version}', '${platform}', '${name}', ${bytes.length}, '${sha(bytes)}', '${b3}', 5)`;39-40-async function kepr2File(path: string, text: string) {41- await mkdir(join(kepr2Data, "releases", path, ".."), { recursive: true });42- await writeFile(join(kepr2Data, "releases", path), text);43- return bytesOf(text);44-}45-46-beforeAll(async () => {47- const repos = await makeRepos(["demo"]);48- bucketDir = repos.bucketDir;49- save = repos.saves.demo as string;50- const probe = Bun.serve({ port: 0, fetch: () => new Response() });51- const port = probe.port;52- probe.stop(true);53- run(["initdb", "-D", pgDir, "-U", "kepr", "-A", "trust"]);54- const options = `-p ${port} -k ${pgDir} -c listen_addresses=127.0.0.1`;55- run(["pg_ctl", "-D", pgDir, "-o", options, "-l", join(root, "pg.log"), "-w", "start"]);56- url = `postgres://[email protected]:${port}/postgres`;57- run([58- "psql",59- url,60- "-q",61- "-v",62- "ON_ERROR_STOP=1",63- "-f",64- join(import.meta.dir, "fixtures/kepr2/schema.sql"),65- ]);66-67- const legacy = await kepr2File("demo/1.0.0/linux-x86_64/demo", "demo 1.0.0 linux");68- const byPlatform = await kepr2File("demo/1.1.0/macos-aarch64", "demo 1.1.0 mac");69- const apk = await kepr2File("demo/1.1.0/android-arm64/demo-1.1.0.apk", "demo 1.1.0 apk");70- const failed = await kepr2File("demo/1.2.0/linux-x86_64/demo", "demo 1.2.0 failed");71- const secret = await kepr2File("secret/0.1.0/linux-x86_64/secret", "secret 0.1.0");72- const pg = new SQL(url);73- await pg.unsafe(`74- INSERT INTO repos (name, created_at, description, categories, private, builds_enabled) VALUES75- ('demo', 1, 'A demo.', 'tools, cli', 0, 1), ('secret', 1, NULL, '', 1, 0);76- INSERT INTO accounts (id, username, recovery_hash, created_at, tier) VALUES77- ('acc-r', 'rita', 'x', 1, 'contributor'), ('acc-o', 'olga', 'x', 1, 'operator'), ('acc-t', 'tom', 'x', 1, 'team');78- INSERT INTO issues (id, repo, number, title, description, contact, contact_email, filed_at, filed_save, filed_ver, status, closed_at, closed_save, type, account_id, reporter_name) VALUES79- (1, 'demo', 7, 'Crash on start', 'It <b>crashes</b>.', NULL, '[email protected]', 1000, 'aaaaaaaaaaaa', '1.0.0', 'inprogress', NULL, NULL, 'bug', 'acc-r', NULL),80- (2, 'demo', 9, 'Dark mode', 'Please.', '[email protected]', NULL, 1500, 'aaaaaaaaaaaa', NULL, 'wontfix', 2000, '${save}', 'enhancement', NULL, 'Sam');81- INSERT INTO issue_entries (id, issue_id, account_id, entry_type, body, created_at) VALUES82- ('e1', 1, 'operator', 'reply', 'Looking.', 1100), ('e2', 1, 'acc-r', 'reply', 'Thanks!', 1200),83- ('e3', 1, 'operator', 'status_change', NULL, 1300), ('e4', 1, 'acc-o', 'reply', 'Me too.', 1400);84- INSERT INTO issue_notes (issue_id, body, posted_at, is_op) VALUES (1, 'internal only', 1250, 1);85- INSERT INTO engagement_events (id, event_type, repo_id, occurred_at) VALUES86- ('v1', 'nix_install', 'demo', 1), ('v2', 'nix_install', 'demo', 2), ('v3', 'nix_install', 'demo', 3),87- ('v4', 'archive_download', 'demo', 4), ('v5', 'nix_install', 'secret', 5);88- INSERT INTO build_runs (id, repo_id, save_id, version, trigger, status, started_at, finished_at, release_notes) VALUES89- ('b1', 'demo', '${save}', '1.0.0', 'manual', 'success', 10, 20, NULL),90- ('b2', 'demo', '${save}', '1.1.0', 'manual', 'partial', 30, 40, 'Starts twice as fast and no longer crashes on start.'),91- ('b3', 'demo', '${save}', '1.2.0', 'manual', 'failed', 50, 60, NULL),92- ('b5', 'secret', '${save}', '0.1.0', 'manual', 'success', 90, 100, NULL);93- INSERT INTO release_artifacts (id, build_run, repo_id, version, platform, filename, size_bytes, sha256, blake3, built_at) VALUES94- ${artifact("a1", "b1", "demo", "1.0.0", "linux-x86_64", "demo", legacy)},95- ${artifact("a2", "b2", "demo", "1.1.0", "macos-aarch64", "demo", byPlatform)},96- ${artifact("a3", "b2", "demo", "1.1.0", "android-arm64", "demo-1.1.0.apk", apk)},97- ${artifact("a4", "b3", "demo", "1.2.0", "linux-x86_64", "demo", failed)},98- ${artifact("a6", "b5", "secret", "0.1.0", "linux-x86_64", "secret", secret)};99- `);100- await pg.close();101-});102-103-afterAll(() => run(["pg_ctl", "-D", pgDir, "-m", "fast", "-w", "stop"]));104-105-async function runImport(target: Record<string, string>, keprData: string, ...args: string[]) {106- const env = {107- PATH: process.env.PATH,108- KEPR2_DATABASE_URL: url,109- KEPR2_DATA: kepr2Data,110- KEPR_DATA: keprData,111- ...target,112- };113- // Not spawnSync: the S3 tests' stand-in server runs on this process's event loop.114- const child = Bun.spawn(["bun", SCRIPT, ...args], { cwd: root, env, stderr: "pipe" });115- const [out, err, code] = await Promise.all([116- new Response(child.stdout).text(),117- new Response(child.stderr).text(),118- child.exited,119- ]);120- return { out, err, code };121-}122-123-async function importKepr2(target: Record<string, string>, keprData: string, ...args: string[]) {124- const { out, err, code } = await runImport(target, keprData, ...args);125- if (code !== 0) throw new Error(err);126- return out;127-}128-129-async function files(dir: string): Promise<string[]> {130- return (await readdir(dir, { recursive: true, withFileTypes: true }))131- .filter((entry) => entry.isFile())132- .map((entry) => join(entry.parentPath, entry.name).slice(dir.length + 1))133- .sort();134-}135-136-test("--dry-run prints the import and writes neither the bucket nor kepr.db", async () => {137- const before = await files(bucketDir);138- const keprData = await mkdtemp(join(tmpdir(), "kepr-import-dry-"));139- const out = await importKepr2({ KOH_FOLDER: bucketDir }, keprData, "--dry-run");140- expect(out).toContain("would put demo/releases/1.1.0/release.json");141- expect(out).toContain('issues {"repo":"demo","number":"7"');142- expect(await files(bucketDir)).toEqual(before);143- const inst = await instance(bucketDir, keprData);144- expect(inst.kepr.query("SELECT COUNT(*) AS n FROM issues").get()).toEqual({ n: 0 });145-});146-147-test("the import lands Kepr 2's issues, counts, settings and releases, and a re-run changes nothing", async () => {148- const keprData = await mkdtemp(join(tmpdir(), "kepr-import-data-"));149- const first = await importKepr2({ KOH_FOLDER: bucketDir }, keprData);150- expect(first).not.toContain("1.2.0");151- const landed = await files(bucketDir);152- expect(landed.filter((key) => key.includes("/releases/"))).toEqual([153- "demo/releases/1.0.0/linux-x86_64/demo-linux-x86_64",154- "demo/releases/1.0.0/release.json",155- "demo/releases/1.1.0/android-arm64/demo-1.1.0.apk",156- "demo/releases/1.1.0/macos-aarch64/demo-macos-aarch64",157- "demo/releases/1.1.0/release.json",158- "demo/releases/latest",159- "secret/releases/0.1.0/linux-x86_64/secret-linux-x86_64",160- "secret/releases/0.1.0/release.json",161- "secret/releases/latest",162- ]);163- const again = await importKepr2({ KOH_FOLDER: bucketDir }, keprData);164- expect(again).not.toMatch(/^(put|would put)/m);165- // Only the repo settings are set again (to the same values); nothing else is added.166- expect(167- again.split("\n").filter((line) => line.endsWith(" set") && !line.startsWith("repos ")),168- ).toEqual([]);169- expect(await files(bucketDir)).toEqual(landed);170-171- const inst = await instance(bucketDir, keprData);172- const q = (sql: string) => inst.kepr.query(sql).all();173- expect(q("SELECT name, public, category FROM repos ORDER BY name")).toEqual([174- { name: "demo", public: 1, category: "tools" },175- { name: "secret", public: 0, category: "" },176- ]);177- expect(q("SELECT repo, count FROM installs ORDER BY repo")).toEqual([178- { repo: "demo", count: 3 },179- { repo: "secret", count: 1 },180- ]);181- expect(q("SELECT COUNT(*) AS n FROM downloads")).toEqual([{ n: 0 }]);182- expect(q("SELECT repo, version, hidden FROM release_settings")).toEqual([183- { repo: "secret", version: "0.1.0", hidden: 1 },184- ]);185- expect(186- q(187- "SELECT number, title, body, type, version, reporter_name, contact_email, filed_at, status, closed_at, fixed_in FROM issues ORDER BY number",188- ),189- ).toEqual([190- {191- number: 7,192- title: "Crash on start",193- body: "It <b>crashes</b>.",194- type: "bug",195- version: "1.0.0",196- reporter_name: "@rita",197- contact_email: "[email protected]",198- filed_at: 1000,199- status: "open",200- closed_at: null,201- fixed_in: "",202- },203- {204- number: 9,205- title: "Dark mode",206- body: "Please.",207- type: "idea",208- version: "",209- reporter_name: "Sam",210- contact_email: "[email protected]",211- filed_at: 1500,212- status: "closed",213- closed_at: 2000,214- fixed_in: save,215- },216- ]);217- expect(q("SELECT author, name, body, created_at FROM issue_entries ORDER BY id")).toEqual([218- { author: "operator", name: "", body: "Looking.", created_at: 1100 },219- { author: "reporter", name: "@rita", body: "Thanks!", created_at: 1200 },220- { author: "operator", name: "", body: "Me too.", created_at: 1400 },221- ]);222-223- // Kepr 3 reads what the import wrote as any Koh 3 release.224- type Latest = { version: string; notes: string; platforms: Record<string, unknown> };225- const latest = (await (await inst.app.request("/api/demo/releases/latest")).json()) as Latest;226- expect(latest.version).toBe("1.1.0");227- expect(latest.notes).toBe("Starts twice as fast and no longer crashes on start.");228- expect(Object.keys(latest.platforms)).toEqual(["android-arm64", "macos-aarch64"]);229- const record = await Bun.file(join(bucketDir, "demo/releases/1.0.0/release.json")).json();230- const legacy = bytesOf("demo 1.0.0 linux");231- expect(record).toEqual({232- format: 1,233- repo: "demo",234- version: "1.0.0",235- save,236- published_at: 20,237- machine: "kepr2",238- notes: "",239- files: [240- {241- platform: "linux-x86_64",242- name: "demo-linux-x86_64",243- size: legacy.length,244- blake3: hex(legacy),245- sha256: sha(legacy),246- },247- ],248- });249- expect(await (await inst.app.request("/demo/issues/7")).text()).toContain("Me too.");250- expect(inst.kepr.query("SELECT last_sync_error FROM repos WHERE name = 'demo'").get()).toEqual({251- last_sync_error: null,252- });253-});254-255-type S3 = { dir: string; puts: string[]; target: Record<string, string>; stop(): void };256-257-/** A stand-in S3 over a folder. A key in `race` appears, holding those bytes, between our GET and PUT. */258-async function standInS3(race = new Map<string, string>()): Promise<S3> {259- const dir = await mkdtemp(join(tmpdir(), "kepr-import-s3-"));260- const puts: string[] = [];261- const server = Bun.serve({262- port: 0,263- async fetch(req) {264- const url = new URL(req.url);265- const key = decodeURIComponent(url.pathname.replace("/koh/", ""));266- const file = Bun.file(join(dir, key));267- if (req.method === "GET")268- return (await file.exists())269- ? new Response(file)270- : new Response("<Error><Code>NoSuchKey</Code></Error>", { status: 404 });271- expect([req.headers.get("if-none-match"), url.searchParams.has("X-Amz-Signature")]).toEqual([272- "*",273- true,274- ]);275- const raced = race.get(key);276- if (raced !== undefined) await Bun.write(join(dir, key), raced);277- if (await file.exists()) return new Response("", { status: 412 });278- puts.push(key);279- await Bun.write(join(dir, key), await req.arrayBuffer());280- return new Response("");281- },282- });283- const target = {284- KOH_S3_ENDPOINT: `http://localhost:${server.port}`,285- KOH_S3_BUCKET: "koh",286- KOH_S3_REGION: "fr-par",287- KOH_S3_ACCESS_KEY_ID: "write",288- KOH_S3_SECRET_ACCESS_KEY: "key",289- };290- return { dir, puts, target, stop: () => server.stop(true) };291-}292-293-const newKeprData = () => mkdtemp(join(tmpdir(), "kepr-import-s3data-"));294-295-test("into an S3 bucket, files go up as presigned PUTs with If-None-Match, never over an existing key", async () => {296- const s3 = await standInS3();297- try {298- await importKepr2(s3.target, await newKeprData());299- expect(s3.puts.length).toBe(9);300- for (const key of await files(s3.dir)) {301- expect(await Bun.file(join(s3.dir, key)).bytes()).toEqual(302- await Bun.file(join(bucketDir, key)).bytes(),303- );304- }305- await importKepr2(s3.target, await newKeprData());306- expect(s3.puts.length).toBe(9);307- } finally {308- s3.stop();309- }310-});311-312-test("a 412 from a key written since the read is success only when it holds the same bytes", async () => {313- const record = await Bun.file(join(bucketDir, "demo/releases/1.0.0/release.json")).text();314- const same = await standInS3(new Map([["demo/releases/1.0.0/release.json", record]]));315- try {316- await importKepr2(same.target, await newKeprData());317- expect(same.puts).not.toContain("demo/releases/1.0.0/release.json");318- expect(same.puts.length).toBe(8);319- } finally {320- same.stop();321- }322- const other = await standInS3(new Map([["demo/releases/latest", "9.9.9"]]));323- try {324- const run = await runImport(other.target, await newKeprData());325- expect(run.code).toBe(1);326- expect(run.err).toContain("demo/releases/latest holds other bytes");327- expect(await Bun.file(join(other.dir, "demo/releases/latest")).text()).toBe("9.9.9");328- } finally {329- other.stop();330- }331-});332-333-test("any imported row that fails a check fails the run: all are listed and nothing is written", async () => {334- await kepr2File("demo/1.3.0/linux-x86_64/demo", "demo 1.3.0 tampered");335- const oldPlatform = await kepr2File("demo/1.4.0/x86_64-linux/demo", "demo 1.4.0 old name");336- const legacy = bytesOf("demo 1.0.0 linux");337- const pg = new SQL(url);338- await pg.unsafe(`339- INSERT INTO build_runs (id, repo_id, save_id, version, trigger, status, started_at, finished_at) VALUES340- ('b4', 'demo', '${save}', '1.3.0', 'manual', 'success', 70, 80), ('b6', 'demo', '${save}', '1.4.0', 'manual', 'success', 110, 120);341- INSERT INTO release_artifacts (id, build_run, repo_id, version, platform, filename, size_bytes, sha256, blake3, built_at) VALUES342- ${artifact("a5", "b4", "demo", "1.3.0", "linux-x86_64", "demo", legacy)},343- ${artifact("a7", "b6", "demo", "1.4.0", "x86_64-linux", "demo", oldPlatform)};344- INSERT INTO issue_entries (id, issue_id, account_id, entry_type, body, created_at) VALUES ('e5', 2, 'acc-t', 'reply', 'Team here.', 1600);345- `);346- await pg.close();347- const before = await files(bucketDir);348- const keprData = await mkdtemp(join(tmpdir(), "kepr-import-bad-"));349- const run = await runImport({ KOH_FOLDER: bucketDir }, keprData);350- expect(run.code).toBe(1);351- expect(run.err).toContain("not imported, nothing written:");352- expect(run.err).toContain("demo#9: third-party reply");353- expect(run.err).toContain("demo/releases/1.3.0: linux-x86_64: hash mismatch");354- expect(run.err).toContain("demo/releases/1.4.0: release record does not match §11.2");355- expect(run.out).not.toMatch(/^put /m);356- expect(await files(bucketDir)).toEqual(before);357- const inst = await instance(bucketDir, keprData);358- for (const table of ["issues", "issue_entries", "installs", "release_settings"]) {359- expect([table, inst.kepr.query(`SELECT COUNT(*) AS n FROM ${table}`).get()]).toEqual([360- table,361- { n: 0 },362- ]);363- }364- expect(inst.kepr.query("SELECT COUNT(*) AS n FROM repos WHERE name = 'secret'").get()).toEqual({365- n: 0,366- });367-});tests/issues.test.ts+26 −0
@@ -48,6 +48,14 @@4848 expect(fileIssue(db, newIssue("lib", "next")).number).toBe(42);4949 });5050 51+ test("refuses a child row whose parent issue is missing", () => {52+ expect(() =>53+ db.run(54+ "INSERT INTO issue_entries (issue_id, author, body, created_at) VALUES (9999, 'reporter', 'x', 0)",55+ ),56+ ).toThrow();57+ });58+5159 test("public reads leave out contact and IP", () => {5260 const issue = findIssue(db, "app", fileIssue(db, newIssue("app", "secret")).number);5361 expect(Object.keys(issue ?? {})).not.toContain("contact_email");@@ -262,6 +270,24 @@262270 expect(thread).not.toContain('href="javascript:');263271 expect(thread).toContain('<span class="issue-author">Bob</span>');264272 expect(await page("/app/issues")).toContain("· 1 reply");273+ });274+275+ test("a picture in a reply shows its words, never a request for the image", async () => {276+ const session = await openForm("/app/issues/1");277+ tick(3);278+ const body =279+ "\n" +280+ "\n" +281+ "[docs](https://example.com)";282+ expect((await post("/app/issues/1", session, { body, name: "Cy" })).status).toBe(303);283+ const thread = await page("/app/issues/1");284+ expect(thread).not.toContain("<img");285+ expect(thread).not.toContain('src="https://elsewhere.example/chart.png"');286+ expect(thread).toContain("chart");287+ expect(thread).toContain(288+ '<a href="https://elsewhere.example/blank.png" rel="nofollow ugc noopener">https://elsewhere.example/blank.png</a>',289+ );290+ expect(thread).toContain('<a href="https://example.com" rel="nofollow ugc noopener">docs</a>');265291 });266292 267293 test("quote starts a reply with the post quoted, and the reply shows what it answers", async () => {tests/releases.test.ts+58 −1
@@ -1,5 +1,5 @@11 import type { Database } from "bun:sqlite";2-import { beforeAll, describe, expect, test } from "bun:test";2+import { beforeAll, describe, expect, setSystemTime, test } from "bun:test";33 import { mkdtemp, writeFile } from "node:fs/promises";44 import { tmpdir } from "node:os";55 import { join } from "node:path";@@ -411,9 +411,66 @@411411 const head = await get("/cli/archive/HEAD.tar.gz", nix);412412 expect(installs()).toBe(0);413413 const tarball = head.headers.get("Location") as string;414+ // A HEAD of the tarball fetches nothing, so it is not an install.415+ expect((await app.request(tarball, { method: "HEAD", headers: nix })).status).toBe(200);416+ expect(installs()).toBe(0);414417 expect((await get(tarball, nix)).status).toBe(200);415418 expect((await get(tarball, { "User-Agent": "curl/8.7.1" })).status).toBe(200);416419 expect(installs()).toBe(1);420+ });421+422+ test("a download counts once per client an hour, and never for previews or a HEAD (P17)", async () => {423+ const path = "/cli/releases/1.0.0/android-arm64";424+ const from = (address: string, init: RequestInit = {}) =>425+ app.request(path, init, { requestIP: () => ({ address }) });426+ const counted = () =>427+ (428+ kepr429+ .query(430+ "SELECT count FROM downloads WHERE version = '1.0.0' AND platform = 'android-arm64'",431+ )432+ .get() as { count: number } | null433+ )?.count ?? 0;434+ try {435+ setSystemTime(new Date("2026-09-30T12:00:00Z"));436+ const before = counted();437+ // A reload storm from one client, then a second client.438+ for (let i = 0; i < 5; i++) expect((await from("198.51.100.7")).status).toBe(302);439+ expect(counted()).toBe(before + 1);440+ expect((await from("198.51.100.8")).status).toBe(302);441+ expect(counted()).toBe(before + 2);442+ for (const agent of [443+ "Slackbot-LinkExpanding 1.0 (+https://api.slack.com/robots)",444+ "Mozilla/5.0 (compatible; Discordbot/2.0; +https://discordapp.com)",445+ "TelegramBot (like TwitterBot)",446+ "WhatsApp/2.23.20.0",447+ "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)",448+ "Twitterbot/1.0",449+ "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",450+ "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)",451+ ]) {452+ const res = await from("198.51.100.9", { headers: { "User-Agent": agent } });453+ expect([agent, res.status]).toEqual([agent, 302]);454+ }455+ expect(counted()).toBe(before + 2);456+ // A HEAD answers the same and fetches nothing.457+ const head = await from("198.51.100.10", { method: "HEAD" });458+ expect([head.status, head.headers.get("Location")]).toEqual([459+ 302,460+ `file://${join(bucketDir, "cli/releases/1.0.0/android-arm64/cli-1.0.0.apk")}`,461+ ]);462+ expect(counted()).toBe(before + 2);463+ // install.sh downloads with curl, which is a person.464+ const curl = await from("198.51.100.11", { headers: { "User-Agent": "curl/8.7.1" } });465+ expect(curl.status).toBe(302);466+ expect(counted()).toBe(before + 3);467+ // The same client an hour later is a new download.468+ setSystemTime(new Date("2026-09-30T13:00:01Z"));469+ expect((await from("198.51.100.7")).status).toBe(302);470+ expect(counted()).toBe(before + 4);471+ } finally {472+ setSystemTime();473+ }417474 });418475 });419476