82287e051d2e
cut sync requests and group abuse limits (v3.2.7)
- time
- 2026-11-17 00:10 UTC · 1 week ago
- machine
- Junes-MacBook-Pro.local
- agent
- deepseek/deepseek-flash
- session
- review findings
- parent
- 53a09c6d3d92
↓ kepr-82287e05.tar.gzatlas at this save
files changed12 files
scripts/budget.ts+3 −3src/bucket/repo.ts+20 −7src/bucket/sync.ts+37 −15src/issues/files.ts+24 −0src/issues/pages.ts+33 −17src/issues/spam.ts+63 −1src/mirror/queries.ts+2 −2src/server/app.ts+8 −0src/server/connect.ts+10 −10src/server/login.ts+13 −9tests/front.test.ts+8 −0tests/sync.test.ts+3 −0scripts/budget.ts+3 −3
@@ -4,16 +4,16 @@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/"], 1220],7+ ["bucket", ["src/bucket/"], 1245],88 ["mirror", ["src/mirror/"], 1100],99 ["describe", ["src/describe/"], 530],10- ["pages", ["src/pages/"], 2600],10+ ["pages", ["src/pages/"], 2565],1111 ["releases", ["src/releases/"], 900],1212 ["tarball", ["src/tarball/"], 300],1313 ["issues", ["src/issues/"], 1700],1414 ["admin", ["src/admin/"], 2800],1515 ["import-kepr2", ["scripts/import-kepr2.ts"], 300],16- ["server", ["src/server/", "src/main.ts", "scripts/budget.ts"], 2030],16+ ["server", ["src/server/", "src/main.ts", "scripts/budget.ts"], 2040],1717 ];1818 const ASSET_AREAS: [string, string, number][] = [1919 ["public/js", "public/js/**/*.js", 1400],src/bucket/repo.ts+20 −7
@@ -95,14 +95,22 @@9595 const JSON_ESCAPE =9696 /\\u[dD][89abAB][0-9a-fA-F]{2}\\u[dD][c-fC-F][0-9a-fA-F]{2}|\\u[dD][89a-fA-F][0-9a-fA-F]{2}|\\[\s\S]/g;9797 98+type Heads = Map<string, string>;99+98100 /**99101 * Every repo in the bucket: a top-level folder with a `head`. A folder without one is not a repo100- * yet, as when a first offer or a rename (which copies `head` last) is still under way.102+ * yet, as when a first offer or a rename (which copies `head` last) is still under way. Fills103+ * `heads` with the head each has, so a sync need not ask the bucket for it again.101104 */102-export async function listRepos(bucket: Bucket): Promise<string[]> {105+export async function listRepos(bucket: Bucket, heads: Heads = new Map()): Promise<string[]> {103106 const names = (await bucket.folders()).filter(isRepoName);104- const heads = await Promise.all(names.map((name) => bucket.get(`${name}/head`)));105- return names.filter((_, i) => heads[i] !== null);107+ const found = await Promise.all(names.map((name) => bucket.get(`${name}/head`)));108+ const repos = names.filter((_, i) => found[i] !== null);109+ for (const [i, repo] of names.entries()) {110+ const bytes = found[i];111+ if (bytes !== null) heads.set(repo, decoder.decode(bytes).trim());112+ }113+ return repos;106114 }107115 108116 function isRepoName(name: string): boolean {@@ -129,13 +137,18 @@129137 }130138 }131139 140+/** A head's text against §9.2's save ID rule, wherever it came from: the bucket or a listing. */141+export function checkHead(repo: string, head: string): string {142+ requireRepo(repo);143+ if (!SAVE_ID.test(head)) throw new BucketError(`${repo}/head is not a save ID: "${head}"`);144+ return head;145+}146+132147 export async function readHead(bucket: Bucket, repo: string): Promise<string | null> {133148 requireRepo(repo);134149 const bytes = await bucket.get(`${repo}/head`);135150 if (bytes === null) return null;136- const head = decoder.decode(bytes).trim();137- if (!SAVE_ID.test(head)) throw new BucketError(`${repo}/head is not a save ID: "${head}"`);138- return head;151+ return checkHead(repo, decoder.decode(bytes).trim());139152 }140153 141154 export async function readSave(bucket: Bucket, repo: string, id: string): Promise<ArrivingSave> {src/bucket/sync.ts+37 −15
@@ -27,8 +27,10 @@2727 import { dropTarballs } from "../tarball/cache.ts";2828 import { type Bucket, inTurn, KEPR_PREFIX, openBucket } from "./reader.ts";2929 import {30+ type ArrivingSave,3031 BucketError,3132 checkFormat,33+ checkHead,3234 type EventRecord,3335 escapePath,3436 isSafePath,@@ -56,6 +58,11 @@5658 const READS_AT_ONCE = 16;5759 // Compressed object bytes being read at once; a larger object waits and is read alone.5860 const READ_BYTES = 32 * 1024 * 1024;61+// Repos synced at once: every read waits on the bucket, so a serial pass left the line idle.62+const REPOS_AT_ONCE = 4;63+// Each repo of a pass gets this share of the pass's bytes, so a few in flight hold the same total.64+const LANDING = LANDING_BYTES / REPOS_AT_ONCE;65+const READS = READ_BYTES / REPOS_AT_ONCE;5966 6067 export type SyncTarget = {6168 bucket: Bucket;@@ -176,9 +183,9 @@176183 }177184 178185 async function syncEach(target: SyncTarget): Promise<void> {179- let repos: string[];186+ const heads = new Map<string, string>();180187 try {181- repos = await listRepos(target.bucket);188+ await listRepos(target.bucket, heads);182189 } catch (error) {183190 keepState(target.kepr, "bucket_error", String(error));184191 throw error;@@ -186,10 +193,11 @@186193 // What the console's status shows, so it never asks the bucket itself.187194 keepState(target.kepr, "bucket_error", null);188195 keepState(target.kepr, "bucket_read_at", String(Math.floor(Date.now() / 1000)));189- keepState(target.kepr, "bucket_repos", JSON.stringify(repos));190- for (const repo of repos) {196+ keepState(target.kepr, "bucket_repos", JSON.stringify([...heads.keys()]));197+ // A few repos at a time, each from the head the listing read; a failure stays that repo's.198+ await inTurn([...heads], REPOS_AT_ONCE, async ([repo, head]) => {191199 // A repo being deleted is left alone: landing its records mid-delete would put its row back.192- if (repo === removal(target.kepr)?.repo) continue;200+ if (repo === removal(target.kepr)?.repo) return;193201 registerRepo(target.kepr, repo);194202 let error: string | null = null;195203 if (RESERVED_NAMES.has(repo)) {@@ -197,7 +205,8 @@197205 } else {198206 try {199207 const mirror = openMirror(target.mirrorDir, repo);200- const events = await syncRepo(target.bucket, mirror, repo, hiddenPaths(target.kepr, repo));208+ const paths = hiddenPaths(target.kepr, repo);209+ const events = await syncRepo(target.bucket, mirror, repo, paths, LANDING, READS, head);201210 if (events.some((event) => event.kind === "strip")) await dropTarballs(target.bucket, repo);202211 } catch (cause) {203212 error = cause instanceof Error ? cause.message : String(cause);@@ -205,7 +214,7 @@205214 }206215 recordSync(target.kepr, repo, Math.floor(Date.now() / 1000), error);207216 await handHidden(target, repo);208- }217+ });209218 }210219 211220 /**@@ -251,21 +260,31 @@251260 hidden: string[] = [],252261 landingBytes = LANDING_BYTES,253262 readBytes = READ_BYTES,263+ listed?: string,254264 ): Promise<EventRecord[]> {255265 applyHidden(mirror, hidden);256- await checkFormat(bucket, repo);257- const head = await readHead(bucket, repo);266+ // A listing read the head already; without one, the bucket is asked.267+ const head = listed === undefined ? await readHead(bucket, repo) : checkHead(repo, listed);268+ // The format is read once per head: koh writes `format` only when it offers, which moves the269+ // head, so asking on every pass spent a request per repo per pass to hear nothing new.270+ if (head === null || mirrorState(mirror, "head") !== head) await checkFormat(bucket, repo);258271 if (head === null) return [];259272 const unknown = new Set<string>();273+ // What the walk back read, so the landing pass need not read it again: the walk goes down from274+ // the head, so its last records are the landing's first; a landing batch's worth is kept and no275+ // more, so a first sync of a huge repo still never holds its history in memory.276+ const walked = new Map<string, ArrivingSave>();260277 for (let cursor = head; cursor !== "" && !knownSave(mirror, cursor); ) {261278 if (unknown.has(cursor)) throw new BucketError(`${repo}: save ${cursor} is its own ancestor`);262279 unknown.add(cursor);263- cursor = (await readSave(bucket, repo, cursor)).parent;280+ const save = await readSave(bucket, repo, cursor);281+ if (walked.size === LANDING_SAVES) walked.delete(walked.keys().next().value as string);282+ walked.set(save.id, save);283+ cursor = save.parent;264284 }265285 // Oldest first, landing whenever the batch passes `landingBytes` of objects or LANDING_SAVES266286 // records: a first sync of a big repo never holds its whole history in memory, and one cut short267- // resumes from the last batch. Records are read again here rather than kept from the walk, since268- // each lists every file of its tree.287+ // resumes from the last batch.269288 let saves: SaveRecord[] = [];270289 let objects = new Map<string, StoredObject>();271290 let quarantined: string[] = [];@@ -310,9 +329,12 @@310329 };311330 const ids = [...unknown].reverse();312331 for (let start = 0; start < ids.length; start += READS_AT_ONCE) {313- const records = await inTurn(ids.slice(start, start + READS_AT_ONCE), READS_AT_ONCE, (id) =>314- readSave(bucket, repo, id),315- );332+ const records = await inTurn(ids.slice(start, start + READS_AT_ONCE), READS_AT_ONCE, (id) => {333+ const read = walked.get(id);334+ if (read === undefined) return readSave(bucket, repo, id);335+ walked.delete(id);336+ return Promise.resolve(read);337+ });316338 for (const save of records) {317339 quarantined.push(...save.quarantined);318340 // One save can hold more than a batch, as a first import does: its objects are storedsrc/issues/files.ts+24 −0
@@ -3,11 +3,31 @@33 // §23: what an issue or reply may carry.44 export const FILES_PER_POST = 4;55 export const FILE_BYTES_PER_HOUR = 64 * 1024 * 1024;6+// The whole site's attachments per UTC day: one address's hour is no ceiling on a botnet sharing7+// the same files, and 200 MB leaves a busy repository's ordinary screenshots untouched.8+export const ATTACHMENT_BYTES_PER_DAY = 200 * 1024 * 1024;69 const IMAGE_BYTES = 8 * 1024 * 1024;710 const LOG_BYTES = 2 * 1024 * 1024;811 // A log shows this much of its start in the thread; the whole file is a link away.912 const PREVIEW_BYTES = 16 * 1024;1013 14+// Bytes kept today, in memory, like the rest of the limits: a restart forgets them.15+let day = -1;16+let bytesToday = 0;17+18+function rollDay(at: number): void {19+ const today = Math.floor(at / 86_400);20+ if (today === day) return;21+ day = today;22+ bytesToday = 0;23+}24+25+/** Bytes attached site-wide on `at`'s UTC day, before this post's own. */26+export function attachmentBytesToday(at: number): number {27+ rollDay(at);28+ return bytesToday;29+}30+1131 // A picture is known by its first bytes, never by the name or type the browser sent.1232 const IMAGES: [type: string, ext: string, magic: (head: string) => boolean][] = [1333 ["image/png", "png", (head) => head.startsWith("\x89PNG\r\n\x1a\n")],@@ -88,6 +108,10 @@88108 `INSERT INTO issue_files (issue_id, entry_id, name, type, size, data, ip_hash, created_at)89109 VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,90110 );111+ // Counted where bytes are actually kept, so a post refused after its uploads were read costs112+ // nothing against the day's ceiling.113+ rollDay(at);114+ bytesToday += uploads.reduce((sum, upload) => sum + upload.data.length, 0);91115 db.transaction(() => {92116 for (const upload of uploads) {93117 insert.run(src/issues/pages.ts+33 −17
@@ -17,8 +17,10 @@1717 import type { Config } from "../server/config.ts";1818 import { notify } from "../server/db.ts";1919 import {20+ ATTACHMENT_BYTES_PER_DAY,2021 type Attachment,2122 attachFiles,23+ attachmentBytesToday,2224 FILE_BYTES_PER_HOUR,2325 FILE_EXTENSIONS,2426 FILES_PER_POST,@@ -131,8 +133,17 @@131133 const repo = openPublicRepo(ctx, c.req.param("repo"));132134 if (!repo) return notFound(c, ctx);133135 if (repo.settings.issuesPaused) return formPage(c, ctx, repo, {}, "", 403, mail());134- const { fields, files } = await readForm(c, FORM_FIELDS);135136 const now = unixNow();137+ const hash = ipHash(ctx.kepr, c);138+ // Answered before the body is read: a blocked or over-quota address is refused without139+ // parsing the 34 MB a post may carry (§25).140+ const early = (message: string, status: 400 | 403 | 429) =>141+ formPage(c, ctx, repo, {}, message, status, mail());142+ if (isBlocked(ctx.kepr, hash)) return early(BLOCKED, 403);143+ if (filingsSince(ctx.kepr, hash, now - 3600) >= FILINGS_PER_HOUR) {144+ return early("Too many issues from here this hour. Please try again later.", 429);145+ }146+ const { fields, files } = await readForm(c, FORM_FIELDS);136147 const refuse = (message: string, status: 400 | 403 | 429) =>137148 formPage(c, ctx, repo, fields, attachAgain(message, files), status, mail());138149 // A bot that fills the hidden field learns nothing from the answer.@@ -152,11 +163,6 @@152163 400,153164 );154165 }155- const hash = ipHash(ctx.kepr, c);156- if (isBlocked(ctx.kepr, hash)) return refuse(BLOCKED, 403);157- if (filingsSince(ctx.kepr, hash, now - 3600) >= FILINGS_PER_HOUR) {158- return refuse("Too many issues from here this hour. Please try again later.", 429);159- }160166 const uploads = await checkUploads(ctx, files, hash, now);161167 if (!Array.isArray(uploads)) return refuse(uploads.error, uploads.status);162168 const name = repo.settings.name;@@ -226,14 +232,28 @@226232 const found = open(c);227233 if (!found) return notFound(c, ctx);228234 const { repo, issue, base } = found;229- const { fields, files } = await readForm(c, REPLY_FIELDS);230235 const entries = threadEntries(ctx.kepr, issue.id);236+ const now = unixNow();237+ privatePage(c);238+ // Before the body is read: a closed issue, a blocked address and an over-quota one all239+ // answer without parsing the uploads a reply may carry (§25).240+ const hash = ipHash(ctx.kepr, c);241+ const early = (error: string, status: 400 | 403 | 429) => {242+ const view = { mail: mail(), refused: "reply" as const, error };243+ return c.html(threadPage(c, ctx, repo, issue, entries, view), status);244+ };245+ if (issue.status === "closed") return early("This issue is closed to new replies.", 403);246+ if (isBlocked(ctx.kepr, hash)) return early(BLOCKED, 403);247+ const posted =248+ repliesSince(ctx.kepr, hash, now - 3600) + followsSince(ctx.kepr, hash, now - 3600);249+ if (posted >= REPLIES_PER_HOUR) {250+ return early("Too many replies from here this hour. Please try again later.", 429);251+ }252+ const { fields, files } = await readForm(c, REPLY_FIELDS);231253 const answering = entries.find((entry) => String(entry.id) === fields.reply_to);232254 const body = fields.body?.trim() ?? "";233255 const name = fields.name?.trim() ?? "";234256 const email = fields.email?.trim() ?? "";235- const now = unixNow();236- privatePage(c);237257 const refuse = (message: string, status: 400 | 403 | 429) => {238258 const view = {239259 mail: mail(),@@ -247,7 +267,6 @@247267 return c.html(threadPage(c, ctx, repo, issue, entries, view), status);248268 };249269 if (fields.website !== "") return refuse("This reply could not be posted.", 400);250- if (issue.status === "closed") return refuse("This issue is closed to new replies.", 403);251270 const stamp = checkStamp(ctx.kepr, c, fields.stamp ?? "", now);252271 if (stamp === "invalid") return refuse("This form expired. Please send it again.", 403);253272 if (stamp === "too-fast") return refuse("That was quick. Please send it again.", 400);@@ -256,13 +275,6 @@256275 return refuse(`Please keep it under ${MAX_CHARS.toLocaleString("en-US")} characters.`, 400);257276 }258277 if (email !== "" && !isEmail(email)) return refuse(BAD_EMAIL, 400);259- const hash = ipHash(ctx.kepr, c);260- if (isBlocked(ctx.kepr, hash)) return refuse(BLOCKED, 403);261- const posted =262- repliesSince(ctx.kepr, hash, now - 3600) + followsSince(ctx.kepr, hash, now - 3600);263- if (posted >= REPLIES_PER_HOUR) {264- return refuse("Too many replies from here this hour. Please try again later.", 429);265- }266278 const uploads = await checkUploads(ctx, files, hash, now);267279 if (!Array.isArray(uploads)) return refuse(uploads.error, uploads.status);268280 const entry = addEntry(ctx.kepr, issue.id, {@@ -419,6 +431,10 @@419431 error: "Too many attachments from here this hour. Please try again later.",420432 status: 429,421433 };434+ }435+ // The site's day, not this address's hour: a botnet sharing one prefix still fills one bucket.436+ if (bytes > 0 && attachmentBytesToday(now) + bytes > ATTACHMENT_BYTES_PER_DAY) {437+ return { error: "Too many attachments today. Please try again tomorrow.", status: 429 };422438 }423439 return uploads;424440 }src/issues/spam.ts+63 −1
@@ -28,7 +28,69 @@2828 2929 /** A keyed hash, so the stored value can't be reversed by hashing every IPv4 address. */3030 export function ipHash(db: Database, c: Context): string {31- return mac(db, `ip:${clientIp(c)}`);31+ return mac(db, `ip:${limitKey(clientIp(c))}`);32+}33+34+/**35+ * What a limit counts: IPv4 as it stands, IPv6 as its /64. One machine can walk every address in36+ * its prefix, so a limit keyed on the exact address is no limit at all.37+ */38+export function limitKey(address: string): string {39+ const bare = address.split("%")[0].toLowerCase();40+ const mapped = bare.startsWith("::ffff:") ? bare.slice(7) : "";41+ if (mapped.includes(".")) return mapped;42+ // Two `::` is not an address; anything else is expanded so its first four groups are real.43+ if (!bare.includes(":") || bare.split("::").length > 2) return bare;44+ const [head = "", tail = ""] = bare.split("::");45+ const left = head === "" ? [] : head.split(":");46+ const right = tail === "" ? [] : tail.split(":");47+ const fill = 8 - left.length - right.length;48+ if (fill < 0) return bare;49+ const groups = [...left, ...Array<string>(fill).fill("0"), ...right];50+ if (!groups.every((group) => /^[0-9a-f]{1,4}$/.test(group))) return bare;51+ // Unpadded, so `0db8` and `db8` are the same prefix, as an address may be written either way.52+ return groups53+ .slice(0, 4)54+ .map((group) => Number.parseInt(group, 16).toString(16))55+ .join(":");56+}57+58+/**59+ * A windowed count per key, in memory, with an optional ceiling for the whole site per UTC day.60+ * Entries are pruned by time, not position — a clock that stepped backwards outside this process61+ * (a test's fake timer, an NTP correction) leaves an old entry in the middle, not the front — and62+ * a check reads that key's own handful of entries, never a scan of everything remembered.63+ */64+export function attemptLimiter(65+ windowMs: number,66+ perKey: number,67+ perDay = Number.POSITIVE_INFINITY,68+) {69+ const seen = new Map<string, number[]>();70+ let day = -1;71+ let today = 0;72+ const roll = (now: number) => {73+ const utcDay = Math.floor(now / 86_400_000);74+ if (utcDay === day) return;75+ day = utcDay;76+ today = 0;77+ };78+ return {79+ /** Whether the key may try now; nothing is counted until `note`. */80+ allowed(key: string, now: number): boolean {81+ roll(now);82+ const recent = (seen.get(key) ?? []).filter((at) => at > now - windowMs);83+ if (recent.length === 0) seen.delete(key);84+ else seen.set(key, recent);85+ return recent.length < perKey && today < perDay;86+ },87+ /** Records an attempt: a caller that only learns it failed does so afterwards. */88+ note(key: string, now: number): void {89+ roll(now);90+ today++;91+ seen.set(key, [...(seen.get(key) ?? []), now]);92+ },93+ };3294 }3395 3496 /**src/mirror/queries.ts+2 −2
@@ -64,8 +64,8 @@6464 .get(prefix);6565 if (exact) return asSave(exact);6666 const rows = db67- .query<Save, [string]>(`SELECT ${SAVE_COLUMNS} FROM saves WHERE id LIKE ? || '%' LIMIT 2`)68- .all(prefix);67+ .query<Save, [string]>(`SELECT ${SAVE_COLUMNS} FROM saves WHERE id GLOB ? LIMIT 2`)68+ .all(`${prefix}*`);6969 return rows.length === 1 ? asSave(rows[0] as Save) : null;7070 }7171 src/server/app.ts+8 −0
@@ -153,6 +153,9 @@153153 path.startsWith("assets/") ? join(assetsDir, path.slice(7)) : join(PUBLIC_DIR, path),154154 );155155 if (!(await file.exists())) return c.notFound();156+ // Size and mtime are a strong validator; the path keeps two files with the same stamp apart.157+ const stamp = `${file.size.toString(16)}-${file.lastModified.toString(36)}`;158+ const etag = `"${Bun.hash(path).toString(16)}-${stamp}"`;156159 // A versioned URL names one build's file, and a font file never changes under its name, so157160 // neither needs asking again.158161 const versioned = c.req.query("v") !== undefined || path.startsWith("fonts/");@@ -160,6 +163,11 @@160163 "Cache-Control",161164 versioned ? "public, max-age=31536000, immutable" : "public, max-age=3600",162165 );166+ c.header("ETag", etag);167+ const asked = c.req.header("If-None-Match");168+ // Matching first answers without reading the file, which is the whole point of the tag.169+ if (asked?.split(",").some((it) => it.trim() === etag) || asked === "*")170+ return c.body(null, 304);163171 return c.body(await file.bytes(), 200, { "Content-Type": file.type });164172 });165173 const mirrorDir = join(config.dataDir, "mirror");src/server/connect.ts+10 −10
@@ -1,5 +1,6 @@11 import { createHash, randomBytes } from "node:crypto";22 import type { Context, Hono } from "hono";3+import { attemptLimiter, limitKey } from "../issues/spam.ts";34 import { html } from "../pages/html.ts";45 import { type PageContext, page } from "../pages/layout.ts";56 import { clientIp } from "./client.ts";@@ -28,10 +29,10 @@2829 // One body for every failure — unknown, expired, used, malformed and rate-limited alike — so a2930 // caller learns nothing but "no code".3031 const NO_CODE = '{"error":"no_code","message":"no code"}';31-// Failed codes, oldest first, in memory: a restart forgets them, but an attacker can't cause one.32-let attempts: { at: number; address: string }[] = [];32+// Failed codes per address, in memory: a restart forgets them, but an attacker can't cause one.3333 // Addresses are keyed hashes even in memory, as issue filings store them (§23).34-const attemptKey = randomBytes(32);34+const attempts = attemptLimiter(ATTEMPT_WINDOW_MS, ATTEMPTS_PER_ADDRESS);35+const ipKey = randomBytes(32);3536 const sha256 = (value: string) => createHash("sha256").update(value).digest("hex");3637 3738 /** The S3 key a signed-in machine is handed, or null when Kepr hands out none. */@@ -111,15 +112,14 @@111112 if (!connectKeys(config)) return c.notFound();112113 c.header("Cache-Control", "no-store");113114 const now = Date.now();114- // By value, not by position: a clock that stepped backwards outside this process (a test's115- // fake timer, an NTP correction) would leave the oldest entry in the middle of the list.116- attempts = attempts.filter((attempt) => attempt.at > now - ATTEMPT_WINDOW_MS);117- const address = createHash("sha256").update(attemptKey).update(clientIp(c)).digest("hex");118- const used = attempts.filter((attempt) => attempt.address === address).length;115+ const address = createHash("sha256")116+ .update(ipKey)117+ .update(limitKey(clientIp(c)))118+ .digest("hex");119119 // A refused attempt is not recorded: that caps the list at ten entries per address, and keeps120120 // hammering from moving the block out past the hour.121- if (used >= ATTEMPTS_PER_ADDRESS) return noCode(c);122- attempts.push({ at: now, address });121+ if (!attempts.allowed(address, now)) return noCode(c);122+ attempts.note(address, now);123123 let code = "";124124 try {125125 const fields = await c.req.parseBody();src/server/login.ts+13 −9
@@ -1,6 +1,7 @@11 import { createHash, randomBytes, timingSafeEqual } from "node:crypto";22 import type { Context, Hono } from "hono";33 import { deleteCookie, getCookie, setCookie } from "hono/cookie";4+import { attemptLimiter, limitKey } from "../issues/spam.ts";45 import { html } from "../pages/html.ts";56 import { type PageContext, page } from "../pages/layout.ts";67 import { clientIp } from "./client.ts";@@ -17,11 +18,13 @@1718 const HEX64 = /^[0-9a-f]{64}$/;1819 const FAILURE_WINDOW_MS = 15 * 60 * 1000;1920 const FAILURES_PER_ADDRESS = 5;21+// Failed sign-ins site-wide per UTC day: a per-address bucket leaves a bot with a /64 unlimited.22+const FAILURES_PER_DAY = 100;2023 21-// Failed sign-ins, oldest first, in memory: a restart forgets them, but an attacker can't cause one.22-const failures: { at: number; address: string }[] = [];23-// Addresses are keyed hashes even in memory, as issue filings store them (§23).24-const addressKey = randomBytes(32);24+// Failed sign-ins are held per address in memory: a restart forgets them, but an attacker can't25+// cause one. Addresses are keyed hashes even in memory, as issue filings store them (§23).26+const failures = attemptLimiter(FAILURE_WINDOW_MS, FAILURES_PER_ADDRESS, FAILURES_PER_DAY);27+const ipKey = randomBytes(32);2528 2629 const nowSeconds = () => Math.floor(Date.now() / 1000);2730 const sha256 = (text: string) => createHash("sha256").update(text).digest("hex");@@ -157,10 +160,11 @@157160 return refuse(c, 403, "Refused: this form expired. Reload and try again.");158161 }159162 const now = Date.now();160- while (failures[0] && failures[0].at <= now - FAILURE_WINDOW_MS) failures.shift();161- const address = createHash("sha256").update(addressKey).update(clientIp(c)).digest("hex");162- const mine = failures.filter((failure) => failure.address === address).length;163- if (mine >= FAILURES_PER_ADDRESS) {163+ const address = createHash("sha256")164+ .update(ipKey)165+ .update(limitKey(clientIp(c)))166+ .digest("hex");167+ if (!failures.allowed(address, now)) {164168 c.header("Retry-After", String(FAILURE_WINDOW_MS / 1000));165169 return signInPage(c, ctx, "Too many attempts. Try again later.", 429, next, asksCode());166170 }@@ -171,7 +175,7 @@171175 ? "That password and code did not match."172176 : "That password is not right.";173177 const refused = () => {174- failures.push({ at: now, address });178+ failures.note(address, now);175179 return signInPage(c, ctx, wrong, 401, next, asksCode());176180 };177181 if (!passwordOk) return refused();tests/front.test.ts+8 −0
@@ -203,6 +203,14 @@203203 const asset = await app.request("/static/assets/sig.svg");204204 expect(asset.status).toBe(200);205205 expect(asset.headers.get("content-type")).toContain("image/svg+xml");206+ // The tag is the file's size, mtime and path; asking again costs no body.207+ const etag = asset.headers.get("etag") ?? "";208+ expect(etag).not.toBe("");209+ const again = await app.request("/static/assets/sig.svg", {210+ headers: { "If-None-Match": etag },211+ });212+ expect(again.status).toBe(304);213+ expect(await again.text()).toBe("");206214 await mkdir(join(dataDir, "assets/logos"));207215 await writeFile(join(dataDir, "assets/logos/mark.svg"), "<svg/>");208216 expect((await app.request("/static/assets/logos/mark.svg")).status).toBe(200);tests/sync.test.ts+3 −0
@@ -289,6 +289,9 @@289289 expect(history(t.mirror(), 1, 0)[0]?.message).toBe("add new");290290 291291 await writeFile(join(fx.bucketDir, fx.repo, "format"), "koh-remote 2");292+ // koh writes `format` only when it offers, which moves the head; a head at rest keeps the293+ // format the sync already checked.294+ await writeFile(join(fx.bucketDir, fx.repo, "head"), fx.saveIds[1] as string);292295 await syncAll(t);293296 const row = t.kepr.query("SELECT last_sync_error FROM repos").get() as {294297 last_sync_error: string;