diff --git a/web/src/App.tsx b/web/src/App.tsx index cb7096a..1cc9a15 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -35,6 +35,9 @@ const ForgotPasswordPage = lazy(() => default: m.ForgotPasswordPage, })), ); +const SetupPage = lazy(() => + import("@/pages/setup/SetupPage").then((m) => ({ default: m.SetupPage })), +); const ItemNewPage = lazy(() => import("@/pages/items/ItemNewPage").then((m) => ({ default: m.ItemNewPage })), ); @@ -71,6 +74,11 @@ const AdminSecurityPage = lazy(() => default: m.AdminSecurityPage, })), ); +const AdminSystemPage = lazy(() => + import("@/pages/admin/AdminSystemPage").then((m) => ({ + default: m.AdminSystemPage, + })), +); const AboutPage = lazy(() => import("@/pages/about/AboutPage").then((m) => ({ default: m.AboutPage })), ); @@ -137,6 +145,7 @@ export function App() { } /> + } /> {/* Protected routes */} } /> } /> } /> + } /> diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index 97e54bb..d107cd5 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -130,4 +130,34 @@ export const api = { request(path, { method: "DELETE", ...opts }), }; +// Public setup endpoints (no auth): use raw fetch because /api/setup requires the +// X-Setup-Secret header and its errors are status-coded (403 wrong secret, 429 rate +// limited), not the 401/session flow the generic `request` wrapper handles. +export interface SetupResult { + success: boolean; + alreadyInitialized?: boolean; +} + +export const setupApi = { + state: async (): Promise<{ enabled: boolean }> => { + const res = await fetch(`${BASE_URL}/setup/state`, { + credentials: "include", + }); + if (!res.ok) throw new Error("Setup state unavailable"); + return res.json(); + }, + run: async (secret: string): Promise => { + const res = await fetch(`${BASE_URL}/setup`, { + method: "POST", + headers: { "X-Setup-Secret": secret }, + credentials: "include", + }); + const body = await res.json().catch(() => ({})); + if (!res.ok) { + throw new ApiError(res.status, body.error || "Request failed"); + } + return body as SetupResult; + }, +}; + export { ApiError }; diff --git a/web/src/locales/en.json b/web/src/locales/en.json index 8e6f65e..2b511c5 100644 --- a/web/src/locales/en.json +++ b/web/src/locales/en.json @@ -324,7 +324,18 @@ "testEmail": "Send Test Email", "testEmailAddress": "Test recipient address", "testEmailSent": "Test email sent successfully", - "testEmailFailed": "Failed to send test email" + "testEmailFailed": "Failed to send test email", + "setupPage": "Allow access to the setup page", + "setupPageDesc": "Allow access to the /setup page. Disabling only hides the page; POST /api/setup still works with the secret.", + "dbMaintenance": "Database Maintenance", + "dbMaintenanceDesc": "Check and upgrade the database structure directly, without SETUP_SECRET.", + "checkUpgradeDb": "Check and upgrade database", + "checkingDb": "Checking...", + "dbUpToDate": "The database is already up to date", + "dbInitialized": "Database initialized successfully", + "dbUpgradeFailed": "Upgrade failed, please try again later", + "dbUpgradeUnauthorized": "Please sign in again", + "dbUpgradeForbidden": "Administrator permission required" }, "channels": { "title": "Channel Management", @@ -364,5 +375,22 @@ "notificationHoursHint": "Notifications are sent at most once per hour. Leave empty to allow every hour.", "notificationHoursClear": "Clear", "notificationHoursNoLimit": "No restriction" + }, + "setup": { + "title": "Setup", + "desc": "Enter your SETUP_SECRET to initialize or upgrade the database.", + "disabled": "The setup page has been disabled by an administrator.", + "secretLabel": "SETUP_SECRET", + "submit": "Start initialization", + "submitting": "Initializing...", + "alreadyInitialized": "The database is already initialized — no need to run it again.", + "success": "Initialization successful!", + "successGuide": "The database is ready. You can log in or go to the home page.", + "goLogin": "Go to login", + "goHome": "Go to home", + "missingSecret": "Please enter the setup secret.", + "wrongSecret": "Incorrect setup secret.", + "rateLimited": "Too many requests, please try again later.", + "genericError": "Initialization failed, please try again later." } } diff --git a/web/src/locales/zh.json b/web/src/locales/zh.json index 78eead1..f9e761f 100644 --- a/web/src/locales/zh.json +++ b/web/src/locales/zh.json @@ -324,7 +324,18 @@ "testEmail": "发送测试邮件", "testEmailAddress": "测试收件地址", "testEmailSent": "测试邮件发送成功", - "testEmailFailed": "测试邮件发送失败" + "testEmailFailed": "测试邮件发送失败", + "setupPage": "允许访问初始化页面", + "setupPageDesc": "允许访问 /setup 页面。关闭后页面显示禁用提示;POST /api/setup 仍可用密钥调用。", + "dbMaintenance": "数据库维护", + "dbMaintenanceDesc": "检查并升级数据库结构,无需 SETUP_SECRET。", + "checkUpgradeDb": "检查并升级数据库", + "checkingDb": "检查中...", + "dbUpToDate": "数据库已是最新", + "dbInitialized": "数据库初始化成功", + "dbUpgradeFailed": "升级失败,请稍后再试", + "dbUpgradeUnauthorized": "请重新登录", + "dbUpgradeForbidden": "需要管理员权限" }, "channels": { "title": "通道管理", @@ -364,5 +375,22 @@ "notificationHoursHint": "每小时仅发送一次通知。不选则每小时都会发送通知。", "notificationHoursClear": "清空", "notificationHoursNoLimit": "不限制" + }, + "setup": { + "title": "初始化", + "desc": "输入 SETUP_SECRET 密钥以初始化或升级数据库。", + "disabled": "初始化页面已被管理员关闭", + "secretLabel": "SETUP_SECRET 密钥", + "submit": "开始初始化", + "submitting": "初始化中...", + "alreadyInitialized": "数据库已初始化,不需要重复执行。", + "success": "初始化成功!", + "successGuide": "数据库已就绪,请前往登录或首页。", + "goLogin": "前往登录", + "goHome": "前往首页", + "missingSecret": "请输入密钥。", + "wrongSecret": "密钥错误,请检查后重试。", + "rateLimited": "请求过于频繁,请稍后再试。", + "genericError": "初始化失败,请稍后再试。" } } diff --git a/web/src/pages/admin/AdminPage.tsx b/web/src/pages/admin/AdminPage.tsx index 8371036..1e5b4ae 100644 --- a/web/src/pages/admin/AdminPage.tsx +++ b/web/src/pages/admin/AdminPage.tsx @@ -1,7 +1,14 @@ import { useEffect } from "react"; import { useTranslation } from "react-i18next"; import { NavLink, Outlet, useLocation, useNavigate } from "react-router"; -import { Users, Settings, Mail, ShieldCheck, ChevronRight } from "lucide-react"; +import { + Users, + Settings, + Mail, + ShieldCheck, + ChevronRight, + Database, +} from "lucide-react"; import { cn } from "@/lib/utils"; import { useIsMobile } from "@/hooks/useIsMobile"; @@ -22,6 +29,11 @@ export function AdminPage() { label: t("admin.accessSecurity"), icon: ShieldCheck, }, + { + to: "/admin/system", + label: t("admin.system"), + icon: Database, + }, ]; // Desktop: redirect /admin to /admin/users diff --git a/web/src/pages/admin/AdminSystemPage.tsx b/web/src/pages/admin/AdminSystemPage.tsx index c0db2d3..c27d8d9 100644 --- a/web/src/pages/admin/AdminSystemPage.tsx +++ b/web/src/pages/admin/AdminSystemPage.tsx @@ -1,40 +1,10 @@ -import { useEffect, useState, type ReactNode } from "react"; +import { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import { useNavigate } from "react-router"; -import { ArrowLeft, AlertCircle } from "lucide-react"; -import { api } from "@/lib/api"; +import { ArrowLeft, AlertCircle, Database } from "lucide-react"; +import { api, ApiError } from "@/lib/api"; import { cn } from "@/lib/utils"; import type { SystemSettings } from "@/types"; -import { useAuth } from "@/hooks/useAuth"; - -type EmailProvider = "none" | "smtp" | "resend"; - -interface SmtpConfig { - host: string; - port: string; - username: string; - password: string; - from: string; - from_name: string; -} - -interface ResendConfig { - api_key: string; - from: string; - from_name: string; -} - -const INPUT = - "w-full rounded-lg border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 transition-shadow"; - -function Field({ label, children }: { label: string; children: ReactNode }) { - return ( -
- - {children} -
- ); -} function Toggle({ checked, @@ -67,7 +37,7 @@ function Toggle({ > @@ -76,124 +46,38 @@ function Toggle({ ); } -const DEFAULT_SMTP: SmtpConfig = { - host: "", - port: "587", - username: "", - password: "", - from: "", - from_name: "", -}; -const DEFAULT_RESEND: ResendConfig = { api_key: "", from: "", from_name: "" }; - export function AdminSystemPage() { const { t } = useTranslation(); const navigate = useNavigate(); - const { user } = useAuth(); - const [appName, setAppName] = useState(""); - const [emailProvider, setEmailProvider] = useState("none"); - const [smtp, setSmtp] = useState(DEFAULT_SMTP); - const [resend, setResend] = useState(DEFAULT_RESEND); - const [emailVerification, setEmailVerification] = useState(false); - const [require2fa, setRequire2fa] = useState(false); - const [registration, setRegistration] = useState(true); + const [setupPageEnabled, setSetupPageEnabled] = useState(true); const [loading, setLoading] = useState(true); const [saving, setSaving] = useState(false); const [error, setError] = useState(""); const [saveMsg, setSaveMsg] = useState(""); - const [testEmailTo, setTestEmailTo] = useState(""); - const [testEmailLoading, setTestEmailLoading] = useState(false); - const [testEmailMsg, setTestEmailMsg] = useState(""); - const [testEmailError, setTestEmailError] = useState(""); - - useEffect(() => { - if (user?.email) setTestEmailTo(user.email); - }, [user?.email]); + const [upgrading, setUpgrading] = useState(false); + const [upgradeResult, setUpgradeResult] = useState(""); + const [upgradeError, setUpgradeError] = useState(""); useEffect(() => { api .get("/admin/system/settings") - .then((s) => { - setAppName(s.app_name || "eNotify"); - setEmailProvider((s.email_provider as EmailProvider) || "none"); - setEmailVerification(s.email_verification_enabled === "true"); - setRequire2fa(s.require_2fa === "true"); - setRegistration(s.registration_enabled !== "false"); - - if (s.smtp_config) { - try { - const parsed = JSON.parse(s.smtp_config); - const hasPassword = parsed.password && parsed.password !== ""; - setSmtp({ - ...DEFAULT_SMTP, - ...parsed, - password: "", - _hasExisting: hasPassword, - } as any); - } catch { - // ignore - } - } - if (s.resend_config) { - try { - const parsed = JSON.parse(s.resend_config); - const hasKey = parsed.api_key && parsed.api_key !== ""; - setResend({ - ...DEFAULT_RESEND, - ...parsed, - api_key: "", - _hasExisting: hasKey, - } as any); - } catch { - // ignore - } - } - }) + .then((s) => setSetupPageEnabled((s.setup_page_enabled ?? "1") !== "0")) .catch((e) => setError(e.message)) .finally(() => setLoading(false)); }, []); - const setSmtpField = (key: keyof SmtpConfig, val: string) => - setSmtp((prev) => ({ ...prev, [key]: val })); - - const setResendField = (key: keyof ResendConfig, val: string) => - setResend((prev) => ({ ...prev, [key]: val })); - const handleSave = async (e: React.SyntheticEvent) => { e.preventDefault(); setSaving(true); setError(""); setSaveMsg(""); - - const payload: Record = { - app_name: appName.trim() || "eNotify", - email_provider: emailProvider, - email_verification_enabled: String(emailVerification), - require_2fa: String(require2fa), - registration_enabled: String(registration), - }; - - if (emailProvider === "smtp") { - const smtpPayload: Record = { - ...smtp, - port: Number(smtp.port) || 587, - }; - delete smtpPayload._hasExisting; - if (!smtpPayload.password) delete smtpPayload.password; - payload.smtp_config = JSON.stringify(smtpPayload); - } - if (emailProvider === "resend") { - const resendPayload: Record = { ...resend }; - delete resendPayload._hasExisting; - if (!resendPayload.api_key) delete resendPayload.api_key; - payload.resend_config = JSON.stringify(resendPayload); - } - try { - await api.put("/admin/system/settings", payload); + await api.put("/admin/system/settings", { + setup_page_enabled: setupPageEnabled ? "1" : "0", + }); setSaveMsg(t("common.success")); setTimeout(() => setSaveMsg(""), 3000); } catch (e: any) { @@ -203,18 +87,34 @@ export function AdminSystemPage() { } }; - const handleTestEmail = async () => { - setTestEmailLoading(true); - setTestEmailMsg(""); - setTestEmailError(""); + const handleUpgrade = async () => { + setUpgrading(true); + setUpgradeError(""); + setUpgradeResult(""); try { - await api.post("/admin/system/settings/test-email", { to: testEmailTo }); - setTestEmailMsg(t("admin.testEmailSent")); - setTimeout(() => setTestEmailMsg(""), 4000); + const res = await api.post<{ + success: boolean; + alreadyInitialized?: boolean; + }>("/admin/setup"); + setUpgradeResult( + res.alreadyInitialized + ? t("admin.dbUpToDate") + : t("admin.dbInitialized"), + ); } catch (e: any) { - setTestEmailError(e.message || t("admin.testEmailFailed")); + if (e instanceof ApiError) { + setUpgradeError( + e.status === 401 + ? t("admin.dbUpgradeUnauthorized") + : e.status === 403 + ? t("admin.dbUpgradeForbidden") + : t("admin.dbUpgradeFailed"), + ); + } else { + setUpgradeError(t("admin.dbUpgradeFailed")); + } } finally { - setTestEmailLoading(false); + setUpgrading(false); } }; @@ -249,191 +149,15 @@ export function AdminSystemPage() { )}
- {/* App settings */} -
-

{t("admin.appSettings")}

- - setAppName(e.target.value)} - placeholder="eNotify" - maxLength={64} - /> - -
- - {/* Email provider */} -
-

{t("admin.emailProvider")}

- -
- {(["none", "smtp", "resend"] as EmailProvider[]).map((p) => ( - - ))} -
- - {emailProvider === "smtp" && ( -
- - setSmtpField("host", e.target.value)} - placeholder="smtp.example.com" - /> - - - setSmtpField("port", e.target.value)} - /> - - - setSmtpField("username", e.target.value)} - /> - - - setSmtpField("password", e.target.value)} - placeholder="Leave blank to keep existing" - /> - - - setSmtpField("from", e.target.value)} - /> - - - setSmtpField("from_name", e.target.value)} - /> - -
- )} - - {emailProvider === "resend" && ( -
-
- - setResendField("api_key", e.target.value)} - placeholder="Leave blank to keep existing" - /> - -
- - setResendField("from", e.target.value)} - /> - - - setResendField("from_name", e.target.value)} - /> - -
- )} -
- - {/* Test email */} - {emailProvider !== "none" && ( -
-

{t("admin.testEmail")}

- - setTestEmailTo(e.target.value)} - /> - -
- - {testEmailMsg && ( - {testEmailMsg} - )} - {testEmailError && ( - - {testEmailError} - - )} -
-
- )} - - {/* Toggles */}
-

{t("admin.accessSecurity")}

+

{t("admin.appSettings")}

- -
- -
- -
- -
@@ -447,6 +171,30 @@ export function AdminSystemPage() { {saveMsg && {saveMsg}}
+ +
+

{t("admin.dbMaintenance")}

+

+ {t("admin.dbMaintenanceDesc")} +

+ + {upgradeResult && ( +

{upgradeResult}

+ )} + {upgradeError && ( +

{upgradeError}

+ )} + + +
); } diff --git a/web/src/pages/setup/SetupPage.tsx b/web/src/pages/setup/SetupPage.tsx new file mode 100644 index 0000000..2dfe4fb --- /dev/null +++ b/web/src/pages/setup/SetupPage.tsx @@ -0,0 +1,187 @@ +import { useState, useEffect } from "react"; +import { Link } from "react-router"; +import { useTranslation } from "react-i18next"; +import { Database, Globe } from "lucide-react"; +import { setupApi, ApiError } from "@/lib/api"; + +type View = "loading" | "disabled" | "form" | "done"; + +export function SetupPage() { + const { t, i18n } = useTranslation(); + + const [view, setView] = useState("loading"); + const [secret, setSecret] = useState(""); + const [alreadyInitialized, setAlreadyInitialized] = useState(false); + const [error, setError] = useState(""); + const [submitting, setSubmitting] = useState(false); + + useEffect(() => { + let cancelled = false; + setupApi + .state() + .then((s) => { + if (!cancelled) setView(s.enabled === false ? "disabled" : "form"); + }) + .catch(() => { + // A failed state request still lets the user try; treat setup as available. + if (!cancelled) setView("form"); + }); + return () => { + cancelled = true; + }; + }, []); + + const handleSubmit = async (e: React.SyntheticEvent) => { + e.preventDefault(); + setError(""); + if (!secret.trim()) { + setError(t("setup.missingSecret")); + return; + } + setSubmitting(true); + try { + const res = await setupApi.run(secret.trim()); + setAlreadyInitialized(!!res.alreadyInitialized); + setView("done"); + } catch (err) { + if (err instanceof ApiError) { + if (err.status === 403) setError(t("setup.wrongSecret")); + else if (err.status === 429) setError(t("setup.rateLimited")); + else setError(t("setup.genericError")); + } else { + setError(t("setup.genericError")); + } + } finally { + setSecret(""); + setSubmitting(false); + } + }; + + const toggleLang = () => { + i18n.changeLanguage(i18n.language === "zh" ? "en" : "zh"); + }; + + return ( +
+
+ +
+ +
+
+
+ +
+ + {t("app.name")} + +
+ +
+ {view === "loading" && ( +

+ {t("common.loading")} +

+ )} + + {view === "disabled" && ( +
+

+ {t("setup.title")} +

+

+ {t("setup.disabled")} +

+ + {t("setup.goLogin")} + +
+ )} + + {view === "done" && ( +
+

+ {t("setup.title")} +

+

+ {alreadyInitialized + ? t("setup.alreadyInitialized") + : t("setup.success")} +

+ {!alreadyInitialized && ( +

+ {t("setup.successGuide")} +

+ )} +
+ + {t("setup.goLogin")} + + + {t("setup.goHome")} + +
+
+ )} + + {view === "form" && ( + <> +

+ {t("setup.title")} +

+

+ {t("setup.desc")} +

+ +
+
+ + setSecret(e.target.value)} + className="w-full px-3 py-2 rounded-md border border-input bg-background text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-ring" + /> +
+ + {error && ( +

+ {error} +

+ )} + + +
+ + )} +
+
+
+ ); +} diff --git a/web/src/types/index.ts b/web/src/types/index.ts index 94a531b..8af9c07 100644 --- a/web/src/types/index.ts +++ b/web/src/types/index.ts @@ -97,6 +97,7 @@ export interface SystemSettings { resend_config: string; email_provider: string; app_name?: string; + setup_page_enabled?: string; } export interface NotificationHistory {