新增「系统 → 通知推送」页,把扫描发现的漏洞推送到钉钉、飞书、企业微信、 通用 Webhook、Telegram、邮件。同一类型可配任意多个机器人实例,每个实例独立 设启停、限流与过滤规则(最低级别 / 任务资产范围 / 漏洞类型关键词 / 是否接收 处置状态变更)。推送时机分实时与汇总两种模式,「高危实时、其余汇总」建两个 渠道即可表达,策略不写死在代码里。带投递历史与失败重发。 三个关键设计: 1. 写漏洞的事务只做一次盲 INSERT。notification_events 由 RecordFindingTx 在同一事务内写入,保证「漏洞落库」与「推送任务存在」原子一致;这条 INSERT 刻意不读渠道表、不跑用户的过滤规则,否则一条配错的过滤条件就能污染甚至 中止事务,让高危漏洞存不进库。为把失败隔离在这一条语句上(PostgreSQL 中 事务内任一语句报错会让整个事务作废、连 COMMIT 都失败),它被 SAVEPOINT 包住,失败时只记日志。 2. 投递用租约领取而非长事务。FOR UPDATE SKIP LOCKED 领取后把行置为 sending、 把 next_attempt_at 推到未来作为租约,提交后再做网络投递,因此投递期间不 持有数据库锁;崩溃留下的 sending 行会被下一轮重新领取,自愈且不会无限重试。 3. 限流不消耗重试预算。先按渠道令牌桶算出本轮还能发几条,再按这个数量领取; 顺序反过来会让被限流挡下的投递白计一次尝试,三次预算被等待耗光后落入失败。 审计并修复的四个问题: - 推送凭据经错误信息外泄:http.Client.Do 返回的 *url.Error 会把完整 URL 打进 错误文本,而钉钉 access_token、企业微信 key、飞书 hook id、Telegram /bot<token>/ 都就在 URL 里。该串流入 last_error(明文落库)、投递历史接口 (绕过渠道掩码)、服务端日志与前端错误提示。现统一脱敏为 scheme://host + 底层原因,并拒绝跨主机重定向。 - 最低级别门槛打错字会让过滤器静默失效:未知级别序数为 0,判定退化成 rank >= 0 恒真,用户以为限制「仅高危」实际全推。现于写入路径校验取值。 - 汇总批次无上限:一次领取把全部待发行读进内存、消息被渠道长度上限截掉大半 且静默丢失。现单批上限 500 条,超出部分留库成为下一批。 - 邮件渠道把 SMTP 4xx(灰名单等临时失败)判成永久失败,导致这类最该重试的 场景从不重试。现按应答码首位区分 4xx/5xx。 测试:notify 包 82% 覆盖(含用自建最小 SMTP 服务器驱动的完整邮件协议会话、 两种签名算法对 OpenSSL 基准值的比对、UTF-8 边界截断、以及模板能力边界的 反射断言);db 与 server 侧共 29 个用例跑真实 PostgreSQL,其中端到端用例 真发 HTTP 到假接收端并断言消息内容与投递状态。 Co-Authored-By: Claude Code <noreply@anthropic.com>
1096 lines
41 KiB
TypeScript
1096 lines
41 KiB
TypeScript
"use client";
|
||
|
||
import * as React from "react";
|
||
|
||
import { BellIcon, CheckIcon, PlusIcon, RefreshCwIcon, RotateCcwIcon, SendIcon, Trash2Icon } from "lucide-react";
|
||
import { toast } from "sonner";
|
||
|
||
import { Badge } from "@/components/ui/badge";
|
||
import { Button } from "@/components/ui/button";
|
||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||
import { Input } from "@/components/ui/input";
|
||
import { Label } from "@/components/ui/label";
|
||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";
|
||
import { Switch } from "@/components/ui/switch";
|
||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||
import { Textarea } from "@/components/ui/textarea";
|
||
import { api } from "@/lib/api";
|
||
import { statusMeta, toneClasses } from "@/lib/status";
|
||
import type { NotificationChannel, NotificationDelivery, NotificationFilter, NotificationMeta } from "@/lib/types";
|
||
|
||
// 渠道类型的展示名与简介。放在前端是因为它只影响文案,后端不需要知道。
|
||
const KIND_LABEL: Record<string, string> = {
|
||
dingtalk: "钉钉",
|
||
feishu: "飞书",
|
||
wecom: "企业微信",
|
||
webhook: "通用 Webhook",
|
||
telegram: "Telegram",
|
||
email: "邮件",
|
||
};
|
||
|
||
// 各渠道的配置字段定义。
|
||
//
|
||
// 这里刻意保留一份前端字段表,而不是让后端下发 schema:后端只负责
|
||
// Validate(必填/格式),UI 需要的是布局与控件类型,两者关注的不是同一件事。
|
||
// 唯一的耦合点是 secret_keys —— 哪些字段该渲染成密码框由后端给出,
|
||
// 因为只有渠道实现自己清楚哪些值算凭据(企业微信的整个 Webhook 就是凭据,
|
||
// 而钉钉的只是其中一个 secret)。新增渠道时这里少一个条目只会让表单变空白,
|
||
// 不会静默出错(下面的 hasFields 会提示)。
|
||
type FieldKind = "text" | "password" | "number" | "select" | "textarea" | "switch" | "kv" | "list";
|
||
interface FieldDef {
|
||
key: string;
|
||
label: string;
|
||
kind: FieldKind;
|
||
placeholder?: string;
|
||
help?: string;
|
||
options?: { value: string; label: string }[];
|
||
}
|
||
const CHANNEL_FIELDS: Record<string, FieldDef[]> = {
|
||
dingtalk: [
|
||
{
|
||
key: "webhook",
|
||
label: "Webhook 地址",
|
||
kind: "text",
|
||
placeholder: "https://oapi.dingtalk.com/robot/send?access_token=...",
|
||
},
|
||
{
|
||
key: "secret",
|
||
label: "加签密钥",
|
||
kind: "password",
|
||
help: "机器人安全设置选「加签」时填写;选「自定义关键词」或未开启安全设置则留空",
|
||
},
|
||
],
|
||
feishu: [
|
||
{
|
||
key: "webhook",
|
||
label: "Webhook 地址",
|
||
kind: "text",
|
||
placeholder: "https://open.feishu.cn/open-apis/bot/v2/hook/...",
|
||
},
|
||
{ key: "secret", label: "签名校验密钥", kind: "password", help: "机器人开启「签名校验」时填写,否则留空" },
|
||
],
|
||
wecom: [
|
||
{
|
||
key: "webhook",
|
||
label: "Webhook 地址",
|
||
kind: "text",
|
||
placeholder: "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...",
|
||
},
|
||
],
|
||
webhook: [
|
||
{ key: "url", label: "目标 URL", kind: "text", placeholder: "https://your-endpoint.example.com/hook" },
|
||
{
|
||
key: "method",
|
||
label: "请求方法",
|
||
kind: "select",
|
||
options: [
|
||
{ value: "POST", label: "POST(带请求体)" },
|
||
{ value: "PUT", label: "PUT(带请求体)" },
|
||
{ value: "PATCH", label: "PATCH(带请求体)" },
|
||
{ value: "GET", label: "GET(不带请求体)" },
|
||
],
|
||
},
|
||
{ key: "headers", label: "自定义请求头", kind: "kv", help: "每行 KEY=VALUE,例如 Authorization=Bearer xxx" },
|
||
{
|
||
key: "body_template",
|
||
label: "请求体模板",
|
||
kind: "textarea",
|
||
help:
|
||
"留空用内置默认模板。变量:{{.Title}} {{.Batch}} {{.Count}} {{.HomeURL}} {{.SentAt}}," +
|
||
"以及 range .Items 下的 .Name/.VulnClass/.Severity/.Summary/.Assets/.DetailURL/.StatusLabel。" +
|
||
"插入字符串请用 {{json .Xxx}} 而不是 {{.Xxx}},否则标题里的引号会破坏 JSON。",
|
||
},
|
||
],
|
||
telegram: [
|
||
{ key: "bot_token", label: "Bot Token", kind: "password", placeholder: "123456:ABC-DEF..." },
|
||
{ key: "chat_id", label: "Chat ID", kind: "text", placeholder: "-1001234567890" },
|
||
{
|
||
key: "base_url",
|
||
label: "API 地址",
|
||
kind: "text",
|
||
placeholder: "https://api.telegram.org",
|
||
help: "留空用官方地址;自建 Bot API 反代时填写",
|
||
},
|
||
],
|
||
email: [
|
||
{ key: "host", label: "SMTP 服务器", kind: "text", placeholder: "smtp.example.com" },
|
||
{
|
||
key: "port",
|
||
label: "端口",
|
||
kind: "number",
|
||
placeholder: "587",
|
||
help: "587 走 STARTTLS;465 请把「隐式 TLS」打开",
|
||
},
|
||
{ key: "username", label: "账号", kind: "text" },
|
||
{ key: "password", label: "密码 / 授权码", kind: "password" },
|
||
{ key: "from", label: "发件人", kind: "text", placeholder: "artex@example.com" },
|
||
{ key: "to", label: "收件人", kind: "list", help: "多个地址用逗号分隔" },
|
||
{ key: "tls", label: "隐式 TLS", kind: "switch", help: "465 端口打开;587 保持关闭(会自动 STARTTLS)" },
|
||
],
|
||
};
|
||
|
||
const SEVERITY_OPTIONS = [
|
||
{ value: "", label: "不限" },
|
||
{ value: "low", label: "低危及以上" },
|
||
{ value: "medium", label: "中危及以上" },
|
||
{ value: "high", label: "高危及以上" },
|
||
{ value: "critical", label: "仅严重" },
|
||
];
|
||
|
||
type ChannelForm = {
|
||
name: string;
|
||
kind: string;
|
||
mode: "realtime" | "digest";
|
||
enabled: boolean;
|
||
ratePerMin: string;
|
||
config: Record<string, unknown>;
|
||
minSeverity: string;
|
||
includeText: string;
|
||
excludeText: string;
|
||
taskIDsText: string;
|
||
assetIDsText: string;
|
||
onStatusChange: boolean;
|
||
};
|
||
|
||
const emptyForm = (kind: string): ChannelForm => ({
|
||
name: "",
|
||
kind,
|
||
mode: "realtime",
|
||
enabled: true,
|
||
ratePerMin: "",
|
||
config: {},
|
||
minSeverity: "",
|
||
includeText: "",
|
||
excludeText: "",
|
||
taskIDsText: "",
|
||
assetIDsText: "",
|
||
onStatusChange: false,
|
||
});
|
||
|
||
// parseKV 解析「每行 KEY=VALUE」的文本域。
|
||
function parseKV(text: string): Record<string, string> {
|
||
const out: Record<string, string> = {};
|
||
for (const line of text.split("\n")) {
|
||
const t = line.trim();
|
||
if (!t) continue;
|
||
const i = t.indexOf("=");
|
||
if (i > 0) out[t.slice(0, i).trim()] = t.slice(i + 1).trim();
|
||
}
|
||
return out;
|
||
}
|
||
// parseIDs 解析逗号/空白分隔的 id 列表。
|
||
function parseIDs(text: string): number[] {
|
||
return text
|
||
.split(/[\s,,]+/)
|
||
.map((s) => s.trim())
|
||
.filter(Boolean)
|
||
.map((s) => Number(s))
|
||
.filter((n) => Number.isFinite(n) && n > 0);
|
||
}
|
||
// parseKeywords 解析行/逗号分隔的关键词列表(漏洞类型名可能含空格,所以按行或逗号切)。
|
||
function parseKeywords(text: string): string[] {
|
||
return text
|
||
.split(/[\n,,]+/)
|
||
.map((s) => s.trim())
|
||
.filter(Boolean);
|
||
}
|
||
|
||
export default function NotifyPage() {
|
||
const [meta, setMeta] = React.useState<NotificationMeta | null>(null);
|
||
const [channels, setChannels] = React.useState<NotificationChannel[]>([]);
|
||
const [tab, setTab] = React.useState<"channels" | "deliveries">("channels");
|
||
|
||
const [open, setOpen] = React.useState(false);
|
||
const [editing, setEditing] = React.useState<NotificationChannel | null>(null);
|
||
const [form, setForm] = React.useState<ChannelForm>(emptyForm("dingtalk"));
|
||
const [saving, setSaving] = React.useState(false);
|
||
const [testing, setTesting] = React.useState(false);
|
||
|
||
const [globalSaving, setGlobalSaving] = React.useState(false);
|
||
const [baseURL, setBaseURL] = React.useState("");
|
||
const [digestMin, setDigestMin] = React.useState("");
|
||
|
||
const load = React.useCallback(() => {
|
||
api
|
||
.notifyMeta()
|
||
.then((m) => {
|
||
setMeta(m);
|
||
setBaseURL(m.public_base_url);
|
||
setDigestMin(m.digest_interval_min);
|
||
})
|
||
.catch((e) => toast.error("读取推送配置失败:" + (e as Error).message));
|
||
// 渠道列表加载失败要报出来:静默失败会显示成「一个渠道都没有」,
|
||
// 用户会以为配置丢了,比直接报错更让人慌。
|
||
api
|
||
.notifyChannels()
|
||
.then(setChannels)
|
||
.catch((e) => toast.error("读取渠道列表失败:" + (e as Error).message));
|
||
}, []);
|
||
React.useEffect(() => {
|
||
load();
|
||
}, [load]);
|
||
|
||
function setF(patch: Partial<ChannelForm>) {
|
||
setForm((f) => ({ ...f, ...patch }));
|
||
}
|
||
function setCfg(key: string, value: unknown) {
|
||
setForm((f) => ({ ...f, config: { ...f.config, [key]: value } }));
|
||
}
|
||
|
||
function openAdd() {
|
||
setEditing(null);
|
||
setForm(emptyForm(meta?.kinds[0]?.kind ?? "dingtalk"));
|
||
setOpen(true);
|
||
}
|
||
|
||
function openEdit(ch: NotificationChannel) {
|
||
setEditing(ch);
|
||
// filter 在后端是 Go 结构体,永远序列化成对象(不会是 null),所以不需要兜底。
|
||
const f = ch.filter;
|
||
setForm({
|
||
name: ch.name,
|
||
kind: ch.kind,
|
||
mode: ch.mode,
|
||
enabled: ch.enabled,
|
||
ratePerMin: String(ch.rate_per_min),
|
||
// 后端回显的 config 里凭据是掩码值;原样放进表单,提交时原样送回,
|
||
// 后端据此保留库中原值。
|
||
config: { ...ch.config },
|
||
minSeverity: f.min_severity ?? "",
|
||
includeText: (f.vulnclass_include ?? []).join("\n"),
|
||
excludeText: (f.vulnclass_exclude ?? []).join("\n"),
|
||
taskIDsText: (f.task_ids ?? []).join(","),
|
||
assetIDsText: (f.asset_ids ?? []).join(","),
|
||
onStatusChange: f.on_status_change ?? false,
|
||
});
|
||
setOpen(true);
|
||
}
|
||
|
||
// buildConfig 把表单状态转成渠道 config。
|
||
//
|
||
// 唯一的规则,两类值:
|
||
// - 掩码值("__masked__...")原样送回 → 后端解读为「这个字段没改,保留库中原值」
|
||
// - 其余一律按用户输入提交,空串即「清空该字段」
|
||
//
|
||
// 之所以不特殊照顾凭据字段(比如「凭据留空就跳过」),是因为那会让用户**无法清除**
|
||
// 一个设错的密钥——界面上没有任何操作能表达「我要把它删掉」。现在的规则下,
|
||
// 清空输入框就等于清空该字段,语义唯一且用户可控。
|
||
// 掩码值不会出现在输入框里(见 ConfigField),所以「框里有字」永远等于
|
||
// 「用户主动填的」。
|
||
function buildConfig(): Record<string, unknown> {
|
||
const defs = CHANNEL_FIELDS[form.kind] ?? [];
|
||
const out: Record<string, unknown> = {};
|
||
for (const d of defs) {
|
||
const raw = form.config[d.key];
|
||
if (d.kind === "switch") {
|
||
out[d.key] = raw === true;
|
||
continue;
|
||
}
|
||
if (typeof raw === "string" && raw.startsWith("__masked__")) {
|
||
out[d.key] = raw;
|
||
continue;
|
||
}
|
||
if (d.kind === "number") {
|
||
const n = Number(raw);
|
||
out[d.key] = Number.isFinite(n) && n > 0 ? n : 0;
|
||
continue;
|
||
}
|
||
if (d.kind === "kv") {
|
||
out[d.key] = parseKV(String(raw ?? ""));
|
||
continue;
|
||
}
|
||
if (d.kind === "list") {
|
||
out[d.key] = String(raw ?? "")
|
||
.split(/[\s,,]+/)
|
||
.map((s) => s.trim())
|
||
.filter(Boolean);
|
||
continue;
|
||
}
|
||
out[d.key] = String(raw ?? "").trim();
|
||
}
|
||
return out;
|
||
}
|
||
|
||
function buildFilter(): NotificationFilter {
|
||
return {
|
||
min_severity: form.minSeverity || undefined,
|
||
vulnclass_include: parseKeywords(form.includeText),
|
||
vulnclass_exclude: parseKeywords(form.excludeText),
|
||
task_ids: parseIDs(form.taskIDsText),
|
||
asset_ids: parseIDs(form.assetIDsText),
|
||
on_status_change: form.onStatusChange,
|
||
};
|
||
}
|
||
|
||
async function saveForm() {
|
||
if (!form.name.trim()) {
|
||
toast.error("请填写渠道名称");
|
||
return;
|
||
}
|
||
setSaving(true);
|
||
try {
|
||
const payload = {
|
||
name: form.name.trim(),
|
||
kind: form.kind,
|
||
mode: form.mode,
|
||
enabled: form.enabled,
|
||
config: buildConfig(),
|
||
filter: buildFilter(),
|
||
rate_per_min: form.ratePerMin.trim() === "" ? undefined : Number(form.ratePerMin),
|
||
};
|
||
if (editing) {
|
||
await api.notifyUpdateChannel(editing.id, payload);
|
||
toast.success("已保存");
|
||
setOpen(false);
|
||
} else {
|
||
await api.notifyCreateChannel(payload);
|
||
toast.success("已添加渠道");
|
||
setOpen(false);
|
||
}
|
||
load();
|
||
} catch (e) {
|
||
toast.error("保存失败:" + (e as Error).message);
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
}
|
||
|
||
async function testChannel() {
|
||
if (!editing) return;
|
||
setTesting(true);
|
||
try {
|
||
const r = await api.notifyTestChannel(editing.id);
|
||
toast.success(`已发出测试消息(${r.latency_ms} ms),请到群里确认`);
|
||
} catch (e) {
|
||
// 后端把渠道返回的原始错误如实回传,这是排查配置的唯一线索,原样展示。
|
||
toast.error("测试失败:" + (e as Error).message, { duration: 12000 });
|
||
} finally {
|
||
setTesting(false);
|
||
}
|
||
}
|
||
|
||
async function removeChannel(ch: NotificationChannel) {
|
||
try {
|
||
await api.notifyDeleteChannel(ch.id);
|
||
toast.success(`已删除:${ch.name}`);
|
||
setOpen(false);
|
||
load();
|
||
} catch (e) {
|
||
toast.error("删除失败:" + (e as Error).message);
|
||
}
|
||
}
|
||
|
||
async function toggleEnabled(ch: NotificationChannel) {
|
||
try {
|
||
await api.notifyUpdateChannel(ch.id, { enabled: !ch.enabled });
|
||
load();
|
||
} catch (e) {
|
||
toast.error("操作失败:" + (e as Error).message);
|
||
}
|
||
}
|
||
|
||
async function toggleGlobal(on: boolean) {
|
||
setGlobalSaving(true);
|
||
try {
|
||
await api.setSettings({ notify_enabled: on });
|
||
setMeta((m) => (m ? { ...m, enabled: on } : m));
|
||
toast.success(on ? "推送已开启" : "推送已暂停");
|
||
} catch (e) {
|
||
toast.error("操作失败:" + (e as Error).message);
|
||
} finally {
|
||
setGlobalSaving(false);
|
||
}
|
||
}
|
||
|
||
async function saveGlobal() {
|
||
setGlobalSaving(true);
|
||
try {
|
||
const patch: Record<string, unknown> = { notify_public_base_url: baseURL.trim() };
|
||
const n = Number(digestMin);
|
||
if (Number.isFinite(n) && n > 0) patch.notify_digest_interval_min = n;
|
||
await api.setSettings(patch);
|
||
toast.success("已保存");
|
||
load();
|
||
} catch (e) {
|
||
toast.error("保存失败:" + (e as Error).message);
|
||
} finally {
|
||
setGlobalSaving(false);
|
||
}
|
||
}
|
||
|
||
const fields = CHANNEL_FIELDS[form.kind] ?? [];
|
||
const secretKeys = new Set(meta?.kinds.find((k) => k.kind === form.kind)?.secret_keys ?? []);
|
||
const defaultRate = meta?.kinds.find((k) => k.kind === form.kind)?.default_rate_per_min ?? 0;
|
||
|
||
return (
|
||
<div className="flex flex-1 flex-col gap-4 md:gap-6">
|
||
<div className="flex items-start justify-between gap-4">
|
||
<div>
|
||
<h1 className="text-xl font-semibold tracking-tight">通知推送</h1>
|
||
<p className="text-muted-foreground text-sm">
|
||
发现漏洞时推送到钉钉 / 飞书 / 企业微信等渠道 · 每个渠道可独立设推送时机与过滤规则
|
||
</p>
|
||
</div>
|
||
{meta && (
|
||
// 用 div 而不是 label:Switch 自带 aria-label,外面再套一层 label
|
||
// 既关联不到任何原生控件,又会让点击文字看起来应该能切换。
|
||
<div className="flex shrink-0 items-center gap-2 text-sm">
|
||
<span className="text-muted-foreground">总开关</span>
|
||
<Switch
|
||
checked={meta.enabled}
|
||
disabled={globalSaving}
|
||
onCheckedChange={toggleGlobal}
|
||
aria-label="推送总开关"
|
||
/>
|
||
</div>
|
||
)}
|
||
</div>
|
||
|
||
{meta && (
|
||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">
|
||
<StatTile label="渠道" value={`${meta.stats.channels_on} / ${meta.stats.channels}`} hint="启用 / 总数" />
|
||
<StatTile label="今日送达" value={String(meta.stats.sent_today)} />
|
||
<StatTile label="待发送" value={String(meta.stats.pending)} />
|
||
<StatTile label="失败" value={String(meta.stats.failed)} tone={meta.stats.failed > 0 ? "red" : undefined} />
|
||
<StatTile
|
||
label="最久积压"
|
||
value={formatBacklog(meta.stats.backlog_age_ms)}
|
||
// 积压年龄比积压条数有用得多:积压 3 条可以是从 3 秒到 3 小时。
|
||
hint={meta.stats.backlog_age_ms > 5 * 60_000 ? "推送可能卡住了" : undefined}
|
||
tone={meta.stats.backlog_age_ms > 5 * 60_000 ? "red" : undefined}
|
||
/>
|
||
</div>
|
||
)}
|
||
|
||
<Card className="gap-3">
|
||
<CardHeader>
|
||
<CardTitle className="text-base">全局设置</CardTitle>
|
||
</CardHeader>
|
||
<CardContent className="grid gap-4 sm:grid-cols-2">
|
||
<div className="grid gap-2">
|
||
<Label htmlFor="n-base">回链地址</Label>
|
||
<Input
|
||
id="n-base"
|
||
placeholder="https://artex.example.com"
|
||
value={baseURL}
|
||
onChange={(e) => setBaseURL(e.target.value)}
|
||
/>
|
||
<p className="text-muted-foreground text-xs">消息里「查看详情」按钮指向的地址。留空则不带按钮。</p>
|
||
</div>
|
||
<div className="grid gap-2">
|
||
<Label htmlFor="n-digest">汇总周期(分钟)</Label>
|
||
<Input
|
||
id="n-digest"
|
||
type="number"
|
||
min={1}
|
||
max={1440}
|
||
placeholder="30"
|
||
value={digestMin}
|
||
onChange={(e) => setDigestMin(e.target.value)}
|
||
/>
|
||
<p className="text-muted-foreground text-xs">仅对「汇总」模式的渠道生效。</p>
|
||
</div>
|
||
<div className="sm:col-span-2">
|
||
<Button onClick={saveGlobal} disabled={globalSaving}>
|
||
保存全局设置
|
||
</Button>
|
||
</div>
|
||
</CardContent>
|
||
</Card>
|
||
|
||
<Tabs value={tab} onValueChange={(v) => setTab(v as "channels" | "deliveries")} className="flex flex-col gap-4">
|
||
<TabsList>
|
||
<TabsTrigger value="channels">渠道</TabsTrigger>
|
||
<TabsTrigger value="deliveries">投递记录</TabsTrigger>
|
||
</TabsList>
|
||
|
||
<TabsContent value="channels">
|
||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||
<button
|
||
type="button"
|
||
onClick={openAdd}
|
||
className="text-foreground/70 border-foreground/70 hover:bg-muted/60 hover:shadow-sm flex min-h-[130px] flex-col items-center justify-center gap-2 rounded-xl border border-dashed transition"
|
||
>
|
||
<PlusIcon className="size-6" />
|
||
<span className="text-sm">添加渠道</span>
|
||
</button>
|
||
|
||
{channels.map((ch) => (
|
||
<Card
|
||
key={ch.id}
|
||
onClick={() => openEdit(ch)}
|
||
className="hover:border-primary/60 cursor-pointer gap-3 transition hover:shadow-sm"
|
||
>
|
||
<CardHeader>
|
||
<div className="flex items-center gap-2">
|
||
<BellIcon className="text-muted-foreground size-4 shrink-0" />
|
||
<CardTitle className="truncate text-base">{ch.name}</CardTitle>
|
||
{/* 卡片整体可点(进入编辑),所以这两个控件必须各自吞掉冒泡,
|
||
否则开关/删除会顺带触发编辑。把 stopPropagation 挂在控件自己
|
||
身上,而不是套一层 div:套 div 会造出一个「看起来可交互但没有
|
||
角色」的静态元素,既触发 a11y 告警,语义上也说不通。 */}
|
||
<div className="ml-auto flex items-center gap-2">
|
||
<Switch
|
||
checked={ch.enabled}
|
||
onCheckedChange={() => toggleEnabled(ch)}
|
||
onClick={(e) => e.stopPropagation()}
|
||
aria-label="启用"
|
||
/>
|
||
<Button
|
||
size="icon"
|
||
variant="outline"
|
||
aria-label="删除"
|
||
onClick={(e) => {
|
||
e.stopPropagation();
|
||
// void 显式丢弃 Promise:removeChannel 自己 catch 并 toast,
|
||
// 这里不需要 await(onClick 不是 async)。
|
||
void removeChannel(ch);
|
||
}}
|
||
>
|
||
<Trash2Icon className="text-destructive" />
|
||
</Button>
|
||
</div>
|
||
</div>
|
||
</CardHeader>
|
||
<CardContent className="grid gap-3">
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
<Badge variant="outline">{KIND_LABEL[ch.kind] ?? ch.kind}</Badge>
|
||
<Badge variant="outline">{ch.mode === "digest" ? "汇总" : "实时"}</Badge>
|
||
{!ch.enabled && <Badge variant="outline">已停用</Badge>}
|
||
</div>
|
||
<FilterSummary filter={ch.filter} />
|
||
</CardContent>
|
||
</Card>
|
||
))}
|
||
</div>
|
||
</TabsContent>
|
||
|
||
<TabsContent value="deliveries">
|
||
<DeliveryList channels={channels} />
|
||
</TabsContent>
|
||
</Tabs>
|
||
|
||
<Sheet open={open} onOpenChange={setOpen}>
|
||
<SheetContent side="right" className="w-full data-[side=right]:sm:max-w-lg">
|
||
<SheetHeader>
|
||
<SheetTitle>{editing ? editing.name : "添加通知渠道"}</SheetTitle>
|
||
<SheetDescription>
|
||
{KIND_LABEL[form.kind] ?? form.kind}
|
||
{defaultRate > 0 ? ` · 默认限流 ${defaultRate} 条/分钟` : " · 不限流"}
|
||
</SheetDescription>
|
||
</SheetHeader>
|
||
|
||
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto px-4">
|
||
<div className="grid gap-4 py-4">
|
||
<div className="grid gap-2">
|
||
<Label>渠道类型</Label>
|
||
<Select
|
||
value={form.kind}
|
||
onValueChange={(v) => {
|
||
// 换类型等于换一套凭据字段,不能把旧配置合并进来。
|
||
setF({ kind: v, config: {} });
|
||
}}
|
||
disabled={!!editing}
|
||
>
|
||
<SelectTrigger>
|
||
<SelectValue />
|
||
</SelectTrigger>
|
||
<SelectContent>
|
||
{(meta?.kinds ?? []).map((k) => (
|
||
<SelectItem key={k.kind} value={k.kind}>
|
||
{KIND_LABEL[k.kind] ?? k.kind}
|
||
</SelectItem>
|
||
))}
|
||
</SelectContent>
|
||
</Select>
|
||
{editing && (
|
||
<p className="text-muted-foreground text-xs">
|
||
渠道类型不可修改——改了类型等于换一套凭据,请新建渠道。
|
||
</p>
|
||
)}
|
||
</div>
|
||
|
||
<div className="grid gap-2">
|
||
<Label htmlFor="n-name">渠道名称</Label>
|
||
<Input
|
||
id="n-name"
|
||
placeholder="应急响应群 / 日常播报群"
|
||
value={form.name}
|
||
onChange={(e) => setF({ name: e.target.value })}
|
||
/>
|
||
</div>
|
||
|
||
{fields.length === 0 ? (
|
||
<p className="text-muted-foreground text-sm">
|
||
该渠道的表单尚未定义(前端缺 CHANNEL_FIELDS 条目),请补全后再试。
|
||
</p>
|
||
) : (
|
||
fields.map((d) => (
|
||
<ConfigField
|
||
key={d.key}
|
||
def={d}
|
||
value={form.config[d.key]}
|
||
isSecret={secretKeys.has(d.key)}
|
||
onChange={(v) => setCfg(d.key, v)}
|
||
/>
|
||
))
|
||
)}
|
||
|
||
<div className="grid gap-2">
|
||
<Label>推送时机</Label>
|
||
<Select value={form.mode} onValueChange={(v) => setF({ mode: v as "realtime" | "digest" })}>
|
||
<SelectTrigger>
|
||
<SelectValue />
|
||
</SelectTrigger>
|
||
<SelectContent>
|
||
<SelectItem value="realtime">实时 · 每条漏洞单独发一条</SelectItem>
|
||
<SelectItem value="digest">汇总 · 按周期合并成一条</SelectItem>
|
||
</SelectContent>
|
||
</Select>
|
||
<p className="text-muted-foreground text-xs">
|
||
想做「高危实时、其余汇总」就建两个渠道:一个实时 + 门槛高危,一个汇总 + 不限级别。
|
||
</p>
|
||
</div>
|
||
|
||
<div className="grid gap-2">
|
||
<Label htmlFor="n-rate">限流(条/分钟)</Label>
|
||
<Input
|
||
id="n-rate"
|
||
type="number"
|
||
min={0}
|
||
placeholder={defaultRate > 0 ? String(defaultRate) : "0 = 不限"}
|
||
value={form.ratePerMin}
|
||
onChange={(e) => setF({ ratePerMin: e.target.value })}
|
||
/>
|
||
<p className="text-muted-foreground text-xs">
|
||
留空用渠道默认值;0 表示不限流。超限不会丢消息,只会推迟发送。
|
||
</p>
|
||
</div>
|
||
|
||
<div className="border-t pt-4">
|
||
<p className="mb-3 text-sm font-medium">过滤规则(留空即不过滤)</p>
|
||
<div className="grid gap-4">
|
||
<div className="grid gap-2">
|
||
<Label>最低级别</Label>
|
||
<Select
|
||
value={form.minSeverity || "all"}
|
||
onValueChange={(v) => setF({ minSeverity: v === "all" ? "" : v })}
|
||
>
|
||
<SelectTrigger>
|
||
<SelectValue />
|
||
</SelectTrigger>
|
||
<SelectContent>
|
||
{SEVERITY_OPTIONS.map((o) => (
|
||
<SelectItem key={o.value || "all"} value={o.value || "all"}>
|
||
{o.label}
|
||
</SelectItem>
|
||
))}
|
||
</SelectContent>
|
||
</Select>
|
||
</div>
|
||
<div className="grid gap-2">
|
||
<Label htmlFor="n-inc">只推这些漏洞类型</Label>
|
||
<Textarea
|
||
id="n-inc"
|
||
placeholder={"SQL注入\n命令执行"}
|
||
value={form.includeText}
|
||
onChange={(e) => setF({ includeText: e.target.value })}
|
||
/>
|
||
<p className="text-muted-foreground text-xs">
|
||
每行一个关键词,大小写不敏感的子串匹配。留空=全部类型。
|
||
</p>
|
||
</div>
|
||
<div className="grid gap-2">
|
||
<Label htmlFor="n-exc">排除这些漏洞类型</Label>
|
||
<Textarea
|
||
id="n-exc"
|
||
placeholder={"信息泄露"}
|
||
value={form.excludeText}
|
||
onChange={(e) => setF({ excludeText: e.target.value })}
|
||
/>
|
||
<p className="text-muted-foreground text-xs">排除优先于包含:同时命中时会被排除。</p>
|
||
</div>
|
||
<div className="grid gap-2">
|
||
<Label htmlFor="n-tasks">限定任务 ID</Label>
|
||
<Input
|
||
id="n-tasks"
|
||
placeholder="1, 2, 3"
|
||
value={form.taskIDsText}
|
||
onChange={(e) => setF({ taskIDsText: e.target.value })}
|
||
/>
|
||
</div>
|
||
<div className="grid gap-2">
|
||
<Label htmlFor="n-assets">限定资产 ID</Label>
|
||
<Input
|
||
id="n-assets"
|
||
placeholder="10, 11"
|
||
value={form.assetIDsText}
|
||
onChange={(e) => setF({ assetIDsText: e.target.value })}
|
||
/>
|
||
<p className="text-muted-foreground text-xs">任务/资产留空=不限;填写后要求与漏洞有交集。</p>
|
||
</div>
|
||
<div className="flex items-center gap-2 text-sm">
|
||
<Switch
|
||
checked={form.onStatusChange}
|
||
onCheckedChange={(v) => setF({ onStatusChange: v })}
|
||
aria-label="接收状态变更"
|
||
/>
|
||
漏洞处置状态变更时也推送(仅实时模式)
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div className="flex items-center gap-2 text-sm">
|
||
<Switch checked={form.enabled} onCheckedChange={(v) => setF({ enabled: v })} aria-label="启用" />
|
||
启用该渠道
|
||
</div>
|
||
</div>
|
||
|
||
<div className="flex gap-2 pt-2 pb-6">
|
||
<Button onClick={saveForm} disabled={saving}>
|
||
{editing ? "保存" : "添加"}
|
||
</Button>
|
||
{editing && (
|
||
<Button variant="outline" onClick={testChannel} disabled={testing}>
|
||
<SendIcon /> 发送测试消息
|
||
</Button>
|
||
)}
|
||
</div>
|
||
</div>
|
||
</SheetContent>
|
||
</Sheet>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
// asText 把任意配置值渲染成输入框可用的字符串。
|
||
// config 来自 JSON,值可能是 string / number / boolean / array / null,
|
||
// 这里只关心「能不能塞进文本框」,具体序列化由 buildConfig 负责。
|
||
function asText(v: unknown): string {
|
||
if (typeof v === "string") return v;
|
||
if (v === null || v === undefined) return "";
|
||
return String(v);
|
||
}
|
||
|
||
// inputType 把字段类型映射到 input 的 type 属性。
|
||
function inputType(kind: FieldKind): "text" | "password" | "number" {
|
||
if (kind === "password") return "password";
|
||
if (kind === "number") return "number";
|
||
return "text";
|
||
}
|
||
|
||
// ConfigField 按字段定义渲染对应的控件。
|
||
//
|
||
// 掩码字段的处理是这里唯一的讲究:输入框**不显示**掩码值本身,只显示一行
|
||
// 「已保存」提示。这样界面上就只有一个规则——框里有字就是用户填的,
|
||
// 空框就是空值。若把 "__masked__:…abc123" 塞进输入框,用户会以为那是要自己
|
||
// 删掉的占位文本,反而更容易误清凭据。
|
||
function ConfigField({
|
||
def,
|
||
value,
|
||
isSecret,
|
||
onChange,
|
||
}: {
|
||
def: FieldDef;
|
||
value: unknown;
|
||
isSecret: boolean;
|
||
onChange: (v: unknown) => void;
|
||
}) {
|
||
const id = `n-cfg-${def.key}`;
|
||
const raw = asText(value);
|
||
// 后端回显的掩码值:形如 "__masked__:…abc123",尾部是原值的可辨识片段。
|
||
const masked = isSecret && raw.startsWith("__masked__");
|
||
const maskedTail = masked ? (raw.split("…")[1] ?? "") : "";
|
||
|
||
if (def.kind === "switch") {
|
||
return (
|
||
<div className="flex items-center gap-2 text-sm">
|
||
<Switch checked={value === true} onCheckedChange={onChange} aria-label={def.label} />
|
||
{def.label}
|
||
{def.help && <span className="text-muted-foreground">({def.help})</span>}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
if (def.kind === "select") {
|
||
return (
|
||
<div className="grid gap-2">
|
||
<Label>{def.label}</Label>
|
||
<Select value={raw || def.options?.[0]?.value} onValueChange={onChange}>
|
||
<SelectTrigger>
|
||
<SelectValue />
|
||
</SelectTrigger>
|
||
<SelectContent>
|
||
{(def.options ?? []).map((o) => (
|
||
<SelectItem key={o.value} value={o.value}>
|
||
{o.label}
|
||
</SelectItem>
|
||
))}
|
||
</SelectContent>
|
||
</Select>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
// 控件按字段类型分派。用 if 链而不是嵌套三元,是因为这里要区分四种控件,
|
||
// 三层三元读起来已经要停下来数括号了。
|
||
function control() {
|
||
if (def.kind === "textarea" || def.kind === "kv") {
|
||
return (
|
||
<Textarea
|
||
id={id}
|
||
className="font-mono"
|
||
placeholder={def.placeholder}
|
||
value={masked ? "" : raw}
|
||
onChange={(e) => onChange(e.target.value)}
|
||
/>
|
||
);
|
||
}
|
||
if (def.kind === "list") {
|
||
return (
|
||
<Input
|
||
id={id}
|
||
value={Array.isArray(value) ? (value as string[]).join(", ") : raw}
|
||
onChange={(e) => onChange(e.target.value)}
|
||
placeholder={def.placeholder}
|
||
/>
|
||
);
|
||
}
|
||
return (
|
||
<Input
|
||
id={id}
|
||
className={def.kind === "text" ? "font-mono" : ""}
|
||
type={inputType(def.kind)}
|
||
placeholder={def.placeholder}
|
||
value={masked ? "" : raw}
|
||
onChange={(e) => onChange(e.target.value)}
|
||
/>
|
||
);
|
||
}
|
||
|
||
const hint = masked ? (
|
||
<p className="text-muted-foreground flex items-center gap-1 text-xs">
|
||
<CheckIcon className="size-3" />
|
||
已保存{maskedTail ? `(尾号 ${maskedTail})` : ""} · 填入新值即覆盖,清空则删除该项
|
||
</p>
|
||
) : (
|
||
def.help && <p className="text-muted-foreground text-xs">{def.help}</p>
|
||
);
|
||
|
||
return (
|
||
<div className="grid gap-2">
|
||
<Label htmlFor={id}>{def.label}</Label>
|
||
{control()}
|
||
{hint}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
// FilterSummary 把过滤条件摘要成一行,让卡片不用展开就能看出这个渠道推什么。
|
||
function FilterSummary({ filter }: { filter: NotificationFilter }) {
|
||
const parts: string[] = [];
|
||
if (filter.min_severity) {
|
||
parts.push(SEVERITY_OPTIONS.find((o) => o.value === filter.min_severity)?.label ?? filter.min_severity);
|
||
}
|
||
if (filter.vulnclass_include?.length) parts.push(`类型含 ${filter.vulnclass_include.length} 词`);
|
||
if (filter.vulnclass_exclude?.length) parts.push(`排除 ${filter.vulnclass_exclude.length} 词`);
|
||
if (filter.task_ids?.length) parts.push(`${filter.task_ids.length} 个任务`);
|
||
if (filter.asset_ids?.length) parts.push(`${filter.asset_ids.length} 个资产`);
|
||
if (filter.on_status_change) parts.push("含状态变更");
|
||
if (parts.length === 0) {
|
||
return <p className="text-muted-foreground text-sm">全部漏洞</p>;
|
||
}
|
||
return <p className="text-muted-foreground text-sm">{parts.join(" · ")}</p>;
|
||
}
|
||
|
||
function StatTile({ label, value, hint, tone }: { label: string; value: string; hint?: string; tone?: string }) {
|
||
return (
|
||
<Card size="sm" className="gap-1">
|
||
<CardContent>
|
||
<p className="text-muted-foreground text-xs">{label}</p>
|
||
<p className={`text-lg font-semibold ${tone === "red" ? "text-rose-600" : ""}`}>{value}</p>
|
||
{hint && <p className={`text-xs ${tone === "red" ? "text-rose-600" : "text-muted-foreground"}`}>{hint}</p>}
|
||
</CardContent>
|
||
</Card>
|
||
);
|
||
}
|
||
|
||
// formatBacklog 把积压毫秒数渲染成人看得懂的量级。
|
||
function formatBacklog(ms: number): string {
|
||
if (!ms) return "—";
|
||
if (ms < 60_000) return `${Math.round(ms / 1000)} 秒`;
|
||
if (ms < 3_600_000) return `${Math.round(ms / 60_000)} 分钟`;
|
||
return `${(ms / 3_600_000).toFixed(1)} 小时`;
|
||
}
|
||
|
||
// DeliveryList 是投递记录表:可按渠道与状态筛选,失败项可手动重发。
|
||
function DeliveryList({ channels }: { channels: NotificationChannel[] }) {
|
||
const [rows, setRows] = React.useState<NotificationDelivery[]>([]);
|
||
const [total, setTotal] = React.useState(0);
|
||
const [page, setPage] = React.useState(1);
|
||
const [channelID, setChannelID] = React.useState<number | undefined>(undefined);
|
||
const [state, setState] = React.useState<string | undefined>(undefined);
|
||
const [loading, setLoading] = React.useState(false);
|
||
const pageSize = 50;
|
||
|
||
const load = React.useCallback(() => {
|
||
setLoading(true);
|
||
api
|
||
.notifyDeliveries({ channelId: channelID, state, page, pageSize })
|
||
.then((r) => {
|
||
setRows(r.deliveries);
|
||
setTotal(r.total);
|
||
})
|
||
.catch((e) => toast.error("读取投递记录失败:" + (e as Error).message))
|
||
.finally(() => setLoading(false));
|
||
}, [channelID, state, page]);
|
||
React.useEffect(() => {
|
||
load();
|
||
}, [load]);
|
||
|
||
async function retry(id: number) {
|
||
try {
|
||
await api.notifyRetryDelivery(id);
|
||
toast.success("已重新入队");
|
||
load();
|
||
} catch (e) {
|
||
toast.error("重发失败:" + (e as Error).message);
|
||
}
|
||
}
|
||
|
||
const maxPage = Math.max(1, Math.ceil(total / pageSize));
|
||
|
||
return (
|
||
<div className="flex flex-col gap-3">
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
<Select
|
||
value={channelID ? String(channelID) : "all"}
|
||
onValueChange={(v) => {
|
||
setPage(1);
|
||
setChannelID(v === "all" ? undefined : Number(v));
|
||
}}
|
||
>
|
||
<SelectTrigger size="sm" className="w-44">
|
||
<SelectValue placeholder="全部渠道" />
|
||
</SelectTrigger>
|
||
<SelectContent>
|
||
<SelectItem value="all">全部渠道</SelectItem>
|
||
{channels.map((c) => (
|
||
<SelectItem key={c.id} value={String(c.id)}>
|
||
{c.name}
|
||
</SelectItem>
|
||
))}
|
||
</SelectContent>
|
||
</Select>
|
||
<Select
|
||
value={state ?? "all"}
|
||
onValueChange={(v) => {
|
||
setPage(1);
|
||
setState(v === "all" ? undefined : v);
|
||
}}
|
||
>
|
||
<SelectTrigger size="sm" className="w-32">
|
||
<SelectValue placeholder="全部状态" />
|
||
</SelectTrigger>
|
||
<SelectContent>
|
||
<SelectItem value="all">全部状态</SelectItem>
|
||
{["pending", "sending", "sent", "failed", "skipped"].map((s) => (
|
||
<SelectItem key={s} value={s}>
|
||
{statusMeta("delivery", s).label}
|
||
</SelectItem>
|
||
))}
|
||
</SelectContent>
|
||
</Select>
|
||
<Button size="sm" variant="outline" onClick={load} disabled={loading}>
|
||
<RefreshCwIcon className={loading ? "animate-spin" : ""} /> 刷新
|
||
</Button>
|
||
<span className="text-muted-foreground ml-auto text-xs">共 {total} 条</span>
|
||
</div>
|
||
|
||
<Card className="py-0">
|
||
<Table>
|
||
<TableHeader>
|
||
<TableRow>
|
||
<TableHead className="w-40">时间</TableHead>
|
||
<TableHead>漏洞</TableHead>
|
||
<TableHead className="w-40">渠道</TableHead>
|
||
<TableHead className="w-24">状态</TableHead>
|
||
<TableHead className="w-16">尝试</TableHead>
|
||
<TableHead>错误</TableHead>
|
||
<TableHead className="w-20" />
|
||
</TableRow>
|
||
</TableHeader>
|
||
<TableBody>
|
||
{rows.length === 0 ? (
|
||
<TableRow>
|
||
<TableCell colSpan={7} className="text-muted-foreground py-8 text-center">
|
||
{loading ? "加载中…" : "暂无投递记录"}
|
||
</TableCell>
|
||
</TableRow>
|
||
) : (
|
||
rows.map((d) => (
|
||
<TableRow key={d.id}>
|
||
<TableCell className="text-muted-foreground text-xs whitespace-nowrap">
|
||
{formatTime(d.created_at)}
|
||
</TableCell>
|
||
<TableCell>
|
||
<div className="flex items-center gap-2">
|
||
<Badge variant="outline" className={toneClasses[statusMeta("severity", d.severity).tone]}>
|
||
{statusMeta("severity", d.severity).label}
|
||
</Badge>
|
||
<span className="truncate text-sm">{d.title || "(无标题)"}</span>
|
||
{d.event_kind === "finding_status_changed" && (
|
||
<Badge variant="outline" className="shrink-0">
|
||
状态变更
|
||
</Badge>
|
||
)}
|
||
</div>
|
||
</TableCell>
|
||
<TableCell className="text-sm">{d.channel_name}</TableCell>
|
||
<TableCell>
|
||
<Badge variant="outline" className={toneClasses[statusMeta("delivery", d.state).tone]}>
|
||
{statusMeta("delivery", d.state).label}
|
||
</Badge>
|
||
</TableCell>
|
||
<TableCell className="text-muted-foreground text-sm">{d.attempts}</TableCell>
|
||
<TableCell className="text-muted-foreground max-w-md text-xs break-all">{d.last_error}</TableCell>
|
||
<TableCell>
|
||
{/* 只有失败/跳过的才给重发入口:已送达的重发会造成重复推送。 */}
|
||
{(d.state === "failed" || d.state === "skipped") && (
|
||
<Button size="sm" variant="outline" onClick={() => retry(d.id)}>
|
||
<RotateCcwIcon /> 重发
|
||
</Button>
|
||
)}
|
||
</TableCell>
|
||
</TableRow>
|
||
))
|
||
)}
|
||
</TableBody>
|
||
</Table>
|
||
</Card>
|
||
|
||
{maxPage > 1 && (
|
||
<div className="flex items-center justify-end gap-2">
|
||
<Button size="sm" variant="outline" disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>
|
||
上一页
|
||
</Button>
|
||
<span className="text-muted-foreground text-sm">
|
||
{page} / {maxPage}
|
||
</span>
|
||
<Button size="sm" variant="outline" disabled={page >= maxPage} onClick={() => setPage((p) => p + 1)}>
|
||
下一页
|
||
</Button>
|
||
</div>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function formatTime(iso: string): string {
|
||
const d = new Date(iso);
|
||
if (Number.isNaN(d.getTime())) return iso;
|
||
return d.toLocaleString("zh-CN", { hour12: false });
|
||
}
|