spam.ts

6.1 KB · raw

1import type { Database } from "bun:sqlite";2import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";3import type { Context } from "hono";4import { getCookie, setCookie } from "hono/cookie";5import { clientIp } from "../server/client.ts";6import { setting } from "../server/db.ts";78// §23's spam defenses, all server-side: nothing here trusts a clock or a value from the browser.9export const MIN_SECONDS_ON_PAGE = 3;10const STAMP_MAX_AGE = 86400;11export const FILINGS_PER_HOUR = 5;12export const REPLIES_PER_HOUR = 20;13export const MAX_CHARS = 20_000;14const FORM_COOKIE = "kepr_form";15const HEX = /^[0-9a-f]{32,64}$/;1617// 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.19const secrets = new WeakMap<Database, string>();2021/** One random key, made on first use and kept in kepr.db, for the IP hash and the form stamps. */22function secret(db: Database): 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;36}3738function mac(db: Database, message: string): string {39	return createHmac("sha256", secret(db)).update(message).digest("hex");40}4142/** A keyed hash, so the stored value can't be reversed by hashing every IPv4 address. */43export function ipHash(db: Database, c: Context): string {44	return mac(db, `ip:${limitKey(clientIp(c))}`);45}4647/**48 * What a limit counts: IPv4 as it stands, IPv6 as its /64. One machine can walk every address in49 * its prefix, so a limit keyed on the exact address is no limit at all.50 */51export function limitKey(address: string): string {52	const bare = address.split("%")[0].toLowerCase();53	const mapped = bare.startsWith("::ffff:") ? bare.slice(7) : "";54	if (mapped.includes(".")) return mapped;55	// Two `::` is not an address; anything else is expanded so its first four groups are real.56	if (!bare.includes(":") || bare.split("::").length > 2) return bare;57	const [head = "", tail = ""] = bare.split("::");58	const left = head === "" ? [] : head.split(":");59	const right = tail === "" ? [] : tail.split(":");60	const fill = 8 - left.length - right.length;61	if (fill < 0) return bare;62	const groups = [...left, ...Array<string>(fill).fill("0"), ...right];63	if (!groups.every((group) => /^[0-9a-f]{1,4}$/.test(group))) return bare;64	// Unpadded, so `0db8` and `db8` are the same prefix, as an address may be written either way.65	return groups66		.slice(0, 4)67		.map((group) => Number.parseInt(group, 16).toString(16))68		.join(":");69}7071/**72 * A windowed count per key, in memory, with an optional ceiling for the whole site per UTC day.73 * Entries are pruned by time, not position — a clock that stepped backwards outside this process74 * (a test's fake timer, an NTP correction) leaves an old entry in the middle, not the front — and75 * a check reads that key's own handful of entries, never a scan of everything remembered.76 */77export function attemptLimiter(78	windowMs: number,79	perKey: number,80	perDay = Number.POSITIVE_INFINITY,81) {82	const seen = new Map<string, number[]>();83	let day = -1;84	let today = 0;85	const roll = (now: number) => {86		const utcDay = Math.floor(now / 86_400_000);87		if (utcDay === day) return;88		day = utcDay;89		today = 0;90	};91	return {92		/** Whether the key may try now; nothing is counted until `note`. */93		allowed(key: string, now: number): boolean {94			roll(now);95			const recent = (seen.get(key) ?? []).filter((at) => at > now - windowMs);96			if (recent.length === 0) seen.delete(key);97			else seen.set(key, recent);98			return recent.length < perKey && today < perDay;99		},100		/** Records an attempt: a caller that only learns it failed does so afterwards. */101		note(key: string, now: number): void {102			roll(now);103			today++;104			seen.set(key, [...(seen.get(key) ?? []), now]);105		},106	};107}108109/**110 * What a follower's confirm and stop links carry (§23): only their inbox ever sees it. The111 * address is covered too, so a link whose row is gone cannot reach a later follower that reuses112 * the id — `issue_followers.id` is a rowid, and SQLite hands a deleted row's id back out.113 */114export function followToken(db: Database, followerId: number, email: string): string {115	return mac(db, `follow:${followerId}:${email.toLowerCase()}`);116}117118export function followTokenMatches(119	db: Database,120	followerId: number,121	email: string,122	token: string,123): boolean {124	const expected = Buffer.from(followToken(db, followerId, email));125	const given = Buffer.from(token);126	return given.length === expected.length && timingSafeEqual(given, expected);127}128129/**130 * SameSite=Strict so a cross-site post arrives without it, and a form stamp131 * `<unix time>.<HMAC(time, cookie)>`.132 */133export function formStamp(db: Database, c: Context, now: number): string {134	let cookie = getCookie(c, FORM_COOKIE);135	if (!cookie || !HEX.test(cookie)) {136		cookie = randomBytes(16).toString("hex");137		setCookie(c, FORM_COOKIE, cookie, {138			httpOnly: true,139			secure: true,140			sameSite: "Strict",141			path: "/",142		});143	}144	return `${now}.${mac(db, `form:${now}:${cookie}`)}`;145}146147export type StampCheck = "ok" | "invalid" | "too-fast";148149export function checkStamp(db: Database, c: Context, stamp: string, now: number): StampCheck {150	const cookie = getCookie(c, FORM_COOKIE);151	const [time, signature] = stamp.split(".");152	if (!cookie || !time || !signature || !/^\d{1,12}$/.test(time)) return "invalid";153	const expected = Buffer.from(mac(db, `form:${time}:${cookie}`));154	const given = Buffer.from(signature);155	if (given.length !== expected.length || !timingSafeEqual(given, expected)) return "invalid";156	const age = now - Number(time);157	if (age > STAMP_MAX_AGE || age < 0) return "invalid";158	return age < MIN_SECONDS_ON_PAGE ? "too-fast" : "ok";159}