diff --git a/web/src/App.tsx b/web/src/App.tsx index 126cc5d..801d595 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -2,22 +2,42 @@ import * as React from "react"; import { Toaster } from "@/components/ui/sonner"; import { AdminPage } from "@/components/admin/admin-page"; import { PublicPage } from "@/components/public-page"; +import { SetupPage } from "@/components/setup/setup-page"; import { useNavStore } from "@/lib/nav-store"; /** * 应用路由:/ 公开页,登录以 /api/private 401 触发的弹窗承载(不整页跳转), - * #admin 后台(登录后可用)。 + * /setup 数据库初始化/升级页,/#admin 后台(登录后可用)。 + * + * pathname 优先(/setup 是独立页面,后端 SPA 回退已落到 index.html), + * 其余保持原有的 #admin 哈希路由。 */ +type Route = "public" | "admin" | "setup"; + +function readRoute(): Route { + if (window.location.pathname.replace(/\/+$/, "") === "/setup") return "setup"; + return window.location.hash === "#admin" ? "admin" : "public"; +} + export default function App() { - const [route, setRoute] = React.useState<"public" | "admin">("public"); + const [route, setRoute] = React.useState(() => readRoute()); const { authenticated, loginPromptOpen, setLoginPrompt } = useNavStore(); React.useEffect(() => { - const onPop = () => - setRoute(window.location.hash === "#admin" ? "admin" : "public"); - window.addEventListener("hashchange", onPop); - onPop(); - return () => window.removeEventListener("hashchange", onPop); + const sync = () => setRoute(readRoute()); + window.addEventListener("hashchange", sync); + window.addEventListener("popstate", sync); + sync(); + return () => { + window.removeEventListener("hashchange", sync); + window.removeEventListener("popstate", sync); + }; + }, []); + + // 站内跳转(不整页刷新):写历史再同步路由状态 + const navigate = React.useCallback((path: string) => { + window.history.pushState({}, "", path); + setRoute(readRoute()); }, []); // 未登录访问 #admin → 弹登录 @@ -29,20 +49,15 @@ export default function App() { return ( <> - {route === "admin" && authenticated ? ( - { - window.location.hash = ""; - setRoute("public"); - }} + {route === "setup" ? ( + navigate("/")} + onGoAdmin={() => navigate("/#admin")} /> + ) : route === "admin" && authenticated ? ( + navigate("/")} /> ) : ( - { - window.location.hash = "#admin"; - setRoute("admin"); - }} - /> + navigate("/#admin")} /> )} diff --git a/web/src/components/admin/admin-page.tsx b/web/src/components/admin/admin-page.tsx index 40bc67c..83d94bd 100644 --- a/web/src/components/admin/admin-page.tsx +++ b/web/src/components/admin/admin-page.tsx @@ -9,10 +9,11 @@ import { SearchEnginePanel, SettingsPanel, } from "@/components/admin/settings-panels"; +import { SystemPanel } from "@/components/admin/system-panel"; import { useNavStore } from "@/lib/nav-store"; /** - * 后台(/admin):分类 / 链接 / 搜索引擎 / 站点设置 CRUD + 导入导出, + * 后台(/admin):分类 / 链接 / 搜索引擎 / 站点设置 CRUD + 导入导出 + 系统管理, * 列表用 dnd-kit 拖拽排序(含上移/下移键盘替代)。 * 后台数据由 store(useNavStore.adminData)承载,本页只负责加载与分发。 */ @@ -58,6 +59,7 @@ export function AdminPage({ onBack }: { onBack: () => void }) { 搜索引擎 站点设置 导入导出 + 系统管理 @@ -98,6 +100,10 @@ export function AdminPage({ onBack }: { onBack: () => void }) { onChanged={() => void loadAdmin()} /> + + + + ) : (

加载中…

diff --git a/web/src/components/admin/system-panel.tsx b/web/src/components/admin/system-panel.tsx new file mode 100644 index 0000000..58b9c80 --- /dev/null +++ b/web/src/components/admin/system-panel.tsx @@ -0,0 +1,245 @@ +import * as React from "react"; +import { Database, ExternalLink, Loader2 } from "lucide-react"; +import { toast } from "sonner"; +import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { Label } from "@/components/ui/label"; +import { Separator } from "@/components/ui/separator"; +import { Switch } from "@/components/ui/switch"; +import { + ApiError, + adminGetSystem, + adminRunSetup, + adminSetSetupPage, +} from "@/lib/api"; +import { MigrationResults } from "@/components/setup/migration-results"; +import type { AdminSystem, SetupResult } from "@/lib/types"; + +/** + * 后台「系统管理」选项卡(SETUP-PAGE-SPEC §5): + * - 数据库维护:生效 tablePrefix + 账本已记录迁移;「检查并升级数据库」走 + * POST /api/admin/setup(免密钥,会话鉴权),逐条展示 applied/skipped; + * - setup 页面:Switch 绑定 setupPageEnabled,PUT 后回读确认;旁注说明开关只 + * 门控页面、不门控密钥接口。 + */ +export function SystemPanel() { + const [system, setSystem] = React.useState(null); + const [loadError, setLoadError] = React.useState(null); + const [upgrading, setUpgrading] = React.useState(false); + const [saving, setSaving] = React.useState(false); + const [result, setResult] = React.useState(null); + const [runError, setRunError] = React.useState(null); + + const load = React.useCallback(async () => { + try { + setSystem(await adminGetSystem()); + setLoadError(null); + } catch (e) { + setLoadError( + e instanceof ApiError && e.status === 401 + ? "会话已失效,请重新登录。" + : "读取系统信息失败,请稍后重试。", + ); + } + }, []); + + React.useEffect(() => { + void load(); + }, [load]); + + const upgrade = async () => { + setUpgrading(true); + setResult(null); + setRunError(null); + try { + const res = await adminRunSetup(); + setResult(res); + const applied = res.migrations.filter( + (m) => m.status === "applied", + ).length; + const skipped = res.migrations.filter( + (m) => m.status === "skipped", + ).length; + toast.success( + `数据库检查完成:${applied} 个迁移已应用,${skipped} 个已是最新`, + ); + await load(); // 回读账本,账本状态以库为准 + } catch (e) { + if (e instanceof ApiError && e.status === 409) { + // 前缀冲突:后端 detail 原文直接显示在区内,不吞错误 + const detail = e.detail ?? e.message; + setRunError(detail); + toast.error(`表前缀冲突:${detail}`); + } else { + const message = "升级失败,请稍后重试。"; + setRunError(message); + toast.error(message); + } + } finally { + setUpgrading(false); + } + }; + + const toggleSetupPage = async (enabled: boolean) => { + setSaving(true); + try { + const saved = await adminSetSetupPage(enabled); + toast.success( + saved.setupPageEnabled ? "已开启 setup 页面" : "已关闭 setup 页面", + ); + } catch { + toast.error("保存失败,请稍后重试"); + } finally { + // 无论成败都回读确认,开关状态以服务端为准 + await load(); + setSaving(false); + } + }; + + return ( +
+

系统管理

+ + + + + + + 只做前进式账本迁移:不建号、不改密码、不删任何表。 + + + + {loadError ? ( + + 读取失败 + {loadError} + + ) : !system ? ( +

+

+ ) : ( + <> +
+ 生效表前缀 + + {system.tablePrefix || "(无前缀)"} + +
+ +
+ + 账本已记录迁移 + + {system.ledger.length === 0 ? ( +

+ 账本中暂无迁移记录。 +

+ ) : ( +
+ {system.ledger.map((name) => ( + + {name} + + ))} +
+ )} +
+ + + +
+ + + 免密钥,使用当前登录会话执行。 + +
+ + {runError && ( + + 升级失败 + + {runError} + + + )} + + {result && ( +
+ + 本次执行结果 + + +

+ 未创建或修改任何账号。 +

+
+ )} + + )} +
+
+ + + + setup 页面 + + 控制 /setup 页面是否对外开放(单人站点,初始化完成后默认关闭)。 + + + +
+
+ +

+ 关闭后 /setup + 只显示已关闭提示;管理面升级按钮与密钥接口不受此开关影响。 +

+
+ void toggleSetupPage(checked)} + /> +
+ + +
+
+
+ ); +} diff --git a/web/src/components/setup/migration-results.tsx b/web/src/components/setup/migration-results.tsx new file mode 100644 index 0000000..a1d3fba --- /dev/null +++ b/web/src/components/setup/migration-results.tsx @@ -0,0 +1,50 @@ +import { Badge } from "@/components/ui/badge"; +import type { SetupMigration } from "@/lib/types"; + +/** + * 迁移结果展示(/setup 页与后台系统管理共用):生效表前缀 + 逐条 applied/skipped。 + * 两种形态共用同一渲染,不各自手搓列表。 + */ +export function MigrationResults({ + tablePrefix, + migrations, +}: { + tablePrefix: string; + migrations: SetupMigration[]; +}) { + return ( +
+
+ 生效表前缀 + + {tablePrefix || "(无前缀)"} + +
+ {migrations.length === 0 ? ( +

账本中没有迁移记录。

+ ) : ( +
    + {migrations.map((migration) => ( +
  • + {migration.name} + + {migration.status} + +
  • + ))} +
+ )} +
+ ); +} diff --git a/web/src/components/setup/setup-page.tsx b/web/src/components/setup/setup-page.tsx new file mode 100644 index 0000000..13f240b --- /dev/null +++ b/web/src/components/setup/setup-page.tsx @@ -0,0 +1,491 @@ +import * as React from "react"; +import { + ArrowLeft, + ArrowRight, + Database, + KeyRound, + Loader2, + LogIn, + ShieldAlert, +} from "lucide-react"; +import { toast } from "sonner"; +import { LoginDialog } from "@/components/login-dialog"; +import { MigrationResults } from "@/components/setup/migration-results"; +import { Button } from "@/components/ui/button"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Separator } from "@/components/ui/separator"; +import { + ApiError, + getSetupState, + runOwnerSetup, + runSetupUpgrade, +} from "@/lib/api"; +import { useNavStore } from "@/lib/nav-store"; +import type { SetupOwnerResult, SetupResult, SetupState } from "@/lib/types"; + +/** + * /setup 页面(SETUP-PAGE-SPEC §4)。 + * + * 形态状态机(先查 GET /api/setup/state): + * loading → error / disabled(enabled===false)/ 未初始化(ownerExists===false)/ 已初始化。 + * + * 安全口径: + * - disabled 形态 DOM 中不出现任何密钥输入框; + * - 密钥只走 X-Setup-Secret 请求头,提交后立刻清空 state 与输入框,不写 + * localStorage / 日志 / URL; + * - 未初始化与已初始化是两个独立表单组件 + 不同 key,形态切换时 DOM 节点必换 + * (防密码管理器按节点缓存语义);密钥框 autocomplete="off"(不是登录密码)。 + */ +type Phase = + | { kind: "loading" } + | { kind: "error"; message: string } + | { kind: "disabled" } + | { kind: "uninitialized"; tablePrefix: string } + | { kind: "initialized"; tablePrefix: string }; + +function toPhase(state: SetupState): Phase { + if (!state.enabled) return { kind: "disabled" }; + if (!state.ownerExists) + return { kind: "uninitialized", tablePrefix: state.tablePrefix }; + return { kind: "initialized", tablePrefix: state.tablePrefix }; +} + +/** 403 密钥错误 / 429 限流 / 409 后端 detail 原文 / 其余通用错误。 */ +function setupErrorMessage(err: unknown): string { + if (err instanceof ApiError) { + if (err.status === 403) return "密钥错误,请检查 SETUP_SECRET 后重试。"; + if (err.status === 429) + return "尝试过于频繁,请稍后再试(同一 IP 每 10 分钟最多 3 次)。"; + if (err.status === 409) return err.detail ?? err.message; + } + return "操作失败,请稍后重试。"; +} + +export function SetupPage({ + onGoHome, + onGoAdmin, +}: { + onGoHome: () => void; + onGoAdmin: () => void; +}) { + const [phase, setPhase] = React.useState({ kind: "loading" }); + const authenticated = useNavStore((s) => s.authenticated); + const setLoginPrompt = useNavStore((s) => s.setLoginPrompt); + + const refresh = React.useCallback(async () => { + setPhase({ kind: "loading" }); + try { + setPhase(toPhase(await getSetupState())); + } catch { + setPhase({ kind: "error", message: "无法读取数据库状态,请稍后重试。" }); + } + }, []); + + React.useEffect(() => { + void refresh(); + }, [refresh]); + + // 登录后重新取一次状态:所有者刚在管理面开启页面时,这里会立刻翻到已初始化形态。 + // 仅在 disabled 形态下触发 —— 未初始化形态建号成功后会保留迁移结果,不被刷新覆盖。 + React.useEffect(() => { + if (authenticated && phase.kind === "disabled") void refresh(); + }, [authenticated, phase.kind, refresh]); + + // 未初始化形态建号成功后会话已签发:把 store 的私有数据/登录态同步过来, + // 「进入管理面」即可直接进后台(不另造登录逻辑)。 + const handleOwnerCreated = React.useCallback(() => { + void useNavStore.getState().loadPrivate(); + }, []); + + return ( +
+
+ + + + nav 数据库初始化 / 升级 + + + 输入 SETUP_SECRET + 检查并升级数据库(只做前进式账本迁移,不删任何表)。 + + + + {phase.kind === "loading" && } + {phase.kind === "error" && ( + void refresh()} + /> + )} + {phase.kind === "disabled" && ( + setLoginPrompt(true)} + onGoAdmin={onGoAdmin} + /> + )} + {phase.kind === "uninitialized" && ( + // 未初始化表单:独立组件 + 固定 key,与已初始化表单互不共享 DOM 节点 + + )} + {phase.kind === "initialized" && ( + + )} + + + +
+ + {authenticated && ( + + )} +
+
+ + {/* disabled 形态的「去登录」复用既有登录弹窗,不另造登录入口 */} + +
+ ); +} + +function LoadingBlock() { + return ( +
+
+ ); +} + +function ErrorBlock({ + message, + onRetry, +}: { + message: string; + onRetry: () => void; +}) { + return ( +
+

+

+ +
+ ); +} + +/** setup 页面开关关闭:只给提示与登录入口,DOM 里没有任何密钥表单。 */ +function DisabledBlock({ + authenticated, + onLogin, + onGoAdmin, +}: { + authenticated: boolean; + onLogin: () => void; + onGoAdmin: () => void; +}) { + return ( +
+

+ setup 页面已关闭,请登录后在管理面 → 系统管理中开启 +

+
+ + {authenticated && ( + + )} +
+
+ ); +} + +/** + * 未初始化形态(ownerExists === false):SETUP_SECRET + 用户名 + 密码(含确认), + * 提交 POST /api/auth/setup;成功后展示迁移结果与首页/管理面入口(会话已签发)。 + */ +function OwnerSetupForm({ + tablePrefix, + onCreated, + onGoHome, + onGoAdmin, +}: { + tablePrefix: string; + onCreated: () => void; + onGoHome: () => void; + onGoAdmin: () => void; +}) { + const [secret, setSecret] = React.useState(""); + const [username, setUsername] = React.useState(""); + const [password, setPassword] = React.useState(""); + const [confirm, setConfirm] = React.useState(""); + const [busy, setBusy] = React.useState(false); + const [error, setError] = React.useState(null); + const [result, setResult] = React.useState(null); + + const submit = async (e: React.FormEvent) => { + e.preventDefault(); + if (busy) return; + if (password.length < 8) { + setError("密码至少 8 位。"); + return; + } + if (password !== confirm) { + setError("两次输入的密码不一致。"); + return; + } + + // 密钥一提交立即从 state/输入框清掉(无论成功失败),不在内存里多留一秒 + const submittedSecret = secret; + setSecret(""); + setError(null); + setBusy(true); + try { + const res = await runOwnerSetup({ + secret: submittedSecret, + username: username.trim(), + password, + }); + setPassword(""); + setConfirm(""); + setResult(res); + toast.success("数据库初始化完成,已登录"); + onCreated(); + } catch (err) { + setError(setupErrorMessage(err)); + } finally { + setBusy(false); + } + }; + + if (result) { + return ( +
+

数据库初始化完成

+ +

+ 已创建所有者账号{" "} + {result.user.username} + ,并已签发登录会话。 +

+
+ + +
+
+ ); + } + + return ( +
+

+ 数据库尚未初始化:填写 SETUP_SECRET 并创建唯一的所有者账号。 + 当前生效表前缀为{" "} + {tablePrefix}。 +

+ +
+ + setSecret(e.target.value)} + required + autoFocus + /> +
+ + + +
+ + setUsername(e.target.value)} + required + /> +
+
+ + setPassword(e.target.value)} + required + minLength={8} + /> +
+
+ + setConfirm(e.target.value)} + required + minLength={8} + /> +
+ + {error && ( +

+ {error} +

+ )} + + + + ); +} + +/** + * 已初始化形态(ownerExists === true 且页面开启):只有 SETUP_SECRET 一项, + * 提交 POST /api/setup;成功展示迁移结果并明示未创建/修改任何账号。 + */ +function UpgradeSetupForm({ + tablePrefix, + onGoHome, +}: { + tablePrefix: string; + onGoHome: () => void; +}) { + const [secret, setSecret] = React.useState(""); + const [busy, setBusy] = React.useState(false); + const [error, setError] = React.useState(null); + const [result, setResult] = React.useState(null); + + const submit = async (e: React.FormEvent) => { + e.preventDefault(); + if (busy) return; + + const submittedSecret = secret; + setSecret(""); + setError(null); + setBusy(true); + try { + setResult(await runSetupUpgrade(submittedSecret)); + toast.success("数据库检查完成"); + } catch (err) { + setError(setupErrorMessage(err)); + } finally { + setBusy(false); + } + }; + + if (result) { + return ( +
+

数据库检查完成

+ +

+ 本次未创建或修改任何账号,只执行了账本迁移。 +

+ +
+ ); + } + + return ( +
+

+ 数据库已初始化:输入 SETUP_SECRET + 执行一次账本迁移检查(已应用的迁移会显示 + skipped,不会改动账号)。当前生效表前缀为{" "} + {tablePrefix}。 +

+ +
+ + setSecret(e.target.value)} + required + autoFocus + /> +
+ + {error && ( +

+ {error} +

+ )} + + +
+ ); +} diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index 8a507f0..3f6c715 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -7,9 +7,13 @@ import type { AdminCategory, AdminLink, + AdminSystem, PrivateData, PublicData, SearchEngine, + SetupOwnerResult, + SetupResult, + SetupState, SiteSettings, ImportCategory, } from "./types"; @@ -21,8 +25,13 @@ const API = { private: "/api/private", auth: "/api/auth", admin: "/api/admin", + setup: "/api/setup", + setupState: "/api/setup/state", }; +/** SETUP_SECRET 只走请求头(不进 URL、不进 localStorage、不打日志)。 */ +const SETUP_SECRET_HEADER = "X-Setup-Secret"; + /** 动态加载 dev mock(仅开发环境;生产构建死代码消除) */ async function devMock() { return import("./mockDb").then((m) => m.mockDb); @@ -35,30 +44,35 @@ export class UnauthorizedError extends Error { } } -class ApiError extends Error { +/** HTTP 失败:`status` 供调用方分支(403/409/429),`detail` 为后端原文(如前缀冲突说明)。 */ +export class ApiError extends Error { status: number; - constructor(message: string, status: number) { + detail?: string; + constructor(message: string, status: number, detail?: string) { super(message); this.name = "ApiError"; this.status = status; + this.detail = detail; } } async function request(path: string, init?: RequestInit): Promise { const res = await fetch(path, { credentials: "include", - headers: { "Content-Type": "application/json", ...(init?.headers ?? {}) }, ...init, + headers: { "Content-Type": "application/json", ...(init?.headers ?? {}) }, }); if (!res.ok) { let message = `${path} failed: ${res.status}`; + let detail: string | undefined; try { - const body = (await res.json()) as { error?: string }; + const body = (await res.json()) as { error?: string; detail?: string }; if (body?.error) message = body.error; + if (typeof body?.detail === "string") detail = body.detail; } catch { /* non-JSON error body */ } - throw new ApiError(message, res.status); + throw new ApiError(message, res.status, detail); } return (await res.json()) as T; } @@ -368,6 +382,64 @@ export async function adminUpdateSettings( }); } +// ─── Setup 三件套(/api/setup/*、/api/auth/setup、/api/admin/system*)───────── +// +// 这里刻意没有 dev mock:setup 走真实数据库迁移与密钥校验,mock 出来只会掩盖 +// 契约问题。开发时页面与系统管理区需连真实 worker(未连时显示错误态)。 + +/** GET /api/setup/state —— 页面形态状态机入口(无鉴权、no-store) */ +export async function getSetupState(): Promise { + return request(API.setupState, { cache: "no-store" }); +} + +/** POST /api/setup —— 密钥升级(只跑账本迁移,不建号/不改密码/不删表) */ +export async function runSetupUpgrade(secret: string): Promise { + return request(API.setup, { + method: "POST", + headers: { [SETUP_SECRET_HEADER]: secret }, + body: JSON.stringify({}), + }); +} + +/** POST /api/auth/setup —— 未初始化形态:迁移 + 建唯一所有者 + 签发会话 */ +export async function runOwnerSetup(input: { + secret: string; + username: string; + password: string; +}): Promise { + return request(`${API.auth}/setup`, { + method: "POST", + headers: { [SETUP_SECRET_HEADER]: input.secret }, + body: JSON.stringify({ + username: input.username, + password: input.password, + }), + }); +} + +/** POST /api/admin/setup —— 管理面免密钥升级(需会话) */ +export async function adminRunSetup(): Promise { + return request(`${API.admin}/setup`, { + method: "POST", + body: JSON.stringify({}), + }); +} + +/** GET /api/admin/system —— 生效前缀 + setup 页面开关 + 账本已记录迁移 */ +export async function adminGetSystem(): Promise { + return request(`${API.admin}/system`, { cache: "no-store" }); +} + +/** PUT /api/admin/system/setup-page —— 开关只门控页面,不门控密钥接口 */ +export async function adminSetSetupPage( + enabled: boolean, +): Promise<{ setupPageEnabled: boolean }> { + return request<{ setupPageEnabled: boolean }>( + `${API.admin}/system/setup-page`, + { method: "PUT", body: JSON.stringify({ enabled }) }, + ); +} + // ─── 导入(前端解析 → 逐条经 admin CRUD 落库,契约无批量导入端点)────────────── export async function adminImportCategories( diff --git a/web/src/lib/types.ts b/web/src/lib/types.ts index 9f223b3..90b7ec5 100644 --- a/web/src/lib/types.ts +++ b/web/src/lib/types.ts @@ -80,6 +80,43 @@ export interface AdminLink { updatedAt: string; } +// ─── setup 三件套(SETUP-PAGE-SPEC §3,对齐 worker types.ts)────────────────── + +/** `GET /api/setup/state`(及兼容别名 `status`)—— 不含任何密钥/哈希。 */ +export interface SetupState { + enabled: boolean; + ownerExists: boolean; + tablePrefix: string; +} + +export interface SetupMigration { + name: string; + status: "applied" | "skipped" | "error"; +} + +/** `POST /api/setup` 与 `POST /api/admin/setup`(形状完全一致)。 */ +export interface SetupResult { + success: true; + tablePrefix: string; + migrations: SetupMigration[]; + ownerExists: boolean; +} + +/** `POST /api/auth/setup`(迁移 + 建唯一所有者 + 签发会话)。 */ +export interface SetupOwnerResult { + success: true; + user: { id: string; username: string }; + tablePrefix: string; + migrations: SetupMigration[]; +} + +/** `GET /api/admin/system`。 */ +export interface AdminSystem { + tablePrefix: string; + setupPageEnabled: boolean; + ledger: string[]; +} + // ─── 导入导出 ───────────────────────────────────────────────────────────────── export interface ImportLink {