From d576782925e8bc06e31299af2e57e03706227111 Mon Sep 17 00:00:00 2001 From: Todos Date: Sun, 18 Oct 2026 15:12:54 +0800 Subject: [PATCH 1/2] feat(web): add /setup page and admin database upgrade entry - Add public /setup page (state check, secret form, migration results) - Add setup_page_enabled toggle and "check & upgrade" button to admin settings - Surface Retry-After on ApiRequestError and map setup errors by status code - Add setupApi/adminApi.runSetup to the typed client plus en/zh-CN strings - Cover state, submit success, 429 and admin upgrade in node --test Checkpoint: T89ynSWY-zOYYWExTx-dD --- apps/web/package.json | 2 +- apps/web/src/App.tsx | 2 + apps/web/src/api/client.ts | 64 +++++- apps/web/src/components/setup-migrations.tsx | 56 +++++ apps/web/src/i18n/locales/en.ts | 34 +++ apps/web/src/i18n/locales/zh-CN.ts | 32 +++ apps/web/src/lib/setup.test.ts | 201 ++++++++++++++++++ apps/web/src/lib/setup.ts | 69 ++++++ apps/web/src/pages/SetupPage.tsx | 116 ++++++++++ .../web/src/pages/admin/AdminSettingsPage.tsx | 103 +++++++++ 10 files changed, 674 insertions(+), 5 deletions(-) create mode 100644 apps/web/src/components/setup-migrations.tsx create mode 100644 apps/web/src/lib/setup.test.ts create mode 100644 apps/web/src/lib/setup.ts create mode 100644 apps/web/src/pages/SetupPage.tsx diff --git a/apps/web/package.json b/apps/web/package.json index 4967367..e72f55f 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -7,7 +7,7 @@ "dev": "vite", "build": "tsc --noEmit && vite build", "typecheck": "tsc --noEmit", - "test": "node --test src/api/client.test.ts src/lib/utils.test.ts src/lib/apiErrorCodes.test.ts", + "test": "node --test src/api/client.test.ts src/lib/utils.test.ts src/lib/apiErrorCodes.test.ts src/lib/setup.test.ts", "preview": "vite preview" }, "dependencies": { diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 94524c1..ee5a81c 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -20,6 +20,7 @@ const ForgotPasswordPage = lazy( const LoginPage = lazy(() => import('./pages/auth/LoginPage.tsx')); const RegisterPage = lazy(() => import('./pages/auth/RegisterPage.tsx')); const TwoFactorPage = lazy(() => import('./pages/auth/TwoFactorPage.tsx')); +const SetupPage = lazy(() => import('./pages/SetupPage.tsx')); const AnalyticsPage = lazy(() => import('./pages/dashboard/AnalyticsPage.tsx')); const LinksPage = lazy(() => import('./pages/dashboard/LinksPage.tsx')); const SettingsPage = lazy(() => import('./pages/dashboard/SettingsPage.tsx')); @@ -93,6 +94,7 @@ export default function App() { } /> } /> } /> + } /> {/* Dashboard */} = 0 ? Math.ceil(n) : undefined; +} + export function isRetryableError(error: unknown): boolean { if (isSessionExpiredError(error)) return false; if (error instanceof ApiRequestError) return error.status >= 500; @@ -139,7 +156,12 @@ async function request( const err = (await retryRes .json() .catch(() => ({ error: 'Request failed' }))) as ApiError; - throw new ApiRequestError(err.error, retryRes.status, err.code); + throw new ApiRequestError( + err.error, + retryRes.status, + err.code, + parseRetryAfter(retryRes.headers.get('Retry-After')), + ); } return retryRes.json() as Promise; } @@ -158,7 +180,12 @@ async function request( const err = (await res .json() .catch(() => ({ error: 'Request failed' }))) as ApiError; - throw new ApiRequestError(err.error, res.status, err.code); + throw new ApiRequestError( + err.error, + res.status, + err.code, + parseRetryAfter(res.headers.get('Retry-After')), + ); } if (res.status === 204) return undefined as T; @@ -606,6 +633,32 @@ export const analyticsApi = { }>(`/analytics/${linkId}?days=${days}`), }; +// ─── Setup API ──────────────────────────────────────────────────────────────── + +export interface SetupMigration { + name: string; + status: 'applied' | 'skipped' | 'error'; + error?: string; +} + +export interface SetupResult { + migrations: SetupMigration[]; +} + +export const setupApi = { + // Public: reports whether the /setup page is enabled (defaults to enabled). + state: () => + request<{ enabled: boolean }>('/setup/state', { skipAuth: true }), + + // Public: runs schema migrations keyed to the setup secret. + run: (secret: string) => + request('/setup', { + method: 'POST', + body: JSON.stringify({ secret }), + skipAuth: true, + }), +}; + // ─── Admin API ──────────────────────────────────────────────────────────────── export const adminApi = { @@ -670,6 +723,9 @@ export const adminApi = { method: 'PUT', body: JSON.stringify(settings), }), + // Runs the same schema-migration routine as POST /api/setup, keyed to the + // admin session (no setup secret required). + runSetup: () => request('/admin/setup', { method: 'POST' }), }; // Re-export WebAuthn types used by auth API diff --git a/apps/web/src/components/setup-migrations.tsx b/apps/web/src/components/setup-migrations.tsx new file mode 100644 index 0000000..3939dc3 --- /dev/null +++ b/apps/web/src/components/setup-migrations.tsx @@ -0,0 +1,56 @@ +import type { SetupMigration } from '@/api/client'; +import { Badge } from '@/components/ui/badge'; +import type { TranslationKey } from '@/i18n'; +import { useTranslation } from '@/i18n'; + +const STATUS_VARIANT = { + applied: 'success', + skipped: 'secondary', + error: 'destructive', +} as const; + +function statusLabel(status: SetupMigration['status']): TranslationKey { + switch (status) { + case 'applied': + return 'setup.statusApplied'; + case 'skipped': + return 'setup.statusSkipped'; + case 'error': + return 'setup.statusError'; + } +} + +// Renders the migration list returned by POST /api/setup and POST /api/admin/setup. +// Shared by the public /setup page and the admin "check & upgrade" action so the +// two stay consistent. +export function SetupMigrationsResult({ + migrations, +}: { + migrations: SetupMigration[]; +}) { + const { t } = useTranslation(); + + if (migrations.length === 0) { + return ( +

{t('setup.noMigrations')}

+ ); + } + + return ( +
    + {migrations.map((m) => ( +
  • +
    + {m.name} + + {t(statusLabel(m.status))} + +
    + {m.status === 'error' && m.error && ( +

    {m.error}

    + )} +
  • + ))} +
+ ); +} diff --git a/apps/web/src/i18n/locales/en.ts b/apps/web/src/i18n/locales/en.ts index ab1e50f..ee0a837 100644 --- a/apps/web/src/i18n/locales/en.ts +++ b/apps/web/src/i18n/locales/en.ts @@ -183,6 +183,29 @@ export const en = { remove: 'Remove', passwordsDoNotMatch: 'Passwords do not match', }, + setup: { + title: 'Database Setup', + titleDesc: 'Initialize or upgrade the database schema.', + secretLabel: 'Setup Secret', + secretPlaceholder: 'Enter the setup secret', + submit: 'Initialize / Upgrade Database', + submitting: 'Running migrations…', + disabledTitle: 'Setup page is disabled', + disabledDesc: + 'The public setup page has been turned off. An administrator can still check and upgrade the database from the admin settings, or use the POST endpoint with the setup secret as an emergency channel.', + migrationsTitle: 'Migration Results', + noMigrations: 'No migrations were reported.', + statusApplied: 'applied', + statusSkipped: 'skipped', + statusError: 'error', + errorBadRequest: + 'Invalid request. A JSON body {"secret": "…"} is required.', + errorForbidden: 'Invalid setup secret.', + errorTooManyRequests: 'Too many requests. Try again in {{seconds}}s.', + errorServer: 'The server is not configured, or the migration failed.', + errorNotFound: 'The backend has not provided this endpoint yet.', + errorGeneric: 'Setup failed. Please try again.', + }, admin: { adminPanel: 'Admin Panel', users: 'Users', @@ -223,6 +246,15 @@ export const en = { emailVerificationDisabled: 'Email verification disabled', emailVerificationRequired: 'required', emailVerificationNotRequired: 'not required', + setupPageToggle: 'Public Setup Page', + setupPageDesc: + 'Show the public /setup page. This only hides the page — the keyed POST endpoint stays available as an emergency channel.', + setupPageCurrent: 'Setup page is currently', + setupPageEnabled: 'enabled', + setupPageDisabled: 'disabled', + runSetup: 'Check & Upgrade Database', + runSetupDesc: + 'Run pending database migrations. Already-applied migrations are reported as skipped.', }, toast: { sessionExpired: 'Session expired. Please sign in again.', @@ -260,6 +292,8 @@ export const en = { registrationDisabled: 'Registration disabled', appNameUpdated: 'App name updated', emailSettingsSaved: 'Email settings saved', + setupPageEnabled: 'Setup page enabled', + setupPageDisabled: 'Setup page disabled', }, errors: { emailOrUsernameTaken: 'This email or username is already taken.', diff --git a/apps/web/src/i18n/locales/zh-CN.ts b/apps/web/src/i18n/locales/zh-CN.ts index b0a4cbb..c1809a9 100644 --- a/apps/web/src/i18n/locales/zh-CN.ts +++ b/apps/web/src/i18n/locales/zh-CN.ts @@ -177,6 +177,28 @@ export const zhCN: Translations = { remove: '删除', passwordsDoNotMatch: '两次输入的密码不一致', }, + setup: { + title: '数据库初始化', + titleDesc: '初始化或升级数据库结构。', + secretLabel: '初始化密钥', + secretPlaceholder: '请输入初始化密钥', + submit: '初始化 / 升级数据库', + submitting: '正在执行迁移…', + disabledTitle: '初始化页面已关闭', + disabledDesc: + '公开的初始化页面已被关闭。管理员仍可在后台执行「检查并升级数据库」,或使用带密钥的 POST 接口作为救急通道。', + migrationsTitle: '迁移结果', + noMigrations: '没有返回任何迁移记录。', + statusApplied: '已应用', + statusSkipped: '已跳过', + statusError: '失败', + errorBadRequest: '请求格式错误,需要 JSON 正文 {"secret": "…"}。', + errorForbidden: '初始化密钥错误。', + errorTooManyRequests: '请求过于频繁,请在 {{seconds}} 秒后重试。', + errorServer: '服务端未配置密钥,或迁移执行失败。', + errorNotFound: '后端尚未提供该接口。', + errorGeneric: '初始化失败,请重试。', + }, admin: { adminPanel: '管理面板', users: '用户', @@ -213,6 +235,14 @@ export const zhCN: Translations = { emailVerificationDisabled: '邮箱验证已禁用', emailVerificationRequired: '必须', emailVerificationNotRequired: '不需要', + setupPageToggle: '公开初始化页面', + setupPageDesc: + '显示公开的 /setup 页面。此开关只隐藏页面,带密钥的 POST 接口仍可作为救急通道使用。', + setupPageCurrent: '初始化页面当前', + setupPageEnabled: '已开启', + setupPageDisabled: '已关闭', + runSetup: '检查并升级数据库', + runSetupDesc: '执行待处理的数据库迁移,已应用的迁移将显示为「已跳过」。', }, toast: { sessionExpired: '登录已过期,请重新登录。', @@ -250,6 +280,8 @@ export const zhCN: Translations = { registrationDisabled: '注册已关闭', appNameUpdated: '应用名称已更新', emailSettingsSaved: '邮件设置已保存', + setupPageEnabled: '初始化页面已开启', + setupPageDisabled: '初始化页面已关闭', }, errors: { emailOrUsernameTaken: '该邮箱或用户名已被占用。', diff --git a/apps/web/src/lib/setup.test.ts b/apps/web/src/lib/setup.test.ts new file mode 100644 index 0000000..ae6aea6 --- /dev/null +++ b/apps/web/src/lib/setup.test.ts @@ -0,0 +1,201 @@ +import assert from 'node:assert/strict'; +import { afterEach, describe, test } from 'node:test'; +import { ApiRequestError, adminApi, setupApi } from '../api/client.ts'; +import { en } from '../i18n/locales/en.ts'; +import { zhCN } from '../i18n/locales/zh-CN.ts'; +import { resolveSetupError } from './setup.ts'; + +// Setup/upgrade frontend behaviour, pinned down with a stubbed fetch and pure +// helpers (same style as client.test.ts and apiErrorCodes.test.ts — no extra +// test dependencies). Covers the public /setup page state, migration results, +// the 429 Retry-After mapping, and the admin "check & upgrade" action. + +const originalFetch = globalThis.fetch; + +function jsonResponse( + body: unknown, + status = 200, + headers?: Record, +): Response { + return new Response(JSON.stringify(body), { status, headers }); +} + +function mockFetch( + handler: (url: string, init?: RequestInit) => Response | Promise, +): string[] { + const calls: string[] = []; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + calls.push(url); + return handler(url, init); + }) as typeof fetch; + return calls; +} + +afterEach(() => { + globalThis.fetch = originalFetch; +}); + +describe('setupApi.state', () => { + test('reports disabled when the backend says enabled=false', async () => { + mockFetch((url) => { + assert.match(url, /\/api\/setup\/state$/); + return jsonResponse({ enabled: false }); + }); + + assert.equal((await setupApi.state()).enabled, false); + }); + + test('reports enabled', async () => { + mockFetch((url) => { + assert.match(url, /\/api\/setup\/state$/); + return jsonResponse({ enabled: true }); + }); + + assert.equal((await setupApi.state()).enabled, true); + }); +}); + +describe('setupApi.run', () => { + test('returns migration results on success and sends the secret in the body', async () => { + const calls = mockFetch((url, init) => { + assert.match(url, /\/api\/setup$/); + assert.equal(JSON.parse(String(init?.body)).secret, 'top-secret'); + return jsonResponse({ + migrations: [ + { name: 'schema_v1', status: 'applied' }, + { name: 'schema_v2', status: 'skipped' }, + ], + }); + }); + + const result = await setupApi.run('top-secret'); + assert.equal(calls.length, 1); + assert.deepEqual( + result.migrations.map((m) => m.status), + ['applied', 'skipped'], + ); + }); + + test('surfaces Retry-After seconds on a 429', async () => { + mockFetch( + () => + new Response(JSON.stringify({ error: 'Too many setup attempts.' }), { + status: 429, + headers: { 'Retry-After': '120', 'Content-Type': 'application/json' }, + }), + ); + + await assert.rejects(setupApi.run('secret'), (error: unknown) => { + assert.ok(error instanceof ApiRequestError); + assert.equal(error.status, 429); + assert.equal(error.retryAfter, 120); + return true; + }); + }); +}); + +describe('adminApi.runSetup', () => { + test('returns migration results on success', async () => { + const calls = mockFetch((url, init) => { + assert.match(url, /\/api\/admin\/setup$/); + assert.equal(init?.method, 'POST'); + return jsonResponse({ + migrations: [ + { name: 'schema_v1', status: 'skipped' }, + { name: 'schema_v2', status: 'error', error: 'boom' }, + ], + }); + }); + + const result = await adminApi.runSetup(); + assert.equal(calls.length, 1); + assert.equal(result.migrations[1]?.status, 'error'); + assert.equal(result.migrations[1]?.error, 'boom'); + }); +}); + +describe('resolveSetupError', () => { + test('maps a 429 with Retry-After to the localized too-many-requests key', () => { + assert.deepEqual(resolveSetupError({ status: 429, retryAfter: 120 }), { + kind: 'i18n', + key: 'setup.errorTooManyRequests', + params: { seconds: 120 }, + }); + }); + + test('maps 400, 403, 404 and 500 to their status keys', () => { + assert.deepEqual(resolveSetupError({ status: 400 }), { + kind: 'i18n', + key: 'setup.errorBadRequest', + }); + assert.deepEqual(resolveSetupError({ status: 403 }), { + kind: 'i18n', + key: 'setup.errorForbidden', + }); + assert.deepEqual(resolveSetupError({ status: 404 }), { + kind: 'i18n', + key: 'setup.errorNotFound', + }); + assert.deepEqual(resolveSetupError({ status: 500 }), { + kind: 'i18n', + key: 'setup.errorServer', + }); + }); + + test('falls back to the raw backend message for unmatched errors', () => { + assert.deepEqual(resolveSetupError(new Error('boom')), { + kind: 'raw', + message: 'boom', + }); + }); + + test('maps a known backend code through API_ERROR_CODES', () => { + assert.deepEqual( + resolveSetupError({ status: 400, code: 'REGISTRATION_DISABLED' }), + { kind: 'i18n', key: 'errors.registrationDisabled' }, + ); + }); +}); + +describe('setup i18n keys', () => { + function resolve(obj: unknown, path: string): unknown { + let curr = obj; + for (const p of path.split('.')) { + if (curr == null || typeof curr !== 'object') return undefined; + curr = (curr as Record)[p]; + } + return curr; + } + + test('resolve to non-empty strings in both locales', () => { + const keys = [ + 'setup.title', + 'setup.disabledTitle', + 'setup.disabledDesc', + 'setup.errorBadRequest', + 'setup.errorForbidden', + 'setup.errorTooManyRequests', + 'setup.errorServer', + 'setup.errorNotFound', + 'setup.statusApplied', + 'setup.statusSkipped', + 'setup.statusError', + 'admin.setupPageToggle', + 'admin.setupPageDesc', + 'admin.runSetup', + 'toast.setupPageEnabled', + 'toast.setupPageDisabled', + ]; + for (const key of keys) { + assert.equal(typeof resolve(en, key), 'string', `${key} (en) is missing`); + assert.equal( + typeof resolve(zhCN, key), + 'string', + `${key} (zh-CN) is missing`, + ); + assert.ok((resolve(en, key) as string).length > 0, `${key} (en) empty`); + assert.ok((resolve(zhCN, key) as string).length > 0, `${key} (zh) empty`); + } + }); +}); diff --git a/apps/web/src/lib/setup.ts b/apps/web/src/lib/setup.ts new file mode 100644 index 0000000..8b684c9 --- /dev/null +++ b/apps/web/src/lib/setup.ts @@ -0,0 +1,69 @@ +import type { TFunction, TranslationKey } from '@/i18n'; +import { API_ERROR_CODES } from './apiErrorCodes.ts'; + +// A setup/upgrade error, resolved either to a localized message key (with +// optional interpolation params) or to a raw fallback string — the backend's +// own `error` text when no mapping applies. + +export type SetupErrorMsg = + | { + kind: 'i18n'; + key: TranslationKey; + params?: Record; + } + | { kind: 'raw'; message: string }; + +// Structural view of what an API error looks like for setup/upgrade, so this +// helper needs no runtime import of `@/api/client` and can be unit-tested with +// `node --test` (Node's type stripping does no `@/` alias resolution). +export interface SetupErrorLike { + status: number; + code?: string; + retryAfter?: number; + message?: string; +} + +// Maps a setup/upgrade error to a display message. The endpoints return plain +// `{ error }` bodies without a `code`, so status codes drive the mapping. A +// `code`, when the backend does send one, still goes through API_ERROR_CODES so +// future codes localize without a frontend change; an unknown code falls through +// to the status-based mapping, and an unmatched status to the raw text. +export function resolveSetupError(error: unknown): SetupErrorMsg { + if (error && typeof error === 'object') { + const e = error as SetupErrorLike; + if (typeof e.code === 'string' && e.code !== '') { + const key = API_ERROR_CODES[e.code] as TranslationKey | undefined; + if (key) return { kind: 'i18n', key }; + } + switch (e.status) { + case 400: + return { kind: 'i18n', key: 'setup.errorBadRequest' }; + case 403: + return { kind: 'i18n', key: 'setup.errorForbidden' }; + case 404: + return { kind: 'i18n', key: 'setup.errorNotFound' }; + case 429: + return { + kind: 'i18n', + key: 'setup.errorTooManyRequests', + params: { seconds: e.retryAfter ?? 0 }, + }; + case 500: + return { kind: 'i18n', key: 'setup.errorServer' }; + } + } + const message = + error instanceof Error && error.message ? error.message : undefined; + if (message) return { kind: 'raw', message }; + return { kind: 'i18n', key: 'setup.errorGeneric' }; +} + +// Turns a resolved setup error into its display string (localized key, or the +// backend's raw message), or null when there is no error to show. +export function formatSetupError( + msg: SetupErrorMsg | null, + t: TFunction, +): string | null { + if (!msg) return null; + return msg.kind === 'i18n' ? t(msg.key, msg.params) : msg.message; +} diff --git a/apps/web/src/pages/SetupPage.tsx b/apps/web/src/pages/SetupPage.tsx new file mode 100644 index 0000000..90504cf --- /dev/null +++ b/apps/web/src/pages/SetupPage.tsx @@ -0,0 +1,116 @@ +import { useEffect, useState } from 'react'; +import type { SetupResult } from '@/api/client'; +import { setupApi } from '@/api/client'; +import { SetupMigrationsResult } from '@/components/setup-migrations'; +import { AuthCard } from '@/components/ui/auth-card'; +import { Button } from '@/components/ui/button'; +import { + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from '@/components/ui/card'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { useTranslation } from '@/i18n'; +import type { SetupErrorMsg } from '@/lib/setup'; +import { formatSetupError, resolveSetupError } from '@/lib/setup'; + +export default function SetupPage() { + const { t } = useTranslation(); + const [stateLoading, setStateLoading] = useState(true); + const [stateError, setStateError] = useState(null); + const [enabled, setEnabled] = useState(false); + const [secret, setSecret] = useState(''); + const [submitting, setSubmitting] = useState(false); + const [result, setResult] = useState(null); + const [runError, setRunError] = useState(null); + + useEffect(() => { + let cancelled = false; + setupApi + .state() + .then((s) => { + if (!cancelled) setEnabled(s.enabled); + }) + .catch((err: unknown) => { + if (!cancelled) setStateError(resolveSetupError(err)); + }) + .finally(() => { + if (!cancelled) setStateLoading(false); + }); + return () => { + cancelled = true; + }; + }, []); + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + setSubmitting(true); + setRunError(null); + setResult(null); + try { + setResult(await setupApi.run(secret)); + } catch (err) { + setRunError(resolveSetupError(err)); + } finally { + setSubmitting(false); + } + }; + + return ( + + + {t('setup.title')} + {t('setup.titleDesc')} + + + {stateLoading ? ( +

{t('common.loading')}

+ ) : stateError ? ( +

+ {formatSetupError(stateError, t)} +

+ ) : !enabled ? ( +
+

{t('setup.disabledTitle')}

+

+ {t('setup.disabledDesc')} +

+
+ ) : ( +
+
+ + setSecret(e.target.value)} + placeholder={t('setup.secretPlaceholder')} + required + autoComplete="off" + /> +
+ +
+ )} + + {runError && ( +

+ {formatSetupError(runError, t)} +

+ )} + + {result && ( +
+

{t('setup.migrationsTitle')}

+ +
+ )} +
+
+ ); +} diff --git a/apps/web/src/pages/admin/AdminSettingsPage.tsx b/apps/web/src/pages/admin/AdminSettingsPage.tsx index d21d585..45a247c 100644 --- a/apps/web/src/pages/admin/AdminSettingsPage.tsx +++ b/apps/web/src/pages/admin/AdminSettingsPage.tsx @@ -1,7 +1,9 @@ import { useQuery } from '@tanstack/react-query'; import { useEffect, useState } from 'react'; import { toast } from 'sonner'; +import type { SetupResult } from '@/api/client'; import { adminApi } from '@/api/client'; +import { SetupMigrationsResult } from '@/components/setup-migrations'; import { Button } from '@/components/ui/button'; import { Card, @@ -15,6 +17,8 @@ import { Label } from '@/components/ui/label'; import { Switch } from '@/components/ui/switch'; import { useAppConfig } from '@/contexts/AppConfigContext'; import { useTranslation } from '@/i18n'; +import type { SetupErrorMsg } from '@/lib/setup'; +import { formatSetupError, resolveSetupError } from '@/lib/setup'; import { toastApiError } from '@/lib/toast'; export default function AdminSettingsPage() { @@ -51,6 +55,16 @@ export default function AdminSettingsPage() { const [resendKeyIsSet, setResendKeyIsSet] = useState(false); const [smtpPassIsSet, setSmtpPassIsSet] = useState(false); + // Setup page toggle + "check & upgrade database" action + const [setupPageEnabled, setSetupPageEnabled] = useState(true); + const [runSetupLoading, setRunSetupLoading] = useState(false); + const [runSetupResult, setRunSetupResult] = useState( + null, + ); + const [runSetupError, setRunSetupError] = useState( + null, + ); + useEffect(() => { if (data?.settings) { const s = data.settings; @@ -70,6 +84,8 @@ export default function AdminSettingsPage() { setSmtpPass(''); setSmtpPassIsSet(s.smtp_pass === '***'); setSmtpFrom(s.smtp_from ?? ''); + // FE-S13: setup_page_enabled is stored as '0'/'1'; absent defaults to on. + setSetupPageEnabled(s.setup_page_enabled !== '0'); } }, [data]); @@ -147,6 +163,34 @@ export default function AdminSettingsPage() { } }; + const handleSetupPageToggle = async (enabled: boolean) => { + setSetupPageEnabled(enabled); + try { + await adminApi.updateSettings({ + setup_page_enabled: enabled ? '1' : '0', + }); + toast.success( + enabled ? t('toast.setupPageEnabled') : t('toast.setupPageDisabled'), + ); + } catch (err) { + setSetupPageEnabled(!enabled); + toastApiError(err, t('toast.requestFailed'), t); + } + }; + + const handleRunSetup = async () => { + setRunSetupLoading(true); + setRunSetupError(null); + setRunSetupResult(null); + try { + setRunSetupResult(await adminApi.runSetup()); + } catch (err) { + setRunSetupError(resolveSetupError(err)); + } finally { + setRunSetupLoading(false); + } + }; + if (isLoading) return (
{t('common.loading')}
@@ -208,6 +252,33 @@ export default function AdminSettingsPage() { + {/* Setup page toggle */} + + + + {t('admin.setupPageToggle')} + + {t('admin.setupPageDesc')} + + +
+ + +
+
+
+ {/* App name */} @@ -397,6 +468,38 @@ export default function AdminSettingsPage() { + + {/* Check & upgrade database */} + + + {t('admin.runSetup')} + {t('admin.runSetupDesc')} + + + + + {runSetupError && ( +

+ {formatSetupError(runSetupError, t)} +

+ )} + + {runSetupResult && ( +
+

+ {t('setup.migrationsTitle')} +

+ +
+ )} +
+
); } From 06334239455746dffaf95eb5fbcd99b698ec7410 Mon Sep 17 00:00:00 2001 From: Todos Date: Sun, 18 Oct 2026 15:26:11 +0800 Subject: [PATCH 2/2] fix(web): localize setup errors and test display mapping - Return null for session-expired setup/admin errors instead of leaking untranslated text alongside AuthProvider's global toast - Fall back to setup.errorGeneric for unclassified errors, dropping the raw backend-message branch that bypassed i18n - Extract migration status label/variant and formatSetupError into pure helpers and cover them (plus session-expiry and interpolation) in node --test Checkpoint: kWYiOxJIc96_8plsowQ7v --- apps/web/src/components/setup-migrations.tsx | 26 +---- apps/web/src/lib/setup.test.ts | 111 ++++++++++++++++--- apps/web/src/lib/setup.ts | 81 +++++++++----- 3 files changed, 154 insertions(+), 64 deletions(-) diff --git a/apps/web/src/components/setup-migrations.tsx b/apps/web/src/components/setup-migrations.tsx index 3939dc3..52079bb 100644 --- a/apps/web/src/components/setup-migrations.tsx +++ b/apps/web/src/components/setup-migrations.tsx @@ -1,28 +1,12 @@ import type { SetupMigration } from '@/api/client'; import { Badge } from '@/components/ui/badge'; -import type { TranslationKey } from '@/i18n'; import { useTranslation } from '@/i18n'; - -const STATUS_VARIANT = { - applied: 'success', - skipped: 'secondary', - error: 'destructive', -} as const; - -function statusLabel(status: SetupMigration['status']): TranslationKey { - switch (status) { - case 'applied': - return 'setup.statusApplied'; - case 'skipped': - return 'setup.statusSkipped'; - case 'error': - return 'setup.statusError'; - } -} +import { MIGRATION_STATUS_VARIANT, migrationStatusLabel } from '@/lib/setup'; // Renders the migration list returned by POST /api/setup and POST /api/admin/setup. // Shared by the public /setup page and the admin "check & upgrade" action so the -// two stay consistent. +// two stay consistent. The status → label / variant mapping lives in +// lib/setup.ts as pure functions so it can be unit-tested. export function SetupMigrationsResult({ migrations, }: { @@ -42,8 +26,8 @@ export function SetupMigrationsResult({
  • {m.name} - - {t(statusLabel(m.status))} + + {t(migrationStatusLabel(m.status))}
    {m.status === 'error' && m.error && ( diff --git a/apps/web/src/lib/setup.test.ts b/apps/web/src/lib/setup.test.ts index ae6aea6..b269630 100644 --- a/apps/web/src/lib/setup.test.ts +++ b/apps/web/src/lib/setup.test.ts @@ -1,14 +1,25 @@ import assert from 'node:assert/strict'; import { afterEach, describe, test } from 'node:test'; -import { ApiRequestError, adminApi, setupApi } from '../api/client.ts'; +import { + ApiRequestError, + adminApi, + SessionExpiredError, + setupApi, +} from '../api/client.ts'; import { en } from '../i18n/locales/en.ts'; import { zhCN } from '../i18n/locales/zh-CN.ts'; -import { resolveSetupError } from './setup.ts'; +import { + formatSetupError, + MIGRATION_STATUS_VARIANT, + migrationStatusLabel, + resolveSetupError, +} from './setup.ts'; // Setup/upgrade frontend behaviour, pinned down with a stubbed fetch and pure // helpers (same style as client.test.ts and apiErrorCodes.test.ts — no extra -// test dependencies). Covers the public /setup page state, migration results, -// the 429 Retry-After mapping, and the admin "check & upgrade" action. +// test dependencies). The React components (SetupPage, SetupMigrationsResult, +// AdminSettingsPage) are not rendered here; their display logic is extracted +// into the pure functions asserted below, which is what those components call. const originalFetch = globalThis.fetch; @@ -118,7 +129,6 @@ describe('adminApi.runSetup', () => { describe('resolveSetupError', () => { test('maps a 429 with Retry-After to the localized too-many-requests key', () => { assert.deepEqual(resolveSetupError({ status: 429, retryAfter: 120 }), { - kind: 'i18n', key: 'setup.errorTooManyRequests', params: { seconds: 120 }, }); @@ -126,36 +136,110 @@ describe('resolveSetupError', () => { test('maps 400, 403, 404 and 500 to their status keys', () => { assert.deepEqual(resolveSetupError({ status: 400 }), { - kind: 'i18n', key: 'setup.errorBadRequest', }); assert.deepEqual(resolveSetupError({ status: 403 }), { - kind: 'i18n', key: 'setup.errorForbidden', }); assert.deepEqual(resolveSetupError({ status: 404 }), { - kind: 'i18n', key: 'setup.errorNotFound', }); assert.deepEqual(resolveSetupError({ status: 500 }), { - kind: 'i18n', key: 'setup.errorServer', }); }); - test('falls back to the raw backend message for unmatched errors', () => { + test('falls back to the generic key for unmatched errors', () => { assert.deepEqual(resolveSetupError(new Error('boom')), { - kind: 'raw', - message: 'boom', + key: 'setup.errorGeneric', }); }); test('maps a known backend code through API_ERROR_CODES', () => { assert.deepEqual( resolveSetupError({ status: 400, code: 'REGISTRATION_DISABLED' }), - { kind: 'i18n', key: 'errors.registrationDisabled' }, + { key: 'errors.registrationDisabled' }, ); }); + + test('is silent for a session-expired error', () => { + assert.equal(resolveSetupError(new SessionExpiredError()), null); + }); +}); + +describe('formatSetupError', () => { + function makeT(locale: unknown) { + const resolve = (obj: unknown, path: string): string => { + let curr = obj; + for (const p of path.split('.')) { + curr = (curr as Record)[p]; + } + return String(curr); + }; + return (key: string, params?: Record): string => { + let text = resolve(locale, key); + if (params) { + for (const [k, v] of Object.entries(params)) { + text = text.replace(`{{${k}}}`, String(v)); + } + } + return text; + }; + } + + test('returns null when there is no error to show', () => { + assert.equal(formatSetupError(null, makeT(en)), null); + }); + + test('interpolates the Retry-After seconds into the localized message', () => { + const msg = resolveSetupError({ status: 429, retryAfter: 120 }); + assert.equal( + formatSetupError(msg, makeT(en)), + 'Too many requests. Try again in 120s.', + ); + assert.equal( + formatSetupError(msg, makeT(zhCN)), + '请求过于频繁,请在 120 秒后重试。', + ); + }); +}); + +describe('migration status display', () => { + test('maps each status to a localized label key', () => { + assert.equal(migrationStatusLabel('applied'), 'setup.statusApplied'); + assert.equal(migrationStatusLabel('skipped'), 'setup.statusSkipped'); + assert.equal(migrationStatusLabel('error'), 'setup.statusError'); + }); + + test('maps each status to a Badge variant', () => { + assert.equal(MIGRATION_STATUS_VARIANT.applied, 'success'); + assert.equal(MIGRATION_STATUS_VARIANT.skipped, 'secondary'); + assert.equal(MIGRATION_STATUS_VARIANT.error, 'destructive'); + }); + + test('status label keys resolve in both locales', () => { + const resolve = (obj: unknown, path: string): unknown => { + let curr = obj; + for (const p of path.split('.')) { + if (curr == null || typeof curr !== 'object') return undefined; + curr = (curr as Record)[p]; + } + return curr; + }; + for (const status of ['applied', 'skipped', 'error'] as const) { + const key = migrationStatusLabel(status); + assert.ok( + typeof resolve(en, key) === 'string' && + (resolve(en, key) as string).length > 0, + `${key} (en) is missing`, + ); + assert.ok( + typeof resolve(zhCN, key) === 'string' && + (resolve(zhCN, key) as string).length > 0, + `${key} (zh-CN) is missing`, + ); + } + }); }); describe('setup i18n keys', () => { @@ -178,6 +262,7 @@ describe('setup i18n keys', () => { 'setup.errorTooManyRequests', 'setup.errorServer', 'setup.errorNotFound', + 'setup.errorGeneric', 'setup.statusApplied', 'setup.statusSkipped', 'setup.statusError', diff --git a/apps/web/src/lib/setup.ts b/apps/web/src/lib/setup.ts index 8b684c9..4d9377b 100644 --- a/apps/web/src/lib/setup.ts +++ b/apps/web/src/lib/setup.ts @@ -1,21 +1,43 @@ import type { TFunction, TranslationKey } from '@/i18n'; +import { isSessionExpiredError } from '../api/client.ts'; import { API_ERROR_CODES } from './apiErrorCodes.ts'; -// A setup/upgrade error, resolved either to a localized message key (with -// optional interpolation params) or to a raw fallback string — the backend's -// own `error` text when no mapping applies. +// Pure, testable helpers for the /setup page and the admin "check & upgrade" +// action. Kept free of React so they run under `node --test`; the runtime import +// below is relative (`.ts`) because Node's type stripping does no `@/` alias +// resolution. -export type SetupErrorMsg = - | { - kind: 'i18n'; - key: TranslationKey; - params?: Record; - } - | { kind: 'raw'; message: string }; +// ─── Migration result display ──────────────────────────────────────────────── + +export type MigrationStatus = 'applied' | 'skipped' | 'error'; + +// Maps a migration status to the Badge variant shown next to its name. +export const MIGRATION_STATUS_VARIANT = { + applied: 'success', + skipped: 'secondary', + error: 'destructive', +} as const; + +// Maps a migration status to its localized label key. +export function migrationStatusLabel(status: MigrationStatus): TranslationKey { + switch (status) { + case 'applied': + return 'setup.statusApplied'; + case 'skipped': + return 'setup.statusSkipped'; + case 'error': + return 'setup.statusError'; + } +} + +// ─── Error mapping ──────────────────────────────────────────────────────────── + +export type SetupErrorMsg = { + key: TranslationKey; + params?: Record; +}; -// Structural view of what an API error looks like for setup/upgrade, so this -// helper needs no runtime import of `@/api/client` and can be unit-tested with -// `node --test` (Node's type stripping does no `@/` alias resolution). +// Structural view of what an API error looks like for setup/upgrade. export interface SetupErrorLike { status: number; code?: string; @@ -23,47 +45,46 @@ export interface SetupErrorLike { message?: string; } -// Maps a setup/upgrade error to a display message. The endpoints return plain +// Maps a setup/upgrade error to a localized message. The endpoints return plain // `{ error }` bodies without a `code`, so status codes drive the mapping. A // `code`, when the backend does send one, still goes through API_ERROR_CODES so -// future codes localize without a frontend change; an unknown code falls through -// to the status-based mapping, and an unmatched status to the raw text. -export function resolveSetupError(error: unknown): SetupErrorMsg { +// future codes localize without a frontend change. Returns null for a +// session-expired error so callers stay quiet (AuthProvider shows the single +// global toast); every other unclassified error falls back to the generic key +// rather than leaking an untranslated backend/network string. +export function resolveSetupError(error: unknown): SetupErrorMsg | null { + if (isSessionExpiredError(error)) return null; if (error && typeof error === 'object') { const e = error as SetupErrorLike; if (typeof e.code === 'string' && e.code !== '') { const key = API_ERROR_CODES[e.code] as TranslationKey | undefined; - if (key) return { kind: 'i18n', key }; + if (key) return { key }; } switch (e.status) { case 400: - return { kind: 'i18n', key: 'setup.errorBadRequest' }; + return { key: 'setup.errorBadRequest' }; case 403: - return { kind: 'i18n', key: 'setup.errorForbidden' }; + return { key: 'setup.errorForbidden' }; case 404: - return { kind: 'i18n', key: 'setup.errorNotFound' }; + return { key: 'setup.errorNotFound' }; case 429: return { - kind: 'i18n', key: 'setup.errorTooManyRequests', params: { seconds: e.retryAfter ?? 0 }, }; case 500: - return { kind: 'i18n', key: 'setup.errorServer' }; + return { key: 'setup.errorServer' }; } } - const message = - error instanceof Error && error.message ? error.message : undefined; - if (message) return { kind: 'raw', message }; - return { kind: 'i18n', key: 'setup.errorGeneric' }; + return { key: 'setup.errorGeneric' }; } -// Turns a resolved setup error into its display string (localized key, or the -// backend's raw message), or null when there is no error to show. +// Turns a resolved setup error into its display string, or null when there is +// nothing to show (no error, or a session-expired error handled elsewhere). export function formatSetupError( msg: SetupErrorMsg | null, t: TFunction, ): string | null { if (!msg) return null; - return msg.kind === 'i18n' ? t(msg.key, msg.params) : msg.message; + return t(msg.key, msg.params); }