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";111213const EDITOR_COOKIE = "kepr_editor";14const COOKIE = { httpOnly: true, secure: true, sameSite: "Strict", path: "/" } as const;15const HEX64 = /^[0-9a-f]{64}$/;16const FAILURE_WINDOW_MS = 15 * 60 * 1000;17const FAILURES_PER_ADDRESS = 5;181920const failures: { at: number; address: string }[] = [];2122const addressKey = randomBytes(32);2324const nowSeconds = () => Math.floor(Date.now() / 1000);25const sha256 = (text: string) => createHash("sha256").update(text).digest("hex");2627function sameText(a: string, b: string): boolean {28 const [x, y] = [Buffer.from(a), Buffer.from(b)];29 return x.length === y.length && timingSafeEqual(x, y);30}313233function sessionToken(ctx: PageContext, c: Context): string | null {34 const token = getCookie(c, SESSION_COOKIE);35 if (!token || !HEX64.test(token)) return null;36 const row = ctx.kepr37 .query<{ n: number }, [string, number]>(38 "SELECT 1 AS n FROM sessions WHERE token_hash = ? AND expires_at > ?",39 )40 .get(sha256(token), nowSeconds());41 return row ? token : null;42}4344export function signedIn(ctx: PageContext, c: Context): boolean {45 return sessionToken(ctx, c) !== null;46}4748export async function adminPostRefusal(ctx: PageContext, c: Context): Promise<string> {49 if (c.req.header("origin") !== `https://${ctx.domain}`) return "Refused: wrong origin.";50 const form = (await c.req.parseBody()).form;51 return typeof form !== "string" || !sameText(form, formToken(c))52 ? "Refused: this form expired. Reload and try again."53 : "";54}555657585960export function formToken(c: Context): string {61 return sha256(`form:${getCookie(c, SESSION_COOKIE) ?? ""}`);62}636465666768export function adminRefusal(69 c: Context,70 ctx: PageContext,71 status: 401 | 403 | 429,72 text: string,73): Response {74 c.header("Cache-Control", "no-store");75 const body = html`<h1 class="file-page-title">${text}</h1>`;76 return c.html(page(ctx, { title: "admin", description: "", path: c.req.path, body }), status);77}787980818283export function registerLogin(app: Hono, ctx: PageContext, passwordHash: string): void {84 const origin = `https://${ctx.domain}`;85 const refuse = (c: Context, status: 401 | 403 | 429, text: string) =>86 adminRefusal(c, ctx, status, text);8788 app.use("/admin/*", async (c, next) => {89 const token = sessionToken(ctx, c);90 if (!token) return refuse(c, 401, "Sign in first.");91 if (c.req.method !== "GET") {92 const error = await adminPostRefusal(ctx, c);93 if (error) return refuse(c, 403, error);94 }95 await next();96 c.header("Cache-Control", "no-store");97 });9899 app.get("/sign-in", (c) => signInPage(c, ctx, "", 200, nextPath(c.req.query("next"))));100101 app.post("/sign-in", async (c) => {102 const fields = await c.req.parseBody();103 const next = nextPath(fields.next);104 const cookie = getCookie(c, SIGN_IN_COOKIE) ?? "";105 const form = typeof fields.form === "string" ? fields.form : "";106 if (c.req.header("origin") !== origin || !HEX64.test(cookie) || !sameText(form, cookie)) {107 return refuse(c, 403, "Refused: this form expired. Reload and try again.");108 }109 const now = Date.now();110 while (failures[0] && failures[0].at <= now - FAILURE_WINDOW_MS) failures.shift();111 const address = createHash("sha256").update(addressKey).update(clientIp(c)).digest("hex");112 const mine = failures.filter((failure) => failure.address === address).length;113 if (mine >= FAILURES_PER_ADDRESS) {114 c.header("Retry-After", String(FAILURE_WINDOW_MS / 1000));115 return signInPage(c, ctx, "Too many attempts. Try again later.", 429, next);116 }117 const password = typeof fields.password === "string" ? fields.password : "";118 if (!(await Bun.password.verify(password, passwordHash))) {119 failures.push({ at: now, address });120 return signInPage(c, ctx, "That password is not right.", 401, next);121 }122 const token = randomBytes(32).toString("hex");123 const at = nowSeconds();124 ctx.kepr.query("DELETE FROM sessions WHERE expires_at <= ?").run(at);125 ctx.kepr126 .query("INSERT INTO sessions (token_hash, expires_at) VALUES (?, ?)")127 .run(sha256(token), at + SESSION_SECONDS);128 setCookie(c, SESSION_COOKIE, token, { ...COOKIE, maxAge: SESSION_SECONDS });129 setCookie(c, EDITOR_COOKIE, "1", { ...COOKIE, httpOnly: false, maxAge: SESSION_SECONDS });130 deleteCookie(c, SIGN_IN_COOKIE, COOKIE);131 return c.redirect(next, 303);132 });133134 app.post("/admin/sign-out", (c) => {135 ctx.kepr136 .query("DELETE FROM sessions WHERE token_hash = ?")137 .run(sha256(getCookie(c, SESSION_COOKIE) ?? ""));138 deleteCookie(c, SESSION_COOKIE, COOKIE);139 deleteCookie(c, EDITOR_COOKIE, { ...COOKIE, httpOnly: false });140 return c.redirect("/", 303);141 });142}143144145146147148function nextPath(value: unknown): string {149 if (typeof value !== "string" || !value.startsWith("/")) return "/admin";150 if (value.startsWith("//") || value.startsWith("/\\")) return "/admin";151 if ([...value].some((char) => char.charCodeAt(0) <= 31 || char.charCodeAt(0) === 127))152 return "/admin";153 return value;154}155156157function signInPage(158 c: Context,159 ctx: PageContext,160 error: string,161 status: 200 | 401 | 429,162 next: string,163) {164 let cookie = getCookie(c, SIGN_IN_COOKIE) ?? "";165 if (!HEX64.test(cookie)) {166 cookie = randomBytes(32).toString("hex");167 setCookie(c, SIGN_IN_COOKIE, cookie, COOKIE);168 }169 c.header("Cache-Control", "no-store");170 const body = html`<h1 class="file-page-title">sign in</h1>171${error && html`<p class="issues-error mono" role="alert">${error}</p>`}172<form class="issues-form" method="post" action="/sign-in">173<input type="hidden" name="form" value="${cookie}">174<input type="hidden" name="next" value="${next}">175<label class="issues-label" for="password">password</label>176<input class="issues-input" id="password" name="password" type="password" required autocomplete="current-password" autofocus>177<button class="issues-submit" type="submit">sign in</button>178</form>`;179 return c.html(page(ctx, { title: "sign in", description: "", path: "/sign-in", body }), status);180}