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}474849505152function fromSite(c: Context, domain: string): boolean {53 const origin = c.req.header("origin");54 if (origin === `https://${domain}`) return true;55 return origin === `http://${domain}` && /^localhost(:\d+)?$/.test(domain);56}5758export async function adminPostRefusal(ctx: PageContext, c: Context): Promise<string> {59 if (!fromSite(c, ctx.domain)) return "Refused: wrong origin.";60 const form = (await c.req.parseBody()).form;61 return typeof form !== "string" || !sameText(form, formToken(c))62 ? "Refused: this form expired. Reload and try again."63 : "";64}656667686970export function formToken(c: Context): string {71 return sha256(`form:${getCookie(c, SESSION_COOKIE) ?? ""}`);72}737475767778export function adminRefusal(79 c: Context,80 ctx: PageContext,81 status: 401 | 403 | 429,82 text: string,83): Response {84 c.header("Cache-Control", "no-store");85 const body = html`<h1 class="file-page-title">${text}</h1>`;86 return c.html(page(ctx, { title: "admin", description: "", path: c.req.path, body }), status);87}888990919293export function registerLogin(app: Hono, ctx: PageContext, passwordHash: string): void {94 const refuse = (c: Context, status: 401 | 403 | 429, text: string) =>95 adminRefusal(c, ctx, status, text);9697 app.use("/admin/*", async (c, next) => {98 const token = sessionToken(ctx, c);99 if (!token) return refuse(c, 401, "Sign in first.");100 if (c.req.method !== "GET") {101 const error = await adminPostRefusal(ctx, c);102 if (error) return refuse(c, 403, error);103 }104 await next();105 c.header("Cache-Control", "no-store");106 });107108 app.get("/sign-in", (c) => signInPage(c, ctx, "", 200, nextPath(c.req.query("next"))));109110 app.post("/sign-in", async (c) => {111 const fields = await c.req.parseBody();112 const next = nextPath(fields.next);113 const cookie = getCookie(c, SIGN_IN_COOKIE) ?? "";114 const form = typeof fields.form === "string" ? fields.form : "";115 if (!fromSite(c, ctx.domain) || !HEX64.test(cookie) || !sameText(form, cookie)) {116 return refuse(c, 403, "Refused: this form expired. Reload and try again.");117 }118 const now = Date.now();119 while (failures[0] && failures[0].at <= now - FAILURE_WINDOW_MS) failures.shift();120 const address = createHash("sha256").update(addressKey).update(clientIp(c)).digest("hex");121 const mine = failures.filter((failure) => failure.address === address).length;122 if (mine >= FAILURES_PER_ADDRESS) {123 c.header("Retry-After", String(FAILURE_WINDOW_MS / 1000));124 return signInPage(c, ctx, "Too many attempts. Try again later.", 429, next);125 }126 const password = typeof fields.password === "string" ? fields.password : "";127 if (!(await Bun.password.verify(password, passwordHash))) {128 failures.push({ at: now, address });129 return signInPage(c, ctx, "That password is not right.", 401, next);130 }131 const token = randomBytes(32).toString("hex");132 const at = nowSeconds();133 ctx.kepr.query("DELETE FROM sessions WHERE expires_at <= ?").run(at);134 ctx.kepr135 .query("INSERT INTO sessions (token_hash, expires_at) VALUES (?, ?)")136 .run(sha256(token), at + SESSION_SECONDS);137 setCookie(c, SESSION_COOKIE, token, { ...COOKIE, maxAge: SESSION_SECONDS });138 setCookie(c, EDITOR_COOKIE, "1", { ...COOKIE, httpOnly: false, maxAge: SESSION_SECONDS });139 deleteCookie(c, SIGN_IN_COOKIE, COOKIE);140 return c.redirect(next, 303);141 });142143 app.post("/admin/sign-out", (c) => {144 ctx.kepr145 .query("DELETE FROM sessions WHERE token_hash = ?")146 .run(sha256(getCookie(c, SESSION_COOKIE) ?? ""));147 deleteCookie(c, SESSION_COOKIE, COOKIE);148 deleteCookie(c, EDITOR_COOKIE, { ...COOKIE, httpOnly: false });149 return c.redirect("/", 303);150 });151}152153154155156157function nextPath(value: unknown): string {158 if (typeof value !== "string" || !value.startsWith("/")) return "/admin";159 if (value.startsWith("//") || value.startsWith("/\\")) return "/admin";160 if ([...value].some((char) => char.charCodeAt(0) <= 31 || char.charCodeAt(0) === 127))161 return "/admin";162 return value;163}164165166function signInPage(167 c: Context,168 ctx: PageContext,169 error: string,170 status: 200 | 401 | 429,171 next: string,172) {173 let cookie = getCookie(c, SIGN_IN_COOKIE) ?? "";174 if (!HEX64.test(cookie)) {175 cookie = randomBytes(32).toString("hex");176 setCookie(c, SIGN_IN_COOKIE, cookie, COOKIE);177 }178 c.header("Cache-Control", "no-store");179 const body = html`<h1 class="file-page-title">sign in</h1>180${error && html`<p class="issues-error mono" role="alert">${error}</p>`}181<form class="issues-form" method="post" action="/sign-in">182<input type="hidden" name="form" value="${cookie}">183<input type="hidden" name="next" value="${next}">184<label class="issues-label" for="password">password</label>185<input class="issues-input" id="password" name="password" type="password" required autocomplete="current-password" autofocus>186<button class="issues-submit" type="submit">sign in</button>187</form>`;188 return c.html(page(ctx, { title: "sign in", description: "", path: "/sign-in", body }), status);189}