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";91011const ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";12const CODE_SECONDS = 600;1314export const MACHINES_LISTED = 20;151617export function oneTimeCode(): string {18 19 return Array.from({ length: 8 }, () => ALPHABET[randomBytes(1)[0] % ALPHABET.length]).join("");20}212223export 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;293031const NO_CODE = '{"error":"no_code","message":"no code"}';323334const attempts = attemptLimiter(ATTEMPT_WINDOW_MS, ATTEMPTS_PER_ADDRESS);35const ipKey = randomBytes(32);36const sha256 = (value: string) => createHash("sha256").update(value).digest("hex");373839export function connectKeys(40 config: Config,41): { accessKeyId: string; secretAccessKey: string } | null {42 return config.bucket.kind === "s3" ? config.bucket : null;43}444546function 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 51 52 if (/[\p{C}\p{Zl}\p{Zp}]/u.test(value)) return null;53 return value;54}555657export 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}636465export function registerConnect(app: Hono, config: Config, ctx: PageContext): void {66 app.get("/connect", (c) => {67 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 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 120 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 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 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}