Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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'));
Expand Down Expand Up @@ -93,6 +94,7 @@ export default function App() {
<Route path="/register" element={<RegisterPage />} />
<Route path="/two-factor" element={<TwoFactorPage />} />
<Route path="/forgot-password" element={<ForgotPasswordPage />} />
<Route path="/setup" element={<SetupPage />} />

{/* Dashboard */}
<Route
Expand Down
64 changes: 60 additions & 4 deletions apps/web/src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,21 @@ interface ApiError {
export class ApiRequestError extends Error {
readonly status: number;
readonly code?: string;

constructor(message: string, status: number, code?: string) {
// FE-S14: the setup endpoint rate-limits per IP and tells the caller how long
// to wait via `Retry-After`. Surfaces it so the UI can show the seconds.
readonly retryAfter?: number;

constructor(
message: string,
status: number,
code?: string,
retryAfter?: number,
) {
super(message);
this.name = 'ApiRequestError';
this.status = status;
this.code = code;
this.retryAfter = retryAfter;
}
}

Expand Down Expand Up @@ -86,6 +95,14 @@ export function isSessionExpiredError(error: unknown): boolean {
return error instanceof SessionExpiredError;
}

// Parses a `Retry-After` header (seconds) into a non-negative integer, or
// undefined when absent or unparsable.
function parseRetryAfter(value: string | null): number | undefined {
if (!value) return undefined;
const n = Number(value);
return Number.isFinite(n) && n >= 0 ? Math.ceil(n) : undefined;
}

export function isRetryableError(error: unknown): boolean {
if (isSessionExpiredError(error)) return false;
if (error instanceof ApiRequestError) return error.status >= 500;
Expand Down Expand Up @@ -139,7 +156,12 @@ async function request<T>(
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<T>;
}
Expand All @@ -158,7 +180,12 @@ async function request<T>(
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;
Expand Down Expand Up @@ -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<SetupResult>('/setup', {
method: 'POST',
body: JSON.stringify({ secret }),
skipAuth: true,
}),
};

// ─── Admin API ────────────────────────────────────────────────────────────────

export const adminApi = {
Expand Down Expand Up @@ -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<SetupResult>('/admin/setup', { method: 'POST' }),
};

// Re-export WebAuthn types used by auth API
Expand Down
40 changes: 40 additions & 0 deletions apps/web/src/components/setup-migrations.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import type { SetupMigration } from '@/api/client';
import { Badge } from '@/components/ui/badge';
import { useTranslation } from '@/i18n';
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. The status → label / variant mapping lives in
// lib/setup.ts as pure functions so it can be unit-tested.
export function SetupMigrationsResult({
migrations,
}: {
migrations: SetupMigration[];
}) {
const { t } = useTranslation();

if (migrations.length === 0) {
return (
<p className="text-sm text-muted-foreground">{t('setup.noMigrations')}</p>
);
}

return (
<ul className="space-y-2">
{migrations.map((m) => (
<li key={m.name} className="rounded-md border p-3">
<div className="flex items-center justify-between gap-2">
<span className="font-mono text-sm">{m.name}</span>
<Badge variant={MIGRATION_STATUS_VARIANT[m.status]}>
{t(migrationStatusLabel(m.status))}
</Badge>
</div>
{m.status === 'error' && m.error && (
<p className="mt-1 break-all text-xs text-destructive">{m.error}</p>
)}
</li>
))}
</ul>
);
}
34 changes: 34 additions & 0 deletions apps/web/src/i18n/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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.',
Expand Down Expand Up @@ -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.',
Expand Down
32 changes: 32 additions & 0 deletions apps/web/src/i18n/locales/zh-CN.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: '用户',
Expand Down Expand Up @@ -213,6 +235,14 @@ export const zhCN: Translations = {
emailVerificationDisabled: '邮箱验证已禁用',
emailVerificationRequired: '必须',
emailVerificationNotRequired: '不需要',
setupPageToggle: '公开初始化页面',
setupPageDesc:
'显示公开的 /setup 页面。此开关只隐藏页面,带密钥的 POST 接口仍可作为救急通道使用。',
setupPageCurrent: '初始化页面当前',
setupPageEnabled: '已开启',
setupPageDisabled: '已关闭',
runSetup: '检查并升级数据库',
runSetupDesc: '执行待处理的数据库迁移,已应用的迁移将显示为「已跳过」。',
},
toast: {
sessionExpired: '登录已过期,请重新登录。',
Expand Down Expand Up @@ -250,6 +280,8 @@ export const zhCN: Translations = {
registrationDisabled: '注册已关闭',
appNameUpdated: '应用名称已更新',
emailSettingsSaved: '邮件设置已保存',
setupPageEnabled: '初始化页面已开启',
setupPageDisabled: '初始化页面已关闭',
},
errors: {
emailOrUsernameTaken: '该邮箱或用户名已被占用。',
Expand Down
Loading
Loading