spam.ts

2.3 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 MAX_CHARS = 20_000;13const FORM_COOKIE = "kepr_form";14const HEX = /^[0-9a-f]{32,64}$/;1516/** One random key, made on first use and kept in kepr.db, for the IP hash and the form stamps. */17function secret(db: Database): string {18	db.query("INSERT OR IGNORE INTO settings (key, value) VALUES ('issue_secret', ?)").run(19		randomBytes(32).toString("hex"),20	);21	return setting(db, "issue_secret") as string;22}2324function mac(db: Database, message: string): string {25	return createHmac("sha256", secret(db)).update(message).digest("hex");26}2728/** A keyed hash, so the stored value can't be reversed by hashing every IPv4 address. */29export function ipHash(db: Database, c: Context): string {30	return mac(db, `ip:${clientIp(c)}`);31}3233/**34 * SameSite=Strict so a cross-site post arrives without it, and a form stamp35 * `<unix time>.<HMAC(time, cookie)>`.36 */37export function formStamp(db: Database, c: Context, now: number): string {38	let cookie = getCookie(c, FORM_COOKIE);39	if (!cookie || !HEX.test(cookie)) {40		cookie = randomBytes(16).toString("hex");41		setCookie(c, FORM_COOKIE, cookie, {42			httpOnly: true,43			secure: true,44			sameSite: "Strict",45			path: "/",46		});47	}48	return `${now}.${mac(db, `form:${now}:${cookie}`)}`;49}5051export type StampCheck = "ok" | "invalid" | "too-fast";5253export function checkStamp(db: Database, c: Context, stamp: string, now: number): StampCheck {54	const cookie = getCookie(c, FORM_COOKIE);55	const [time, signature] = stamp.split(".");56	if (!cookie || !time || !signature || !/^\d{1,12}$/.test(time)) return "invalid";57	const expected = Buffer.from(mac(db, `form:${time}:${cookie}`));58	const given = Buffer.from(signature);59	if (given.length !== expected.length || !timingSafeEqual(given, expected)) return "invalid";60	const age = now - Number(time);61	if (age > STAMP_MAX_AGE || age < 0) return "invalid";62	return age < MIN_SECONDS_ON_PAGE ? "too-fast" : "ok";63}