Skip to content

armgit / ARTEX

Public Imported from GitHub
0

ARTEX - AI autonomous penetration testing system (English translation; upstream: Autumn-27/ARTEX, AGPL-3.0)

feat(web): show WebSocket and SSE messages in the traffic detail

BaaRai212e29cd15f7
diff --git a/web/src/app/(main)/function/traffic/_components/stream-messages.tsx b/web/src/app/(main)/function/traffic/_components/stream-messages.tsx
new file mode 100644
index 0000000..83c0bc3
--- /dev/null
+++ b/web/src/app/(main)/function/traffic/_components/stream-messages.tsx
@@ -0,0 +1,200 @@
+"use client";
+
+import * as React from "react";
+
+import { Loader2Icon, RefreshCwIcon } from "lucide-react";
+
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { api } from "@/lib/api";
+import type { TrafficStreamMessage } from "@/lib/types";
+
+const PAGE_SIZE = 50;
+// Binary payloads loaded in full are shown as hex of their first 64 KiB.
+const HEX_PREVIEW_BYTES = 64 * 1024;
+
+function fmtBytes(n: number) {
+ if (n <= 0) return "0 B";
+ const units = ["B", "KB", "MB", "GB"];
+ const i = Math.min(Math.floor(Math.log(n) / Math.log(1024)), units.length - 1);
+ const v = n / 1024 ** i;
+ return `${i === 0 ? v : v.toFixed(1)} ${units[i]}`;
+}
+
+function fmtDirection(direction: string) {
+ if (direction === "c2s") return "client -> server";
+ if (direction === "s2c") return "server -> client";
+ return direction;
+}
+
+// Hex dump: 16 bytes per line, offset first.
+function hexDump(bytes: Uint8Array) {
+ const lines: string[] = [];
+ for (let i = 0; i < bytes.length; i += 16) {
+ const row = Array.from(bytes.subarray(i, i + 16), (b) => b.toString(16).padStart(2, "0")).join(" ");
+ lines.push(`${i.toString(16).padStart(8, "0")} ${row}`);
+ }
+ return lines.join("\n");
+}
+
+type FullPayload = { loading: boolean; text?: string; error?: string };
+
+const payloadClass =
+ "max-h-64 overflow-auto rounded-md bg-muted/50 p-2 font-mono text-xs break-all whitespace-pre-wrap";
+
+function StreamMessageRow({ message }: { message: TrafficStreamMessage }) {
+ const [full, setFull] = React.useState<FullPayload | null>(null);
+ const binary = message.type === "binary";
+
+ const loadFull = () => {
+ if (!message.blob) return;
+ setFull({ loading: true });
+ api
+ .trafficBlob(message.blob)
+ .then((bytes) => {
+ const text = binary
+ ? `${hexDump(bytes.subarray(0, HEX_PREVIEW_BYTES))}\n(${bytes.length} bytes total)`
+ : new TextDecoder().decode(bytes);
+ setFull({ loading: false, text });
+ })
+ .catch((e: Error) => setFull({ loading: false, error: e.message }));
+ };
+
+ if (message.type === "meta") {
+ return (
+ <div className="mx-5 my-3 space-y-1 rounded-md border border-amber-500/40 bg-amber-500/10 p-3">
+ <div className="font-medium text-amber-700 text-xs dark:text-amber-400">
+ #{message.seq} Recording limit reached: later messages were not stored
+ </div>
+ <pre className={payloadClass}>{message.payload}</pre>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-1.5 border-b px-5 py-3 last:border-b-0">
+ <div className="flex flex-wrap items-center gap-2 text-xs">
+ <span className="font-mono text-muted-foreground tabular-nums">#{message.seq}</span>
+ <Badge variant="outline">{fmtDirection(message.direction)}</Badge>
+ <Badge variant="secondary">{message.type}</Badge>
+ {binary && message.encoding === "base64" && <Badge variant="outline">base64</Badge>}
+ {message.truncated && <Badge variant="destructive">truncated</Badge>}
+ {message.event && <span className="font-mono">event: {message.event}</span>}
+ {message.event_id && <span className="font-mono">id: {message.event_id}</span>}
+ {message.retry ? <span className="font-mono">retry: {message.retry}</span> : null}
+ <span className="ml-auto text-muted-foreground tabular-nums">
+ {fmtBytes(message.size)} · {new Date(message.ts * 1000).toLocaleTimeString()}
+ </span>
+ </div>
+ <pre className={payloadClass}>{full?.text ?? message.payload}</pre>
+ {message.blob && (
+ <div className="flex flex-wrap items-center gap-2 text-muted-foreground text-xs">
+ <span className="break-all font-mono">blob {message.blob}</span>
+ {!full?.text && (
+ <Button variant="outline" size="xs" disabled={full?.loading} onClick={loadFull}>
+ {full?.loading && <Loader2Icon className="animate-spin" />}
+ Load full payload
+ </Button>
+ )}
+ {full?.error && <span className="text-destructive">{full.error}</span>}
+ </div>
+ )}
+ </div>
+ );
+}
+
+// StreamMessagesPanel lists the messages of one WebSocket or SSE exchange, a
+// page at a time. It does not poll: Refresh reloads from the start.
+export function StreamMessagesPanel({ exchangeId, kind }: { exchangeId: string; kind: "websocket" | "sse" }) {
+ const [items, setItems] = React.useState<TrafficStreamMessage[]>([]);
+ const [total, setTotal] = React.useState(0);
+ const [loading, setLoading] = React.useState(true);
+ const [loadingMore, setLoadingMore] = React.useState(false);
+ const [error, setError] = React.useState<string | null>(null);
+ // Answers for an older exchange (or an older refresh) are dropped.
+ const generation = React.useRef(0);
+
+ const load = React.useCallback(
+ (offset: number) => {
+ const gen = offset === 0 ? ++generation.current : generation.current;
+ if (offset === 0) {
+ setLoading(true);
+ setError(null);
+ } else {
+ setLoadingMore(true);
+ }
+ api
+ .trafficStream(exchangeId, offset, PAGE_SIZE)
+ .then((page) => {
+ if (gen !== generation.current) return;
+ const next = page.items ?? [];
+ setItems((prev) => (offset === 0 ? next : [...prev, ...next]));
+ setTotal(page.total ?? 0);
+ })
+ .catch((e: Error) => {
+ if (gen === generation.current) setError(e.message);
+ })
+ .finally(() => {
+ if (gen !== generation.current) return;
+ setLoading(false);
+ setLoadingMore(false);
+ });
+ },
+ [exchangeId],
+ );
+
+ React.useEffect(() => {
+ setItems([]);
+ setTotal(0);
+ load(0);
+ }, [load]);
+
+ return (
+ <div className="flex flex-col">
+ <div className="flex items-center gap-2 px-5 py-3 text-muted-foreground text-xs">
+ <span>
+ {kind === "websocket" ? "WebSocket" : "Server-Sent Events"} · {items.length} of {total} messages
+ </span>
+ <Button variant="outline" size="xs" className="ml-auto" disabled={loading} onClick={() => load(0)}>
+ <RefreshCwIcon className={loading ? "animate-spin" : undefined} />
+ Refresh
+ </Button>
+ </div>
+ {renderBody()}
+ </div>
+ );
+
+ function renderBody() {
+ if (loading) {
+ return (
+ <div className="flex items-center gap-2 p-5 text-muted-foreground text-xs">
+ <Loader2Icon className="size-3.5 animate-spin" />
+ Loading messages…
+ </div>
+ );
+ }
+ if (error) {
+ return <div className="p-5 text-destructive text-xs">Failed to load messages: {error}</div>;
+ }
+ if (items.length === 0) {
+ return <div className="p-5 text-muted-foreground text-xs">No messages recorded for this stream.</div>;
+ }
+ return (
+ <>
+ <div className="border-t">
+ {items.map((m) => (
+ <StreamMessageRow key={`${exchangeId}:${m.seq}`} message={m} />
+ ))}
+ </div>
+ {items.length < total && (
+ <div className="flex justify-center p-4">
+ <Button variant="outline" size="sm" disabled={loadingMore} onClick={() => load(items.length)}>
+ {loadingMore && <Loader2Icon className="animate-spin" />}
+ Load more
+ </Button>
+ </div>
+ )}
+ </>
+ );
+ }
+}
diff --git a/web/src/app/(main)/function/traffic/page.tsx b/web/src/app/(main)/function/traffic/page.tsx
index 07fb213..115d59b 100644
--- a/web/src/app/(main)/function/traffic/page.tsx
+++ b/web/src/app/(main)/function/traffic/page.tsx
@@ -42,10 +42,12 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { api } from "@/lib/api";
+import { setVisibleInterval } from "@/lib/polling";
import { useStoredSortPreference } from "@/lib/sort-preference";
import type { TrafficDetail, TrafficExchange, TrafficHost, TrafficResp } from "@/lib/types";
import { cn } from "@/lib/utils";
-import { setVisibleInterval } from "@/lib/polling";
+
+import { StreamMessagesPanel } from "./_components/stream-messages";
function fmtTime(ts: string) {
return new Date(ts).toLocaleString("zh-CN", {
@@ -141,6 +143,9 @@ export default function TrafficPage() {
const [selected, setSelected] = React.useState<TrafficExchange | null>(null);
const [detail, setDetail] = React.useState<TrafficDetail | null>(null);
const [detailLoading, setDetailLoading] = React.useState(false);
+ const [detailTab, setDetailTab] = React.useState("request");
+ const streamKind = detail?.stream_kind === "websocket" || detail?.stream_kind === "sse" ? detail.stream_kind : null;
+ const hasStream = streamKind !== null;
const [hosts, setHosts] = React.useState<TrafficHost[]>([]); // target picker
const [selectedHosts, setSelectedHosts] = React.useState<string[]>([]); // checked in picker
@@ -298,8 +303,10 @@ export default function TrafficPage() {
.finally(() => setDeleting(false));
};
- // Lazy-load the raw request/response for the selected exchange.
+ // Lazy-load the raw request/response for the selected exchange. A new
+ // selection opens on Request; a WebSocket/SSE exchange then opens on Stream.
React.useEffect(() => {
+ setDetailTab("request");
if (!selected) {
setDetail(null);
return;
@@ -310,7 +317,9 @@ export default function TrafficPage() {
api
.trafficExchange(selected.id)
.then((d) => {
- if (alive) setDetail(d);
+ if (!alive) return;
+ setDetail(d);
+ if (d.stream_kind === "websocket" || d.stream_kind === "sse") setDetailTab("stream");
})
.catch(() => {
if (alive) setDetail({ req: "(failed to load the messages)", resp: "" });
@@ -742,10 +751,18 @@ export default function TrafficPage() {
<SheetTitle className="break-all font-mono">{selected.host}</SheetTitle>
<SheetDescription className="break-all font-mono">{selected.url}</SheetDescription>
</SheetHeader>
- <Tabs defaultValue="request" className="min-h-0 flex-1 gap-0">
- <TabsList className="mx-5 mt-4 grid w-auto grid-cols-2">
+ <Tabs value={detailTab} onValueChange={setDetailTab} className="min-h-0 flex-1 gap-0">
+ <TabsList className={cn("mx-5 mt-4 grid w-auto", hasStream ? "grid-cols-3" : "grid-cols-2")}>
<TabsTrigger value="request">Request</TabsTrigger>
<TabsTrigger value="response">Response</TabsTrigger>
+ {hasStream && (
+ <TabsTrigger value="stream">
+ Stream
+ {(detail?.stream_count ?? 0) > 0 && (
+ <span className="text-muted-foreground text-xs tabular-nums">{detail?.stream_count}</span>
+ )}
+ </TabsTrigger>
+ )}
</TabsList>
<TabsContent value="request" className="min-h-0 overflow-auto">
{detailLoading ? (
@@ -767,6 +784,11 @@ export default function TrafficPage() {
<HttpCodeBlock raw={detail?.resp ?? ""} />
)}
</TabsContent>
+ {streamKind && (
+ <TabsContent value="stream" className="min-h-0 overflow-auto">
+ <StreamMessagesPanel exchangeId={selected.id} kind={streamKind} />
+ </TabsContent>
+ )}
</Tabs>
</>
)}
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
index 03f5eb2..943e2e2 100644
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@ -102,6 +102,7 @@ import type {
TrafficEvidenceRole,
TrafficHost,
TrafficResp,
+ TrafficStreamPage,
UsageStats,
WorkspaceFile,
WorkspaceListing,
@@ -816,6 +817,20 @@ export const api = {
(opts.order ? `&order=${encodeURIComponent(opts.order)}` : ""),
),
trafficExchange: (id: string) => get<TrafficDetail>(`/traffic/exchange?id=${encodeURIComponent(id)}`),
+ // One page of a WebSocket/SSE exchange's messages, in order.
+ trafficStream: (id: string, offset = 0, limit = 50) =>
+ get<TrafficStreamPage>(`/traffic/stream?exchange=${encodeURIComponent(id)}&offset=${offset}&limit=${limit}`),
+ // Raw bytes of one stored blob (a full message payload or an oversized body).
+ // The JSON-only `get` cannot carry binary, hence the direct fetch.
+ trafficBlob: async (hash: string) => {
+ if (MOCK) throw new Error("Blob download is not available in mock mode");
+ const token = getToken();
+ const r = await fetch(`/api/traffic/blob?hash=${encodeURIComponent(hash)}`, {
+ headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}) },
+ });
+ if (!r.ok) throw new Error(`Blob download failed: ${r.status}`);
+ return new Uint8Array(await r.arrayBuffer());
+ },
trafficHosts: () => get<{ hosts: TrafficHost[] }>(`/traffic/hosts`),
trafficDeleteHost: (host: string) => del<{ deleted: number }>(`/traffic?host=${encodeURIComponent(host)}`),
trafficDeleteHosts: (hosts: string[]) => del<{ deleted: number }>(`/traffic/hosts`, { hosts }),
diff --git a/web/src/lib/types.ts b/web/src/lib/types.ts
index 7d6d1dd..bd9d14a 100644
--- a/web/src/lib/types.ts
+++ b/web/src/lib/types.ts
@@ -911,6 +911,34 @@ export interface TrafficResp {
export interface TrafficDetail {
req: string;
resp: string;
+ // WebSocket/SSE exchanges carry their messages separately (trafficStream);
+ // stream_kind is "" for an ordinary exchange.
+ stream_count?: number;
+ stream_kind?: "websocket" | "sse" | "";
+}
+
+// One recorded WebSocket message or SSE event. ts is in Unix seconds; seq
+// orders. payload is a preview of at most 4 KiB (base64 when encoding is
+// "base64"); blob names the full payload when it was stored separately.
+export interface TrafficStreamMessage {
+ seq: number;
+ ts: number;
+ direction: "c2s" | "s2c" | "meta" | (string & {});
+ kind: number;
+ type: "text" | "binary" | "event" | "meta" | (string & {});
+ event?: string;
+ event_id?: string;
+ retry?: number;
+ size: number;
+ payload: string;
+ encoding?: string;
+ blob?: string;
+ truncated?: boolean;
+}
+
+export interface TrafficStreamPage {
+ items: TrafficStreamMessage[];
+ total: number;
}
// One distinct recorded host with its exchange count (target picker).