1import { createHash, randomBytes } from "node:crypto";2import type { Context, Hono } from "hono";3import { html } from "../pages/html.ts";4import { type PageContext, page } from "../pages/layout.ts";5import { clientIp } from "./client.ts";6import type { Config } from "./config.ts";7import { adminPostRefusal, adminRefusal, formToken, signedIn } from "./login.ts";8910const ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";11const CODE_SECONDS = 600;1213export const MACHINES_LISTED = 20;14const ATTEMPTS_PER_ADDRESS = 10;15const ATTEMPT_WINDOW_MS = 3600000;161718const NO_CODE = '{"error":"no_code","message":"no code"}';1920let attempts: { at: number; address: string }[] = [];2122const attemptKey = randomBytes(32);23const sha256 = (value: string) => createHash("sha256").update(value).digest("hex");242526export function connectKeys(27 config: Config,28): { accessKeyId: string; secretAccessKey: string } | null {29 return config.bucket.kind === "s3" && config.bucket.write ? config.bucket.write : null;30}313233function machineName(value: unknown): string | null {34 if (typeof value !== "string") return null;35 const characters = [...value];36 if (characters.length === 0 || characters.length > 64) return null;37 38 39 if (/[\p{C}\p{Zl}\p{Zp}]/u.test(value)) return null;40 return value;41}424344export function noCode(c: Context): Response {45 return c.body(NO_CODE, 404, {46 "Content-Type": "application/json; charset=UTF-8",47 "Cache-Control": "no-store",48 });49}505152export function registerConnect(app: Hono, config: Config, ctx: PageContext): void {53 const bucket = config.bucket.kind === "s3" ? config.bucket : null;54 const write = bucket?.write ?? null;5556 app.get("/connect", (c) => {57 58 if (!write) return c.notFound();59 c.header("Cache-Control", "no-store");60 const machine = machineName(c.req.query("machine"));61 if (!signedIn(ctx, c)) {62 const back = machine ? `/connect?machine=${encodeURIComponent(machine)}` : "/connect";63 return c.redirect(`/sign-in?next=${encodeURIComponent(back)}`, 302);64 }65 if (!machine)66 return c.text("a machine name of 64 printable characters or fewer is required", 400);67 const body = html`<h1 class="file-page-title">Connect <b>${machine}</b> to your bucket?</h1>68<p class="muted">That machine is handed the bucket key, once.</p>69<form class="issues-form" method="post" action="/connect">70<input type="hidden" name="machine" value="${machine}">71<input type="hidden" name="form" value="${formToken(c)}">72<button class="issues-submit" type="submit">connect</button>73</form>`;74 return c.html(page(ctx, { title: "connect", description: "", path: c.req.path, body }));75 });7677 app.post("/connect", async (c) => {78 if (!write) return c.notFound();79 c.header("Cache-Control", "no-store");80 81 if (!signedIn(ctx, c)) return adminRefusal(c, ctx, 401, "Sign in first.");82 const refusal = await adminPostRefusal(ctx, c);83 if (refusal) return adminRefusal(c, ctx, 403, refusal);84 const machine = machineName((await c.req.parseBody()).machine);85 if (!machine)86 return c.text("a machine name of 64 printable characters or fewer is required", 400);87 const now = Math.floor(Date.now() / 1000);88 ctx.kepr.query("DELETE FROM connect_codes WHERE used_at IS NULL AND expires_at <= ?").run(now);89 90 const code = Array.from(91 { length: 8 },92 () => ALPHABET[randomBytes(1)[0] % ALPHABET.length],93 ).join("");94 ctx.kepr95 .query(96 "INSERT INTO connect_codes (code_hash, machine, created_at, expires_at) VALUES (?, ?, ?, ?)",97 )98 .run(sha256(code), machine, now, now + CODE_SECONDS);99 const body = html`<h1 class="file-page-title">Connect <b>${machine}</b></h1>100<p>Type this code on that machine, within ten minutes. It is shown once.</p>101<p class="mono code">${code.slice(0, 4)}-${code.slice(4)}</p>`;102 return c.html(page(ctx, { title: "connect", description: "", path: c.req.path, body }));103 });104105 app.post("/api/connect", async (c) => {106 if (!write || !bucket) return c.notFound();107 c.header("Cache-Control", "no-store");108 const now = Date.now();109 110 111 attempts = attempts.filter((attempt) => attempt.at > now - ATTEMPT_WINDOW_MS);112 const address = createHash("sha256").update(attemptKey).update(clientIp(c)).digest("hex");113 const used = attempts.filter((attempt) => attempt.address === address).length;114 115 116 if (used >= ATTEMPTS_PER_ADDRESS) return noCode(c);117 attempts.push({ at: now, address });118 let code = "";119 try {120 const fields = await c.req.parseBody();121 code = typeof fields.code === "string" ? fields.code : "";122 } catch {123 return noCode(c);124 }125 const submitted = code.trim().replaceAll("-", "").toUpperCase();126 if (submitted.length !== 8 || [...submitted].some((char) => !ALPHABET.includes(char)))127 return noCode(c);128 const at = Math.floor(now / 1000);129 130 const redeemed = ctx.kepr131 .query(132 `UPDATE connect_codes SET used_at = ?133 WHERE code_hash = ?134 AND used_at IS NULL135 AND expires_at > ?`,136 )137 .run(at, sha256(submitted), at);138 if (redeemed.changes !== 1) return noCode(c);139 ctx.kepr140 .query(141 `DELETE FROM connect_codes142 WHERE used_at IS NOT NULL143 AND code_hash NOT IN (144 SELECT code_hash FROM connect_codes145 WHERE used_at IS NOT NULL146 ORDER BY used_at DESC, rowid DESC147 LIMIT ?148 )`,149 )150 .run(MACHINES_LISTED);151 return c.json({152 endpoint: bucket.endpoint,153 bucket: bucket.name,154 region: bucket.region,155 access_key_id: write.accessKeyId,156 secret_access_key: write.secretAccessKey,157 });158 });159}