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";789export 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}$/;16171819const secrets = new WeakMap<Database, string>();202122function 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 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}414243export function ipHash(db: Database, c: Context): string {44 return mac(db, `ip:${limitKey(clientIp(c))}`);45}464748495051export 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 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 65 return groups66 .slice(0, 4)67 .map((group) => Number.parseInt(group, 16).toString(16))68 .join(":");69}7071727374757677export 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 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 101 note(key: string, now: number): void {102 roll(now);103 today++;104 seen.set(key, [...(seen.get(key) ?? []), now]);105 },106 };107}108109110111112113114export 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}128129130131132133export 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}