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;151617const failures: { at: number; address: string }[] = [];1819const 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}282930function 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}4041export function signedIn(ctx: PageContext, c: Context): boolean {42 return sessionToken(ctx, c) !== null;43}4445export async function adminPostRefusal(ctx: PageContext, c: Context): Promise<string> {46 if (c.req.header("origin") !== `https://${ctx.domain}`) return "Refused: wrong origin.";47 const form = (await c.req.parseBody()).form;48 return typeof form !== "string" || !sameText(form, formToken(c))49 ? "Refused: this form expired. Reload and try again."50 : "";51}525354555657export function formToken(c: Context): string {58 return sha256(`form:${getCookie(c, SESSION_COOKIE) ?? ""}`);59}606162636465export function adminRefusal(66 c: Context,67 ctx: PageContext,68 status: 401 | 403 | 429,69 text: string,70): Response {71 c.header("Cache-Control", "no-store");72 const body = html`<h1 class="file-page-title">${text}</h1>`;73 return c.html(page(ctx, { title: "admin", description: "", path: c.req.path, body }), status);74}757677787980export function registerLogin(app: Hono, ctx: PageContext, passwordHash: string): void {81 const origin = `https://${ctx.domain}`;82 const refuse = (c: Context, status: 401 | 403 | 429, text: string) =>83 adminRefusal(c, ctx, status, text);8485 app.use("/admin/*", async (c, next) => {86 const token = sessionToken(ctx, c);87 if (!token) return refuse(c, 401, "Sign in first.");88 if (c.req.method !== "GET") {89 const error = await adminPostRefusal(ctx, c);90 if (error) return refuse(c, 403, error);91 }92 await next();93 c.header("Cache-Control", "no-store");94 });9596 app.get("/sign-in", (c) => signInPage(c, ctx, "", 200, nextPath(c.req.query("next"))));9798 app.post("/sign-in", async (c) => {99 const fields = await c.req.parseBody();100 const next = nextPath(fields.next);101 const cookie = getCookie(c, SIGN_IN_COOKIE) ?? "";102 const form = typeof fields.form === "string" ? fields.form : "";103 if (c.req.header("origin") !== origin || !HEX64.test(cookie) || !sameText(form, cookie)) {104 return refuse(c, 403, "Refused: this form expired. Reload and try again.");105 }106 const now = Date.now();107 while (failures[0] && failures[0].at <= now - FAILURE_WINDOW_MS) failures.shift();108 const address = createHash("sha256").update(addressKey).update(clientIp(c)).digest("hex");109 const mine = failures.filter((failure) => failure.address === address).length;110 if (mine >= FAILURES_PER_ADDRESS) {111 c.header("Retry-After", String(FAILURE_WINDOW_MS / 1000));112 return signInPage(c, ctx, "Too many attempts. Try again later.", 429, next);113 }114 const password = typeof fields.password === "string" ? fields.password : "";115 if (!(await Bun.password.verify(password, passwordHash))) {116 failures.push({ at: now, address });117 return signInPage(c, ctx, "That password is not right.", 401, next);118 }119 const token = randomBytes(32).toString("hex");120 const at = nowSeconds();121 ctx.kepr.query("DELETE FROM sessions WHERE expires_at <= ?").run(at);122 ctx.kepr123 .query("INSERT INTO sessions (token_hash, expires_at) VALUES (?, ?)")124 .run(sha256(token), at + SESSION_SECONDS);125 setCookie(c, SESSION_COOKIE, token, { ...COOKIE, maxAge: SESSION_SECONDS });126 deleteCookie(c, SIGN_IN_COOKIE, COOKIE);127 return c.redirect(next, 303);128 });129130 app.post("/admin/sign-out", (c) => {131 ctx.kepr132 .query("DELETE FROM sessions WHERE token_hash = ?")133 .run(sha256(getCookie(c, SESSION_COOKIE) ?? ""));134 deleteCookie(c, SESSION_COOKIE, COOKIE);135 return c.redirect("/", 303);136 });137}138139140141142143function nextPath(value: unknown): string {144 if (typeof value !== "string" || !value.startsWith("/")) return "/admin";145 if (value.startsWith("//") || value.startsWith("/\\")) return "/admin";146 if ([...value].some((char) => char.charCodeAt(0) <= 31 || char.charCodeAt(0) === 127))147 return "/admin";148 return value;149}150151152function signInPage(153 c: Context,154 ctx: PageContext,155 error: string,156 status: 200 | 401 | 429,157 next: string,158) {159 let cookie = getCookie(c, SIGN_IN_COOKIE) ?? "";160 if (!HEX64.test(cookie)) {161 cookie = randomBytes(32).toString("hex");162 setCookie(c, SIGN_IN_COOKIE, cookie, COOKIE);163 }164 c.header("Cache-Control", "no-store");165 const body = html`<h1 class="file-page-title">sign in</h1>166${error && html`<p class="issues-error mono" role="alert">${error}</p>`}167<form class="issues-form" method="post" action="/sign-in">168<input type="hidden" name="form" value="${cookie}">169<input type="hidden" name="next" value="${next}">170<label class="issues-label" for="password">password</label>171<input class="issues-input" id="password" name="password" type="password" required autocomplete="current-password" autofocus>172<button class="issues-submit" type="submit">sign in</button>173</form>`;174 return c.html(page(ctx, { title: "sign in", description: "", path: "/sign-in", body }), status);175}