"use client" import {useEffect, useMemo, useState} from "react" import {useMutation, useQuery, useQueryClient} from "@tanstack/react-query" import { Fingerprint, Globe, Info, Loader2, Lock, 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 {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, }, ] 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 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 || "") } }, [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() } 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 允许源将更新为该地址,消除跨域安全隐患。

应用信息 当前前端应用的版本与构建信息
服务连接 前端 API 客户端的基础连接参数
setAuthSourceModalOpen(false)} onChanged={async () => { await queryClient.invalidateQueries({ queryKey: ["auth", "sources"] }) await queryClient.invalidateQueries({ queryKey: ["auth", "public-sources"] }) await authSourcesQuery.refetch() }} />
) }