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}$/;161718function 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}282930export function ipHash(db: Database, c: Context): string {31 return mac(db, `ip:${limitKey(clientIp(c))}`);32}333435363738export 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 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 52 return groups53 .slice(0, 4)54 .map((group) => Number.parseInt(group, 16).toString(16))55 .join(":");56}5758596061626364export 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 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 88 note(key: string, now: number): void {89 roll(now);90 today++;91 seen.set(key, [...(seen.get(key) ?? []), now]);92 },93 };94}9596979899100101export 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}115116117118119120export 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}