Files
OSGAccountServer/admin-web/src/features/providers/providers-page.tsx
T
Rocky 544e0d7356 Add TOTP-gated provider API key reveal
Allow super administrators to inspect effective provider credentials only after audited, rate-limited step-up verification.
2026-08-22 17:56:35 +08:00

358 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Eye, EyeOff, KeyRound, RefreshCw, ServerCog } from "lucide-react";
import { useCallback, useEffect, useState, type FormEvent } from "react";
import { toast } from "sonner";
import { adminApi, ApiError } from "../../api/client";
import type {
ManagedProviderId,
ManagedProviderOverview,
ManagedProviderStatus,
} from "../../api/types";
import {
Badge,
Button,
Card,
Dialog,
ErrorState,
Input,
LoadingState,
PageHeader,
} from "../../components/primitives";
import { formatDateTime } from "../../lib/format";
const PROVIDERS: Array<{
id: ManagedProviderId;
name: string;
description: string;
}> = [
{
id: "deepseek",
name: "DeepSeek",
description: "用于润色、AI 和 Agent 等托管文本能力。",
},
{
id: "volcengine",
name: "火山引擎",
description: "用于托管语音识别能力,仅替换 API Key。",
},
];
export function ProvidersPage() {
const [overview, setOverview] = useState<ManagedProviderOverview>();
const [loading, setLoading] = useState(true);
const [error, setError] = useState<unknown>();
const load = useCallback(async () => {
setLoading(true);
setError(undefined);
try {
setOverview(await adminApi.providers());
} catch (cause) {
setError(cause);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
void load();
}, [load]);
const updateStatus = useCallback((updated: ManagedProviderStatus) => {
setOverview((current) => {
if (!current) return current;
const providers = current.filter(
(item) => item.providerId !== updated.providerId,
);
return [...providers, updated];
});
}, []);
if (loading) return <LoadingState label="加载 Provider 配置" />;
if (error || !overview) return <ErrorState error={error} retry={() => void load()} />;
return (
<div className="space-y-6">
<PageHeader
eyebrow="Managed Providers"
title="Provider 配置"
description="查看或替换托管网关使用的上游 API Key。新配置只影响之后开始的请求。"
actions={
<Button variant="secondary" onClick={() => void load()}>
<RefreshCw className="size-4" aria-hidden />
刷新状态
</Button>
}
/>
<Card className="border-warning/25 bg-warning-soft/30 p-5 text-sm leading-6 text-foreground sm:p-6">
<div className="flex gap-3">
<span className="mt-0.5 grid size-9 shrink-0 place-items-center rounded-xl bg-warning-soft text-warning">
<KeyRound className="size-4" aria-hidden />
</span>
<p>
查看当前 Key 需要再次验证动态验证码;查看与替换都会写入审计日志,但不会记录密钥内容。
</p>
</div>
</Card>
<div className="grid gap-5 xl:grid-cols-2">
{PROVIDERS.map((provider) => (
<ProviderCard
key={provider.id}
providerId={provider.id}
name={provider.name}
description={provider.description}
status={overview.find((item) => item.providerId === provider.id)}
onUpdated={updateStatus}
/>
))}
</div>
</div>
);
}
function ProviderCard({
providerId,
name,
description,
status,
onUpdated,
}: {
providerId: ManagedProviderId;
name: string;
description: string;
status?: ManagedProviderStatus;
onUpdated: (status: ManagedProviderStatus) => void;
}) {
const [apiKey, setApiKey] = useState("");
const [currentApiKey, setCurrentApiKey] = useState<string>();
const [revealOpen, setRevealOpen] = useState(false);
const [totpCode, setTotpCode] = useState("");
const [revealError, setRevealError] = useState("");
const [revealing, setRevealing] = useState(false);
const [saving, setSaving] = useState(false);
function toggleCurrentApiKey() {
if (currentApiKey) {
setCurrentApiKey(undefined);
return;
}
setTotpCode("");
setRevealError("");
setRevealOpen(true);
}
function handleRevealOpenChange(open: boolean) {
setRevealOpen(open);
if (!open) {
setTotpCode("");
setRevealError("");
}
}
async function reveal(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!/^\d{6}$/.test(totpCode)) {
setRevealError("请输入 6 位动态验证码");
return;
}
setRevealing(true);
setRevealError("");
try {
const response = await adminApi.revealProviderApiKey(providerId, { totpCode });
setCurrentApiKey(response.apiKey);
handleRevealOpenChange(false);
} catch (error) {
setRevealError(error instanceof ApiError ? error.message : "当前 API Key 读取失败");
} finally {
setRevealing(false);
}
}
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const normalized = apiKey.trim();
if (!validApiKey(normalized)) {
toast.error("API Key 必须为 1512 个字符,且不能包含换行");
return;
}
if (!window.confirm(`确定替换 ${name} API Key?保存后,新请求将立即使用该 Key。`)) {
return;
}
setSaving(true);
try {
const updated = await adminApi.updateProviderApiKey(providerId, {
apiKey: normalized,
});
setApiKey("");
setCurrentApiKey((current) => (current ? normalized : undefined));
onUpdated(updated);
toast.success(`${name} API Key 已替换`);
} catch (error) {
toast.error(error instanceof ApiError ? error.message : `${name} API Key 替换失败`);
} finally {
setSaving(false);
}
}
return (
<Card className="overflow-hidden">
<div className="border-b border-border bg-surface-muted/35 p-5 sm:p-6">
<div className="flex items-start gap-3">
<span className="grid size-10 shrink-0 place-items-center rounded-xl bg-primary-soft text-primary">
<ServerCog className="size-5" aria-hidden />
</span>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
<h2 className="text-lg font-bold">{name}</h2>
<Badge tone={status?.configured ? "success" : "danger"}>
{status?.configured ? "已配置" : "未配置"}
</Badge>
</div>
<p className="mt-1 text-sm leading-6 text-muted">{description}</p>
</div>
</div>
<dl className="mt-5 grid gap-3 text-sm sm:grid-cols-2">
<StatusItem label="当前来源" value={sourceLabel(status)} />
<StatusItem
label="最后替换"
value={status?.updatedAt ? formatDateTime(status.updatedAt) : "随服务器部署"}
/>
</dl>
</div>
<div className="border-b border-border p-5 sm:p-6">
<label
className="block text-sm font-semibold"
htmlFor={`${providerId}-current-api-key`}
>
<span className="mb-2 block">{name} 当前 API Key</span>
</label>
<div className="relative">
<Input
id={`${providerId}-current-api-key`}
className="pr-12 font-mono"
type="text"
autoComplete="off"
readOnly
spellCheck={false}
value={
status?.configured
? currentApiKey ?? "••••••••••••••••"
: "未配置"
}
/>
<Button
className="absolute right-0.5 top-0.5"
type="button"
variant="ghost"
size="icon"
disabled={!status?.configured || revealing}
aria-label={currentApiKey ? `隐藏 ${name} 当前 API Key` : `显示 ${name} 当前 API Key`}
onClick={toggleCurrentApiKey}
>
{currentApiKey ? (
<EyeOff className="size-4" aria-hidden />
) : (
<Eye className="size-4" aria-hidden />
)}
</Button>
</div>
<p className="mt-2 text-xs leading-5 text-muted">
点击眼睛并通过动态验证码验证后显示;再次点击或离开页面时隐藏。
</p>
</div>
<form className="space-y-4 p-5 sm:p-6" onSubmit={(event) => void submit(event)}>
<label className="block text-sm font-semibold" htmlFor={`${providerId}-api-key`}>
<span className="mb-2 block">{name} API Key</span>
<Input
id={`${providerId}-api-key`}
type="password"
autoComplete="new-password"
maxLength={512}
value={apiKey}
onChange={(event) => setApiKey(event.target.value)}
placeholder={`输入新的 ${name} API Key`}
aria-describedby={`${providerId}-api-key-help`}
/>
</label>
<p id={`${providerId}-api-key-help`} className="text-xs leading-5 text-muted">
留空不会修改配置。若当前 Key 已显示,替换成功后会同步显示新 Key
</p>
<Button type="submit" loading={saving} disabled={!apiKey.trim()}>
<KeyRound className="size-4" aria-hidden />
替换 {name} API Key
</Button>
</form>
<Dialog
open={revealOpen}
onOpenChange={handleRevealOpenChange}
title={`验证后显示 ${name} API Key`}
description="请输入当前管理员的 6 位动态验证码。本次查看会写入审计日志。"
>
<form className="space-y-5" onSubmit={(event) => void reveal(event)} noValidate>
<label className="block text-sm font-semibold" htmlFor={`${providerId}-reveal-totp`}>
<span className="mb-2 block">动态验证码</span>
<Input
id={`${providerId}-reveal-totp`}
className="text-center text-lg font-semibold tracking-[0.35em]"
inputMode="numeric"
autoComplete="one-time-code"
pattern="[0-9]{6}"
maxLength={6}
value={totpCode}
onChange={(event) => setTotpCode(event.target.value.replace(/\D/g, ""))}
autoFocus
/>
</label>
{revealError ? (
<p className="text-sm text-danger" role="alert">
{revealError}
</p>
) : null}
<div className="flex justify-end gap-3">
<Button
type="button"
variant="secondary"
onClick={() => handleRevealOpenChange(false)}
>
取消
</Button>
<Button type="submit" loading={revealing} disabled={totpCode.length !== 6}>
验证并显示
</Button>
</div>
</form>
</Dialog>
</Card>
);
}
function StatusItem({ label, value }: { label: string; value: string }) {
return (
<div>
<dt className="text-xs font-semibold text-muted">{label}</dt>
<dd className="mt-1 font-medium text-foreground">{value}</dd>
</div>
);
}
function sourceLabel(status?: ManagedProviderStatus): string {
if (!status?.configured) return "尚未配置";
return status.source === "RUNTIME_OVERRIDE" ? "管理后台" : "环境变量";
}
function validApiKey(value: string): boolean {
return (
value.length >= 1 &&
value.length <= 512 &&
!value.includes("\n") &&
!value.includes("\r")
);
}