login.ts

10.1 KB · raw

1import { createHash, randomBytes, timingSafeEqual } from "node:crypto";2import type { Context, Hono } from "hono";3import { deleteCookie, getCookie, setCookie } from "hono/cookie";4import { attemptLimiter, limitKey } from "../issues/spam.ts";5import { html } from "../pages/html.ts";6import { type PageContext, page } from "../pages/layout.ts";7import { clientIp } from "./client.ts";8import { keepState, setting } from "./db.ts";9import { DIGITS, stepFor } from "./totp.ts";1011const SESSION_SECONDS = 30 * 86400;12const SESSION_COOKIE = "kepr_session";13const SIGN_IN_COOKIE = "kepr_sign_in";14// Readable by kepr.js, and saying only that someone signed in here: public pages stay the same15// cacheable HTML for everyone, and the script asks the admin routes for the editing controls.16const EDITOR_COOKIE = "kepr_editor";17const COOKIE = { httpOnly: true, secure: true, sameSite: "Strict", path: "/" } as const;18const HEX64 = /^[0-9a-f]{64}$/;19const FAILURE_WINDOW_MS = 15 * 60 * 1000;20const FAILURES_PER_ADDRESS = 5;21// Failed sign-ins site-wide per UTC day: a per-address bucket leaves a bot with a /64 unlimited.22const FAILURES_PER_DAY = 100;2324// Failed sign-ins are held per address in memory: a restart forgets them, but an attacker can't25// cause one. Addresses are keyed hashes even in memory, as issue filings store them (§23).26const failures = attemptLimiter(FAILURE_WINDOW_MS, FAILURES_PER_ADDRESS, FAILURES_PER_DAY);27const ipKey = randomBytes(32);2829const nowSeconds = () => Math.floor(Date.now() / 1000);30const sha256 = (text: string) => createHash("sha256").update(text).digest("hex");3132function sameText(a: string, b: string): boolean {33	const [x, y] = [Buffer.from(a), Buffer.from(b)];34	return x.length === y.length && timingSafeEqual(x, y);35}3637/** The session cookie's token when it names a live session in kepr.db, else null. */38function sessionToken(ctx: PageContext, c: Context): string | null {39	const token = getCookie(c, SESSION_COOKIE);40	if (!token || !HEX64.test(token)) return null;41	const row = ctx.kepr42		.query<{ n: number }, [string, number]>(43			"SELECT 1 AS n FROM sessions WHERE token_hash = ? AND expires_at > ?",44		)45		.get(sha256(token), nowSeconds());46	return row ? token : null;47}4849export function signedIn(ctx: PageContext, c: Context): boolean {50	return sessionToken(ctx, c) !== null;51}5253/** How many sessions are live, this one included. */54export function liveSessions(ctx: PageContext): number {55	return (56		ctx.kepr57			.query<{ n: number }, [number]>("SELECT COUNT(*) AS n FROM sessions WHERE expires_at > ?")58			.get(nowSeconds())?.n ?? 059	);60}6162/** Revokes every session but the one making this request. */63export function endOtherSessions(ctx: PageContext, c: Context): void {64	const token = sessionToken(ctx, c) ?? "";65	ctx.kepr.query("DELETE FROM sessions WHERE token_hash != ?").run(sha256(token));66}6768/**69 * Whether a request came from this site. A localhost domain also accepts plain http, since a70 * local run has no TLS in front of it; browsers keep Secure cookies on http://localhost.71 */72function fromSite(c: Context, domain: string): boolean {73	const origin = c.req.header("origin");74	if (origin === `https://${domain}`) return true;75	return origin === `http://${domain}` && /^localhost(:\d+)?$/.test(domain);76}7778export async function adminPostRefusal(ctx: PageContext, c: Context): Promise<string> {79	if (!fromSite(c, ctx.domain)) return "Refused: wrong origin.";80	const form = (await c.req.parseBody()).form;81	return typeof form !== "string" || !sameText(form, formToken(c))82		? "Refused: this form expired. Reload and try again."83		: "";84}8586/**87 * The same-site token every admin form carries (§25): derived from the session's secret token, so88 * a page on another site can neither read nor guess it, and it dies with the session.89 */90export function formToken(c: Context): string {91	return formTokenOf(getCookie(c, SESSION_COOKIE) ?? "");92}9394function formTokenOf(session: string): string {95	return sha256(`form:${session}`);96}9798// The readable mark beside the session: its form token, so the navbar can offer log out without99// asking the server (nav.js). Readable by the site's own scripts only, as any page's form is.100function setEditorCookie(c: Context, session: string): void {101	setCookie(c, EDITOR_COOKIE, formTokenOf(session), {102		...COOKIE,103		httpOnly: false,104		maxAge: SESSION_SECONDS,105	});106}107108/**109 * The refusal page behind every admin entry point, `/connect` included: one answer for a missing110 * session, a foreign origin, an expired form token or too many attempts, wherever it arrives.111 */112export function adminRefusal(113	c: Context,114	ctx: PageContext,115	status: 401 | 403 | 429,116	text: string,117): Response {118	c.header("Cache-Control", "no-store");119	const body = html`<h1 class="file-page-title">${text}</h1>`;120	return c.html(page(ctx, { title: "admin", description: "", path: c.req.path, body }), status);121}122123/**124 * §24's login at `/sign-in`, sessions, sign-out, and the guard in front of every125 * `/admin` route: a live session, and for anything but GET a matching `Origin` and form token.126 */127export function registerLogin(128	app: Hono,129	ctx: PageContext,130	// The live config, so a password or a two-step secret changed in the console works at once.131	config: { adminPasswordHash: string; totpSecret?: string },132): void {133	const refuse = (c: Context, status: 401 | 403 | 429, text: string) =>134		adminRefusal(c, ctx, status, text);135	const asksCode = () => (config.totpSecret ?? "") !== "";136137	app.use("/admin/*", async (c, next) => {138		const token = sessionToken(ctx, c);139		if (!token) return refuse(c, 401, "Sign in first.");140		// A mark set before it carried the token is brought up to date.141		if (getCookie(c, EDITOR_COOKIE) !== formTokenOf(token)) setEditorCookie(c, token);142		if (c.req.method !== "GET") {143			const error = await adminPostRefusal(ctx, c);144			if (error) return refuse(c, 403, error);145		}146		await next();147		c.header("Cache-Control", "no-store");148	});149150	app.get("/sign-in", (c) =>151		signInPage(c, ctx, "", 200, nextPath(c.req.query("next")), asksCode()),152	);153154	app.post("/sign-in", async (c) => {155		const fields = await c.req.parseBody();156		const next = nextPath(fields.next);157		const cookie = getCookie(c, SIGN_IN_COOKIE) ?? "";158		const form = typeof fields.form === "string" ? fields.form : "";159		if (!fromSite(c, ctx.domain) || !HEX64.test(cookie) || !sameText(form, cookie)) {160			return refuse(c, 403, "Refused: this form expired. Reload and try again.");161		}162		const now = Date.now();163		const address = createHash("sha256")164			.update(ipKey)165			.update(limitKey(clientIp(c)))166			.digest("hex");167		if (!failures.allowed(address, now)) {168			c.header("Retry-After", String(FAILURE_WINDOW_MS / 1000));169			return signInPage(c, ctx, "Too many attempts. Try again later.", 429, next, asksCode());170		}171		const password = typeof fields.password === "string" ? fields.password : "";172		const passwordOk = await Bun.password.verify(password, config.adminPasswordHash);173		// With two-step sign-in on, one refusal covers both, so no page says which was wrong (§24).174		const wrong = asksCode()175			? "That password and code did not match."176			: "That password is not right.";177		const refused = () => {178			failures.note(address, now);179			return signInPage(c, ctx, wrong, 401, next, asksCode());180		};181		if (!passwordOk) return refused();182		if (asksCode()) {183			const code = typeof fields.code === "string" ? fields.code.trim() : "";184			const step = stepFor(config.totpSecret ?? "", code, nowSeconds());185			const used = Number(setting(ctx.kepr, "totp_step") ?? -1);186			if (step === null || step <= used) return refused();187			// The step is remembered, so a code that has signed in once cannot sign in again (§24).188			keepState(ctx.kepr, "totp_step", String(step));189		}190		const token = randomBytes(32).toString("hex");191		const at = nowSeconds();192		ctx.kepr.query("DELETE FROM sessions WHERE expires_at <= ?").run(at);193		ctx.kepr194			.query("INSERT INTO sessions (token_hash, expires_at) VALUES (?, ?)")195			.run(sha256(token), at + SESSION_SECONDS);196		setCookie(c, SESSION_COOKIE, token, { ...COOKIE, maxAge: SESSION_SECONDS });197		setEditorCookie(c, token);198		deleteCookie(c, SIGN_IN_COOKIE, COOKIE);199		return c.redirect(next, 303);200	});201202	app.post("/admin/sign-out", (c) => {203		ctx.kepr204			.query("DELETE FROM sessions WHERE token_hash = ?")205			.run(sha256(getCookie(c, SESSION_COOKIE) ?? ""));206		deleteCookie(c, SESSION_COOKIE, COOKIE);207		deleteCookie(c, EDITOR_COOKIE, { ...COOKIE, httpOnly: false });208		return c.redirect("/", 303);209	});210}211212/**213 * Where a sign-in goes on to: a path on this site, or `/admin`. `//host` and `/\host` are other214 * sites to a browser, and a control character could split the Location header.215 */216function nextPath(value: unknown): string {217	if (typeof value !== "string" || !value.startsWith("/")) return "/admin";218	if (value.startsWith("//") || value.startsWith("/\\")) return "/admin";219	if ([...value].some((char) => char.charCodeAt(0) <= 31 || char.charCodeAt(0) === 127))220		return "/admin";221	return value;222}223224// A double-submit token repeats a SameSite=Strict cookie that a cross-site post never has.225function signInPage(226	c: Context,227	ctx: PageContext,228	error: string,229	status: 200 | 401 | 429,230	next: string,231	code: boolean,232) {233	let cookie = getCookie(c, SIGN_IN_COOKIE) ?? "";234	if (!HEX64.test(cookie)) {235		cookie = randomBytes(32).toString("hex");236		setCookie(c, SIGN_IN_COOKIE, cookie, COOKIE);237	}238	c.header("Cache-Control", "no-store");239	const body = html`<h1 class="file-page-title">sign in</h1>240${error && html`<p class="issues-error mono" role="alert">${error}</p>`}241<form class="issues-form" method="post" action="/sign-in">242<input type="hidden" name="form" value="${cookie}">243<input type="hidden" name="next" value="${next}">244<label class="issues-label" for="password">password</label>245<input class="issues-input" id="password" name="password" type="password" required autocomplete="current-password"${code ? "" : html` autofocus`}>246${247	code &&248	html`<label class="issues-label" for="code">code from your authenticator app</label>249<input class="issues-input mono" id="code" name="code" inputmode="numeric" autocomplete="one-time-code"250pattern="[0-9]{${DIGITS}}" required autofocus>`251}252<button class="issues-submit" type="submit">sign in</button>253</form>`;254	return c.html(page(ctx, { title: "sign in", description: "", path: "/sign-in", body }), status);255}