- 新增 PageShell/PageTabs/ContentPanel/PageLoading/PageEmpty 页面骨架 - index.css 设计令牌文档化,布局令牌与纯色主按钮(去除渐变粉彩) - 全站路由页接入 PageShell,云账单三 Tab 为标杆 - 主题体系:跟随系统 + 主流/开发者分组,新增 Dracula/Tokyo Night,One Dark 暖灰差异化 - 登录页/侧栏/顶栏去渐变光球,企业克制风 - 修复 AIAlertAnalyzer JSX 与构建依赖导入问题
274 lines
12 KiB
TypeScript
274 lines
12 KiB
TypeScript
// 终端审计 — 会话命令子面板(筛选 / 虚拟滚动 / 导出) // Logan.Li
|
|
|
|
import { useMemo, useState, useRef } from 'react';
|
|
import { useTranslation } from 'react-i18next';
|
|
import { useVirtualizer } from '@tanstack/react-virtual';
|
|
import { Card, CardContent } from '@/components/ui/card';
|
|
import { Button } from '@/components/ui/button';
|
|
import { Input } from '@/components/ui/input';
|
|
import { Search, RefreshCw, Play, FileText } from 'lucide-react';
|
|
import { useSessionCommands } from '@/hooks/api';
|
|
import { terminalSessionApi, sessionCommandApi } from '@/api';
|
|
import { ReplayDialog } from '@/components/system/ReplayDialog';
|
|
import { formatCommandOutput, presetAuditRange } from './helpers';
|
|
import { isHighRiskCommand } from '@/components/system/replay/replay-utils';
|
|
import { exportCommandsListCsv } from '@/components/system/replay/export-audit';
|
|
import { unwrapList } from '@/hooks/api/unwrap';
|
|
import { cn } from '@/lib/utils';
|
|
import { toast } from 'sonner';
|
|
import type { SessionCommand } from './types';
|
|
|
|
const GRID_COLS = 'minmax(150px,1fr) minmax(80px,0.8fr) minmax(200px,2fr) minmax(100px,0.8fr) minmax(80px,0.5fr) 40px';
|
|
const PAGE_SIZE = 1000;
|
|
|
|
export function SessionCommandsPanel() {
|
|
const { t } = useTranslation();
|
|
const [keyword, setKeyword] = useState('');
|
|
const [username, setUsername] = useState('');
|
|
const [sessionIdInput, setSessionIdInput] = useState('');
|
|
const [startDate, setStartDate] = useState('');
|
|
const [endDate, setEndDate] = useState('');
|
|
const [applied, setApplied] = useState({
|
|
keyword: '', username: '', sessionId: '', startDate: '', endDate: '',
|
|
});
|
|
|
|
const [replayOpen, setReplayOpen] = useState(false);
|
|
const [replayId, setReplayId] = useState<number | null>(null);
|
|
const [replaySeek, setReplaySeek] = useState<number | undefined>(undefined);
|
|
const [exporting, setExporting] = useState(false);
|
|
|
|
const queryParams = useMemo(() => ({
|
|
page: 1,
|
|
page_size: PAGE_SIZE,
|
|
...(applied.sessionId ? { session_id: Number(applied.sessionId) } : {}),
|
|
...(applied.username ? { username: applied.username } : {}),
|
|
...(applied.keyword ? { command: applied.keyword } : {}),
|
|
...(applied.startDate ? { start_date: applied.startDate } : {}),
|
|
...(applied.endDate ? { end_date: applied.endDate } : {}),
|
|
}), [applied]);
|
|
|
|
const { data, isLoading, refetch } = useSessionCommands(queryParams);
|
|
const commands = data?.list ?? [];
|
|
const total = data?.total ?? 0;
|
|
|
|
const applyFilters = () => {
|
|
setApplied({ keyword, username, sessionId: sessionIdInput, startDate, endDate });
|
|
};
|
|
|
|
const handleExportCsv = async () => {
|
|
setExporting(true);
|
|
try {
|
|
const resp = await sessionCommandApi.list({
|
|
...queryParams,
|
|
page: 1,
|
|
page_size: Math.min(Math.max(total, 1), 10000),
|
|
});
|
|
const list = unwrapList<SessionCommand>(resp);
|
|
if (list.length === 0) {
|
|
toast.error(t('audit.terminal.noCommands'));
|
|
return;
|
|
}
|
|
exportCommandsListCsv(list);
|
|
} catch {
|
|
toast.error(t('audit.terminal.exportFailed'));
|
|
} finally {
|
|
setExporting(false);
|
|
}
|
|
};
|
|
|
|
// 虚拟滚动
|
|
const scrollRef = useRef<HTMLDivElement>(null);
|
|
const virtualizer = useVirtualizer({
|
|
count: commands.length,
|
|
getScrollElement: () => scrollRef.current,
|
|
estimateSize: () => 48,
|
|
overscan: 10,
|
|
});
|
|
const virtualRows = virtualizer.getVirtualItems();
|
|
const totalHeight = virtualizer.getTotalSize();
|
|
|
|
// 从命令行打开回放并跳到该命令时刻(无录制则提示) // Logan.Li
|
|
const openReplayAtCommand = async (cmd: SessionCommand) => {
|
|
if (!cmd.session_record_size) {
|
|
toast.error(t('audit.terminal.replayPlayer.noRecord'));
|
|
return;
|
|
}
|
|
try {
|
|
const sess = await terminalSessionApi.get(cmd.session_id) as { start_time?: string };
|
|
const ts = cmd.timestamp || cmd.created_at;
|
|
let seek: number | undefined;
|
|
if (sess?.start_time && ts) {
|
|
seek = (new Date(ts).getTime() - new Date(sess.start_time).getTime()) / 1000;
|
|
if (seek < 0) seek = 0;
|
|
}
|
|
setReplayId(cmd.session_id);
|
|
setReplaySeek(seek);
|
|
setReplayOpen(true);
|
|
} catch {
|
|
toast.error(t('audit.terminal.replayPlayer.loadFailed'));
|
|
}
|
|
};
|
|
|
|
return (
|
|
<>
|
|
<div className="flex items-center gap-2 flex-wrap">
|
|
<div className="relative w-52">
|
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 dg-text-muted" />
|
|
<Input
|
|
placeholder={t('audit.terminal.searchUserCommand')}
|
|
value={keyword}
|
|
onChange={(e) => setKeyword(e.target.value)}
|
|
onKeyDown={(e) => e.key === 'Enter' && applyFilters()}
|
|
className="pl-9 h-9 dg-input"
|
|
/>
|
|
</div>
|
|
<Input
|
|
placeholder={t('audit.terminal.filterUsername')}
|
|
value={username}
|
|
onChange={(e) => setUsername(e.target.value)}
|
|
onKeyDown={(e) => e.key === 'Enter' && applyFilters()}
|
|
className="w-28 h-9 dg-input"
|
|
/>
|
|
<Input
|
|
placeholder={t('audit.terminal.sessionIdPlaceholder')}
|
|
value={sessionIdInput}
|
|
onChange={(e) => setSessionIdInput(e.target.value)}
|
|
onKeyDown={(e) => e.key === 'Enter' && applyFilters()}
|
|
className="w-32 h-9 dg-input"
|
|
/>
|
|
<Input type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)} className="w-36 h-9 dg-input" />
|
|
<span className="dg-text-muted text-sm">—</span>
|
|
<Input type="date" value={endDate} onChange={(e) => setEndDate(e.target.value)} className="w-36 h-9 dg-input" />
|
|
<Button variant="outline" size="sm" className="dg-btn-secondary h-9" onClick={() => { const r = presetAuditRange(1); setStartDate(r.start); setEndDate(r.end); }}>
|
|
{t('audit.terminal.presetToday')}
|
|
</Button>
|
|
<Button variant="outline" size="sm" className="dg-btn-secondary h-9" onClick={() => { const r = presetAuditRange(7); setStartDate(r.start); setEndDate(r.end); }}>
|
|
{t('audit.terminal.preset7d')}
|
|
</Button>
|
|
<Button variant="outline" size="sm" className="dg-btn-secondary h-9" onClick={() => { const r = presetAuditRange(30); setStartDate(r.start); setEndDate(r.end); }}>
|
|
{t('audit.terminal.preset30d')}
|
|
</Button>
|
|
<Button size="sm" className="h-9" onClick={applyFilters}>{t('audit.terminal.applyFilter')}</Button>
|
|
<Button
|
|
variant="outline"
|
|
className="dg-btn-secondary h-9"
|
|
onClick={() => refetch()}
|
|
>
|
|
<RefreshCw className="h-4 w-4 mr-2" />
|
|
{t('common.refresh')}
|
|
</Button>
|
|
<Button
|
|
variant="outline"
|
|
className="dg-btn-secondary hover:text-[var(--dg-orange)] h-9"
|
|
onClick={handleExportCsv}
|
|
disabled={exporting || total === 0}
|
|
title={t('audit.terminal.exportCommandsCsv')}
|
|
>
|
|
<FileText className="h-4 w-4 mr-2" />
|
|
{t('audit.terminal.exportCommands')}
|
|
</Button>
|
|
</div>
|
|
|
|
<Card className="dg-card">
|
|
<CardContent className="p-0">
|
|
<div className="border-t border-[var(--dg-border)]">
|
|
{isLoading ? (
|
|
<div className="flex items-center justify-center py-16">
|
|
<div className="w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />
|
|
</div>
|
|
) : commands.length === 0 ? (
|
|
<div className="flex flex-col items-center justify-center py-16 dg-text-muted">
|
|
<Search className="h-8 w-8 mb-3 opacity-40" />
|
|
<p className="text-sm">{t('audit.terminal.noCommands')}</p>
|
|
</div>
|
|
) : (
|
|
<>
|
|
<div
|
|
className="grid gap-2 px-4 py-2 border-b border-[var(--dg-border)] bg-[var(--dg-bg-secondary)] text-xs font-medium dg-text-secondary"
|
|
style={{ gridTemplateColumns: GRID_COLS }}
|
|
>
|
|
<span>{t('audit.terminal.col.startTime')}</span>
|
|
<span>{t('audit.terminal.col.user')}</span>
|
|
<span>{t('audit.terminal.col.command')}</span>
|
|
<span>{t('audit.terminal.col.outputSize')}</span>
|
|
<span>{t('audit.terminal.col.sessionRef')}</span>
|
|
<span />
|
|
</div>
|
|
|
|
<div ref={scrollRef} style={{ height: 'min(600px, calc(100vh - 340px))', overflow: 'auto' }}>
|
|
<div style={{ height: totalHeight, position: 'relative' }}>
|
|
{virtualRows.map((vr) => {
|
|
const c = commands[vr.index];
|
|
if (!c) return null;
|
|
return (
|
|
<div
|
|
key={c.id}
|
|
data-index={vr.index}
|
|
ref={virtualizer.measureElement}
|
|
style={{
|
|
position: 'absolute',
|
|
top: 0,
|
|
left: 0,
|
|
width: '100%',
|
|
transform: `translateY(${vr.start}px)`,
|
|
display: 'grid',
|
|
gridTemplateColumns: GRID_COLS,
|
|
gap: '0.5rem',
|
|
}}
|
|
className="px-4 py-2.5 border-b border-[var(--dg-border)] hover:bg-[var(--dg-bg-hover)]"
|
|
>
|
|
<span className="text-sm dg-text-secondary truncate">
|
|
{c.created_at ? new Date(c.created_at).toLocaleString() : '--'}
|
|
</span>
|
|
<span className="text-sm text-[var(--dg-text-primary)] truncate">{c.username || '--'}</span>
|
|
<code className={cn(
|
|
'text-xs bg-[var(--dg-bg-tertiary)] px-2 py-0.5 rounded max-w-[400px] truncate block',
|
|
isHighRiskCommand(c.command || '') ? 'dg-text-red' : 'text-[var(--dg-text-secondary)]',
|
|
)}>
|
|
{c.command || '--'}
|
|
</code>
|
|
<span className="text-sm dg-text-secondary">{formatCommandOutput(c.output_size)}</span>
|
|
<span className={cn(
|
|
'text-xs',
|
|
c.session_record_size ? 'dg-text-muted' : 'text-amber-500/80',
|
|
)} title={!c.session_record_size ? t('audit.terminal.replayPlayer.noRecord') : undefined}>
|
|
#{c.session_id}
|
|
</span>
|
|
<Button
|
|
variant="ghost"
|
|
size="icon"
|
|
className="h-7 w-7 dg-text-secondary hover:dg-text-blue disabled:opacity-30"
|
|
onClick={() => openReplayAtCommand(c)}
|
|
disabled={!c.session_record_size}
|
|
title={c.session_record_size
|
|
? t('audit.terminal.replayAtCommand')
|
|
: t('audit.terminal.replayPlayer.noRecord')}
|
|
>
|
|
<Play className="h-3.5 w-3.5" />
|
|
</Button>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
|
|
<div className="text-center py-2 text-xs dg-text-muted border-t border-[var(--dg-border)]">
|
|
{t('audit.terminal.totalCommands', { count: total })}
|
|
{commands.length < total && ` · ${t('audit.terminal.showingLoaded', { loaded: commands.length })}`}
|
|
{commands.length > 200 && ` · ${t('audit.terminal.virtualScroll')}`}
|
|
</div>
|
|
</>
|
|
)}
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
|
|
<ReplayDialog
|
|
open={replayOpen}
|
|
onOpenChange={setReplayOpen}
|
|
sessionId={replayId}
|
|
initialSeekSec={replaySeek}
|
|
/>
|
|
</>
|
|
);
|
|
} |