1import type { Context, Hono } from "hono";2import { checkS3Access, openBucket } from "../bucket/reader.ts";3import { html } from "../pages/html.ts";4import { type BucketSource, saveConfig } from "../server/config.ts";5import { type AdminContext, adminPage, formField, notice, textFields } from "./console.ts";67type S3Source = Extract<BucketSource, { kind: "s3" }>;8910const SHOWN: [key: string, label: string][] = [11 ["endpoint", "endpoint"],12 ["name", "bucket name"],13 ["region", "region"],14 ["access_key_id", "read access key ID"],15 ["write_access_key_id", "write access key ID"],16];17const REQUIRED = new Set(["endpoint", "name", "region", "access_key_id"]);1819const UNPRINTABLE = /[\s\p{C}]/u;202122function candidate(fields: Record<string, string>, current: S3Source): S3Source | string {23 const value = (key: string) => (fields[key] ?? "").trim();24 for (const [key, label] of SHOWN) {25 if (REQUIRED.has(key) && value(key) === "") return `The ${label} is required.`;26 if (UNPRINTABLE.test(fields[key] ?? ""))27 return `The ${label} cannot contain spaces or control characters.`;28 }29 for (const key of ["secret_access_key", "write_secret_access_key"]) {30 if (UNPRINTABLE.test(value(key)))31 return "A secret cannot contain spaces or control characters.";32 }33 const endpoint = value("endpoint");34 if (!URL.canParse(endpoint) || !/^https?:$/.test(new URL(endpoint).protocol))35 return "The endpoint must be an http or https URL.";36 const source: S3Source = {37 kind: "s3",38 endpoint,39 name: value("name"),40 region: value("region"),41 accessKeyId: value("access_key_id"),42 secretAccessKey: value("secret_access_key") || current.secretAccessKey,43 };44 if (value("write_access_key_id") === "") return source;45 const writeSecret = value("write_secret_access_key") || current.write?.secretAccessKey;46 if (!writeSecret) return "A new write key needs its secret.";47 return {48 ...source,49 write: { accessKeyId: value("write_access_key_id"), secretAccessKey: writeSecret },50 };51}525354export function registerBucket(app: Hono, ctx: AdminContext): void {55 app.get("/admin/bucket", (c) => c.html(bucketPage(c, ctx)));5657 app.post("/admin/bucket", async (c) => {58 const current = ctx.config.bucket;59 if (current.kind !== "s3") return c.html(bucketPage(c, ctx), 400);60 const fields = await textFields(c);61 const next = candidate(fields, current);62 if (typeof next === "string") return c.html(bucketPage(c, ctx, { fields, error: next }), 400);63 const failure = await checkS3Access(next);64 if (failure) return c.html(bucketPage(c, ctx, { fields, error: failure }), 400);65 if (fields.action !== "save") {66 return c.html(bucketPage(c, ctx, { fields, status: "Connection works. Nothing was saved." }));67 }68 try {69 await saveConfig(ctx.configPath, { ...ctx.config, bucket: next });70 } catch (error) {71 const reason = error instanceof Error ? error.message : String(error);72 const failed = `The settings work, but kepr.toml could not be written: ${reason}`;73 return c.html(bucketPage(c, ctx, { fields, error: failed }), 500);74 }75 76 ctx.config.bucket = next;77 Object.assign(ctx.sync.bucket, openBucket(next));78 return c.redirect("/admin/bucket?saved=1", 303);79 });80}8182function bucketPage(83 c: Context,84 ctx: AdminContext,85 shown: { fields?: Record<string, string>; error?: string; status?: string } = {},86): string {87 const source = ctx.config.bucket;88 if (source.kind === "folder") {89 const body = html`<p class="admin-intro">This instance reads a Koh folder remote at90<span class="mono">${source.path}</span>.</p>91<p class="muted">A folder remote is set in kepr.toml only.</p>`;92 return adminPage(c, ctx, "bucket", body);93 }94 const stored: Record<string, string> = {95 endpoint: source.endpoint,96 name: source.name,97 region: source.region,98 access_key_id: source.accessKeyId,99 write_access_key_id: source.write?.accessKeyId ?? "",100 };101 const value = (key: string) => shown.fields?.[key] ?? stored[key] ?? "";102 const input = ([key, label]: (typeof SHOWN)[number]) =>103 html`<label class="issues-label" for="${key}">${label}</label>104<input class="issues-input mono" id="${key}" name="${key}" value="${value(key)}"105autocomplete="off" spellcheck="false">`;106 const secret = (key: string, label: string, hint: string) =>107 html`<label class="issues-label" for="${key}">${label}</label>108<input class="issues-input mono" id="${key}" name="${key}" type="password"109autocomplete="new-password" placeholder="${hint}">`;110 const body = html`${notice(shown.error ?? "")}111${shown.status && html`<p class="admin-notice" role="status">${shown.status}</p>`}112<p class="admin-intro">The S3 bucket Kepr reads with its read-only key. Secrets are never shown.</p>113<form class="issues-form" method="post" action="/admin/bucket">114${formField(c)}115${SHOWN.slice(0, 4).map(input)}116${secret("secret_access_key", "read secret key", "unchanged")}117${input(SHOWN[4] as (typeof SHOWN)[number])}118${secret("write_secret_access_key", "write secret key", source.write ? "unchanged" : "")}119<p class="muted">The write key is optional: it signs machines in (/connect). Clear its ID to turn that120off. Saving tests the settings first and rewrites kepr.toml without its comments.</p>121<div class="issues-actions">122<button class="issues-submit" type="submit" name="action" value="test">test connection</button>123<button class="issues-submit" type="submit" name="action" value="save">save</button>124</div>125</form>`;126 return adminPage(c, ctx, "bucket", body);127}