diff --git a/README.md b/README.md index 3d2052c..157b2cc 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,13 @@ pnpm lint && pnpm format:check 线上首次部署、库中无账号时开放 setup:`POST /api/auth/setup`(header `X-Setup-Secret`)创建唯一所有者账号,创建后 setup 永久关闭,不设注册接口。响应在 `{ success, user, tablePrefix }` 之外附 `migrations: [{ name, status }]`(`applied` / `skipped`)。 +数据库升级/初始化也可走 setup 三件套(SPEC SETUP-PAGE-SPEC v1.0): +- `GET /api/setup/state`(无鉴权,`no-store`)→ `{enabled, ownerExists, tablePrefix}`;`GET /api/setup/status` 为同逻辑兼容别名。 +- `POST /api/setup`(header `X-Setup-Secret`,按 IP 每 10 分钟 3 次)→ **只跑账本迁移**,不建用户/不改密码/不删表;响应 `{success, tablePrefix, migrations, ownerExists}`,前缀冲突 409。 +- `POST /api/admin/setup`(会话鉴权、免密钥)、`GET /api/admin/system`、`PUT /api/admin/system/setup-page`:管理面「系统管理」的升级按钮与 setup 页面开关。 + +setup 页面开关存在 `{prefix}settings.setup_page_enabled`(`'1'` 开 / `'0'` 关,**默认关**:所有者创建成功即写入 `'0'`):未初始化时页面恒开;开关只门控页面,不门控两个密钥接口本身(密钥即门闩,避免把自己锁在门外)。 + ## 数据库迁移账本(schema ledger) schema 的唯一可信源是 `worker/src/lib/migrations.ts` 的 `getMigrations(prefix)` 迁移列表,执行由 `worker/src/lib/migrations-runner.ts` 的 `runMigrations(env)` 完成(setup 路由与读路径 `ensureSchema` 共用同一个 runner)。原 `worker/src/db/schema.sql` + `gen-schema.mjs` codegen 已删除,不再有第二份 schema 定义。 diff --git a/docs/api-contract.md b/docs/api-contract.md index f25c4e5..37dabdf 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -114,6 +114,21 @@ Passkey(WebAuthn,/api/auth/passkey/*,@simplewebauthn/server v14): - `GET /api/admin/settings` → `{siteTitle, backgroundUrl, theme, columns}` - `PUT /api/admin/settings` body 可含 `{siteTitle, backgroundUrl, theme(light|dark|system), columns(1–12)}` → 更新后对象 +`setup_page_enabled`(setup 页面开关)**不在**站点设置白名单内,也不出现在 `SiteSettingsDto` / `/api/public` 输出;它只走下面的系统管理端点。 + +### 系统管理(`/api/admin/setup`、`/api/admin/system*`,需会话) + +- `POST /api/admin/setup` → 免密钥跑账本迁移,响应形状与 `POST /api/setup` 完全一致(含 409 冲突形状) +- `GET /api/admin/system` → `{tablePrefix, setupPageEnabled, ledger}`(`ledger` 为账本已记录迁移名,按应用顺序) +- `PUT /api/admin/system/setup-page` body `{enabled: boolean}`(严格布尔,非布尔 400 `{"error":"enabled must be a boolean"}`)→ `{setupPageEnabled}` + +## Setup(`/api/setup/*`) + +- `GET /api/setup/state` → 无鉴权,`Cache-Control: no-store`,`{enabled, ownerExists, tablePrefix}`;不含任何密钥/哈希。`ownerExists` = `{prefix}users` 行数 > 0(表不存在按 `false`)。`enabled`:未初始化恒 `true`;已初始化时只有 `{prefix}settings.setup_page_enabled = '1'` 为开,缺省(无此行)与 `'0'` 均为关。 +- `GET /api/setup/status` → 同一逻辑/同一载荷的兼容别名(SPA 已迁到 `state`)。 +- `POST /api/setup` → header `X-Setup-Secret`(只走请求头,无 GET/查询参数形态);密钥缺失/占位符 → 500 `{"error":"server misconfigured"}`,不匹配 → 403;按来源 IP 每 10 分钟最多 3 次,超限 429(带 `Retry-After` 与 `retryAfterSeconds`)。动作只有账本迁移(不建用户、不改密码、不删表):200 `{success, tablePrefix, migrations:[{name,status}], ownerExists}`,前缀冲突 409 `{"error":"table prefix conflict","detail":…}`。 +- setup 页面开关**只门控页面**,不门控 `POST /api/setup` 与 `POST /api/auth/setup`(密钥即门闩)。 + ## 说明 - favicon 自动抓取不在后端做:前端直接请求目标站 / 公共 favicon 服务,失败回退首字圆;后端只存 `iconUrl` 字段。 diff --git a/worker/src/core/setup-rate-limit.ts b/worker/src/core/setup-rate-limit.ts new file mode 100644 index 0000000..51c5575 --- /dev/null +++ b/worker/src/core/setup-rate-limit.ts @@ -0,0 +1,91 @@ +import { recordAttempt } from "./login-attempts"; +import { generateId } from "./auth"; + +/** + * Setup-secret throttle (§3.2): at most 3 `POST /api/setup` attempts per source + * IP per 10 minutes → 429. + * + * Reuses the existing `{prefix}login_attempts` store instead of adding a table + * or a framework: rows are keyed by a reserved pseudo-username namespace, so + * they can never collide with a real account (`USERNAME_RE` forbids `:` and + * caps length at 64) and never affect login lockout counters. + * + * An uninitialised database has no `login_attempts` table yet, so the limiter + * falls back to a per-isolate in-memory window — brute force stays throttled + * before the first migration has ever run. + */ +export const SETUP_RATE_LIMIT_MAX = 3; +export const SETUP_RATE_LIMIT_WINDOW_SECONDS = 10 * 60; + +const WINDOW_MS = SETUP_RATE_LIMIT_WINDOW_SECONDS * 1000; +const SETUP_ATTEMPT_KEY_PREFIX = "__setup_rate__:"; +const MEMORY_MAX_IPS = 500; + +/** ip → attempt timestamps (ms), used only while the schema does not exist yet. */ +const memoryAttempts = new Map(); + +function attemptKey(ip: string): string { + return `${SETUP_ATTEMPT_KEY_PREFIX}${ip}`; +} + +function recentMemoryAttempts(ip: string, now: number): number[] { + const recent = (memoryAttempts.get(ip) ?? []).filter( + (at) => now - at < WINDOW_MS, + ); + if (recent.length > 0) memoryAttempts.set(ip, recent); + else memoryAttempts.delete(ip); + return recent; +} + +function pruneMemory(now: number): void { + if (memoryAttempts.size <= MEMORY_MAX_IPS) return; + for (const ip of [...memoryAttempts.keys()]) { + if (recentMemoryAttempts(ip, now).length === 0) { + memoryAttempts.delete(ip); + } + } +} + +/** True when this IP already spent its attempt budget for the window. */ +export async function isSetupRateLimited( + db: D1Database, + prefix: string, + ip: string, +): Promise { + const now = Date.now(); + try { + const since = new Date(now - WINDOW_MS).toISOString(); + const row = await db + .prepare( + `SELECT COUNT(*) AS n FROM ${prefix}login_attempts + WHERE username = ? AND created_at > ?`, + ) + .bind(attemptKey(ip), since) + .first<{ n: number }>(); + return (row?.n ?? 0) >= SETUP_RATE_LIMIT_MAX; + } catch { + return recentMemoryAttempts(ip, now).length >= SETUP_RATE_LIMIT_MAX; + } +} + +/** Counts one attempt against the IP's budget (best-effort, never throws). */ +export async function recordSetupAttempt( + db: D1Database, + prefix: string, + ip: string, +): Promise { + const now = Date.now(); + try { + await recordAttempt(db, prefix, { + id: generateId(), + username: attemptKey(ip), + ip, + success: true, + lockUntil: null, + }); + } catch { + // Uninitialised database: keep the window in memory for this isolate. + memoryAttempts.set(ip, [...recentMemoryAttempts(ip, now), now]); + pruneMemory(now); + } +} diff --git a/worker/src/index.ts b/worker/src/index.ts index f1c29ad..352bb3a 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -6,8 +6,9 @@ import { webauthnRoutes } from "./routes/passkey"; import { publicRoutes } from "./routes/public"; import { privateRoutes } from "./routes/private"; import { adminRoutes } from "./routes/admin"; +import { setupRoutes } from "./routes/setup"; import { getSetting } from "./db/queries/settings"; -import { countUsers, deleteExpiredSessions } from "./db/queries/users"; +import { deleteExpiredSessions } from "./db/queries/users"; const app = new Hono(); @@ -47,26 +48,14 @@ app.route("/api/auth/passkey", webauthnRoutes); app.route("/api/public", publicRoutes); app.route("/api/private", privateRoutes); app.route("/api/admin", adminRoutes); +// Setup surface: GET /api/setup/state (canonical), GET /api/setup/status +// (legacy alias), POST /api/setup (secret-gated upgrade — SETUP-PAGE-SPEC §3). +app.route("/api", setupRoutes); app.get("/api/health", (c) => c.json({ status: "ok", timestamp: new Date().toISOString() }), ); -/** - * GET /api/setup/status — the one endpoint the SPA calls before rendering. - * 200 { enabled: true } while the owner account does not exist yet. - */ -app.get("/api/setup/status", async (c) => { - const prefix = getTablePrefix(c.env); - try { - const users = await countUsers(c.env.DB, prefix); - return c.json({ enabled: users === 0 }); - } catch { - // Uninitialized DB: setup is open (migration runs on first setup call). - return c.json({ enabled: true }); - } -}); - app.get("/api/system/info", async (c) => { const prefix = getTablePrefix(c.env); try { diff --git a/worker/src/lib/migrations-runner.ts b/worker/src/lib/migrations-runner.ts index 85b3555..79daa7b 100644 --- a/worker/src/lib/migrations-runner.ts +++ b/worker/src/lib/migrations-runner.ts @@ -235,6 +235,25 @@ export async function applyMigrationList( return results; } +/** + * Migration names already recorded in the ledger, in application order. Read-only + * and tolerant of a not-yet-created ledger table (returns an empty list), so the + * admin system panel can always render. + */ +export async function listRecordedMigrations( + db: D1Database, + prefix: string, +): Promise { + try { + const { results } = await db + .prepare(`SELECT name FROM ${migrationsTable(prefix)} ORDER BY rowid`) + .all<{ name: string }>(); + return results.map((row) => row.name); + } catch { + return []; + } +} + /** * Resolves the effective prefix, guards against a silent prefix switch, then * applies every migration not yet recorded in the ledger. Throws diff --git a/worker/src/routes/admin.ts b/worker/src/routes/admin.ts index 03f7092..61eb8c5 100644 --- a/worker/src/routes/admin.ts +++ b/worker/src/routes/admin.ts @@ -26,9 +26,15 @@ import { updateSearchEngine, } from "../db/queries/content"; import { getAllSettings, setSetting } from "../db/queries/settings"; +import { listRecordedMigrations } from "../lib/migrations-runner"; import { generateId } from "../core/auth"; import type { Link } from "../types"; import { toSearchEngineDto, toSiteSettingsDto } from "../services/site-data"; +import { + getSetupPageEnabled, + runSetupMigrations, + setSetupPageEnabled, +} from "../services/setup"; export const adminRoutes = new Hono(); @@ -444,5 +450,37 @@ adminRoutes.put("/settings", async (c) => { adminRoutes.get("/settings/keys", (c) => c.json({ keys: SETTING_KEYS })); +// ─── System: database maintenance + setup page switch (SPEC §3.5) ──────────── + +/** + * POST /api/admin/setup — session-authenticated (no setup secret) upgrade. + * Payload and 409 conflict shape are identical to POST /api/setup. + */ +adminRoutes.post("/setup", async (c) => { + const outcome = await runSetupMigrations(c.env); + if (!outcome.ok) return c.json(outcome.body, outcome.status); + return c.json(outcome.body); +}); + +/** GET /api/admin/system — effective prefix, page switch, recorded ledger. */ +adminRoutes.get("/system", async (c) => { + const prefix = getTablePrefix(c.env); + const [ledger, setupPageEnabled] = await Promise.all([ + listRecordedMigrations(c.env.DB, prefix), + getSetupPageEnabled(c.env, prefix), + ]); + return c.json({ tablePrefix: prefix, setupPageEnabled, ledger }); +}); + +/** PUT /api/admin/system/setup-page — body `{enabled: boolean}` (strict). */ +adminRoutes.put("/system/setup-page", async (c) => { + const body = await c.req.json().catch(() => ({})); + if (typeof body?.enabled !== "boolean") + return badRequest("enabled must be a boolean"); + + await setSetupPageEnabled(c.env, body.enabled); + return c.json({ setupPageEnabled: body.enabled }); +}); + // Fallbacks kept intentionally strict: unknown admin routes are 404 JSON. adminRoutes.all("*", (c) => c.json({ error: "not found" }, 404)); diff --git a/worker/src/routes/auth.ts b/worker/src/routes/auth.ts index 12e60c9..1d04e09 100644 --- a/worker/src/routes/auth.ts +++ b/worker/src/routes/auth.ts @@ -37,6 +37,7 @@ import { putChallenge, } from "../core/challenges"; import { getSetting } from "../db/queries/settings"; +import { setSetupPageEnabled } from "../services/setup"; import { verifyTOTP } from "../core/totp"; import { SESSION_COOKIE, unauthorized } from "../middleware/auth"; import { issueSession, clientIp } from "../services/session"; @@ -118,6 +119,11 @@ authRoutes.post("/setup", async (c) => { const created = await findUserByUsername(c.env.DB, prefix, username); if (!created) return c.json({ error: "setup failed" }, 500); + // SETUP-PAGE-SPEC §3.4: completion closes the setup page by default (nav is a + // single-user site). Routine upgrades go through the admin button; the secret + // endpoints themselves stay reachable regardless of this switch. + await setSetupPageEnabled(c.env, false, prefix); + await issueSession(c, created.id); return c.json( { diff --git a/worker/src/routes/setup.ts b/worker/src/routes/setup.ts new file mode 100644 index 0000000..342a904 --- /dev/null +++ b/worker/src/routes/setup.ts @@ -0,0 +1,68 @@ +import { Hono, type Context } from "hono"; +import { getTablePrefix, type HonoEnv } from "../types"; +import { safeEqual } from "../core/auth"; +import { + isSetupRateLimited, + recordSetupAttempt, + SETUP_RATE_LIMIT_WINDOW_SECONDS, +} from "../core/setup-rate-limit"; +import { clientIp } from "../services/session"; +import { resolveSetupState, runSetupMigrations } from "../services/setup"; + +/** + * Setup surface (SETUP-PAGE-SPEC §3.1–§3.2). Mounted at `/api`, so: + * - `GET /api/setup/state` — canonical state endpoint (no auth, no-store) + * - `GET /api/setup/status` — legacy alias, identical payload/logic + * - `POST /api/setup` — secret-gated, migration-only upgrade endpoint + * + * The switch in §3.4 gates the PAGE only; it never gates these secret-gated + * endpoints (the secret is the latch), so a closed page can never deadlock + * recovery. + */ +export const setupRoutes = new Hono(); + +async function setupState(c: Context): Promise { + const state = await resolveSetupState(c.env); + c.header("Cache-Control", "no-store"); + return c.json(state); +} + +setupRoutes.get("/setup/state", setupState); + +// Deprecated alias kept for SPA compatibility; same logic, same payload. +setupRoutes.get("/setup/status", setupState); + +setupRoutes.post("/setup", async (c) => { + // The secret is a request header only — never URL/query (no GET variant). + const expected = c.env.SETUP_SECRET; + if (!expected || expected.endsWith("_PLACEHOLDER")) { + return c.json({ error: "server misconfigured" }, 500); + } + + const prefix = getTablePrefix(c.env); + const ip = clientIp(c); + + if (await isSetupRateLimited(c.env.DB, prefix, ip)) { + return c.json( + { + error: "too many setup attempts, try again later", + retryAfterSeconds: SETUP_RATE_LIMIT_WINDOW_SECONDS, + }, + 429, + { "Retry-After": String(SETUP_RATE_LIMIT_WINDOW_SECONDS) }, + ); + } + // Every attempt spends budget, including wrong secrets. + await recordSetupAttempt(c.env.DB, prefix, ip); + + const secret = c.req.header("X-Setup-Secret"); + if (!secret || !(await safeEqual(secret, expected))) { + return c.json({ error: "invalid setup secret" }, 403); + } + + // Forward-only, ledgered migrations only: no user created, no password + // changed, no table dropped. + const outcome = await runSetupMigrations(c.env); + if (!outcome.ok) return c.json(outcome.body, outcome.status); + return c.json(outcome.body); +}); diff --git a/worker/src/services/setup.ts b/worker/src/services/setup.ts new file mode 100644 index 0000000..e7c7cf0 --- /dev/null +++ b/worker/src/services/setup.ts @@ -0,0 +1,136 @@ +import { + getTablePrefix, + type Env, + type SetupMigrationDto, + type SetupResultDto, + type SetupStateDto, +} from "../types"; +import { countUsers } from "../db/queries/users"; +import { getSetting, setSetting } from "../db/queries/settings"; +import { applyMigrations } from "../lib/migrate"; +import { + TablePrefixConflictError, + type MigrationResult, +} from "../lib/migrations-runner"; + +/** + * Setup-page switch storage (SETUP-PAGE-SPEC §3.4): a single `{prefix}settings` + * key, `'1'` = page open, `'0'` = page closed. No table, no migration. + * + * This key must never reach the site-settings whitelist / SiteSettingsDto / + * `/api/public`; the only read/write surfaces are the two `/api/admin/system*` + * endpoints and the state endpoint below. + */ +export const SETUP_PAGE_ENABLED_KEY = "setup_page_enabled"; +export const SETUP_PAGE_ENABLED_ON = "1"; +/** nav is a single-user site: once the owner exists the page defaults to CLOSED. */ +export const SETUP_PAGE_ENABLED_OFF = "0"; + +/** + * `{prefix}users` row count, treating an unreadable/absent table as "no owner + * yet" (§3.1) instead of surfacing a database error on a public endpoint. + */ +async function safeCountUsers(env: Env, prefix: string): Promise { + try { + return await countUsers(env.DB, prefix); + } catch { + return 0; + } +} + +/** + * Whether the setup page may be rendered (§3.1): + * - uninitialised (`ownerExists === false`) → always `true`, so an empty + * database can never lock itself out; + * - initialised → only an explicit `'1'` opens the page; a missing key means + * the default, which for nav is OFF (§3.4). + */ +export async function getSetupPageEnabled( + env: Env, + prefix: string = getTablePrefix(env), +): Promise { + try { + return ( + (await getSetting(env.DB, prefix, SETUP_PAGE_ENABLED_KEY)) === + SETUP_PAGE_ENABLED_ON + ); + } catch { + // No settings table yet (uninitialised database) → default OFF. + return false; + } +} + +export async function setSetupPageEnabled( + env: Env, + enabled: boolean, + prefix: string = getTablePrefix(env), +): Promise { + await setSetting( + env.DB, + prefix, + SETUP_PAGE_ENABLED_KEY, + enabled ? SETUP_PAGE_ENABLED_ON : SETUP_PAGE_ENABLED_OFF, + ); +} + +/** Payload of `GET /api/setup/state` (and its `status` alias) — no secrets, no hashes. */ +export async function resolveSetupState(env: Env): Promise { + const tablePrefix = getTablePrefix(env); + const ownerExists = (await safeCountUsers(env, tablePrefix)) > 0; + + if (!ownerExists) return { enabled: true, ownerExists, tablePrefix }; + + return { + enabled: await getSetupPageEnabled(env, tablePrefix), + ownerExists, + tablePrefix, + }; +} + +export type SetupMigrationOutcome = + | { ok: true; body: SetupResultDto } + | { + ok: false; + status: 409; + body: { error: "table prefix conflict"; detail: string }; + }; + +/** + * Runs ONLY the ledgered migrations (forward-only, idempotent): no user is + * created, no password changed, no table dropped. Both setup endpoints share + * this so their payloads and their 409 conflict shape stay identical. + */ +export async function runSetupMigrations( + env: Env, +): Promise { + const tablePrefix = getTablePrefix(env); + let migrations: MigrationResult[]; + + try { + migrations = (await applyMigrations(env)).migrations; + } catch (err) { + if (err instanceof TablePrefixConflictError) { + return { + ok: false, + status: 409, + body: { error: "table prefix conflict", detail: err.message }, + }; + } + throw err; + } + + return { + ok: true, + body: { + success: true, + tablePrefix, + migrations: migrations.map( + (migration): SetupMigrationDto => ({ + name: migration.name, + status: migration.status, + }), + ), + ownerExists: (await safeCountUsers(env, tablePrefix)) > 0, + }, + }; +} diff --git a/worker/src/types.ts b/worker/src/types.ts index 65c1c50..c25587b 100644 --- a/worker/src/types.ts +++ b/worker/src/types.ts @@ -154,6 +154,35 @@ export interface SiteDataDto { settings: SiteSettingsDto; } +// ─── Setup DTOs (SETUP-PAGE-SPEC §3.1/§3.2/§3.5) ───────────────────────────── + +/** `GET /api/setup/state` (and its legacy `status` alias) — no secrets/hashes. */ +export interface SetupStateDto { + enabled: boolean; + ownerExists: boolean; + tablePrefix: string; +} + +export interface SetupMigrationDto { + name: string; + status: "applied" | "skipped" | "error"; +} + +/** `POST /api/setup` and `POST /api/admin/setup` (identical shape). */ +export interface SetupResultDto { + success: true; + tablePrefix: string; + migrations: SetupMigrationDto[]; + ownerExists: boolean; +} + +/** `GET /api/admin/system`. */ +export interface AdminSystemDto { + tablePrefix: string; + setupPageEnabled: boolean; + ledger: string[]; +} + export interface JWTPayload { typ: "access"; sub: string; diff --git a/worker/test/setup.test.ts b/worker/test/setup.test.ts new file mode 100644 index 0000000..2272d56 --- /dev/null +++ b/worker/test/setup.test.ts @@ -0,0 +1,523 @@ +import { describe, expect, it } from "vitest"; +import { Hono } from "hono"; +import worker from "../src/index"; +import { setupRoutes } from "../src/routes/setup"; +import { authRoutes } from "../src/routes/auth"; +import { publicRoutes } from "../src/routes/public"; +import { adminRoutes } from "../src/routes/admin"; +import { runMigrations } from "../src/lib/migrations-runner"; +import type { Env } from "../src/types"; +import { makeEnv, readJson, type SqliteD1 } from "./helpers"; + +const OWNER = { username: "owner", password: "correct horse battery" }; +/** helpers.makeEnv() default SETUP_SECRET. */ +const SECRET = "test-setup-secret"; + +const SETUP_PAGE_KEY = "setup_page_enabled"; + +function makeApp(): Hono { + const app = new Hono(); + app.route("/api", setupRoutes); + app.route("/api/auth", authRoutes); + app.route("/api/public", publicRoutes); + app.route("/api/admin", adminRoutes); + return app; +} + +// Every test spends its own IP budget (the limiter is per source IP). +let ipCounter = 0; +function nextIp(): string { + ipCounter += 1; + return `198.51.100.${ipCounter}`; +} + +function sqliteOf(env: Env): SqliteD1["db"] { + return (env.DB as unknown as SqliteD1).db; +} + +function tableNames(env: Env): string[] { + return sqliteOf(env) + .prepare( + "SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name", + ) + .all() + .map((row: { name: string }) => row.name); +} + +function settingValue(env: Env, prefix: string, key: string): unknown { + return ( + sqliteOf(env) + .prepare(`SELECT value FROM ${prefix}settings WHERE key = ?`) + .get(key) as { value: string } | undefined + )?.value; +} + +function countOwners(env: Env, prefix = ""): number { + const row = sqliteOf(env) + .prepare(`SELECT COUNT(*) AS n FROM ${prefix}users`) + .get() as { n: number }; + return row.n; +} + +function jsonHeaders( + extra: Record = {}, +): Record { + return { "content-type": "application/json", ...extra }; +} + +/** POST /api/setup — the secret-gated, migration-only upgrade endpoint. */ +function upgrade( + app: Hono, + env: Env, + opts: { secret?: string | null; ip?: string } = {}, +): Promise { + const headers = jsonHeaders({ "x-forwarded-for": opts.ip ?? nextIp() }); + if (opts.secret !== undefined && opts.secret !== null) { + headers["X-Setup-Secret"] = opts.secret; + } + return app.request("/api/setup", { method: "POST", headers }, env); +} + +/** POST /api/auth/setup — creates the single owner (existing contract). */ +function createOwner(app: Hono, env: Env): Promise { + return app.request( + "/api/auth/setup", + { + method: "POST", + body: JSON.stringify(OWNER), + headers: jsonHeaders({ "X-Setup-Secret": SECRET }), + }, + env, + ); +} + +function cookieFrom(res: Response): string { + return res.headers.get("set-cookie") ?? ""; +} + +async function ownerSession(prefix = ""): Promise<{ + env: Env; + app: Hono; + cookie: string; +}> { + const env = makeEnv({ TABLE_PREFIX: prefix }); + const app = makeApp(); + // Creates the owner and runs the ledgered migrations. + const res = await createOwner(app, env); + expect(res.status).toBe(201); + return { env, app, cookie: cookieFrom(res) }; +} + +describe("GET /api/setup/state", () => { + it("treats an uninitialised database as open and leaks nothing", async () => { + const env = makeEnv(); + const app = makeApp(); + + const res = await app.request("/api/setup/state", {}, env); + expect(res.status).toBe(200); + expect(res.headers.get("cache-control")).toBe("no-store"); + + const body = await readJson(res); + expect(body).toEqual({ + enabled: true, + ownerExists: false, + tablePrefix: "", + }); + // Frozen shape: no secret/hash fields may ever appear here. + expect(Object.keys(body).sort()).toEqual([ + "enabled", + "ownerExists", + "tablePrefix", + ]); + const text = JSON.stringify(body); + expect(text).not.toMatch(/secret|password|hash/i); + }); + + it("stays open on an empty but migrated database", async () => { + const env = makeEnv(); + const app = makeApp(); + await runMigrations(env); + + expect( + await readJson(await app.request("/api/setup/state", {}, env)), + ).toEqual({ enabled: true, ownerExists: false, tablePrefix: "" }); + }); + + it("is closed by default once the owner exists (§3.4 default OFF)", async () => { + const { env, app } = await ownerSession(); + + expect( + await readJson(await app.request("/api/setup/state", {}, env)), + ).toEqual({ enabled: false, ownerExists: true, tablePrefix: "" }); + expect(settingValue(env, "", SETUP_PAGE_KEY)).toBe("0"); + + // Explicitly opened → enabled flips. + sqliteOf(env) + .prepare("UPDATE settings SET value = '1' WHERE key = ?") + .run(SETUP_PAGE_KEY); + expect( + (await readJson(await app.request("/api/setup/state", {}, env))).enabled, + ).toBe(true); + + // Unknown/missing value under an initialised DB stays closed (default OFF). + sqliteOf(env) + .prepare("DELETE FROM settings WHERE key = ?") + .run(SETUP_PAGE_KEY); + expect( + (await readJson(await app.request("/api/setup/state", {}, env))).enabled, + ).toBe(false); + }); + + it("keeps GET /api/setup/status as an identical alias", async () => { + const { env, app } = await ownerSession(); + + const state = await readJson( + await app.request("/api/setup/state", {}, env), + ); + const res = await app.request("/api/setup/status", {}, env); + expect(res.status).toBe(200); + expect(res.headers.get("cache-control")).toBe("no-store"); + expect(await readJson(res)).toEqual(state); + }); +}); + +describe("POST /api/setup (secret-gated upgrade)", () => { + it("answers 500 when the server setup secret is missing or a placeholder", async () => { + for (const SETUP_SECRET of ["", "SETUP_SECRET_PLACEHOLDER"]) { + const env = makeEnv({ SETUP_SECRET }); + const app = makeApp(); + const res = await upgrade(app, env, { secret: "whatever" }); + expect(res.status).toBe(500); + expect(await readJson(res)).toEqual({ error: "server misconfigured" }); + } + }); + + it("rejects a wrong or missing secret with 403 and never migrates", async () => { + const env = makeEnv(); + const app = makeApp(); + + const wrong = await upgrade(app, env, { secret: "nope" }); + expect(wrong.status).toBe(403); + expect(await readJson(wrong)).toEqual({ error: "invalid setup secret" }); + + const missing = await upgrade(app, env, { secret: null }); + expect(missing.status).toBe(403); + expect(tableNames(env)).toEqual([]); + }); + + it("applies migrations on an empty database without creating an owner", async () => { + const env = makeEnv(); + const app = makeApp(); + + const res = await upgrade(app, env, { secret: SECRET }); + expect(res.status).toBe(200); + expect(await readJson(res)).toEqual({ + success: true, + tablePrefix: "", + migrations: [{ name: "schema_v1", status: "applied" }], + ownerExists: false, + }); + expect(res.headers.get("set-cookie")).toBeNull(); + expect(countOwners(env)).toBe(0); + }); + + it("only skips on an initialised database, even while the page switch is off", async () => { + const { env, app, cookie } = await ownerSession(); + expect(cookie).not.toBe(""); + // Default OFF — the switch gates the page, never this endpoint. + expect( + (await readJson(await app.request("/api/setup/state", {}, env))).enabled, + ).toBe(false); + + const res = await upgrade(app, env, { secret: SECRET }); + expect(res.status).toBe(200); + expect(await readJson(res)).toEqual({ + success: true, + tablePrefix: "", + migrations: [{ name: "schema_v1", status: "skipped" }], + ownerExists: true, + }); + // No account created/changed, no session handed to an anonymous caller. + expect(res.headers.get("set-cookie")).toBeNull(); + expect(countOwners(env)).toBe(1); + }); + + it("throttles one IP to 3 attempts per 10 minutes (4th → 429)", async () => { + const env = makeEnv(); + const app = makeApp(); + const ip = nextIp(); + + for (let attempt = 1; attempt <= 3; attempt += 1) { + const res = await upgrade(app, env, { secret: "wrong", ip }); + expect(res.status).toBe(403); + } + + // Even the correct secret is refused while the IP is throttled. + const limited = await upgrade(app, env, { secret: SECRET, ip }); + expect(limited.status).toBe(429); + expect(limited.headers.get("retry-after")).toBe("600"); + const body = await readJson(limited); + expect(body.error).toContain("too many setup attempts"); + expect(body.retryAfterSeconds).toBe(600); + + // A different source IP keeps its own budget. + const other = await upgrade(app, env, { secret: SECRET, ip: nextIp() }); + expect(other.status).toBe(200); + }); +}); + +describe("admin system endpoints", () => { + it("requires a session on all three endpoints", async () => { + const env = makeEnv(); + const app = makeApp(); + await runMigrations(env); + + const calls: Array<[string, RequestInit]> = [ + ["/api/admin/setup", { method: "POST" }], + ["/api/admin/system", {}], + [ + "/api/admin/system/setup-page", + { method: "PUT", body: JSON.stringify({ enabled: true }) }, + ], + ]; + for (const [path, init] of calls) { + const res = await app.request(path, init, env); + expect(res.status).toBe(401); + expect(await readJson(res)).toEqual({ error: "unauthorized" }); + } + }); + + it("GET /api/admin/system reports prefix, switch and ledger", async () => { + const { env, app, cookie } = await ownerSession(); + + const res = await app.request( + "/api/admin/system", + { headers: { cookie } }, + env, + ); + expect(res.status).toBe(200); + expect(await readJson(res)).toEqual({ + tablePrefix: "", + setupPageEnabled: false, + ledger: ["schema_v1"], + }); + }); + + it("POST /api/admin/setup needs no secret and matches the secret endpoint", async () => { + const { env, app, cookie } = await ownerSession(); + + const adminRes = await app.request( + "/api/admin/setup", + { method: "POST", headers: { cookie } }, + env, + ); + expect(adminRes.status).toBe(200); + const adminBody = await readJson(adminRes); + expect(adminBody).toEqual({ + success: true, + tablePrefix: "", + migrations: [{ name: "schema_v1", status: "skipped" }], + ownerExists: true, + }); + + const secretBody = await readJson( + await upgrade(app, env, { secret: SECRET }), + ); + expect(secretBody).toEqual(adminBody); + expect(countOwners(env)).toBe(1); + }); + + it("PUT /api/admin/system/setup-page toggles and persists the switch", async () => { + const { env, app, cookie } = await ownerSession(); + const put = (body: unknown) => + app.request( + "/api/admin/system/setup-page", + { + method: "PUT", + body: JSON.stringify(body), + headers: jsonHeaders({ cookie }), + }, + env, + ); + + const on = await put({ enabled: true }); + expect(on.status).toBe(200); + expect(await readJson(on)).toEqual({ setupPageEnabled: true }); + expect(settingValue(env, "", SETUP_PAGE_KEY)).toBe("1"); + expect( + (await readJson(await app.request("/api/setup/state", {}, env))).enabled, + ).toBe(true); + + // Persisted: a fresh read (what a page reload uses) still sees it. + expect( + ( + await readJson( + await app.request("/api/admin/system", { headers: { cookie } }, env), + ) + ).setupPageEnabled, + ).toBe(true); + + const off = await put({ enabled: false }); + expect(await readJson(off)).toEqual({ setupPageEnabled: false }); + expect(settingValue(env, "", SETUP_PAGE_KEY)).toBe("0"); + expect( + (await readJson(await app.request("/api/setup/state", {}, env))).enabled, + ).toBe(false); + }); + + it("validates `enabled` strictly as a boolean", async () => { + const { env, app, cookie } = await ownerSession(); + + for (const body of [ + {}, + { enabled: "true" }, + { enabled: 1 }, + { enabled: null }, + ]) { + const res = await app.request( + "/api/admin/system/setup-page", + { + method: "PUT", + body: JSON.stringify(body), + headers: jsonHeaders({ cookie }), + }, + env, + ); + expect(res.status).toBe(400); + expect(await readJson(res)).toEqual({ + error: "enabled must be a boolean", + }); + } + // Untouched by the rejected writes. + expect(settingValue(env, "", SETUP_PAGE_KEY)).toBe("0"); + }); + + it("keeps setup_page_enabled out of the site-settings DTO and /api/public", async () => { + const { env, app, cookie } = await ownerSession(); + await app.request( + "/api/admin/system/setup-page", + { + method: "PUT", + body: JSON.stringify({ enabled: true }), + headers: jsonHeaders({ cookie }), + }, + env, + ); + + const publicBody = await readJson( + await app.request("/api/public", {}, env), + ); + expect(Object.keys(publicBody.settings).sort()).toEqual([ + "backgroundUrl", + "columns", + "siteTitle", + "theme", + ]); + expect(JSON.stringify(publicBody)).not.toContain(SETUP_PAGE_KEY); + + const settingsRes = await app.request( + "/api/admin/settings", + { headers: { cookie } }, + env, + ); + expect(JSON.stringify(await readJson(settingsRes))).not.toContain( + SETUP_PAGE_KEY, + ); + + // The generic settings write is a whitelist: it cannot touch the switch. + const write = await app.request( + "/api/admin/settings", + { + method: "PUT", + body: JSON.stringify({ siteTitle: "nav", setupPageEnabled: false }), + headers: jsonHeaders({ cookie }), + }, + env, + ); + expect(JSON.stringify(await readJson(write))).not.toContain(SETUP_PAGE_KEY); + expect(settingValue(env, "", SETUP_PAGE_KEY)).toBe("1"); + }); +}); + +describe("table prefix conflict", () => { + it("returns the same 409 detail from both endpoints and builds no second schema", async () => { + const { env, app, cookie } = await ownerSession("app_"); + // Simulate a database already carrying nav's schema under another prefix: + // the configured prefix has no ledger of its own (its tables and this admin + // session stay, since sessions live in {prefix}sessions) while a nav_* table + // family appears. Migrating would silently build a second, empty schema. + sqliteOf(env).exec( + "DROP TABLE _app_schema_migrations;" + + "CREATE TABLE nav_passkey_credentials (id TEXT);" + + "CREATE TABLE nav_search_engines (id TEXT);" + + "CREATE TABLE nav_login_attempts (id TEXT);", + ); + const before = tableNames(env); + + const secretRes = await upgrade(app, env, { secret: SECRET }); + expect(secretRes.status).toBe(409); + const secretBody = await readJson(secretRes); + expect(secretBody.error).toBe("table prefix conflict"); + expect(typeof secretBody.detail).toBe("string"); + expect(secretBody.detail).toContain("nav_"); + + const adminRes = await app.request( + "/api/admin/setup", + { method: "POST", headers: { cookie } }, + env, + ); + expect(adminRes.status).toBe(409); + expect(await readJson(adminRes)).toEqual(secretBody); + + // No second set of tables (and no ledger) appeared. + expect(tableNames(env)).toEqual(before); + }); +}); + +describe("worker wiring", () => { + it("serves /api/setup/state and /api/setup/status from the real app", async () => { + const env = makeEnv(); + for (const path of ["/api/setup/state", "/api/setup/status"]) { + const res = await worker.fetch( + new Request(`http://localhost${path}`), + env, + ); + expect(res.status).toBe(200); + expect(await readJson(res)).toEqual({ + enabled: true, + ownerExists: false, + tablePrefix: "", + }); + } + }); + + it("serves index.html for a direct /setup request (SPA fallback)", async () => { + const requested: string[] = []; + const env = makeEnv({ + ASSETS: { + fetch: async (req: Request) => { + const path = new URL(req.url).pathname; + requested.push(path); + if (path === "/") { + return new Response("nav", { + status: 200, + headers: { "content-type": "text/html; charset=utf-8" }, + }); + } + return new Response("not found", { status: 404 }); + }, + } as unknown as Fetcher, + }); + + const res = await worker.fetch( + new Request("http://localhost/setup"), + env, + {} as ExecutionContext, + ); + expect(res.status).toBe(200); + expect(res.headers.get("content-type")).toContain("text/html"); + expect(await res.text()).toContain(""); + // /setup misses in static assets, then falls back to the SPA entry point. + expect(requested).toEqual(["/setup", "/"]); + }); +});