From 0cb9a733fd973a21efe9304534c178c19f369321 Mon Sep 17 00:00:00 2001 From: Todos Date: Sun, 18 Oct 2026 14:40:47 +0800 Subject: [PATCH 1/2] feat(worker): align setup API with Zeta (state, JSON secret, admin) Add GET /api/setup/state (public), a 405 for GET /api/setup/*, a JSON-body POST /api/setup with a legacy X-Setup-Secret header fallback, and a keyless POST /api/admin/setup for admins. - Extract shared runMigrations() into lib/migrations-runner.ts, used by both the setup and admin endpoints - Return 500/400/403 for unconfigured/invalid/wrong secret (constant-time comparison); rate-limit to 3 per IP per 10 min counted before the secret check (429 + Retry-After) - Mount setup at /api/setup, keep /setup as a backward-compatible alias - Whitelist setup_page_enabled ('0'/'1') in admin settings; state defaults to enabled when the setting is absent - Add worker tests; update README/README.zh-CN/CLAUDE docs Checkpoint: WzVRNGv2ju_UNM93bGHLI --- CLAUDE.md | 11 +- README.md | 29 +- README.zh-CN.md | 24 +- apps/worker/src/index.ts | 3 + apps/worker/src/lib/kv.ts | 44 ++- apps/worker/src/lib/migrations-runner.ts | 78 ++++++ apps/worker/src/routes/admin.ts | 38 +++ apps/worker/src/routes/setup.ts | 145 +++++----- apps/worker/test/helpers/env.ts | 10 +- apps/worker/test/setup.test.ts | 330 +++++++++++++++++++++++ 10 files changed, 622 insertions(+), 90 deletions(-) create mode 100644 apps/worker/src/lib/migrations-runner.ts create mode 100644 apps/worker/test/setup.test.ts diff --git a/CLAUDE.md b/CLAUDE.md index 0c3923c..ddeaf22 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -92,7 +92,7 @@ shortlink/ │ │ │ │ ├── analytics.ts # Per-link and summary click analytics (D1 batch queries) │ │ │ │ ├── admin.ts # Admin: user mgmt, link mgmt, settings │ │ │ │ ├── redirect.ts # /:slug redirect + async click logging -│ │ │ │ └── setup.ts # POST /setup — HTTP-triggered DB migration (schema_v1 + schema_v2) +│ │ │ │ └── setup.ts # GET /api/setup/state + POST /api/setup — HTTP-triggered DB migration (schema_v1 + schema_v2) │ │ │ ├── middleware/ │ │ │ │ └── auth.ts # requireAuth and requireAdmin middleware (JWT verification) │ │ │ └── lib/ @@ -105,6 +105,7 @@ shortlink/ │ │ │ ├── email.ts # Provider dispatch: Resend API or SMTP; otpEmailHtml + resetPasswordEmailHtml templates │ │ │ ├── smtp.ts # SMTP client over cloudflare:sockets (STARTTLS + implicit TLS) │ │ │ ├── kv.ts # All KV operations (link cache, challenge store, rate limiting) +│ │ │ ├── migrations-runner.ts # runMigrations() shared by POST /api/setup and POST /api/admin/setup │ │ │ └── ua.ts # User-agent parsing (device/browser/OS detection) │ │ ├── migrations/ │ │ │ └── 0001_init.sql # Canonical schema: all tables + default settings rows (used by wrangler d1 migrations apply) @@ -166,7 +167,7 @@ Stored AES-256-GCM encrypted in D1. The encryption key (`TOTP_ENCRYPTION_KEY`) i | `login_attempts_ip:{ip}` | Login brute-force rate limit (IP dimension) | 900s | | `register_rate:{ip}` | Registration rate limit (IP) | 3600s | | `forgot_pw_rate:{ip}` | Forgot-password rate limit (IP) | 3600s | -| `setup_rate:{ip}` | Setup/migration endpoint rate limit (IP) | 900s | +| `setup_rate:{ip}` | Setup/migration endpoint rate limit (IP) | 600s | | `2fa_attempts:{jti}` | General 2FA attempt counter | 600s | | `passkey_opts:{jti}` | Passkey options attempt counter | 600s | | `totp_confirm:{userId}` | TOTP setup confirm attempt counter | 120s | @@ -243,10 +244,12 @@ Two files in `apps/worker/migrations/`: - `0002_token_version.sql` — adds `users.token_version` for session revocation **HTTP setup route (production):** -`POST /setup` with `X-Setup-Secret` header runs migrations embedded in `routes/setup.ts`. Two migrations: +`POST /api/setup` (legacy alias `/setup`) with a JSON body `{"secret": ""}` runs migrations via the shared `lib/migrations-runner.ts` (`runMigrations`). Two migrations: - `schema_v1` — identical DDL as `0001_init.sql`, but parameterized by `TABLE_PREFIX` and tracked in `_schema_migrations` table - `schema_v2` — adds `token_version` to `users` (mirrors `0002_token_version.sql`) +The legacy `X-Setup-Secret` header is still accepted when the body is empty. The endpoint is rate-limited to 3 attempts per IP per 10 minutes (counted before the secret check; a `429` carries a `Retry-After` header). `GET /api/setup/state` (public) reports `{ enabled }` from the `setup_page_enabled` setting (default enabled); `GET /api/setup/*` returns `405` pointing at the POST form. An admin can run the same migrations keylessly via `POST /api/admin/setup` (no IP rate limit; writes an audit log entry). `setup_page_enabled` only hides the setup page — it never disables the `POST` migration channel. + Re-visiting the setup URL is safe — already-applied migrations return `"skipped"`. --- @@ -260,7 +263,7 @@ Re-visiting the setup URL is safe — already-applied migrations return `"skippe - Password reset codes: max 3 wrong attempts per code; rate-limited 3 sends per 10 min per email - Login brute-force limited to 10 attempts per 15-minute window per email, plus 20 per IP (`login_attempts:{email}` + `login_attempts_ip:{ip}` KV) - Registration and forgot-password additionally rate-limited per IP (`register_rate:{ip}`, `forgot_pw_rate:{ip}`) -- Setup/migration endpoint rate-limited per IP (`setup_rate:{ip}`); secret passed via header and compared in constant time +- Setup/migration endpoint rate-limited per IP (`setup_rate:{ip}`, 3 per 10 min, counted before the secret check); secret sent in the JSON body (legacy header fallback) and compared in constant time - `cf-connecting-ip` used for IP logging (cannot be forged); `x-forwarded-for` ignored - User-Agent and Referer headers truncated before storage (512 and 2048 bytes respectively) - `app_name` setting validated: 1–64 chars, no HTML-special or CR/LF characters diff --git a/README.md b/README.md index 05bce85..3c93932 100644 --- a/README.md +++ b/README.md @@ -108,13 +108,15 @@ it as a secret, and do not change it once data exists. The GitHub `APP_URL` vari point at the production URL. `CLOUDFLARE_API_TOKEN` needs edit access to the D1 database and edit/version-read access to the Worker. -You no longer need to call `/setup` after each deploy. For manual deployments or -emergencies it can still be triggered with a `POST` request carrying the setup secret in -a header (it is no longer accepted in the URL): +You no longer need to call the setup endpoint after each deploy. For manual +deployments or emergencies it can still be triggered with a `POST` request carrying the +setup secret in a JSON body (the legacy `X-Setup-Secret` header still works, and the +secret is no longer accepted in the URL): ``` -curl -X POST https://your-worker.workers.dev/setup \ - -H "X-Setup-Secret: " +curl -X POST https://your-worker.workers.dev/api/setup \ + -H "Content-Type: application/json" \ + -d '{"secret": ""}' ``` Response on success: @@ -126,7 +128,13 @@ Response on success: } ``` -Re-running it is safe — already-applied migrations return `"skipped"`. +Re-running it is safe — already-applied migrations return `"skipped"`. The endpoint is +rate-limited to 3 attempts per IP per 10 minutes (once exceeded it returns `429` with a +`Retry-After` header). `GET /api/setup/state` reports `{ "enabled": true | false }` based +on the `setup_page_enabled` setting (defaults to enabled when unset); it only hides the +setup page, it does not disable the `POST` migration channel. When logged in as an admin, +migrations can also be run from the admin panel via `POST /api/admin/setup` — no setup +secret needed, not IP rate-limited, and each run is written to the audit log. After deploying, the workflow first confirms through the Cloudflare API that the uploaded version serves 100% of production traffic, then probes the public URL. A `403` carrying @@ -240,6 +248,14 @@ The Vite dev server proxies `/api` requests to `:8787` automatically. | DELETE | `/api/admin/links/:id` | Delete any link | | GET | `/api/admin/settings` | Get global settings | | PUT | `/api/admin/settings` | Update global settings | +| POST | `/api/admin/setup` | Run schema migrations as admin (no setup secret; writes an audit log) | + +### Setup (unauthenticated) + +| Method | Path | Description | +|---|---|---| +| GET | `/api/setup/state` | Public — `{ "enabled": true \| false }` from `setup_page_enabled` | +| POST | `/api/setup` | Run schema migrations; JSON body `{"secret": ""}` (legacy `X-Setup-Secret` header also works), 3 attempts / IP / 10 min | ### Miscellaneous @@ -289,6 +305,7 @@ All variables and secrets are managed in the **Cloudflare dashboard** (Workers & | `smtp_from` | email address | Sender address, e.g. `noreply@example.com` | | `smtp_user` | string | SMTP username (leave blank for unauthenticated relay) | | `smtp_pass` | string | SMTP password (stored in D1) | +| `setup_page_enabled` | `0` / `1` | Show (`1`) or hide (`0`) the setup page; only affects page visibility, never the `POST /api/setup` migration channel | --- diff --git a/README.zh-CN.md b/README.zh-CN.md index 4d10e38..5952149 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -107,12 +107,13 @@ GitHub Actions 会在部署代码**之前**自动执行迁移:无前缀时仍 不要把它设为 Secret,也不要在已有数据后更换前缀。GitHub 中的 `APP_URL` 也必须指向生产地址。 现有 `CLOUDFLARE_API_TOKEN` 需要有目标 D1 的编辑权限和 Worker 的编辑/版本读取权限。 -无需在每次部署后调用 `/setup`。手动部署或应急操作仍可通过 `POST` 请求触发, -密钥放在请求头中(不再通过 URL 传递): +无需在每次部署后调用 setup 接口。手动部署或应急操作仍可通过 `POST` 请求触发, +密钥放在 JSON body 中(旧的 `X-Setup-Secret` 请求头仍兼容,密钥不再通过 URL 传递): ``` -curl -X POST https://your-worker.workers.dev/setup \ - -H "X-Setup-Secret: " +curl -X POST https://your-worker.workers.dev/api/setup \ + -H "Content-Type: application/json" \ + -d '{"secret": ""}' ``` 成功响应: @@ -124,7 +125,11 @@ curl -X POST https://your-worker.workers.dev/setup \ } ``` -重复调用是安全的,已执行的迁移会返回 `"skipped"`。自动部署不需要手动调用。 +重复调用是安全的,已执行的迁移会返回 `"skipped"`。该接口按 IP 限流为每 10 分钟 3 次 +(超限返回 `429` 并带 `Retry-After` 头)。`GET /api/setup/state` 返回 +`{ "enabled": true | false }`,反映 `setup_page_enabled` 设置(未设置时默认启用), +它只隐藏 setup 页面、不会关闭 `POST` 迁移通道。以管理员身份登录后,也可在管理面板 +通过 `POST /api/admin/setup` 触发迁移 — 无需 setup 密钥、不受 IP 限流,且每次执行都会写入审计日志。 部署后还会通过 Cloudflare API 核对本次上传的版本承载 100% 流量,再检查公开 URL。 公开 URL 返回带 `cf-mitigated: challenge` 的 403 时仅警告(HTTP/数据库检查未能验证), 其余非 2xx 或错误的 JSON 均失败;无需关闭 Bot Fight Mode。 @@ -235,6 +240,14 @@ Vite 开发服务器会自动将 `/api` 请求代理到 `:8787`。 | DELETE | `/api/admin/links/:id` | 删除任意链接 | | GET | `/api/admin/settings` | 获取全局设置 | | PUT | `/api/admin/settings` | 更新全局设置 | +| POST | `/api/admin/setup` | 以管理员身份执行数据库迁移(无需 setup 密钥;写入审计日志) | + +### Setup(无需认证) + +| 方法 | 路径 | 描述 | +|---|---|---| +| GET | `/api/setup/state` | 公开接口 — 根据 `setup_page_enabled` 返回 `{ "enabled": true \| false }` | +| POST | `/api/setup` | 执行数据库迁移;JSON body `{"secret": ""}`(旧的 `X-Setup-Secret` 请求头仍兼容),每 IP 每 10 分钟限 3 次 | ### 其他 @@ -284,6 +297,7 @@ GET /:slug → 302 跳转到目标 URL | `smtp_from` | 邮件地址 | 发件人地址,例如 `noreply@example.com` | | `smtp_user` | 字符串 | SMTP 用户名(留空则使用未认证中继) | | `smtp_pass` | 字符串 | SMTP 密码(存储在 D1 中) | +| `setup_page_enabled` | `0` / `1` | 显示(`1`)或隐藏(`0`)setup 页面;只影响页面可见性,绝不关闭 `POST /api/setup` 迁移通道 | --- diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.ts index 66e0ecf..bf0853b 100644 --- a/apps/worker/src/index.ts +++ b/apps/worker/src/index.ts @@ -116,6 +116,9 @@ app.route('/api/analytics', analyticsRoutes); app.route('/api/admin', adminRoutes); // ─── Setup / migration endpoint ─────────────────────────────────────────────── +// Mounted at /api/setup to match the rest of the public API; /setup is kept as a +// backward-compatible alias for callers that predate the /api prefix. +app.route('/api/setup', setupRoutes); app.route('/setup', setupRoutes); // ─── Health check ───────────────────────────────────────────────────────────── diff --git a/apps/worker/src/lib/kv.ts b/apps/worker/src/lib/kv.ts index 6d47bca..a33cfc5 100644 --- a/apps/worker/src/lib/kv.ts +++ b/apps/worker/src/lib/kv.ts @@ -153,14 +153,16 @@ export async function deletePending2fa( // the limit before writes settle. A Cloudflare WAF rate-limit rule is the primary // enforcement layer; this provides a defence-in-depth best-effort guard. -// Fixed-window counter. Returns true (allowed) unless the key is already at -// `limit`; records the attempt by incrementing the stored count. -async function fixedWindowIncrement( +// Fixed-window counter. Records the attempt by incrementing the stored count, +// then reports whether it is still within `limit`. The detailed variant also +// returns how many seconds remain in the current window so callers can send an +// exact Retry-After header. +async function fixedWindowIncrementWithRetry( kv: KVNamespace, key: string, limit: number, windowSec: number, -): Promise { +): Promise<{ allowed: boolean; retryAfter: number }> { const current = await kv.get(key); const now = Math.floor(Date.now() / 1000); @@ -172,7 +174,7 @@ async function fixedWindowIncrement( expirationTtl: windowSec, }, ); - return true; + return { allowed: true, retryAfter: 0 }; } let entry: { count: number; windowEnd: number }; @@ -186,17 +188,33 @@ async function fixedWindowIncrement( expirationTtl: windowSec, }, ); - return true; + return { allowed: true, retryAfter: 0 }; } - if (entry.count >= limit) return false; + if (entry.count >= limit) { + return { + allowed: false, + retryAfter: Math.max(entry.windowEnd - now, 0), + }; + } const remaining = Math.max(entry.windowEnd - now, 1); await kv.put( key, JSON.stringify({ count: entry.count + 1, windowEnd: entry.windowEnd }), { expirationTtl: remaining }, ); - return true; + return { allowed: true, retryAfter: 0 }; +} + +// Boolean convenience wrapper for callers that only need allow/deny. +async function fixedWindowIncrement( + kv: KVNamespace, + key: string, + limit: number, + windowSec: number, +): Promise { + return (await fixedWindowIncrementWithRetry(kv, key, limit, windowSec)) + .allowed; } // BE-S6: Rate limit login on two dimensions — email (10/15min) and IP (20/15min). @@ -242,13 +260,15 @@ export async function checkForgotPasswordIpRateLimit( return fixedWindowIncrement(kv, KV_PREFIX.forgotPasswordIp(ip), 10, 3600); } -// BE-S5: IP rate limit for the setup/migration endpoint (5/15min) — prevents -// online brute-forcing of the setup secret. +// BE-S5: IP rate limit for the setup/migration endpoint (3/10min) — prevents +// online brute-forcing of the setup secret. Returns whether the attempt is +// allowed and, when not, how many seconds remain in the window so the caller +// can send an exact Retry-After header. export async function checkSetupRateLimit( kv: KVNamespace, ip: string, -): Promise { - return fixedWindowIncrement(kv, KV_PREFIX.setupRate(ip), 5, 900); +): Promise<{ allowed: boolean; retryAfter: number }> { + return fixedWindowIncrementWithRetry(kv, KV_PREFIX.setupRate(ip), 3, 600); } // ─── 2FA attempt tracking (C2: max 5 per pending token) ────────────────────── diff --git a/apps/worker/src/lib/migrations-runner.ts b/apps/worker/src/lib/migrations-runner.ts new file mode 100644 index 0000000..7b82a97 --- /dev/null +++ b/apps/worker/src/lib/migrations-runner.ts @@ -0,0 +1,78 @@ +import type { Env } from '../types.js'; +import { + createMigrationsTableSql, + getMigrations, + migrationsTable, +} from './migrations.js'; + +// Shared schema-migration execution, parameterised by TABLE_PREFIX. Both the +// secret-keyed HTTP endpoint (routes/setup.ts → POST /api/setup) and the +// admin-session endpoint (routes/admin.ts → POST /api/admin/setup) call this so +// the two stay byte-compatible. + +export interface MigrationResult { + name: string; + status: 'applied' | 'skipped' | 'error'; + error?: string; +} + +export interface RunMigrationsResult { + migrations: MigrationResult[]; +} + +// D1's exec() only processes the first line of a multi-line string. +// Strip SQL line comments and collapse all whitespace to a single line. +function toSingleLine(sql: string): string { + return sql + .split('\n') + .map((line) => { + const idx = line.indexOf('--'); + return idx >= 0 ? line.slice(0, idx) : line; + }) + .join(' ') + .replace(/\s+/g, ' ') + .trim(); +} + +// Applies every migration in getMigrations(prefix) not yet recorded in +// `${prefix}schema_migrations`, stopping at the first error (which is reported +// inline rather than thrown, preserving the original setup-route semantics). +export async function runMigrations( + env: Pick, +): Promise { + const prefix = env.TABLE_PREFIX ?? ''; + const historyTable = migrationsTable(prefix); + + // Use prepare().run() for single-statement DDL — avoids exec()'s newline limitation + await env.DB.prepare(createMigrationsTableSql(prefix)).run(); + + const { results } = await env.DB.prepare( + `SELECT name FROM ${historyTable}`, + ).all<{ name: string }>(); + const applied = new Set(results.map((r) => r.name)); + + const migrations: MigrationResult[] = []; + + for (const migration of getMigrations(prefix)) { + if (applied.has(migration.name)) { + migrations.push({ name: migration.name, status: 'skipped' }); + continue; + } + try { + await env.DB.exec(toSingleLine(migration.sql)); + await env.DB.prepare(`INSERT INTO ${historyTable} (name) VALUES (?)`) + .bind(migration.name) + .run(); + migrations.push({ name: migration.name, status: 'applied' }); + } catch (err) { + migrations.push({ + name: migration.name, + status: 'error', + error: String(err), + }); + break; + } + } + + return { migrations }; +} diff --git a/apps/worker/src/routes/admin.ts b/apps/worker/src/routes/admin.ts index d166c07..5f17f49 100644 --- a/apps/worker/src/routes/admin.ts +++ b/apps/worker/src/routes/admin.ts @@ -2,6 +2,7 @@ import { Hono } from 'hono'; import { hashPassword } from '../lib/crypto.js'; import { isUniqueConstraintError, tbl } from '../lib/db.js'; import { deleteCachedLink, deleteCachedSetting } from '../lib/kv.js'; +import { runMigrations } from '../lib/migrations-runner.js'; import { parsePagination } from '../lib/params.js'; import { requireAdmin } from '../middleware/auth.js'; import type { Env, LinkRow, UserRow, Variables } from '../types.js'; @@ -389,6 +390,7 @@ admin.put('/settings', async (c) => { 'smtp_user', 'smtp_pass', 'smtp_from', + 'setup_page_enabled', ]); // FE-S3/BE-S1: An empty or masked ("***") secret means "leave unchanged". @@ -427,6 +429,13 @@ admin.put('/settings', async (c) => { return c.json({ error: 'email_provider must be "resend" or "smtp"' }, 400); } + // FE-S13: setup_page_enabled only toggles the setup page's visibility; it is + // stored as '0'/'1' (not 'true'/'false') and is not a secret. + const setupPageEntry = updates.find(([k]) => k === 'setup_page_enabled'); + if (setupPageEntry && !['0', '1'].includes(setupPageEntry[1])) { + return c.json({ error: 'setup_page_enabled must be "0" or "1"' }, 400); + } + const portEntry = updates.find(([k]) => k === 'smtp_port'); if (portEntry) { const p = parseInt(portEntry[1], 10); @@ -515,4 +524,33 @@ admin.delete('/links/:id', async (c) => { return c.json({ success: true }); }); +// ───────────────────────────────────────────────────────────────────────────── +// POST /api/admin/setup +// ───────────────────────────────────────────────────────────────────────────── +// Runs the same schema-migration routine as POST /api/setup, but keyed to the +// admin session instead of SETUP_SECRET (and not rate-limited per IP — the +// admin is already authenticated). Because no admin account exists before the +// database is initialised, this covers the "check & upgrade" case after +// first-time setup; the initial setup still happens through POST /api/setup. +admin.post('/setup', async (c) => { + const adminId = c.get('userId'); + const result = await runMigrations(c.env); + + const applied = result.migrations.filter( + (m) => m.status === 'applied', + ).length; + const skipped = result.migrations.filter( + (m) => m.status === 'skipped', + ).length; + const errored = result.migrations.filter((m) => m.status === 'error').length; + + await auditLog(c.env, adminId, 'run_setup', 'setup', { + applied, + skipped, + error: errored, + }); + + return c.json(result); +}); + export default admin; diff --git a/apps/worker/src/routes/setup.ts b/apps/worker/src/routes/setup.ts index 23f3939..9b13044 100644 --- a/apps/worker/src/routes/setup.ts +++ b/apps/worker/src/routes/setup.ts @@ -1,82 +1,107 @@ import { Hono } from 'hono'; import { constantTimeEqual } from '../lib/crypto.js'; +import { tbl } from '../lib/db.js'; import { checkSetupRateLimit } from '../lib/kv.js'; -import { - createMigrationsTableSql, - getMigrations, - migrationsTable, -} from '../lib/migrations.js'; +import { runMigrations } from '../lib/migrations-runner.js'; import type { Env, Variables } from '../types.js'; const app = new Hono<{ Bindings: Env; Variables: Variables }>(); -// D1's exec() only processes the first line of a multi-line string. -// Strip SQL line comments and collapse all whitespace to a single line. -function toSingleLine(sql: string): string { - return sql - .split('\n') - .map((line) => { - const idx = line.indexOf('--'); - return idx >= 0 ? line.slice(0, idx) : line; - }) - .join(' ') - .replace(/\s+/g, ' ') - .trim(); -} - -// BE-S5: POST + header secret (kept out of URL/logs), constant-time comparison, -// and per-IP rate limiting. When SETUP_SECRET is not set the endpoint 404s. -app.post('/', async (c) => { - if (!c.env.SETUP_SECRET) { - return c.notFound(); +// ─── GET /api/setup/state ──────────────────────────────────────────────────── +// Public and unauthenticated: only reports whether the setup page is enabled, +// leaking nothing else (not whether the database is initialised, its schema, or +// its version). A missing settings table (database not yet initialised) and a +// missing row both mean the default: enabled. Registered before the GET '/*' +// 405 fallback below so it is not swallowed by it. +app.get('/state', async (c) => { + let value: string | null = null; + try { + const row = await c.env.DB.prepare( + `SELECT value FROM ${tbl(c.env, 'settings')} WHERE key = 'setup_page_enabled'`, + ).first<{ value: string }>(); + value = row?.value ?? null; + } catch { + // settings table does not exist yet — the database has not been initialised } + return c.json({ enabled: value !== '0' }); +}); + +// ─── GET /api/setup/* (legacy) ─────────────────────────────────────────────── +// The old GET /api/setup/:secret form put the secret in the URL (history, logs, +// Referer). It never initialises anything now; it only points callers at the +// POST form. +app.get('/*', (c) => + c.json( + { + error: + 'Use POST /api/setup with a JSON body {"secret": ""}.', + }, + 405, + { Allow: 'POST' }, + ), +); +// ─── POST /api/setup ───────────────────────────────────────────────────────── +app.post('/', async (c) => { + // Rate-limit by source IP before anything else — including the secret + // comparison — so a wrong secret cannot be brute-forced unthrottled. Success + // and failure both count. const ip = c.req.header('cf-connecting-ip') ?? 'unknown'; - const allowed = await checkSetupRateLimit(c.env.LINKS_KV, ip); + const { allowed, retryAfter } = await checkSetupRateLimit(c.env.LINKS_KV, ip); if (!allowed) { - return c.json({ error: 'Too many requests. Try again later.' }, 429); + return c.json({ error: 'Too many setup attempts. Try again later.' }, 429, { + 'Retry-After': String(retryAfter), + }); } - const provided = c.req.header('X-Setup-Secret') ?? ''; - if (!constantTimeEqual(provided, c.env.SETUP_SECRET)) { - return c.notFound(); + const expected = c.env.SETUP_SECRET; + if (!expected || expected.trim() === '') { + return c.json( + { error: 'SETUP_SECRET is not configured on this Worker.' }, + 500, + ); } - const prefix = c.env.TABLE_PREFIX ?? ''; - const historyTable = migrationsTable(prefix); - - // Use prepare().run() for single-statement DDL — avoids exec()'s newline limitation - await c.env.DB.prepare(createMigrationsTableSql(prefix)).run(); - - const { results } = await c.env.DB.prepare( - `SELECT name FROM ${historyTable}`, - ).all<{ name: string }>(); - const applied = new Set(results.map((r) => r.name)); - - const log: { - name: string; - status: 'applied' | 'skipped' | 'error'; - error?: string; - }[] = []; - - for (const migration of getMigrations(prefix)) { - if (applied.has(migration.name)) { - log.push({ name: migration.name, status: 'skipped' }); - continue; - } + // Primary channel: a JSON body {"secret": ""}. For backward + // compatibility with callers that predate the JSON body, an empty body falls + // back to the X-Setup-Secret header. + const raw = await c.req.text(); + let provided: string; + if (raw.trim() === '') { + provided = c.req.header('X-Setup-Secret') ?? ''; + } else { + let body: unknown; try { - await c.env.DB.exec(toSingleLine(migration.sql)); - await c.env.DB.prepare(`INSERT INTO ${historyTable} (name) VALUES (?)`) - .bind(migration.name) - .run(); - log.push({ name: migration.name, status: 'applied' }); - } catch (err) { - log.push({ name: migration.name, status: 'error', error: String(err) }); - break; + body = JSON.parse(raw); + } catch { + return c.json( + { error: 'A JSON body {"secret": ""} is required.' }, + 400, + ); + } + if (typeof body !== 'object' || body === null || Array.isArray(body)) { + return c.json( + { error: 'A JSON body {"secret": ""} is required.' }, + 400, + ); } + const secret = (body as { secret?: unknown }).secret; + if (typeof secret !== 'string' || secret.length === 0) { + return c.json( + { error: 'A JSON body {"secret": ""} is required.' }, + 400, + ); + } + provided = secret; + } + + // Constant-time comparison so neither the content nor the length of the + // secret leaks through timing. + if (!constantTimeEqual(provided, expected)) { + return c.json({ error: 'Invalid setup secret.' }, 403); } - return c.json({ migrations: log }); + return c.json(await runMigrations(c.env)); }); export default app; diff --git a/apps/worker/test/helpers/env.ts b/apps/worker/test/helpers/env.ts index f0bba05..3a36113 100644 --- a/apps/worker/test/helpers/env.ts +++ b/apps/worker/test/helpers/env.ts @@ -85,10 +85,14 @@ class D1Statement { export class D1Mock { private readonly db: DatabaseSync; - constructor() { + // applyMigrations=false yields an empty database so a test can exercise the + // setup/migration runner end-to-end from a blank slate. + constructor(applyMigrations = true) { this.db = new DatabaseSync(':memory:'); - for (const migration of getMigrations('')) { - this.db.exec(migration.sql); + if (applyMigrations) { + for (const migration of getMigrations('')) { + this.db.exec(migration.sql); + } } } diff --git a/apps/worker/test/setup.test.ts b/apps/worker/test/setup.test.ts new file mode 100644 index 0000000..541ffe7 --- /dev/null +++ b/apps/worker/test/setup.test.ts @@ -0,0 +1,330 @@ +// Setup endpoint tests — GET /api/setup/state (public), POST /api/setup (JSON +// body + legacy header, per-IP rate limit), GET /api/setup/* (405), and the +// admin keyless upgrade POST /api/admin/setup (shared migration runner + audit). +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { app } from '../src/index.ts'; +import { + createMigrationsTableSql, + getMigrations, + migrationsTable, +} from '../src/lib/migrations.ts'; +import type { Env } from '../src/types.ts'; +import { accessTokenFor, makeEnv, request, seedUser } from './helpers/app.ts'; +import { D1Mock } from './helpers/env.ts'; + +const json = (body: unknown, headers: Record = {}) => ({ + method: 'POST', + headers: { 'Content-Type': 'application/json', ...headers }, + body: JSON.stringify(body), +}); + +// Pre-records every migration as applied so a re-run returns "skipped" for all +// (the idempotent re-visit path), keeping assertions deterministic. +function markAllMigrationsApplied(db: D1Mock): void { + db.prepare(createMigrationsTableSql('')).run(); + for (const migration of getMigrations('')) { + db.prepare(`INSERT OR IGNORE INTO ${migrationsTable('')} (name) VALUES (?)`) + .bind(migration.name) + .run(); + } +} + +// ─── GET /api/setup/state ───────────────────────────────────────────────────── + +test('GET /api/setup/state: 缺省 enabled(无 setup_page_enabled 行)', async () => { + const ctx = makeEnv(); + const res = await request(app, '/api/setup/state', { method: 'GET' }, ctx); + assert.equal(res.status, 200); + assert.deepEqual(await res.json(), { enabled: true }); +}); + +test('GET /api/setup/state: setup_page_enabled=0 时 disabled', async () => { + const ctx = makeEnv(); + ctx.db + .prepare( + `INSERT INTO settings (key, value) VALUES ('setup_page_enabled', '0')`, + ) + .run(); + const res = await request(app, '/api/setup/state', { method: 'GET' }, ctx); + assert.equal(res.status, 200); + assert.deepEqual(await res.json(), { enabled: false }); +}); + +test('GET /api/setup/state: settings 表不存在时 enabled', async () => { + const ctx = makeEnv(); + ctx.db.exec('DROP TABLE settings'); + const res = await request(app, '/api/setup/state', { method: 'GET' }, ctx); + assert.equal(res.status, 200); + assert.deepEqual(await res.json(), { enabled: true }); +}); + +// ─── GET /api/setup/* (legacy) ──────────────────────────────────────────────── + +test('GET /api/setup/*: 返回 405 + Allow: POST', async () => { + const ctx = makeEnv(); + const res = await request(app, '/api/setup/anything', { method: 'GET' }, ctx); + assert.equal(res.status, 405); + assert.equal(res.headers.get('Allow'), 'POST'); + const body = await res.json(); + assert.match(body.error, /POST \/api\/setup/); +}); + +// ─── POST /api/setup ────────────────────────────────────────────────────────── + +test('POST /api/setup: 正确 JSON 密钥把迁移应用到空库并返回结果', async () => { + const ctx = makeEnv({ DB: new D1Mock(false) as unknown as Env['DB'] }); + const res = await request( + app, + '/api/setup', + json({ secret: 'test-setup-secret' }, { 'cf-connecting-ip': '1.2.3.4' }), + ctx, + ); + assert.equal(res.status, 200); + const body = await res.json(); + assert.deepEqual( + body.migrations.map((m: { name: string; status: string }) => [ + m.name, + m.status, + ]), + [ + ['schema_v1', 'applied'], + ['schema_v2', 'applied'], + ], + ); +}); + +test('POST /api/setup: 密钥错误返回 403', async () => { + const ctx = makeEnv(); + const res = await request( + app, + '/api/setup', + json({ secret: 'wrong-secret' }, { 'cf-connecting-ip': '2.2.2.2' }), + ctx, + ); + assert.equal(res.status, 403); + assert.match((await res.json()).error, /Invalid setup secret/); +}); + +test('POST /api/setup: SETUP_SECRET 未配置返回 500', async () => { + const ctx = makeEnv({ SETUP_SECRET: '' }); + const res = await request( + app, + '/api/setup', + json({ secret: 'anything' }, { 'cf-connecting-ip': '3.3.3.3' }), + ctx, + ); + assert.equal(res.status, 500); + assert.match((await res.json()).error, /not configured/); +}); + +test('POST /api/setup: body 非法(secret 非字符串/为空)返回 400', async () => { + const ctx = makeEnv(); + + const nonString = await request( + app, + '/api/setup', + json({ secret: 123 }, { 'cf-connecting-ip': '4.4.4.1' }), + ctx, + ); + assert.equal(nonString.status, 400); + + const empty = await request( + app, + '/api/setup', + json({ secret: '' }, { 'cf-connecting-ip': '4.4.4.2' }), + ctx, + ); + assert.equal(empty.status, 400); +}); + +test('POST /api/setup: 旧 X-Setup-Secret 头方式仍可用', async () => { + const ctx = makeEnv({ DB: new D1Mock(false) as unknown as Env['DB'] }); + const res = await request( + app, + '/api/setup', + { + method: 'POST', + headers: { + 'X-Setup-Secret': 'test-setup-secret', + 'cf-connecting-ip': '5.5.5.5', + }, + }, + ctx, + ); + assert.equal(res.status, 200); + assert.ok(Array.isArray((await res.json()).migrations)); +}); + +test('POST /api/setup: 每 IP 每 10 分钟限 3 次,第 4 次 429 + Retry-After(计数先于密钥校验)', async () => { + const ctx = makeEnv(); + const headers = { + 'Content-Type': 'application/json', + 'cf-connecting-ip': '9.9.9.9', + }; + const body = JSON.stringify({ secret: 'wrong-secret' }); + + // 前 3 次都用错误密钥:若计数发生在密钥校验之前,这 3 次会各自返回 403 并 + // 计入配额;第 4 次则因超限返回 429,而不是继续返回 403。 + for (let i = 0; i < 3; i++) { + const res = await request( + app, + '/api/setup', + { method: 'POST', headers, body }, + ctx, + ); + assert.equal(res.status, 403, `第 ${i + 1} 次应为 403(密钥错误)`); + } + + const res = await request( + app, + '/api/setup', + { method: 'POST', headers, body }, + ctx, + ); + assert.equal(res.status, 429); + const retryAfter = Number(res.headers.get('Retry-After')); + assert.ok( + Number.isFinite(retryAfter) && retryAfter > 0, + 'Retry-After 应为正数', + ); + assert.match((await res.json()).error, /Too many setup attempts/); +}); + +// ─── POST /api/admin/setup ──────────────────────────────────────────────────── + +test('POST /api/admin/setup: 非管理员被拒(未认证 401 / 非 admin 403)', async () => { + const ctx = makeEnv(); + await seedUser(ctx.db, { + id: 'u1', + email: 'bob@example.com', + username: 'bob', + role: 'user', + isActive: 1, + tokenVersion: 0, + password: 'password-1', + }); + const token = await accessTokenFor({ + id: 'u1', + email: 'bob@example.com', + role: 'user', + tokenVersion: 0, + }); + + const noAuth = await request( + app, + '/api/admin/setup', + { method: 'POST' }, + ctx, + ); + assert.equal(noAuth.status, 401); + + const asUser = await request( + app, + '/api/admin/setup', + { method: 'POST', headers: { Authorization: `Bearer ${token}` } }, + ctx, + ); + assert.equal(asUser.status, 403); +}); + +test('POST /api/admin/setup: 管理员执行同一迁移逻辑并写审计日志', async () => { + const ctx = makeEnv(); + await seedUser(ctx.db, { + id: 'a1', + email: 'admin@example.com', + username: 'admin', + role: 'admin', + isActive: 1, + tokenVersion: 0, + password: 'password-1', + }); + const token = await accessTokenFor({ + id: 'a1', + email: 'admin@example.com', + role: 'admin', + tokenVersion: 0, + }); + markAllMigrationsApplied(ctx.db); + + const res = await request( + app, + '/api/admin/setup', + { method: 'POST', headers: { Authorization: `Bearer ${token}` } }, + ctx, + ); + assert.equal(res.status, 200); + const body = await res.json(); + assert.deepEqual( + body.migrations.map((m: { status: string }) => m.status), + ['skipped', 'skipped'], + ); + + const row = ctx.db + .prepare( + `SELECT action, target_id, details FROM audit_logs WHERE action = 'run_setup'`, + ) + .first<{ action: string; target_id: string; details: string }>(); + assert.ok(row, '应写入 run_setup 审计日志'); + assert.equal(row?.target_id, 'setup'); + assert.deepEqual(JSON.parse(row?.details ?? '{}'), { + applied: 0, + skipped: 2, + error: 0, + }); +}); + +// ─── 管理设置白名单 ─────────────────────────────────────────────────────────── + +test('PUT /api/admin/settings: 接受 setup_page_enabled,拒绝非法值', async () => { + const ctx = makeEnv(); + await seedUser(ctx.db, { + id: 'a1', + email: 'admin@example.com', + username: 'admin', + role: 'admin', + isActive: 1, + tokenVersion: 0, + password: 'password-1', + }); + const token = await accessTokenFor({ + id: 'a1', + email: 'admin@example.com', + role: 'admin', + tokenVersion: 0, + }); + + const bad = await request( + app, + '/api/admin/settings', + { + method: 'PUT', + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ setup_page_enabled: '2' }), + }, + ctx, + ); + assert.equal(bad.status, 400); + + const good = await request( + app, + '/api/admin/settings', + { + method: 'PUT', + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ setup_page_enabled: '0' }), + }, + ctx, + ); + assert.equal(good.status, 200); + const row = ctx.db + .prepare(`SELECT value FROM settings WHERE key = 'setup_page_enabled'`) + .first<{ value: string }>(); + assert.equal(row?.value, '0'); +}); From 801366c2a10d39d31493f5ee23cba7c10a8e18dd Mon Sep 17 00:00:00 2001 From: Todos Date: Sun, 18 Oct 2026 14:55:03 +0800 Subject: [PATCH 2/2] test(worker): cover the legacy /setup alias path Add two assertions so the backward-compatible /setup mount in index.ts is exercised: POST /setup with the X-Setup-Secret header returns 200, and GET /setup/* returns 405 + Allow: POST. Guards against silently breaking the alias in future changes. Checkpoint: fQy51T3T8GYCOUnLU97of --- apps/worker/test/setup.test.ts | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/apps/worker/test/setup.test.ts b/apps/worker/test/setup.test.ts index 541ffe7..c606261 100644 --- a/apps/worker/test/setup.test.ts +++ b/apps/worker/test/setup.test.ts @@ -70,6 +70,13 @@ test('GET /api/setup/*: 返回 405 + Allow: POST', async () => { assert.match(body.error, /POST \/api\/setup/); }); +test('GET /setup/*: 旧路径别名同样返回 405 + Allow: POST', async () => { + const ctx = makeEnv(); + const res = await request(app, '/setup/anything', { method: 'GET' }, ctx); + assert.equal(res.status, 405); + assert.equal(res.headers.get('Allow'), 'POST'); +}); + // ─── POST /api/setup ────────────────────────────────────────────────────────── test('POST /api/setup: 正确 JSON 密钥把迁移应用到空库并返回结果', async () => { @@ -156,6 +163,24 @@ test('POST /api/setup: 旧 X-Setup-Secret 头方式仍可用', async () => { assert.ok(Array.isArray((await res.json()).migrations)); }); +test('POST /setup: 旧路径别名 + X-Setup-Secret 头仍可用', async () => { + const ctx = makeEnv({ DB: new D1Mock(false) as unknown as Env['DB'] }); + const res = await request( + app, + '/setup', + { + method: 'POST', + headers: { + 'X-Setup-Secret': 'test-setup-secret', + 'cf-connecting-ip': '5.5.5.6', + }, + }, + ctx, + ); + assert.equal(res.status, 200); + assert.ok(Array.isArray((await res.json()).migrations)); +}); + test('POST /api/setup: 每 IP 每 10 分钟限 3 次,第 4 次 429 + Retry-After(计数先于密钥校验)', async () => { const ctx = makeEnv(); const headers = {