login.ts

5.8 KB · raw

1import { createHash, randomBytes, timingSafeEqual } from "node:crypto";2import type { Context, Hono } from "hono";3import { deleteCookie, getCookie, setCookie } from "hono/cookie";4import { html } from "../pages/html.ts";5import { type PageContext, page } from "../pages/layout.ts";6import { clientIp } from "./client.ts";78const SESSION_SECONDS = 30 * 86400;9const SESSION_COOKIE = "kepr_session";10const SIGN_IN_COOKIE = "kepr_sign_in";11const COOKIE = { httpOnly: true, secure: true, sameSite: "Strict", path: "/" } as const;12const HEX64 = /^[0-9a-f]{64}$/;13const FAILURE_WINDOW_MS = 15 * 60 * 1000;14const FAILURES_PER_ADDRESS = 5;1516// Failed sign-ins, oldest first, in memory: a restart forgets them, but an attacker can't cause one.17const failures: { at: number; address: string }[] = [];18// Addresses are keyed hashes even in memory, as issue filings store them (§23).19const addressKey = randomBytes(32);2021const nowSeconds = () => Math.floor(Date.now() / 1000);22const sha256 = (text: string) => createHash("sha256").update(text).digest("hex");2324function sameText(a: string, b: string): boolean {25	const [x, y] = [Buffer.from(a), Buffer.from(b)];26	return x.length === y.length && timingSafeEqual(x, y);27}2829/** The session cookie's token when it names a live session in kepr.db, else null. */30function sessionToken(ctx: PageContext, c: Context): string | null {31	const token = getCookie(c, SESSION_COOKIE);32	if (!token || !HEX64.test(token)) return null;33	const row = ctx.kepr34		.query<{ n: number }, [string, number]>(35			"SELECT 1 AS n FROM sessions WHERE token_hash = ? AND expires_at > ?",36		)37		.get(sha256(token), nowSeconds());38	return row ? token : null;39}4041/**42 * The same-site token every admin form carries (§25): derived from the session's secret token, so43 * a page on another site can neither read nor guess it, and it dies with the session.44 */45export function formToken(c: Context): string {46	return sha256(`form:${getCookie(c, SESSION_COOKIE) ?? ""}`);47}4849/**50 * §24's login at the unlinked `/sign-in`, sessions, sign-out, and the guard in front of every51 * `/admin` route: a live session, and for anything but GET a matching `Origin` and form token.52 */53export function registerLogin(app: Hono, ctx: PageContext, passwordHash: string): void {54	const origin = `https://${ctx.domain}`;55	const refuse = (c: Context, status: 401 | 403 | 429, text: string) => {56		c.header("Cache-Control", "no-store");57		const body = html`<h1 class="file-page-title">${text}</h1>`;58		return c.html(page(ctx, { title: "admin", description: "", path: c.req.path, body }), status);59	};6061	app.use("/admin/*", async (c, next) => {62		const token = sessionToken(ctx, c);63		if (!token) return refuse(c, 401, "Sign in first.");64		if (c.req.method !== "GET") {65			if (c.req.header("origin") !== origin) return refuse(c, 403, "Refused: wrong origin.");66			const form = (await c.req.parseBody()).form;67			if (typeof form !== "string" || !sameText(form, formToken(c))) {68				return refuse(c, 403, "Refused: this form expired. Reload and try again.");69			}70		}71		await next();72		c.header("Cache-Control", "no-store");73	});7475	app.get("/sign-in", (c) => signInPage(c, ctx, "", 200));7677	app.post("/sign-in", async (c) => {78		const fields = await c.req.parseBody();79		const cookie = getCookie(c, SIGN_IN_COOKIE) ?? "";80		const form = typeof fields.form === "string" ? fields.form : "";81		if (c.req.header("origin") !== origin || !HEX64.test(cookie) || !sameText(form, cookie)) {82			return refuse(c, 403, "Refused: this form expired. Reload and try again.");83		}84		const now = Date.now();85		while (failures[0] && failures[0].at <= now - FAILURE_WINDOW_MS) failures.shift();86		const address = createHash("sha256").update(addressKey).update(clientIp(c)).digest("hex");87		const mine = failures.filter((failure) => failure.address === address).length;88		if (mine >= FAILURES_PER_ADDRESS) {89			c.header("Retry-After", String(FAILURE_WINDOW_MS / 1000));90			return signInPage(c, ctx, "Too many attempts. Try again later.", 429);91		}92		const password = typeof fields.password === "string" ? fields.password : "";93		if (!(await Bun.password.verify(password, passwordHash))) {94			failures.push({ at: now, address });95			return signInPage(c, ctx, "That password is not right.", 401);96		}97		const token = randomBytes(32).toString("hex");98		const at = nowSeconds();99		ctx.kepr.query("DELETE FROM sessions WHERE expires_at <= ?").run(at);100		ctx.kepr101			.query("INSERT INTO sessions (token_hash, expires_at) VALUES (?, ?)")102			.run(sha256(token), at + SESSION_SECONDS);103		setCookie(c, SESSION_COOKIE, token, { ...COOKIE, maxAge: SESSION_SECONDS });104		deleteCookie(c, SIGN_IN_COOKIE, COOKIE);105		return c.redirect("/admin", 303);106	});107108	app.post("/admin/sign-out", (c) => {109		ctx.kepr110			.query("DELETE FROM sessions WHERE token_hash = ?")111			.run(sha256(getCookie(c, SESSION_COOKIE) ?? ""));112		deleteCookie(c, SESSION_COOKIE, COOKIE);113		return c.redirect("/", 303);114	});115}116117// A double-submit token repeats a SameSite=Strict cookie that a cross-site post never has.118function signInPage(c: Context, ctx: PageContext, error: string, status: 200 | 401 | 429) {119	let cookie = getCookie(c, SIGN_IN_COOKIE) ?? "";120	if (!HEX64.test(cookie)) {121		cookie = randomBytes(32).toString("hex");122		setCookie(c, SIGN_IN_COOKIE, cookie, COOKIE);123	}124	c.header("Cache-Control", "no-store");125	const body = html`<h1 class="file-page-title">sign in</h1>126${error && html`<p class="issues-error mono" role="alert">${error}</p>`}127<form class="issues-form" method="post" action="/sign-in">128<input type="hidden" name="form" value="${cookie}">129<label class="issues-label" for="password">password</label>130<input class="issues-input" id="password" name="password" type="password" required autocomplete="current-password" autofocus>131<button class="issues-submit" type="submit">sign in</button>132</form>`;133	return c.html(page(ctx, { title: "sign in", description: "", path: "/sign-in", body }), status);134}