login.ts

10.0 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// A hint for kepr.js to ask the admin routes for editing controls; it does not authorize requests.15const EDITOR_COOKIE = "kepr_editor";16const COOKIE = { httpOnly: true, secure: true, sameSite: "Strict", path: "/" } as const;17const HEX64 = /^[0-9a-f]{64}$/;18const FAILURE_WINDOW_MS = 15 * 60 * 1000;19const FAILURES_PER_ADDRESS = 5;20// Failed sign-ins site-wide per UTC day: a per-address bucket leaves a bot with a /64 unlimited.21const FAILURES_PER_DAY = 100;2223// Failed sign-ins are held per address in memory: a restart forgets them, but an attacker can't24// cause one. Addresses are keyed hashes even in memory, as issue filings store them (§23).25const failures = attemptLimiter(FAILURE_WINDOW_MS, FAILURES_PER_ADDRESS, FAILURES_PER_DAY);26const ipKey = randomBytes(32);2728const nowSeconds = () => Math.floor(Date.now() / 1000);29const sha256 = (text: string) => createHash("sha256").update(text).digest("hex");3031function sameText(a: string, b: string): boolean {32	const [x, y] = [Buffer.from(a), Buffer.from(b)];33	return x.length === y.length && timingSafeEqual(x, y);34}3536/** The session cookie's token when it names a live session in kepr.db, else null. */37function sessionToken(ctx: PageContext, c: Context): string | null {38	const token = getCookie(c, SESSION_COOKIE);39	if (!token || !HEX64.test(token)) return null;40	const row = ctx.kepr41		.query<{ n: number }, [string, number]>(42			"SELECT 1 AS n FROM sessions WHERE token_hash = ? AND expires_at > ?",43		)44		.get(sha256(token), nowSeconds());45	return row ? token : null;46}4748export function signedIn(ctx: PageContext, c: Context): boolean {49	return sessionToken(ctx, c) !== null;50}5152/** How many sessions are live, this one included. */53export function liveSessions(ctx: PageContext): number {54	return (55		ctx.kepr56			.query<{ n: number }, [number]>("SELECT COUNT(*) AS n FROM sessions WHERE expires_at > ?")57			.get(nowSeconds())?.n ?? 058	);59}6061/** Revokes every session but the one making this request. */62export function endOtherSessions(ctx: PageContext, c: Context): void {63	const token = sessionToken(ctx, c) ?? "";64	ctx.kepr.query("DELETE FROM sessions WHERE token_hash != ?").run(sha256(token));65}6667/**68 * Whether a request came from this site. A localhost domain also accepts plain http, since a69 * local run has no TLS in front of it; browsers keep Secure cookies on http://localhost.70 */71function fromSite(c: Context, domain: string): boolean {72	const origin = c.req.header("origin");73	if (origin === `https://${domain}`) return true;74	return origin === `http://${domain}` && /^localhost(:\d+)?$/.test(domain);75}7677export async function adminPostRefusal(ctx: PageContext, c: Context): Promise<string> {78	if (!fromSite(c, ctx.domain)) return "Refused: wrong origin.";79	const form = (await c.req.parseBody()).form;80	return typeof form !== "string" || !sameText(form, formToken(c))81		? "Refused: this form expired. Reload and try again."82		: "";83}8485/**86 * The same-site token every admin form carries (§25): derived from the session's secret token, so87 * a page on another site can neither read nor guess it, and it dies with the session.88 */89export function formToken(c: Context): string {90	return formTokenOf(getCookie(c, SESSION_COOKIE) ?? "");91}9293function formTokenOf(session: string): string {94	return sha256(`form:${session}`);95}9697// The readable mark beside the session: its form token, so the navbar can offer log out without98// asking the server (nav.js). Readable by the site's own scripts only, as any page's form is.99function setEditorCookie(c: Context, session: string): void {100	setCookie(c, EDITOR_COOKIE, formTokenOf(session), {101		...COOKIE,102		httpOnly: false,103		maxAge: SESSION_SECONDS,104	});105}106107/**108 * The refusal page behind every admin entry point, `/connect` included: one answer for a missing109 * session, a foreign origin, an expired form token or too many attempts, wherever it arrives.110 */111export function adminRefusal(112	c: Context,113	ctx: PageContext,114	status: 401 | 403 | 429,115	text: string,116): Response {117	c.header("Cache-Control", "no-store");118	const body = html`<h1 class="file-page-title">${text}</h1>`;119	return c.html(page(ctx, { title: "admin", description: "", path: c.req.path, body }), status);120}121122/**123 * §24's login at `/sign-in`, sessions, sign-out, and the guard in front of every124 * `/admin` route: a live session, and for anything but GET a matching `Origin` and form token.125 */126export function registerLogin(127	app: Hono,128	ctx: PageContext,129	// The live config, so a password or a two-step secret changed in the console works at once.130	config: { adminPasswordHash: string; totpSecret?: string },131): void {132	const refuse = (c: Context, status: 401 | 403 | 429, text: string) =>133		adminRefusal(c, ctx, status, text);134	const asksCode = () => (config.totpSecret ?? "") !== "";135136	app.use("/admin/*", async (c, next) => {137		const token = sessionToken(ctx, c);138		if (!token) return refuse(c, 401, "Sign in first.");139		// A mark set before it carried the token is brought up to date.140		if (getCookie(c, EDITOR_COOKIE) !== formTokenOf(token)) setEditorCookie(c, token);141		if (c.req.method !== "GET") {142			const error = await adminPostRefusal(ctx, c);143			if (error) return refuse(c, 403, error);144		}145		await next();146		c.header("Cache-Control", "no-store");147	});148149	app.get("/sign-in", (c) =>150		signInPage(c, ctx, "", 200, nextPath(c.req.query("next")), asksCode()),151	);152153	app.post("/sign-in", async (c) => {154		const fields = await c.req.parseBody();155		const next = nextPath(fields.next);156		const cookie = getCookie(c, SIGN_IN_COOKIE) ?? "";157		const form = typeof fields.form === "string" ? fields.form : "";158		if (!fromSite(c, ctx.domain) || !HEX64.test(cookie) || !sameText(form, cookie)) {159			return refuse(c, 403, "Refused: this form expired. Reload and try again.");160		}161		const now = Date.now();162		const address = createHash("sha256")163			.update(ipKey)164			.update(limitKey(clientIp(c)))165			.digest("hex");166		if (!failures.allowed(address, now)) {167			c.header("Retry-After", String(FAILURE_WINDOW_MS / 1000));168			return signInPage(c, ctx, "Too many attempts. Try again later.", 429, next, asksCode());169		}170		const password = typeof fields.password === "string" ? fields.password : "";171		const passwordOk = await Bun.password.verify(password, config.adminPasswordHash);172		// With two-step sign-in on, one refusal covers both, so no page says which was wrong (§24).173		const wrong = asksCode()174			? "That password and code did not match."175			: "That password is not right.";176		const refused = () => {177			failures.note(address, now);178			return signInPage(c, ctx, wrong, 401, next, asksCode());179		};180		if (!passwordOk) return refused();181		if (asksCode()) {182			const code = typeof fields.code === "string" ? fields.code.trim() : "";183			const step = stepFor(config.totpSecret ?? "", code, nowSeconds());184			const used = Number(setting(ctx.kepr, "totp_step") ?? -1);185			if (step === null || step <= used) return refused();186			// The step is remembered, so a code that has signed in once cannot sign in again (§24).187			keepState(ctx.kepr, "totp_step", String(step));188		}189		const token = randomBytes(32).toString("hex");190		const at = nowSeconds();191		ctx.kepr.query("DELETE FROM sessions WHERE expires_at <= ?").run(at);192		ctx.kepr193			.query("INSERT INTO sessions (token_hash, expires_at) VALUES (?, ?)")194			.run(sha256(token), at + SESSION_SECONDS);195		setCookie(c, SESSION_COOKIE, token, { ...COOKIE, maxAge: SESSION_SECONDS });196		setEditorCookie(c, token);197		deleteCookie(c, SIGN_IN_COOKIE, COOKIE);198		return c.redirect(next, 303);199	});200201	app.post("/admin/sign-out", (c) => {202		ctx.kepr203			.query("DELETE FROM sessions WHERE token_hash = ?")204			.run(sha256(getCookie(c, SESSION_COOKIE) ?? ""));205		deleteCookie(c, SESSION_COOKIE, COOKIE);206		deleteCookie(c, EDITOR_COOKIE, { ...COOKIE, httpOnly: false });207		return c.redirect("/", 303);208	});209}210211/**212 * Where a sign-in goes on to: a path on this site, or `/admin`. `//host` and `/\host` are other213 * sites to a browser, and a control character could split the Location header.214 */215function nextPath(value: unknown): string {216	if (typeof value !== "string" || !value.startsWith("/")) return "/admin";217	if (value.startsWith("//") || value.startsWith("/\\")) return "/admin";218	if ([...value].some((char) => char.charCodeAt(0) <= 31 || char.charCodeAt(0) === 127))219		return "/admin";220	return value;221}222223// A double-submit token repeats a SameSite=Strict cookie that a cross-site post never has.224function signInPage(225	c: Context,226	ctx: PageContext,227	error: string,228	status: 200 | 401 | 429,229	next: string,230	code: boolean,231) {232	let cookie = getCookie(c, SIGN_IN_COOKIE) ?? "";233	if (!HEX64.test(cookie)) {234		cookie = randomBytes(32).toString("hex");235		setCookie(c, SIGN_IN_COOKIE, cookie, COOKIE);236	}237	c.header("Cache-Control", "no-store");238	const body = html`<h1 class="file-page-title">sign in</h1>239${error && html`<p class="issues-error mono" role="alert">${error}</p>`}240<form class="issues-form" method="post" action="/sign-in">241<input type="hidden" name="form" value="${cookie}">242<input type="hidden" name="next" value="${next}">243<label class="issues-label" for="password">password</label>244<input class="issues-input" id="password" name="password" type="password" required autocomplete="current-password"${code ? "" : html` autofocus`}>245${246	code &&247	html`<label class="issues-label" for="code">code from your authenticator app</label>248<input class="issues-input mono" id="code" name="code" inputmode="numeric" autocomplete="one-time-code"249pattern="[0-9]{${DIGITS}}" required autofocus>`250}251<button class="issues-submit" type="submit">sign in</button>252</form>`;253	return c.html(page(ctx, { title: "sign in", description: "", path: "/sign-in", body }), status);254}