feat(web): SessionDrawer + Sessions tab in AttackerDetail

Adds asciinema-player dependency, SessionDrawer.tsx that pages the
transcripts API (500 events per request) and rebuilds a v2 .cast blob
for playback, and a Session Transcripts section in AttackerDetail that
deep-links into the drawer. Truncation banner surfaces the 10 MB
per-session cap when it's been hit.
This commit is contained in:
2026-04-21 23:08:39 -04:00
parent 6e522c5a55
commit 246a82774b
3 changed files with 317 additions and 0 deletions

View File

@@ -10,6 +10,7 @@
"preview": "vite preview" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {
"asciinema-player": "^3.8.0",
"axios": "^1.14.0", "axios": "^1.14.0",
"lucide-react": "^1.7.0", "lucide-react": "^1.7.0",
"react": "^19.2.4", "react": "^19.2.4",

View File

@@ -3,6 +3,7 @@ import { useParams, useNavigate } from 'react-router-dom';
import { Activity, ArrowLeft, ChevronDown, ChevronLeft, ChevronRight, ChevronUp, Crosshair, Fingerprint, Shield, Clock, Wifi, Lock, FileKey, Radio, Timer, Paperclip } from 'lucide-react'; import { Activity, ArrowLeft, ChevronDown, ChevronLeft, ChevronRight, ChevronUp, Crosshair, Fingerprint, Shield, Clock, Wifi, Lock, FileKey, Radio, Timer, Paperclip } from 'lucide-react';
import api from '../utils/api'; import api from '../utils/api';
import ArtifactDrawer from './ArtifactDrawer'; import ArtifactDrawer from './ArtifactDrawer';
import SessionDrawer from './SessionDrawer';
import './Dashboard.css'; import './Dashboard.css';
interface AttackerBehavior { interface AttackerBehavior {
@@ -707,6 +708,7 @@ const AttackerDetail: React.FC = () => {
commands: true, commands: true,
fingerprints: true, fingerprints: true,
artifacts: true, artifacts: true,
sessions: true,
}); });
// Captured file-drop artifacts (ssh inotify farm) for this attacker. // Captured file-drop artifacts (ssh inotify farm) for this attacker.
@@ -719,6 +721,17 @@ const AttackerDetail: React.FC = () => {
}; };
const [artifacts, setArtifacts] = useState<ArtifactLog[]>([]); const [artifacts, setArtifacts] = useState<ArtifactLog[]>([]);
const [artifact, setArtifact] = useState<{ decky: string; storedAs: string; fields: Record<string, any> } | null>(null); const [artifact, setArtifact] = useState<{ decky: string; storedAs: string; fields: Record<string, any> } | null>(null);
// PTY session transcripts (sessrec) for this attacker.
type SessionLog = {
id: number;
timestamp: string;
decky: string;
service: string;
fields: string;
};
const [sessions, setSessions] = useState<SessionLog[]>([]);
const [session, setSession] = useState<{ decky: string; sid: string; fields: Record<string, any> } | null>(null);
const toggle = (key: string) => setOpenSections((prev) => ({ ...prev, [key]: !prev[key] })); const toggle = (key: string) => setOpenSections((prev) => ({ ...prev, [key]: !prev[key] }));
// Commands pagination state // Commands pagination state
@@ -785,6 +798,19 @@ const AttackerDetail: React.FC = () => {
fetchArtifacts(); fetchArtifacts();
}, [id]); }, [id]);
useEffect(() => {
if (!id) return;
const fetchSessions = async () => {
try {
const res = await api.get(`/attackers/${id}/transcripts`);
setSessions(res.data.data ?? []);
} catch {
setSessions([]);
}
};
fetchSessions();
}, [id]);
if (loading) { if (loading) {
return ( return (
<div className="dashboard"> <div className="dashboard">
@@ -1166,6 +1192,87 @@ const AttackerDetail: React.FC = () => {
/> />
)} )}
{/* Recorded PTY Sessions (SSH / Telnet) */}
<Section
title={<>SESSION TRANSCRIPTS ({sessions.length})</>}
open={openSections.sessions}
onToggle={() => toggle('sessions')}
>
{sessions.length > 0 ? (
<div className="logs-table-container">
<table className="logs-table">
<thead>
<tr>
<th>TIMESTAMP</th>
<th>DECKY</th>
<th>SERVICE</th>
<th>DURATION</th>
<th>BYTES</th>
<th></th>
</tr>
</thead>
<tbody>
{sessions.map((row) => {
let fields: Record<string, any> = {};
try { fields = JSON.parse(row.fields || '{}'); } catch {}
const sid = fields.sid ? String(fields.sid) : null;
const dur = fields.duration_s;
const bytes = fields.bytes;
return (
<tr key={row.id}>
<td className="dim" style={{ fontSize: '0.75rem', whiteSpace: 'nowrap' }}>
{new Date(row.timestamp).toLocaleString()}
</td>
<td className="violet-accent">{row.decky}</td>
<td className="matrix-text">{fields.service ?? row.service}</td>
<td className="matrix-text" style={{ fontFamily: 'monospace' }}>
{dur ? `${dur}s` : '—'}
</td>
<td className="matrix-text" style={{ fontFamily: 'monospace' }}>
{bytes ? `${bytes} B` : '—'}
</td>
<td>
{sid && (
<button
onClick={() => setSession({ decky: row.decky, sid, fields })}
title="Replay recorded session"
style={{
display: 'flex', alignItems: 'center', gap: '6px',
fontSize: '0.7rem',
backgroundColor: 'rgba(0, 200, 255, 0.1)',
padding: '2px 8px',
borderRadius: '4px',
border: '1px solid rgba(0, 200, 255, 0.5)',
color: '#00c8ff',
cursor: 'pointer',
}}
>
REPLAY
</button>
)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
) : (
<div style={{ padding: '24px', textAlign: 'center', opacity: 0.5 }}>
NO SESSION TRANSCRIPTS RECORDED FROM THIS ATTACKER
</div>
)}
</Section>
{session && (
<SessionDrawer
decky={session.decky}
sid={session.sid}
fields={session.fields}
onClose={() => setSession(null)}
/>
)}
{/* UUID footer */} {/* UUID footer */}
<div style={{ textAlign: 'right', fontSize: '0.65rem', opacity: 0.3, marginTop: '8px' }}> <div style={{ textAlign: 'right', fontSize: '0.65rem', opacity: 0.3, marginTop: '8px' }}>
UUID: {attacker.uuid} UUID: {attacker.uuid}

View File

@@ -0,0 +1,209 @@
import React, { useEffect, useRef, useState } from 'react';
import { X, AlertTriangle } from 'lucide-react';
import api from '../utils/api';
// @ts-expect-error -- ships without type defs; 3.x CJS build is used directly
import * as AsciinemaPlayer from 'asciinema-player';
import 'asciinema-player/dist/bundle/asciinema-player.css';
interface SessionDrawerProps {
decky: string;
sid: string;
fields: Record<string, any>;
onClose: () => void;
}
interface TranscriptPage {
sid: string;
service: string;
header: Record<string, any>;
events: [number, string, string][];
offset: number;
limit: number;
total: number;
has_more: boolean;
truncated: boolean;
}
const PAGE_SIZE = 500;
const Row: React.FC<{ label: string; value: React.ReactNode }> = ({ label, value }) => (
<div style={{ display: 'flex', gap: '12px', padding: '6px 0', borderBottom: '1px solid rgba(255,255,255,0.05)' }}>
<div style={{ minWidth: '140px', color: 'var(--dim-color)', fontSize: '0.75rem', textTransform: 'uppercase' }}>{label}</div>
<div style={{ flex: 1, fontSize: '0.85rem', wordBreak: 'break-all' }}>{value ?? <span style={{ opacity: 0.4 }}></span>}</div>
</div>
);
function buildCastBlob(header: Record<string, any>, events: [number, string, string][]): string {
const headerLine = JSON.stringify({
version: 2,
width: header.width ?? 80,
height: header.height ?? 24,
timestamp: header.timestamp,
env: header.env,
});
const eventLines = events.map(([t, ch, d]) => JSON.stringify([t, ch, d]));
return [headerLine, ...eventLines].join('\n') + '\n';
}
const SessionDrawer: React.FC<SessionDrawerProps> = ({ decky, sid, fields, onClose }) => {
const [header, setHeader] = useState<Record<string, any> | null>(null);
const [events, setEvents] = useState<[number, string, string][]>([]);
const [loading, setLoading] = useState(true);
const [loadingMore, setLoadingMore] = useState(false);
const [error, setError] = useState<string | null>(null);
const [truncated, setTruncated] = useState(false);
const playerContainer = useRef<HTMLDivElement | null>(null);
const playerInstance = useRef<any>(null);
useEffect(() => {
let cancelled = false;
const fetchAll = async () => {
setLoading(true);
setError(null);
let offset = 0;
let hdr: Record<string, any> | null = null;
const allEvents: [number, string, string][] = [];
let truncFlag = false;
try {
// eslint-disable-next-line no-constant-condition
while (true) {
const res = await api.get<TranscriptPage>(
`/transcripts/${encodeURIComponent(decky)}/${encodeURIComponent(sid)}`,
{ params: { offset, limit: PAGE_SIZE } },
);
if (cancelled) return;
if (!hdr) hdr = res.data.header;
truncFlag = truncFlag || res.data.truncated;
allEvents.push(...res.data.events);
if (offset === 0) {
setHeader(hdr);
setEvents([...allEvents]);
setLoading(false);
} else {
setEvents([...allEvents]);
}
if (!res.data.has_more) break;
offset += PAGE_SIZE;
setLoadingMore(true);
}
setTruncated(truncFlag);
setLoadingMore(false);
} catch (err: any) {
if (cancelled) return;
const status = err?.response?.status;
setError(
status === 403 ? 'Admin role required to view transcripts.' :
status === 404 ? 'Transcript not found (shard may have rotated).' :
'Failed to load transcript — see console.'
);
console.error('transcript fetch failed', err);
setLoading(false);
}
};
fetchAll();
return () => { cancelled = true; };
}, [decky, sid]);
// Re-mount the player whenever the event window grows. asciinema-player
// doesn't expose a public feed() API in v3, so we rebuild from the full
// in-memory blob each time — cheap for v1-scale sessions (≤ 10 MB cap).
useEffect(() => {
if (!header || !playerContainer.current || events.length === 0) return;
if (playerInstance.current) {
try { playerInstance.current.dispose(); } catch { /* ignore */ }
playerInstance.current = null;
}
const cast = buildCastBlob(header, events);
const blob = new Blob([cast], { type: 'application/x-asciicast' });
const url = URL.createObjectURL(blob);
playerInstance.current = AsciinemaPlayer.create(url, playerContainer.current, {
fit: 'width',
terminalFontSize: '12px',
});
return () => {
URL.revokeObjectURL(url);
if (playerInstance.current) {
try { playerInstance.current.dispose(); } catch { /* ignore */ }
playerInstance.current = null;
}
};
}, [header, events]);
const service = fields.service;
const srcIp = fields.src_ip;
const duration = fields.duration_s;
const bytes = fields.bytes;
return (
<div
onClick={onClose}
style={{
position: 'fixed', inset: 0,
backgroundColor: 'rgba(0,0,0,0.6)',
display: 'flex', justifyContent: 'flex-end',
zIndex: 1000,
}}
>
<div
onClick={(e) => e.stopPropagation()}
style={{
width: 'min(920px, 100%)', height: '100%',
backgroundColor: 'var(--bg-color, #0d1117)',
borderLeft: '1px solid var(--border-color, #30363d)',
padding: '24px', overflowY: 'auto',
color: 'var(--text-color)',
}}
>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
<div>
<div style={{ fontSize: '0.7rem', color: 'var(--dim-color)', letterSpacing: '0.1em' }}>
SESSION TRANSCRIPT · {decky}
</div>
<div style={{ fontSize: '1rem', fontWeight: 'bold', marginTop: '4px', fontFamily: 'monospace' }}>
{sid}
</div>
</div>
<button onClick={onClose} style={{ background: 'none', border: 'none', color: 'var(--text-color)', cursor: 'pointer' }}>
<X size={20} />
</button>
</div>
{truncated && (
<div style={{
display: 'flex', alignItems: 'center', gap: '8px',
padding: '8px 12px', marginBottom: '16px',
border: '1px solid rgba(255, 170, 0, 0.3)',
backgroundColor: 'rgba(255, 170, 0, 0.05)',
fontSize: '0.75rem', color: '#ffaa00',
}}>
<AlertTriangle size={14} />
Session exceeded 10 MB cap playback is truncated.
</div>
)}
{error && (
<div style={{ color: '#ff5555', fontSize: '0.8rem', marginBottom: '16px' }}>{error}</div>
)}
<section style={{ marginBottom: '16px' }}>
<div ref={playerContainer} style={{ background: '#000', minHeight: '340px' }} />
{loading && <div style={{ opacity: 0.5, fontSize: '0.75rem', marginTop: '8px' }}>LOADING TRANSCRIPT</div>}
{loadingMore && <div style={{ opacity: 0.5, fontSize: '0.75rem', marginTop: '8px' }}>loading more events</div>}
</section>
<section>
<h3 style={{ fontSize: '0.8rem', letterSpacing: '0.1em', color: 'var(--dim-color)', marginBottom: '8px' }}>
METADATA
</h3>
<Row label="Service" value={service} />
<Row label="Src IP" value={srcIp} />
<Row label="Duration" value={duration ? `${duration}s` : null} />
<Row label="Bytes" value={bytes ? `${bytes}` : null} />
<Row label="Events" value={events.length} />
</section>
</div>
</div>
);
};
export default SessionDrawer;