import { useQuery } from "@tanstack/react-query"; import { createColumnHelper } from "@tanstack/react-table"; import { AlertTriangle, Eraser, RefreshCw, Sparkles, X } from "lucide-react"; import { useEffect, useMemo, useState } from "react"; import { Link } from "react-router-dom"; import { Badge } from "../../components/ui/Badge"; import { Button } from "../../components/ui/Button"; import { Card } from "../../components/ui/Card"; import { DataTable } from "../../components/ui/DataTable"; import { CursorPagination } from "../../components/ui/CursorPagination"; import { Input } from "../../components/ui/Input"; import { Select } from "../../components/ui/Select"; import { ToastContainer } from "../../components/ui/Toast"; import { useToast } from "../../hooks/useToast"; import { useI18n } from "../../i18n"; import { getCurrentLocale, isEnglishLocale } from "../../i18n/locale"; import { formatBytes } from "../../lib/bytes"; import { formatApiErrorMessage } from "../../lib/error-message"; import { formatDateTime } from "../../lib/time"; import { getSystemConfig } from "../systemConfig/api"; import { getRequestLog, getRequestLogPayloads, listRequestLogs } from "./api"; import type { RequestLogItem, RequestLogListFilters } from "./types"; type BoolFilter = "all" | "true" | "false"; type ProxyTypeFilter = "all" | "1" | "2" | "3"; type FilterDraft = { from_local: string; to_local: string; platform_name: string; account: string; target_host: string; egress_ip: string; proxy_type: ProxyTypeFilter; net_ok: BoolFilter; http_status: string; limit: number; }; const defaultFilters: FilterDraft = { from_local: "", to_local: "", platform_name: "", account: "", target_host: "", egress_ip: "", proxy_type: "all", net_ok: "all", http_status: "", limit: 100, }; const PAGE_SIZE_OPTIONS = [20, 50, 100, 200, 500, 1000, 2000] as const; const REQUEST_LOGS_FORWARD_BADGE_CLASS = "request-logs-proxy-badge-forward"; const REQUEST_LOGS_REVERSE_BADGE_CLASS = "request-logs-proxy-badge-reverse"; const REQUEST_LOGS_SOCKS_BADGE_CLASS = "request-logs-proxy-badge-socks"; const PAYLOAD_TABS = ["request", "response"] as const; type PayloadTab = (typeof PAYLOAD_TABS)[number]; const EMPTY_LOGS: RequestLogItem[] = []; const BASE64_DECODE_FAILED = "[Base64 解码失败]"; const UNSUPPORTED_CONTENT_ENCODING_PREFIX = "暂不支持的 Content-Encoding: "; const CONTENT_ENCODING_DECODE_FAILED_PREFIX = "Content-Encoding="; const CONTENT_ENCODING_DECODE_FAILED_SUFFIX = " 解压失败"; function toRFC3339(localDateTime: string): string { if (!localDateTime) { return ""; } const date = new Date(localDateTime); if (Number.isNaN(date.getTime())) { return ""; } return date.toISOString(); } function boolFromFilter(value: BoolFilter): boolean | undefined { if (value === "true") { return true; } if (value === "false") { return false; } return undefined; } function decodeBase64ToBytes(raw: string): Uint8Array | null { if (!raw) { return new Uint8Array(0); } try { const binary = atob(raw); return Uint8Array.from(binary, (char) => char.charCodeAt(0)); } catch { return null; } } function decodeBytesToText(bytes: Uint8Array, charset?: string): string { if (!bytes.length) { return ""; } if (charset) { try { return new TextDecoder(charset).decode(bytes); } catch { // Fallback to UTF-8 when charset is unsupported. } } return new TextDecoder().decode(bytes); } function decodeBase64ToText(raw: string): string { const bytes = decodeBase64ToBytes(raw); if (!bytes) { return BASE64_DECODE_FAILED; } return decodeBytesToText(bytes); } function parseHeaderMap(headersText: string): Map { const map = new Map(); for (const line of headersText.split(/\r?\n/)) { const separatorIndex = line.indexOf(":"); if (separatorIndex <= 0) { continue; } const key = line.slice(0, separatorIndex).trim().toLowerCase(); const value = line.slice(separatorIndex + 1).trim(); if (!key || !value) { continue; } const current = map.get(key); map.set(key, current ? `${current}, ${value}` : value); } return map; } function parseCharset(contentType?: string): string | undefined { if (!contentType) { return undefined; } const match = contentType.match(/charset\s*=\s*["']?([^;"'\s]+)/i); return match?.[1]?.trim(); } function parseContentEncodings(contentEncoding?: string): string[] { if (!contentEncoding) { return []; } return contentEncoding .split(",") .map((token) => token.trim().toLowerCase()) .filter((token) => token && token !== "identity"); } function normalizeContentEncoding(token: string): "gzip" | "deflate" | "br" | "zstd" | null { switch (token) { case "gzip": case "x-gzip": return "gzip"; case "deflate": return "deflate"; case "br": return "br"; case "zstd": case "x-zstd": return "zstd"; default: return null; } } function translatePayloadDecodeErrorMessage(rawMessage: string, t: (text: string, options?: Record) => string): string { if (rawMessage.startsWith(UNSUPPORTED_CONTENT_ENCODING_PREFIX)) { const token = rawMessage.slice(UNSUPPORTED_CONTENT_ENCODING_PREFIX.length).trim(); return t("暂不支持的 Content-Encoding: {{token}}", { token }); } if (rawMessage.startsWith(CONTENT_ENCODING_DECODE_FAILED_PREFIX) && rawMessage.endsWith(CONTENT_ENCODING_DECODE_FAILED_SUFFIX)) { const token = rawMessage .slice(CONTENT_ENCODING_DECODE_FAILED_PREFIX.length, rawMessage.length - CONTENT_ENCODING_DECODE_FAILED_SUFFIX.length) .trim(); return t("Content-Encoding={{token}} 解压失败", { token }); } return t(rawMessage); } async function decompressWithEncoding(bytes: Uint8Array, encoding: "gzip" | "deflate" | "br" | "zstd"): Promise { if (typeof DecompressionStream === "undefined") { throw new Error("当前浏览器不支持 DecompressionStream,无法自动解压"); } const stream = new Blob([new Uint8Array(bytes)]).stream().pipeThrough(new DecompressionStream(encoding as never)); const arrayBuffer = await new Response(stream).arrayBuffer(); return new Uint8Array(arrayBuffer); } async function decodeContentEncodings(bytes: Uint8Array, encodings: string[]): Promise { let decoded = bytes; // Content-Encoding is listed in the order applied, so decoding must reverse it. for (let i = encodings.length - 1; i >= 0; i -= 1) { const token = encodings[i]; const encoding = normalizeContentEncoding(token); if (!encoding) { throw new Error(`暂不支持的 Content-Encoding: ${token}`); } try { decoded = await decompressWithEncoding(decoded, encoding); } catch { throw new Error(`Content-Encoding=${token} 解压失败`); } } return decoded; } async function decodePayloadBodyForDisplay(rawBodyBase64: string, headersText: string): Promise { const bodyBytes = decodeBase64ToBytes(rawBodyBase64); if (!bodyBytes) { return BASE64_DECODE_FAILED; } if (!bodyBytes.length) { return ""; } const headerMap = parseHeaderMap(headersText); const encodings = parseContentEncodings(headerMap.get("content-encoding")); const contentType = headerMap.get("content-type"); let decodedBytes = bodyBytes; if (encodings.length) { try { decodedBytes = await decodeContentEncodings(bodyBytes, encodings); } catch { // Best-effort: fallback to undecoded bytes when content-encoding decode fails. } } return decodeBytesToText(decodedBytes, parseCharset(contentType)); } function isFromBeforeTo(fromISO?: string, toISO?: string): boolean { if (!fromISO || !toISO) { return true; } return new Date(fromISO).getTime() < new Date(toISO).getTime(); } function buildActiveFilters(draft: FilterDraft): Omit { const status = Number(draft.http_status); const hasValidStatus = Number.isInteger(status) && status >= 100 && status <= 599; const from = toRFC3339(draft.from_local); const to = toRFC3339(draft.to_local); const validRange = isFromBeforeTo(from, to); return { from, to: validRange ? to : undefined, platform_name: draft.platform_name, account: draft.account, target_host: draft.target_host, egress_ip: draft.egress_ip, proxy_type: draft.proxy_type === "all" ? undefined : Number(draft.proxy_type), net_ok: boolFromFilter(draft.net_ok), http_status: hasValidStatus ? status : undefined, limit: draft.limit, fuzzy: true, }; } function proxyTypeLabel(proxyType: number): string { if (proxyType === 1) { return "HTTP 正向代理"; } if (proxyType === 2) { return "HTTP 反向代理"; } if (proxyType === 3) { return "SOCKS5 正向代理"; } return String(proxyType); } function proxyTypeBadgeClassName(proxyType: number): string | null { if (proxyType === 1) { return REQUEST_LOGS_FORWARD_BADGE_CLASS; } if (proxyType === 2) { return REQUEST_LOGS_REVERSE_BADGE_CLASS; } if (proxyType === 3) { return REQUEST_LOGS_SOCKS_BADGE_CLASS; } return null; } function dateLocale(): string { return isEnglishLocale(getCurrentLocale()) ? "en-US" : "zh-CN"; } function splitDateTime(input: string): { date: string; time: string } { if (!input) { return { date: "-", time: "-" }; } const value = new Date(input); if (Number.isNaN(value.getTime())) { return { date: input, time: "-" }; } const date = new Intl.DateTimeFormat(dateLocale(), { year: "numeric", month: "2-digit", day: "2-digit", }).format(value); const time = new Intl.DateTimeFormat(dateLocale(), { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false, }).format(value); return { date, time }; } export function RequestLogsPage() { const { t } = useI18n(); const [filters, setFilters] = useState(defaultFilters); const [cursorStack, setCursorStack] = useState([""]); const [pageIndex, setPageIndex] = useState(0); const [selectedLogId, setSelectedLogId] = useState(""); const [drawerOpen, setDrawerOpen] = useState(false); const [payloadTab, setPayloadTab] = useState("request"); const [payloadData, setPayloadData] = useState<{ headers: string; body: string }>({ headers: "", body: "", }); const [payloadDecodePending, setPayloadDecodePending] = useState(false); const { toasts, dismissToast } = useToast(); const configQuery = useQuery({ queryKey: ["system-config"], queryFn: getSystemConfig, staleTime: 60_000, }); const activeFilters = useMemo(() => buildActiveFilters(filters), [filters]); const cursor = cursorStack[pageIndex] || ""; const rangeInvalid = useMemo(() => { const from = toRFC3339(filters.from_local); const to = toRFC3339(filters.to_local); return Boolean(from && to && !isFromBeforeTo(from, to)); }, [filters.from_local, filters.to_local]); const httpStatusInvalid = useMemo(() => { const raw = filters.http_status.trim(); if (!raw) { return false; } const value = Number(raw); return !(Number.isInteger(value) && value >= 100 && value <= 599); }, [filters.http_status]); const logsQuery = useQuery({ queryKey: ["request-logs", activeFilters, cursor], queryFn: () => listRequestLogs({ ...activeFilters, cursor }), refetchInterval: pageIndex === 0 ? 15_000 : false, placeholderData: (prev) => prev, }); const logs = logsQuery.data?.items ?? EMPTY_LOGS; const isPageTransitioning = logsQuery.isFetching && logsQuery.isPlaceholderData; const visibleLogs = isPageTransitioning ? EMPTY_LOGS : logs; const selectedLog = useMemo(() => { if (!selectedLogId) { return null; } return logs.find((item) => item.id === selectedLogId) ?? null; }, [logs, selectedLogId]); const detailLogId = selectedLogId; const drawerVisible = drawerOpen && Boolean(detailLogId); const detailQuery = useQuery({ queryKey: ["request-log", detailLogId], queryFn: () => getRequestLog(detailLogId), enabled: drawerVisible, }); const detailLog: RequestLogItem | null = detailQuery.data ?? selectedLog ?? null; const payloadQuery = useQuery({ queryKey: ["request-log-payload", detailLogId], queryFn: () => getRequestLogPayloads(detailLogId), enabled: drawerVisible && Boolean(detailLog?.payload_present), staleTime: 30_000, }); useEffect(() => { if (!drawerVisible) { return; } const onKeyDown = (event: KeyboardEvent) => { if (event.key !== "Escape") { return; } setDrawerOpen(false); }; window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); }, [drawerVisible]); const updateFilter = (key: K, value: FilterDraft[K]) => { setFilters((prev) => ({ ...prev, [key]: value })); setCursorStack([""]); setPageIndex(0); setSelectedLogId(""); setDrawerOpen(false); }; const resetFilters = () => { setFilters(defaultFilters); setCursorStack([""]); setPageIndex(0); setSelectedLogId(""); setDrawerOpen(false); }; const openDrawer = (logId: string) => { setSelectedLogId(logId); setDrawerOpen(true); setPayloadTab("request"); }; const moveNext = () => { if (isPageTransitioning) { return; } const nextCursor = logsQuery.data?.next_cursor; if (!nextCursor) { return; } setCursorStack((prev) => { const expectedNextIndex = pageIndex + 1; if (prev[expectedNextIndex] === nextCursor) { return prev; } return [...prev.slice(0, expectedNextIndex), nextCursor]; }); setPageIndex((prev) => prev + 1); setSelectedLogId(""); setDrawerOpen(false); }; const movePrev = () => { if (isPageTransitioning) { return; } setPageIndex((prev) => Math.max(0, prev - 1)); setSelectedLogId(""); setDrawerOpen(false); }; useEffect(() => { let cancelled = false; const payload = payloadQuery.data; if (!payload) { setPayloadData({ headers: "", body: "" }); setPayloadDecodePending(false); return () => { cancelled = true; }; } setPayloadData({ headers: "", body: "" }); setPayloadDecodePending(true); const decodePayload = async () => { const [headersBase64, bodyBase64] = payloadTab === "request" ? [payload.req_headers_b64, payload.req_body_b64] : [payload.resp_headers_b64, payload.resp_body_b64]; const rawHeaders = decodeBase64ToText(headersBase64).trimEnd(); const rawBody = (await decodePayloadBodyForDisplay(bodyBase64, rawHeaders)).trimEnd(); const headers = rawHeaders === BASE64_DECODE_FAILED ? t(rawHeaders) : rawHeaders; const body = rawBody === BASE64_DECODE_FAILED ? t(rawBody) : rawBody; if (cancelled) { return; } setPayloadData({ headers, body }); setPayloadDecodePending(false); }; void decodePayload().catch((error: unknown) => { if (cancelled) { return; } const message = error instanceof Error ? translatePayloadDecodeErrorMessage(error.message, t) : t("未知错误"); setPayloadData({ headers: "", body: t("[Body 解码失败:{{message}}]", { message }) }); setPayloadDecodePending(false); }); return () => { cancelled = true; }; }, [payloadQuery.data, payloadTab, t]); const hasMore = Boolean(logsQuery.data?.has_more && logsQuery.data?.next_cursor); const renderProxyTypeBadge = (proxyType: number, context: "table" | "drawer" = "table") => { const className = proxyTypeBadgeClassName(proxyType); if (!className) { return t(proxyTypeLabel(proxyType)); } let label = ""; if (proxyType === 1) { label = context === "drawer" ? t("HTTP") : t("正向"); } else if (proxyType === 2) { label = t("反向"); } else { label = t("SOCKS5"); } return {label}; }; const col = useMemo(() => createColumnHelper(), []); const logColumns = useMemo( () => [ col.accessor("ts", { header: t("时间"), cell: (info) => { const timeParts = splitDateTime(info.getValue()); return (
{timeParts.time} {timeParts.date}
); }, }), col.accessor("proxy_type", { header: t("代理"), cell: (info) => renderProxyTypeBadge(info.getValue()), }), col.display({ id: "platform_account", header: t("平台 / 账号"), cell: (info) => { const log = info.row.original; return (
{log.platform_name || "-"} {log.account || "-"}
); }, }), col.display({ id: "target", header: t("目标"), cell: (info) => { const log = info.row.original; return (
{log.target_host || "-"} {log.target_url || "-"}
); }, }), col.display({ id: "http", header: t("HTTP"), cell: (info) => { const log = info.row.original; return (
{log.http_method || "-"} {log.http_status || "-"}
); }, }), col.accessor("net_ok", { header: t("网络"), cell: (info) => ( {info.getValue() ? t("成功") : t("失败")} ), }), col.accessor("duration_ms", { header: t("耗时"), cell: (info) => `${info.getValue()} ms`, }), col.display({ id: "traffic", header: t("流量"), cell: (info) => { const log = info.row.original; return formatBytes((log.ingress_bytes || 0) + (log.egress_bytes || 0)); }, }), col.display({ id: "node", header: t("节点"), cell: (info) => { const log = info.row.original; return (
{log.node_tag ? ( event.stopPropagation()} style={{ color: "var(--accent-primary)", textDecoration: "none", width: "fit-content", }} > {log.node_tag} ) : ( - )} {log.egress_ip || "-"}
); }, }), ], [col, t] ); return (

{t("请求日志")}

{t("按条件检索请求记录,快速定位问题。")}

{!configQuery.isLoading && configQuery.data && ( {configQuery.data.request_log_enabled ? t("当前实时日志记录已开启") : t("当前实时日志记录未开启")} )}
{/* 时间与路由信息 */}
updateFilter("from_local", event.target.value)} style={{ width: "100%", padding: "4px 8px", fontSize: "0.875rem", minHeight: "32px", height: "32px" }} />
updateFilter("to_local", event.target.value)} style={{ width: "100%", padding: "4px 8px", fontSize: "0.875rem", minHeight: "32px", height: "32px" }} />
updateFilter("platform_name", event.target.value)} style={{ width: "100%", padding: "4px 8px", fontSize: "0.875rem", minHeight: "32px", height: "32px" }} />
updateFilter("account", event.target.value)} style={{ width: "100%", padding: "4px 8px", fontSize: "0.875rem", minHeight: "32px", height: "32px" }} />
updateFilter("target_host", event.target.value)} style={{ width: "100%", padding: "4px 8px", fontSize: "0.875rem", minHeight: "32px", height: "32px" }} />
{/* 网络状态与操作 */}
updateFilter("egress_ip", event.target.value)} style={{ width: "100%", padding: "4px 8px", fontSize: "0.875rem", minHeight: "32px", height: "32px" }} />
updateFilter("http_status", event.target.value)} style={{ width: "100%", padding: "4px 8px", fontSize: "0.875rem", minHeight: "32px", height: "32px" }} />
{rangeInvalid ?
{t("时间范围错误:开始时间必须早于结束时间,已暂不应用结束时间筛选。")}
: null} {httpStatusInvalid ?
{t("HTTP 状态码需为 100-599 的整数,当前输入暂不应用。")}
: null}
{logsQuery.isLoading || isPageTransitioning ?

{t("正在加载日志...")}

: null} {logsQuery.isError ? (
{formatApiErrorMessage(logsQuery.error, t)}
) : null} {!logsQuery.isLoading && !isPageTransitioning && !visibleLogs.length ? (

{t("没有匹配日志")}

) : null} {visibleLogs.length ? ( openDrawer(log.id)} selectedRowId={drawerVisible ? detailLogId : undefined} getRowId={(log) => log.id} wrapClassName="data-table-wrap-logs" /> ) : null} updateFilter("limit", limit)} onPrev={movePrev} onNext={moveNext} />
{drawerVisible && detailLog ? (
setDrawerOpen(false)} > event.stopPropagation()}>

{detailLog.target_host || detailLog.account || t("请求日志详情")}

{detailLog.id}

{t("日志摘要")}

{t("请求时间、协议结果与平台路由信息。")}

{detailQuery.isError ? (
{formatApiErrorMessage(detailQuery.error, t)}
) : null}
{t("时间")}

{formatDateTime(detailLog.ts)}

{t("代理类型")}

{renderProxyTypeBadge(detailLog.proxy_type, "drawer")}

{t("HTTP")}

{detailLog.http_method || "-"} {detailLog.http_status || "-"}

{t("耗时")}

{detailLog.duration_ms} ms

{t("平台")}

{detailLog.platform_name || "-"}

{t("账号")}

{detailLog.account || "-"}

{t("出口 IP")}

{detailLog.egress_ip || "-"}

{t("客户端 IP")}

{detailLog.client_ip || "-"}

{t("诊断")}

{t("异常排查与连接状态分析。")}

{(detailLog.resin_error || detailLog.upstream_stage || detailLog.upstream_err_kind || detailLog.upstream_errno || detailLog.upstream_err_msg) ? ( {detailLog.resin_error ? ( ) : null} {detailLog.upstream_stage ? ( ) : null} {detailLog.upstream_err_kind ? ( ) : null} {detailLog.upstream_errno ? ( ) : null} {detailLog.upstream_err_msg ? ( ) : null}
{t("Resin 错误:")} {detailLog.resin_error}
{t("失败阶段:")} {detailLog.upstream_stage}
{t("错误类型:")} {detailLog.upstream_err_kind}
Errno: {detailLog.upstream_errno}
{t("错误详情:")} {detailLog.upstream_err_msg}
) : null} {!detailLog.resin_error && !detailLog.upstream_stage && !detailLog.upstream_err_kind && !detailLog.upstream_err_msg ? (
{t("当前请求未产生异常诊断信息")}
) : null}

{t("目标与节点")}

{t("请求目标与命中节点信息。")}

{t("目标地址")}

{detailLog.target_host || "-"}

{detailLog.target_url || "-"}
{t("流量")}

{formatBytes((detailLog.ingress_bytes || 0) + (detailLog.egress_bytes || 0))}

↓ {formatBytes(detailLog.ingress_bytes || 0)} ↑ {formatBytes(detailLog.egress_bytes || 0)}
{t("节点")}

{detailLog.node_tag || "-"}

{detailLog.node_hash || "-"}

{t("报文内容")}

{t("查看请求/响应内容。")}

{!detailLog.payload_present ? (

{t("该条日志未记录报文内容。")}

) : (
{PAYLOAD_TABS.map((tab) => { const labelMap: Record = { request: t("请求"), response: t("响应"), }; const truncated = payloadQuery.data ? (tab === "request" ? payloadQuery.data.truncated.req_headers || payloadQuery.data.truncated.req_body : payloadQuery.data.truncated.resp_headers || payloadQuery.data.truncated.resp_body) : false; return ( ); })}
{payloadQuery.isError ? (
{formatApiErrorMessage(payloadQuery.error, t)}
) : null} {(payloadQuery.isFetching || payloadDecodePending) && !(payloadData.headers || payloadData.body) ? (
{t("加载报文内容中...")}
) : ( <>
                          {payloadData.headers || t("(空 Headers)")}
                        
                          {payloadData.body || t("(空 Body)")}
                        
)}
)}
) : null}
); }