spam.ts

5.5 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/** One random key, made on first use and kept in kepr.db, for the IP hash and the form stamps. */18function 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}2425function mac(db: Database, message: string): string {26	return createHmac("sha256", secret(db)).update(message).digest("hex");27}2829/** A keyed hash, so the stored value can't be reversed by hashing every IPv4 address. */30export function ipHash(db: Database, c: Context): string {31	return mac(db, `ip:${limitKey(clientIp(c))}`);32}3334/**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 */38export 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}5758/**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 */64export 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	};94}9596/**97 * What a follower's confirm and stop links carry (§23): only their inbox ever sees it. The98 * address is covered too, so a link whose row is gone cannot reach a later follower that reuses99 * the id — `issue_followers.id` is a rowid, and SQLite hands a deleted row's id back out.100 */101export function followToken(db: Database, followerId: number, email: string): string {102	return mac(db, `follow:${followerId}:${email.toLowerCase()}`);103}104105export function followTokenMatches(106	db: Database,107	followerId: number,108	email: string,109	token: string,110): boolean {111	const expected = Buffer.from(followToken(db, followerId, email));112	const given = Buffer.from(token);113	return given.length === expected.length && timingSafeEqual(given, expected);114}115116/**117 * SameSite=Strict so a cross-site post arrives without it, and a form stamp118 * `<unix time>.<HMAC(time, cookie)>`.119 */120export function formStamp(db: Database, c: Context, now: number): string {121	let cookie = getCookie(c, FORM_COOKIE);122	if (!cookie || !HEX.test(cookie)) {123		cookie = randomBytes(16).toString("hex");124		setCookie(c, FORM_COOKIE, cookie, {125			httpOnly: true,126			secure: true,127			sameSite: "Strict",128			path: "/",129		});130	}131	return `${now}.${mac(db, `form:${now}:${cookie}`)}`;132}133134export type StampCheck = "ok" | "invalid" | "too-fast";135136export function checkStamp(db: Database, c: Context, stamp: string, now: number): StampCheck {137	const cookie = getCookie(c, FORM_COOKIE);138	const [time, signature] = stamp.split(".");139	if (!cookie || !time || !signature || !/^\d{1,12}$/.test(time)) return "invalid";140	const expected = Buffer.from(mac(db, `form:${time}:${cookie}`));141	const given = Buffer.from(signature);142	if (given.length !== expected.length || !timingSafeEqual(given, expected)) return "invalid";143	const age = now - Number(time);144	if (age > STAMP_MAX_AGE || age < 0) return "invalid";145	return age < MIN_SECONDS_ON_PAGE ? "too-fast" : "ok";146}