connect.ts

7.1 KB · raw

1import { createHash, randomBytes } from "node:crypto";2import type { Context, Hono } from "hono";3import { attemptLimiter, limitKey } from "../issues/spam.ts";4import { html } from "../pages/html.ts";5import { type PageContext, page } from "../pages/layout.ts";6import { clientIp } from "./client.ts";7import type { Config } from "./config.ts";8import { adminPostRefusal, adminRefusal, formToken, signedIn } from "./login.ts";910// No I, O, 0 or 1: a code is read off a screen and typed into another machine.11const ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";12const CODE_SECONDS = 600;13/** How many redeemed codes the status page lists, and so how many kepr.db keeps. */14export const MACHINES_LISTED = 20;1516/** Eight characters from an alphabet with no look-alikes, shown as `ABCD-EFGH`. */17export function oneTimeCode(): string {18	// 32 characters into a byte is even, so every character is equally likely.19	return Array.from({ length: 8 }, () => ALPHABET[randomBytes(1)[0] % ALPHABET.length]).join("");20}2122/** A code as typed, dash and case aside, or null when it can't be one. */23export function typedCode(typed: string): string | null {24	const code = typed.trim().replaceAll("-", "").toUpperCase();25	return code.length === 8 && [...code].every((char) => ALPHABET.includes(char)) ? code : null;26}27const ATTEMPTS_PER_ADDRESS = 10;28const ATTEMPT_WINDOW_MS = 3600000;29// One body for every failure — unknown, expired, used, malformed and rate-limited alike — so a30// caller learns nothing but "no code".31const NO_CODE = '{"error":"no_code","message":"no code"}';32// Failed codes per address, in memory: a restart forgets them, but an attacker can't cause one.33// Addresses are keyed hashes even in memory, as issue filings store them (§23).34const attempts = attemptLimiter(ATTEMPT_WINDOW_MS, ATTEMPTS_PER_ADDRESS);35const ipKey = randomBytes(32);36const sha256 = (value: string) => createHash("sha256").update(value).digest("hex");3738/** The S3 key a signed-in machine is handed, or null when Kepr hands out none. */39export function connectKeys(40	config: Config,41): { accessKeyId: string; secretAccessKey: string } | null {42	return config.bucket.kind === "s3" ? config.bucket : null;43}4445/** A machine name as it may be stored and shown: ≤64 characters, none of them a control code. */46function machineName(value: unknown): string | null {47	if (typeof value !== "string") return null;48	const characters = [...value];49	if (characters.length === 0 || characters.length > 64) return null;50	// `\p{C}` covers C0, DEL, C1 and the format codes, a bidi override among them that would reorder51	// the machines list. Letters outside ASCII stay: a machine is named in its owner's language.52	if (/[\p{C}\p{Zl}\p{Zp}]/u.test(value)) return null;53	return value;54}5556/** The one answer every failed redemption gets, whoever asked and however they failed. */57export function noCode(c: Context): Response {58	return c.body(NO_CODE, 404, {59		"Content-Type": "application/json; charset=UTF-8",60		"Cache-Control": "no-store",61	});62}6364/** §24's connect page and the one-time code it hands a machine, plus the API that redeems it. */65export function registerConnect(app: Hono, config: Config, ctx: PageContext): void {66	app.get("/connect", (c) => {67		// A disabled route is an unknown path, byte for byte, so nothing is set before this line.68		if (!connectKeys(config)) return c.notFound();69		c.header("Cache-Control", "no-store");70		const machine = machineName(c.req.query("machine"));71		if (!signedIn(ctx, c)) {72			const back = machine ? `/connect?machine=${encodeURIComponent(machine)}` : "/connect";73			return c.redirect(`/sign-in?next=${encodeURIComponent(back)}`, 302);74		}75		if (!machine)76			return c.text("a machine name of 64 printable characters or fewer is required", 400);77		const body = html`<h1 class="file-page-title">Connect <b>${machine}</b> to your bucket?</h1>78<p class="muted">That machine is handed the bucket key, once.</p>79<form class="issues-form" method="post" action="/connect">80<input type="hidden" name="machine" value="${machine}">81<input type="hidden" name="form" value="${formToken(c)}">82<button class="issues-submit" type="submit">connect</button>83</form>`;84		return c.html(page(ctx, { title: "connect", description: "", path: c.req.path, body }));85	});8687	app.post("/connect", async (c) => {88		if (!connectKeys(config)) return c.notFound();89		c.header("Cache-Control", "no-store");90		// As for every admin POST: a live session, the right origin and the same-site form token.91		if (!signedIn(ctx, c)) return adminRefusal(c, ctx, 401, "Sign in first.");92		const refusal = await adminPostRefusal(ctx, c);93		if (refusal) return adminRefusal(c, ctx, 403, refusal);94		const machine = machineName((await c.req.parseBody()).machine);95		if (!machine)96			return c.text("a machine name of 64 printable characters or fewer is required", 400);97		const now = Math.floor(Date.now() / 1000);98		ctx.kepr.query("DELETE FROM connect_codes WHERE used_at IS NULL AND expires_at <= ?").run(now);99		const code = oneTimeCode();100		ctx.kepr101			.query(102				"INSERT INTO connect_codes (code_hash, machine, created_at, expires_at) VALUES (?, ?, ?, ?)",103			)104			.run(sha256(code), machine, now, now + CODE_SECONDS);105		const body = html`<h1 class="file-page-title">Connect <b>${machine}</b></h1>106<p>Type this code on that machine, within ten minutes. It is shown once.</p>107<p class="mono code">${code.slice(0, 4)}-${code.slice(4)}</p>`;108		return c.html(page(ctx, { title: "connect", description: "", path: c.req.path, body }));109	});110111	app.post("/api/connect", async (c) => {112		if (!connectKeys(config)) return c.notFound();113		c.header("Cache-Control", "no-store");114		const now = Date.now();115		const address = createHash("sha256")116			.update(ipKey)117			.update(limitKey(clientIp(c)))118			.digest("hex");119		// A refused attempt is not recorded: that caps the list at ten entries per address, and keeps120		// hammering from moving the block out past the hour.121		if (!attempts.allowed(address, now)) return noCode(c);122		attempts.note(address, now);123		let code = "";124		try {125			const fields = await c.req.parseBody();126			code = typeof fields.code === "string" ? fields.code : "";127		} catch {128			return noCode(c);129		}130		const submitted = typedCode(code);131		if (!submitted) return noCode(c);132		const at = Math.floor(now / 1000);133		// Marked used in the same statement that proves it live, so one code is never redeemed twice.134		const redeemed = ctx.kepr135			.query(136				`UPDATE connect_codes SET used_at = ?137				 WHERE code_hash = ?138				 AND used_at IS NULL139				 AND expires_at > ?`,140			)141			.run(at, sha256(submitted), at);142		if (redeemed.changes !== 1) return noCode(c);143		ctx.kepr144			.query(145				`DELETE FROM connect_codes146				 WHERE used_at IS NOT NULL147				 AND code_hash NOT IN (148					SELECT code_hash FROM connect_codes149					WHERE used_at IS NOT NULL150					ORDER BY used_at DESC, rowid DESC151					LIMIT ?152				 )`,153			)154			.run(MACHINES_LISTED);155		// Read again after the awaits above: the console may have changed the keys meanwhile.156		const bucket = config.bucket.kind === "s3" ? config.bucket : null;157		if (!bucket) return noCode(c);158		return c.json({159			endpoint: bucket.endpoint,160			bucket: bucket.name,161			region: bucket.region,162			access_key_id: bucket.accessKeyId,163			secret_access_key: bucket.secretAccessKey,164		});165	});166}