"use client" import {useEffect, useMemo, useState} from "react" import {useMutation, useQuery, useQueryClient} from "@tanstack/react-query" import { Fingerprint, Globe, Info, Loader2, Lock, Mail, Pencil, Plus, Server, Settings, Shield, Trash2, UserPlus } from "lucide-react" import {useRouter} from "next/navigation" import {motion} from "motion/react" import packageJson from "../../../package.json" import {Button} from "@/components/ui/button" import {Card, CardContent, CardDescription, CardHeader, CardTitle} from "@/components/ui/card" import {Switch} from "@/components/ui/switch" import {Tabs, TabsContent, TabsList, TabsTrigger} from "@/components/ui/tabs" import {Input} from "@/components/ui/input" import {Label} from "@/components/ui/label" import {Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle} from "@/components/ui/dialog" import {useAuth} from "@/components/providers/auth-provider" import {AuthSourceModal} from "@/components/common/settings/auth-source-modal" import {AdminService, apiConfig} from "@/lib/services" import type {AuthSource, SystemConfig} from "@/lib/services/admin" import {toast} from "sonner" import {SystemStatusManager} from "@/components/common/admin/status" const SECURITY_KEYS = [ { key: "password_login_enabled", title: "允许密码登录", description: "关闭后仅保留第三方 OIDC 认证源进行系统登录。", icon: Lock, }, { key: "registration_enabled", title: "允许注册", description: "关闭后系统将禁止新用户进行自主账号注册。", icon: UserPlus, }, { key: "password_register_enabled", title: "允许密码注册", description: "关闭后只能通过管理员创建或第三方认证关联建号。", icon: Fingerprint, }, { key: "oidc_login_enabled", title: "允许 OIDC 登录", description: "关闭后所有的第三方 OIDC 认证登录入口都会被隐藏。", icon: Globe, }, { key: "email_login_verification_enabled", title: "邮箱登录验证", description: "开启后,使用账号密码登录时需要通过邮箱接收并验证 6 位验证码。", icon: Mail, }, { key: "email_register_verification_enabled", title: "邮箱注册验证", description: "开启后,用户注册账号时需要通过邮箱接收并验证 6 位验证码。", icon: Mail, }, ] as const type SecurityKey = (typeof SECURITY_KEYS)[number]["key"] function systemConfigMap(configs: SystemConfig[]) { return configs.reduce>((accumulator, config) => { accumulator[config.key] = config return accumulator }, {}) } function InfoRow({ label, value }: { label: string; value: React.ReactNode }) { return (
{label} {value || "-"}
) } export function SecurityMain() { const queryClient = useQueryClient() const { user, loading } = useAuth() const router = useRouter() const [authSourceModalOpen, setAuthSourceModalOpen] = useState(false) const [selectedSource, setSelectedSource] = useState(null) const [capCount, setCapCount] = useState("") const [capDifficulty, setCapDifficulty] = useState("") const [capSize, setCapSize] = useState("") const [capTTL, setCapTTL] = useState("") const [capTokenTTL, setCapTokenTTL] = useState("") const [capAutoSolve, setCapAutoSolve] = useState(true) const [serverAddress, setServerAddress] = useState("") const [smtpHost, setSmtpHost] = useState("") const [smtpPort, setSmtpPort] = useState("") const [smtpUsername, setSmtpUsername] = useState("") const [smtpPassword, setSmtpPassword] = useState("") const [smtpTestOpen, setSmtpTestOpen] = useState(false) const [smtpTestTo, setSmtpTestTo] = useState("") const [smtpTestLog, setSmtpTestLog] = useState("") const [smtpTestSuccess, setSmtpTestSuccess] = useState(null) const [smtpTestError, setSmtpTestError] = useState("") const systemConfigsQuery = useQuery({ queryKey: ["admin", "system-configs"], queryFn: () => AdminService.listSystemConfigs("system"), enabled: !!user?.is_admin, }) const authSourcesQuery = useQuery({ queryKey: ["auth", "sources"], queryFn: () => AdminService.listAuthSources(), enabled: !!user?.is_admin, }) const configs = useMemo( () => systemConfigMap(systemConfigsQuery.data ?? []), [systemConfigsQuery.data], ) useEffect(() => { if (!loading && (!user || !user.is_admin)) { router.replace("/settings/profile") } }, [user, loading, router]) useEffect(() => { if (systemConfigsQuery.data) { const cfgMap = systemConfigMap(systemConfigsQuery.data) setCapCount(cfgMap["cap_challenge_count"]?.value || "1") setCapDifficulty(cfgMap["cap_challenge_difficulty"]?.value || "4") setCapSize(cfgMap["cap_challenge_size"]?.value || "32") setCapTTL(cfgMap["cap_challenge_ttl_seconds"]?.value || "600") setCapTokenTTL(cfgMap["cap_token_ttl_seconds"]?.value || "1200") setCapAutoSolve(cfgMap["cap_auto_solve"]?.value !== "false") setServerAddress(cfgMap["server_address"]?.value || "") setSmtpHost(cfgMap["smtp_host"]?.value || "") setSmtpPort(cfgMap["smtp_port"]?.value || "587") setSmtpUsername(cfgMap["smtp_username"]?.value || "") setSmtpPassword(cfgMap["smtp_password"]?.value || "") } }, [systemConfigsQuery.data]) const updateConfigMutation = useMutation({ mutationFn: async ({ key, value }: { key: string; value: boolean }) => { const config = configs[key] if (!config) { throw new Error(`缺少配置项: ${key}`) } await AdminService.updateSystemConfig(key, { value: value ? "true" : "false", description: config.description, }) }, onSuccess: async () => { await queryClient.invalidateQueries({ queryKey: ["admin", "system-configs"] }) toast.success("系统安全配置已更新") }, onError: (error: Error) => { toast.error(error.message || "更新配置失败") }, }) const toggleSourceMutation = useMutation({ mutationFn: async (source: AuthSource) => { await AdminService.toggleAuthSource(source.id, { is_active: !source.is_active }) }, onSuccess: async () => { await queryClient.invalidateQueries({ queryKey: ["auth", "sources"] }) await queryClient.invalidateQueries({ queryKey: ["auth", "public-sources"] }) toast.success("认证源状态已更新") }, onError: (error: Error) => { toast.error(error.message || "切换状态失败") }, }) const deleteSourceMutation = useMutation({ mutationFn: async (sourceId: string) => { await AdminService.deleteAuthSource(sourceId) }, onSuccess: async () => { await queryClient.invalidateQueries({ queryKey: ["auth", "sources"] }) await queryClient.invalidateQueries({ queryKey: ["auth", "public-sources"] }) toast.success("认证源已删除") }, onError: (error: Error) => { toast.error(error.message || "删除认证源失败") }, }) const handleToggle = (key: string, checked: boolean) => { updateConfigMutation.mutate({ key, value: checked }) } const saveCapMutation = useMutation({ mutationFn: async () => { const updates = [ { key: "cap_challenge_count", value: capCount }, { key: "cap_challenge_difficulty", value: capDifficulty }, { key: "cap_challenge_size", value: capSize }, { key: "cap_challenge_ttl_seconds", value: capTTL }, { key: "cap_token_ttl_seconds", value: capTokenTTL }, { key: "cap_auto_solve", value: capAutoSolve ? "true" : "false" }, ] for (const update of updates) { const currentCfg = configs[update.key] await AdminService.updateSystemConfig(update.key, { value: update.value, description: currentCfg?.description || "", }) } }, onSuccess: async () => { await queryClient.invalidateQueries({ queryKey: ["admin", "system-configs"] }) toast.success("人机验证配置已成功保存") }, onError: (error: Error) => { toast.error(error.message || "保存配置失败") }, }) const handleCapSave = (e: React.FormEvent) => { e.preventDefault() saveCapMutation.mutate() } const saveSystemMutation = useMutation({ mutationFn: async () => { const currentCfg = configs["server_address"] await AdminService.updateSystemConfig("server_address", { value: serverAddress, description: currentCfg?.description || "服务器地址", }) }, onSuccess: async () => { await queryClient.invalidateQueries({ queryKey: ["admin", "system-configs"] }) toast.success("通用配置已成功保存") }, onError: (error: Error) => { toast.error(error.message || "保存配置失败") }, }) const handleSystemSave = (e: React.FormEvent) => { e.preventDefault() saveSystemMutation.mutate() } const saveSmtpMutation = useMutation({ mutationFn: async () => { const updates = [ { key: "smtp_host", value: smtpHost }, { key: "smtp_port", value: smtpPort }, { key: "smtp_username", value: smtpUsername }, { key: "smtp_password", value: smtpPassword }, ] for (const update of updates) { const currentCfg = configs[update.key] if (update.key === "smtp_password" && (update.value === "" || update.value === "******")) { // If already configured and sent empty or mask, skip updating it (keep existing) if (currentCfg && currentCfg.value === "******") { continue } } await AdminService.updateSystemConfig(update.key, { value: update.value, description: currentCfg?.description || "", }) } }, onSuccess: async () => { await queryClient.invalidateQueries({ queryKey: ["admin", "system-configs"] }) toast.success("SMTP 邮件配置已成功保存") }, onError: (error: Error) => { toast.error(error.message || "保存配置失败") }, }) const handleSmtpSave = (e: React.FormEvent) => { e.preventDefault() saveSmtpMutation.mutate() } const testSmtpMutation = useMutation({ mutationFn: async () => { setSmtpTestLog("正在发起连接测试...\n") setSmtpTestSuccess(null) setSmtpTestError("") const res = await AdminService.testSMTP({ smtp_host: smtpHost, smtp_port: parseInt(smtpPort, 10) || 587, smtp_username: smtpUsername, smtp_password: smtpPassword, to: smtpTestTo, }) return res }, onSuccess: (data) => { setSmtpTestLog(data.log) if (data.success) { setSmtpTestSuccess(true) toast.success("测试邮件发送成功") } else { setSmtpTestSuccess(false) setSmtpTestError(data.error || "发送失败,请检查配置和日志。") toast.error("测试邮件发送失败") } }, onError: (error: Error) => { setSmtpTestSuccess(false) setSmtpTestError(error.message || "请求发送失败") setSmtpTestLog((prev) => prev + `\n[请求错误] ${error.message}\n`) toast.error(error.message || "测试请求发送失败") }, }) const handleSmtpTestSubmit = (e: React.FormEvent) => { e.preventDefault() if (!smtpTestTo) { toast.error("请输入目标邮箱地址") return } testSmtpMutation.mutate() } if (loading || !user || !user.is_admin) { return (
) } return ( 安全设置 运营设置 系统设置 系统状态 其他设置 系统信息
{/* 系统登录与注册控制 */}
系统安全与注册控制 配置系统的登录限制与用户自主注册权限
{SECURITY_KEYS.map((item) => { const config = configs[item.key] const checked = config ? config.value === "true" : false const Icon = item.icon return (
{Icon && } {item.title}

{item.description}

handleToggle(item.key, value)} />
) })}
{/* 认证源配置管理 */}
认证源管理 添加、修改并启用系统自定义的 OIDC 认证源
{authSourcesQuery.isPending ? (
) : (authSourcesQuery.data ?? []).length > 0 ? ( (authSourcesQuery.data ?? []).map((source) => (
{source.display_name || source.name} {source.is_active ? "已启用" : "已禁用"}
标识符: {source.name} · 类型: {source.type.toUpperCase()}
toggleSourceMutation.mutate(source)} />
)) ) : (
暂无配置的认证源,点击上方按钮新增
)}
{/* 人机验证配置 (Cap CAPTCHA) */}
人机验证配置 (Cap CAPTCHA) 配置基于 Proof-of-Work (PoW) 的无感人机验证,保护系统登录免受暴力破解和撞库攻击
handleToggle("cap_login_enabled", checked)} />
{/* 自动开始计算 Switch */}

打开页面后自动开始计算

setCapCount(e.target.value)} placeholder="50" className="bg-card border-dashed text-xs" />

客户端需求解的难题总数。默认 1,推荐 1 至 5

setCapDifficulty(e.target.value)} placeholder="4" className="bg-card border-dashed text-xs" />

PoW 前缀哈希位数,每加 1 计算时间翻倍。默认 4,推荐 4

setCapSize(e.target.value)} placeholder="32" className="bg-card border-dashed text-xs" />

难题盐值混淆字符长度。默认 32

setCapTTL(e.target.value)} placeholder="600" className="bg-card border-dashed text-xs" />

难题有效期限。默认 600 秒 (10 分钟)

setCapTokenTTL(e.target.value)} placeholder="1200" className="bg-card border-dashed text-xs" />

PoW 计算求解通过后,签发的登录凭证有效时长。默认 1200 秒 (20 分钟)

{/* 通用设置 */}
通用设置 配置系统的全局通用参数
setServerAddress(e.target.value)} placeholder="例如: https://example.com" className="bg-card border-dashed text-xs" />

这里可以编辑更改服务器地址。默认不设定,允许从任意源(*)访问 API,此时存在跨域安全风险;如果手动设置服务器地址,CORS 允许源将更新为该地址,消除跨域安全隐患。

{/* SMTP 邮件设置 */}
SMTP 邮件设置 配置系统的邮件发送服务 (SMTP)
setSmtpHost(e.target.value)} placeholder="例如: smtp.example.com" className="bg-card border-dashed text-xs" />
setSmtpPort(e.target.value)} placeholder="例如: 587 或 465" className="bg-card border-dashed text-xs" />
setSmtpUsername(e.target.value)} placeholder="例如: sender@example.com" className="bg-card border-dashed text-xs" />
setSmtpPassword(e.target.value)} placeholder={configs["smtp_password"]?.value === "******" ? "•••••• (已配置,留空或输入新值)" : "输入凭证密码"} className="bg-card border-dashed text-xs" />
应用信息 当前前端应用的版本与构建信息
服务连接 前端 API 客户端的基础连接参数
setAuthSourceModalOpen(false)} onChanged={async () => { await queryClient.invalidateQueries({ queryKey: ["auth", "sources"] }) await queryClient.invalidateQueries({ queryKey: ["auth", "public-sources"] }) await authSourcesQuery.refetch() }} /> SMTP 发件测试 输入接收测试邮件的邮箱地址。系统将使用您在表单中当前填写的 SMTP 配置进行发件测试。
setSmtpTestTo(e.target.value)} placeholder="例如: receiver@example.com" className="bg-card border-dashed text-xs" disabled={testSmtpMutation.isPending} />
{smtpTestLog && (
                  {smtpTestLog}
                
)} {smtpTestSuccess === true && (
测试成功!邮件已顺利发出。
)} {smtpTestSuccess === false && (
测试失败:{smtpTestError}
)}
) }