mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-02 20:01:51 +08:00
feat(traffic,sandbox): add TUN/netstack transparent gateway, egress controls, CAP_NET_RAW hardening, and i18n fixes
- Implement full-traffic transparent gateway (cmd/artex-gateway, traffic/netstack.go, traffic/transparent.go) using Linux TUN + gVisor netstack deferred TCP handshakes (eliminating nmap/nc false-positive open ports), real ICMPv4 Echo proxying, UDP/DNS interception, and per-container upstream proxy overrides. - Add egress blacklist + asset-intercept sync, non-HTTP flow/DNS SQLite persistence and APIs, and /system/proxy & /function/traffic TCP/UDP/DNS UI panels. - Fix sandbox Playwright MCP browser loopback --proxy-server rewrite and NODE_EXTRA_CA_CERTS override in server/mcpstdio.go. - Strip all SUID/SGID binaries in Dockerfile.sandbox, grant minimal cap_net_raw+ep to nmap/nping/ping with ARTEX_SANDBOX_ALLOW_NET_RAW toggle, and enforce IPv4/IPv6 anti-spoofing in iptables and netstack. - Remove hardcoded Chinese "(全局)" from GET /api/proxy/routes, localize ContainerRoutesTab / NonHTTPTrafficPanel labels, and expose reactive locale/isEn from useLiveTranslation for React Compiler compatibility.
This commit is contained in:
1 parent
9c43e694a3
commit
d786de90af
69 files changed
+13082
-1433
No files matched your search
@@ -69,8 +69,7 @@ export function SessionSandboxControl({
|
||||
conversationId: number;
|
||||
running: boolean;
|
||||
}) {
|
||||
const { i18n } = useLiveTranslation();
|
||||
const isEn = i18n.language.startsWith("en");
|
||||
const { isEn } = useLiveTranslation();
|
||||
const L = (zh: string, en: string) => (isEn ? en : zh);
|
||||
|
||||
const ownerID = `conv-${conversationId}`;
|
||||
|
||||
@@ -63,8 +63,7 @@ function fmtUptime(startedAt?: string): string {
|
||||
}
|
||||
|
||||
export function TaskSandboxControl({ task, onTaskUpdated }: { task: Task; onTaskUpdated: () => void }) {
|
||||
const { i18n } = useLiveTranslation();
|
||||
const isEn = i18n.language.startsWith("en");
|
||||
const { isEn } = useLiveTranslation();
|
||||
const L = (zh: string, en: string) => (isEn ? en : zh);
|
||||
|
||||
const [open, setOpen] = React.useState(false);
|
||||
|
||||
@@ -0,0 +1,445 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
|
||||
import { PlusIcon, RefreshCwIcon, RouteIcon, SaveIcon, Trash2Icon } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, 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 { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { useLiveTranslation } from "@/i18n/use-live-translation";
|
||||
import { api } from "@/lib/api";
|
||||
import type { ContainerRouteStatusItem, ProxyPoolEntry, ProxyRoutesState } from "@/lib/types";
|
||||
|
||||
export function ContainerRoutesTab({
|
||||
proxyPool,
|
||||
routesState,
|
||||
onRefresh,
|
||||
}: {
|
||||
proxyPool: ProxyPoolEntry[];
|
||||
routesState: ProxyRoutesState | null;
|
||||
onRefresh: () => Promise<void>;
|
||||
}) {
|
||||
const { isEn, locale } = useLiveTranslation();
|
||||
const L = (zh: string, en: string) => (isEn ? en : zh);
|
||||
const formatProxyValue = (raw?: string) => {
|
||||
const clean = (raw ?? "").replace(/\s*\((全局|Global)\)\s*$/i, "").trim();
|
||||
if (!clean || clean === "direct") return L("直连", "Direct");
|
||||
return clean;
|
||||
};
|
||||
const formatEffectiveProxy = (c: ContainerRouteStatusItem) => {
|
||||
const base = formatProxyValue(c.effective_proxy);
|
||||
if (!c.mode || c.mode === "inherit") {
|
||||
return `${base} (${L("全局", "Global")})`;
|
||||
}
|
||||
return base;
|
||||
};
|
||||
const formatScope = (scope: string) => {
|
||||
if (scope === "task") return L("任务", "Task");
|
||||
if (scope === "session") return L("对话", "Session");
|
||||
return scope;
|
||||
};
|
||||
const formatState = (state?: string) => {
|
||||
const normalized = (state ?? "").trim().toLowerCase();
|
||||
const labels: Record<string, string> = {
|
||||
running: L("运行中", "Running"),
|
||||
exited: L("已停止", "Stopped"),
|
||||
stopped: L("已停止", "Stopped"),
|
||||
created: L("已创建", "Created"),
|
||||
paused: L("已暂停", "Paused"),
|
||||
inactive: L("未运行", "Inactive"),
|
||||
};
|
||||
return labels[normalized] ?? (normalized ? (state ?? "") : L("未运行", "Inactive"));
|
||||
};
|
||||
|
||||
const [udpPolicy, setUdpPolicy] = React.useState(routesState?.gateway.udp_policy ?? "block_on_proxy");
|
||||
const [dnsUpstream, setDnsUpstream] = React.useState(routesState?.gateway.dns_upstream ?? "");
|
||||
const [savingGW, setSavingGW] = React.useState(false);
|
||||
|
||||
const [newScope, setNewScope] = React.useState<"task" | "session">("task");
|
||||
const [newOwnerID, setNewOwnerID] = React.useState("");
|
||||
const [newMode, setNewMode] = React.useState<"direct" | "proxy">("proxy");
|
||||
const [newPoolID, setNewPoolID] = React.useState("__custom__");
|
||||
const [newProxyURL, setNewProxyURL] = React.useState("");
|
||||
const [newNote, setNewNote] = React.useState("");
|
||||
const [savingRoute, setSavingRoute] = React.useState(false);
|
||||
const [busyKey, setBusyKey] = React.useState<string | null>(null);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (routesState) {
|
||||
setUdpPolicy(routesState.gateway.udp_policy || "block_on_proxy");
|
||||
setDnsUpstream(routesState.gateway.dns_upstream || "");
|
||||
}
|
||||
}, [routesState]);
|
||||
|
||||
const saveGatewaySettings = async () => {
|
||||
setSavingGW(true);
|
||||
try {
|
||||
await api.updateGatewaySettings({ udp_policy: udpPolicy, dns_upstream: dnsUpstream.trim() });
|
||||
await onRefresh();
|
||||
toast.success(L("透明网关策略已更新并热下发", "Transparent gateway policy updated"));
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setSavingGW(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddRoute = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
const owner = newOwnerID.trim();
|
||||
if (!owner) {
|
||||
toast.error(L("请填写任务 ID 或会话 ID", "Enter a task ID or session ID"));
|
||||
return;
|
||||
}
|
||||
setSavingRoute(true);
|
||||
try {
|
||||
await api.putProxyRoute(newScope, owner, {
|
||||
mode: newMode,
|
||||
proxy_pool_id: newMode === "proxy" && newPoolID !== "__custom__" ? newPoolID : undefined,
|
||||
proxy_url: newMode === "proxy" && newPoolID === "__custom__" ? newProxyURL.trim() : undefined,
|
||||
note: newNote.trim(),
|
||||
});
|
||||
setNewOwnerID("");
|
||||
setNewProxyURL("");
|
||||
setNewNote("");
|
||||
await onRefresh();
|
||||
toast.success(L("容器出口路由已生效", "Container egress route saved"));
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setSavingRoute(false);
|
||||
}
|
||||
};
|
||||
|
||||
const quickUpdateRow = async (item: ContainerRouteStatusItem, selection: string) => {
|
||||
const key = `${item.scope}:${item.owner_id}`;
|
||||
setBusyKey(key);
|
||||
try {
|
||||
if (selection === "__inherit__") {
|
||||
await api.deleteProxyRoute(item.scope, item.owner_id);
|
||||
} else if (selection === "__direct__") {
|
||||
await api.putProxyRoute(item.scope, item.owner_id, { mode: "direct", note: item.note });
|
||||
} else if (selection.startsWith("pool:")) {
|
||||
await api.putProxyRoute(item.scope, item.owner_id, {
|
||||
mode: "proxy",
|
||||
proxy_pool_id: selection.slice(5),
|
||||
note: item.note,
|
||||
});
|
||||
}
|
||||
await onRefresh();
|
||||
toast.success(L("已更新容器出口路由", "Container egress route updated"));
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusyKey(null);
|
||||
}
|
||||
};
|
||||
|
||||
const deleteRowRoute = async (item: ContainerRouteStatusItem) => {
|
||||
const key = `${item.scope}:${item.owner_id}`;
|
||||
setBusyKey(key);
|
||||
try {
|
||||
await api.deleteProxyRoute(item.scope, item.owner_id);
|
||||
await onRefresh();
|
||||
toast.success(L("已恢复继承全局代理", "Reverted to global proxy"));
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusyKey(null);
|
||||
}
|
||||
};
|
||||
|
||||
const gw = routesState?.gateway;
|
||||
const containers = routesState?.containers ?? [];
|
||||
|
||||
return (
|
||||
<div className="min-w-0 space-y-4">
|
||||
{/* Transparent Gateway Status & Policy Card */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<RouteIcon className="size-4" />
|
||||
{L("全流量透明网关状态与策略", "Transparent Gateway Status & Policy")}
|
||||
<Badge
|
||||
variant={gw?.connected ? "default" : "secondary"}
|
||||
className={gw?.connected ? "bg-emerald-600 text-white hover:bg-emerald-600" : "text-muted-foreground"}
|
||||
>
|
||||
{(() => {
|
||||
if (!gw?.connected) return L("未连接网关", "Gateway Offline");
|
||||
return gw.embedded ? L("内置运行中", "Embedded Online") : L("网关在线", "Gateway Online");
|
||||
})()}
|
||||
</Badge>
|
||||
</CardTitle>
|
||||
<CardDescription className="mt-1">
|
||||
{L(
|
||||
"artex-gateway 通过网桥透明接管沙箱容器全部 TCP / DNS / UDP 出站流量,杜绝环境变量绕过,并统一应用出口黑名单与上游代理。",
|
||||
"artex-gateway transparently intercepts all sandbox TCP, DNS, and UDP egress at the bridge layer to prevent proxy-env bypass.",
|
||||
)}
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Button size="sm" variant="outline" onClick={() => void onRefresh()}>
|
||||
<RefreshCwIcon className="mr-1.5 size-3.5" />
|
||||
{L("刷新", "Refresh")}
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs">{L("非 DNS UDP 出口策略", "Non-DNS UDP Policy")}</Label>
|
||||
<Select value={udpPolicy} onValueChange={setUdpPolicy}>
|
||||
<SelectTrigger className="h-9 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="block_on_proxy">
|
||||
{L(
|
||||
"启用代理时阻断 UDP(OPSEC 推荐,防真实 IP 泄露)",
|
||||
"Block UDP when proxy active (OPSEC default)",
|
||||
)}
|
||||
</SelectItem>
|
||||
<SelectItem value="block">{L("始终阻断非 DNS UDP", "Always block non-DNS UDP")}</SelectItem>
|
||||
<SelectItem value="direct">
|
||||
{L("允许 UDP 直连(仍受黑名单/SSRF 限制)", "Allow direct UDP (still filtered)")}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs">
|
||||
{L("上游 DNS 服务器(留空使用宿主机/8.8.8.8:53)", "Upstream DNS (empty = system / 8.8.8.8:53)")}
|
||||
</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={dnsUpstream}
|
||||
onChange={(e) => setDnsUpstream(e.target.value)}
|
||||
placeholder="8.8.8.8:53 / 1.1.1.1:53"
|
||||
className="h-9 font-mono text-xs"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
className="h-9 shrink-0"
|
||||
disabled={savingGW}
|
||||
onClick={() => void saveGatewaySettings()}
|
||||
>
|
||||
<SaveIcon className="mr-1.5 size-3.5" />
|
||||
{L("保存策略", "Save")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{gw?.last_seen ? (
|
||||
<p className="font-mono text-muted-foreground text-xs">
|
||||
{L("网关标识:", "Gateway ID: ")}
|
||||
{gw.gateway_id || "artex-gateway"} · {L("最近心跳:", "Last heartbeat: ")}
|
||||
{new Date(gw.last_seen).toLocaleString(locale)}
|
||||
</p>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Add Per-Container / Task Proxy Route Override */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">
|
||||
{L("按任务 / 容器覆盖出口代理", "Per-Task / Container Egress Override")}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{L("默认继承全局出口代理(当前:", "Containers inherit the global egress proxy by default (current: ")}
|
||||
<span className="font-mono">{formatProxyValue(routesState?.global_proxy)}</span>
|
||||
{L(
|
||||
")。可为特定任务或会话容器单独指定代理池节点、自定义代理或强制直连,HTTP / TCP / DNS 均实时生效。",
|
||||
"). Override any task or session container with a pool node, custom proxy, or direct egress.",
|
||||
)}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<form onSubmit={handleAddRoute} className="grid gap-2 md:grid-cols-12">
|
||||
<div className="md:col-span-2">
|
||||
<Select value={newScope} onValueChange={(v) => setNewScope(v as "task" | "session")}>
|
||||
<SelectTrigger className="h-8 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="task">{L("任务 (task)", "Task")}</SelectItem>
|
||||
<SelectItem value="session">{L("对话 (session)", "Session")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="md:col-span-2">
|
||||
<Input
|
||||
value={newOwnerID}
|
||||
onChange={(e) => setNewOwnerID(e.target.value)}
|
||||
placeholder={newScope === "task" ? L("任务 ID,如 42", "Task ID, e.g. 42") : L("会话 ID", "Session ID")}
|
||||
className="h-8 font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div className="md:col-span-2">
|
||||
<Select value={newMode} onValueChange={(v) => setNewMode(v as "direct" | "proxy")}>
|
||||
<SelectTrigger className="h-8 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="proxy">{L("指定代理", "Use proxy")}</SelectItem>
|
||||
<SelectItem value="direct">{L("强制直连", "Force direct")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{newMode === "proxy" ? (
|
||||
<div className="md:col-span-3">
|
||||
<Select value={newPoolID} onValueChange={setNewPoolID}>
|
||||
<SelectTrigger className="h-8 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="__custom__">{L("手动输入代理 URL", "Custom proxy URL")}</SelectItem>
|
||||
{proxyPool.map((p) => (
|
||||
<SelectItem key={p.id} value={p.id}>
|
||||
{p.name || p.url}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
) : null}
|
||||
{newMode === "proxy" && newPoolID === "__custom__" ? (
|
||||
<div className="md:col-span-3">
|
||||
<Input
|
||||
value={newProxyURL}
|
||||
onChange={(e) => setNewProxyURL(e.target.value)}
|
||||
placeholder="socks5://127.0.0.1:1080"
|
||||
className="h-8 font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className={newMode === "proxy" ? "md:col-span-3" : "md:col-span-6"}>
|
||||
<Input
|
||||
value={newNote}
|
||||
onChange={(e) => setNewNote(e.target.value)}
|
||||
placeholder={L("备注(可选)", "Note (optional)")}
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex justify-end md:col-span-12">
|
||||
<Button type="submit" size="sm" className="h-8" disabled={savingRoute}>
|
||||
<PlusIcon className="mr-1.5 size-3.5" />
|
||||
{L("应用覆盖规则", "Save Override")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{/* Active Containers & Persisted Route Rules Table */}
|
||||
<div className="w-full min-w-0 overflow-x-auto rounded-lg border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>{L("归属", "Owner")}</TableHead>
|
||||
<TableHead>{L("容器 / IP", "Container / IP")}</TableHead>
|
||||
<TableHead>{L("状态", "State")}</TableHead>
|
||||
<TableHead>{L("当前生效出口", "Effective Egress")}</TableHead>
|
||||
<TableHead className="w-[220px]">{L("快捷切换", "Quick Override")}</TableHead>
|
||||
<TableHead className="w-[70px] text-right">{L("操作", "Action")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{containers.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={6} className="py-10 text-center text-muted-foreground text-sm">
|
||||
{L(
|
||||
"暂无运行中的沙箱容器或自定义路由规则",
|
||||
"No active sandbox containers or custom egress route overrides",
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
containers.map((c) => {
|
||||
const key = `${c.scope}:${c.owner_id}`;
|
||||
let currentVal = "__custom__";
|
||||
if (c.mode === "inherit") {
|
||||
currentVal = "__inherit__";
|
||||
} else if (c.mode === "direct") {
|
||||
currentVal = "__direct__";
|
||||
} else if (c.proxy_pool_id) {
|
||||
currentVal = `pool:${c.proxy_pool_id}`;
|
||||
}
|
||||
return (
|
||||
<TableRow key={key}>
|
||||
<TableCell className="font-mono text-xs">
|
||||
<Badge variant={c.scope === "task" ? "secondary" : "outline"} className="mr-1.5">
|
||||
{formatScope(c.scope)}
|
||||
</Badge>
|
||||
{c.owner_id}
|
||||
</TableCell>
|
||||
<TableCell className="font-mono text-muted-foreground text-xs">
|
||||
<div>{c.container_name || "—"}</div>
|
||||
{c.ip ? <div className="text-[11px]">{c.ip}</div> : null}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline" className="font-mono text-[11px]">
|
||||
{formatState(c.state)}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="max-w-[260px] truncate font-mono text-xs" title={formatEffectiveProxy(c)}>
|
||||
{formatEffectiveProxy(c)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Select
|
||||
value={currentVal}
|
||||
disabled={busyKey === key}
|
||||
onValueChange={(val) => {
|
||||
if (val !== "__custom__") {
|
||||
void quickUpdateRow(c, val);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="h-8 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="__inherit__">{L("继承全局代理", "Inherit global")}</SelectItem>
|
||||
<SelectItem value="__direct__">{L("强制直连", "Force direct")}</SelectItem>
|
||||
{currentVal === "__custom__" ? (
|
||||
<SelectItem value="__custom__">{L("自定义代理 URL", "Custom proxy URL")}</SelectItem>
|
||||
) : null}
|
||||
{proxyPool.map((p) => (
|
||||
<SelectItem key={p.id} value={`pool:${p.id}`}>
|
||||
{L("节点:", "Node: ")}
|
||||
{p.name || p.url}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
{c.mode !== "inherit" ? (
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="size-7 text-muted-foreground hover:text-destructive"
|
||||
disabled={busyKey === key}
|
||||
title={L("恢复继承全局", "Revert to global")}
|
||||
onClick={() => void deleteRowRoute(c)}
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
</Button>
|
||||
) : null}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -78,8 +78,7 @@ function fmtCreatedAt(iso?: string): string {
|
||||
}
|
||||
|
||||
export default function SandboxPage() {
|
||||
const { i18n } = useLiveTranslation();
|
||||
const isEn = i18n.language.startsWith("en");
|
||||
const { isEn } = useLiveTranslation();
|
||||
const L = (zh: string, en: string) => (isEn ? en : zh);
|
||||
|
||||
const [status, setStatus] = React.useState<SandboxGlobalStatus | null>(null);
|
||||
|
||||
@@ -45,8 +45,7 @@ function ownerHref(c: SandboxContainerInfo): string | null {
|
||||
}
|
||||
|
||||
export function SandboxCard() {
|
||||
const { i18n } = useLiveTranslation();
|
||||
const isEn = i18n.language.startsWith("en");
|
||||
const { isEn } = useLiveTranslation();
|
||||
const L = (zh: string, en: string) => (isEn ? en : zh);
|
||||
|
||||
const [status, setStatus] = React.useState<SandboxGlobalStatus | null>(null);
|
||||
|
||||
@@ -2,9 +2,12 @@
|
||||
|
||||
import * as React from "react";
|
||||
|
||||
import Link from "next/link";
|
||||
|
||||
import {
|
||||
CameraIcon,
|
||||
CpuIcon,
|
||||
ExternalLinkIcon,
|
||||
FlaskConicalIcon,
|
||||
KeyboardIcon,
|
||||
RadioTowerIcon,
|
||||
@@ -27,9 +30,8 @@ import { matchesSettingsQuery } from "@/i18n/settings-search";
|
||||
import { useLiveTranslation } from "@/i18n/use-live-translation";
|
||||
import { api } from "@/lib/api";
|
||||
import { CHAT_SEND_MODE_OPTIONS, type ChatSendMode, setChatSendMode, useChatSendMode } from "@/lib/chat-send-mode";
|
||||
import type { EgressReport, LLMProfile, ProxyPoolEntry, Settings, WorkerPool } from "@/lib/types";
|
||||
import type { LLMProfile, Settings, WorkerPool } from "@/lib/types";
|
||||
|
||||
import { useEgressIp } from "../../_components/egress-ip-banner";
|
||||
import { BackupCard } from "./_components/backup-card";
|
||||
import { BasicAuthCard } from "./_components/basic-auth-card";
|
||||
import { McpServerCard } from "./_components/mcp-server-card";
|
||||
@@ -63,39 +65,8 @@ export default function SystemSettingsPage() {
|
||||
const [savingTavilyKey, setSavingTavilyKey] = React.useState(false);
|
||||
const [proxyInput, setProxyInput] = React.useState("");
|
||||
const [savingProxy, setSavingProxy] = React.useState(false);
|
||||
const [globalProxyInput, setGlobalProxyInput] = React.useState("");
|
||||
const [savingGlobalProxy, setSavingGlobalProxy] = React.useState(false);
|
||||
const [proxyPool, setProxyPool] = React.useState<ProxyPoolEntry[]>([]);
|
||||
const [proxyPoolActiveId, setProxyPoolActiveId] = React.useState("");
|
||||
const [proxyPoolText, setProxyPoolText] = React.useState("");
|
||||
const [proxyPoolTimed, setProxyPoolTimed] = React.useState(false);
|
||||
const [proxyPoolInterval, setProxyPoolInterval] = React.useState("30");
|
||||
const [proxyPoolFailure, setProxyPoolFailure] = React.useState(false);
|
||||
const [proxyPoolStrategy, setProxyPoolStrategy] = React.useState<"sequential" | "random">("sequential");
|
||||
const [proxyPoolThreshold, setProxyPoolThreshold] = React.useState("3");
|
||||
const [proxyPoolCooldown, setProxyPoolCooldown] = React.useState("60");
|
||||
const [proxyPoolHealthInterval, setProxyPoolHealthInterval] = React.useState("30");
|
||||
const [proxyPoolLogs, setProxyPoolLogs] = React.useState<
|
||||
Array<{ at: string; from: string; to: string; reason: string }>
|
||||
>([]);
|
||||
const [proxyReconnectMax, setProxyReconnectMax] = React.useState("5");
|
||||
const [proxyReconnectInterval, setProxyReconnectInterval] = React.useState("30");
|
||||
const [savingEgressVisibility, setSavingEgressVisibility] = React.useState(false);
|
||||
// 出口探测:测一次真实请求,拿到"直连 / 经全局代理"两条出口 IP。
|
||||
const [egressTesting, setEgressTesting] = React.useState(false);
|
||||
const [egressReport, setEgressReport] = React.useState<EgressReport | null>(null);
|
||||
// 请求序号:改了输入/保存/切捕获之后,在途请求回来时序号已经变了,直接丢弃。
|
||||
// 不这么做会出现"结果刚被清空,又被上一次的响应填回来"。
|
||||
const egressSeq = React.useRef(0);
|
||||
// 清空结果并作废在途请求。
|
||||
const clearEgressReport = () => {
|
||||
egressSeq.current += 1;
|
||||
setEgressReport(null);
|
||||
setEgressTesting(false);
|
||||
};
|
||||
// 探测地址:留空用公网回显;隔离网填内网回显服务。
|
||||
const [egressProbeUrl, setEgressProbeUrl] = React.useState("");
|
||||
const [savingEgressProbeUrl, setSavingEgressProbeUrl] = React.useState(false);
|
||||
const [globalProxySummary, setGlobalProxySummary] = React.useState("");
|
||||
const [proxyPoolCount, setProxyPoolCount] = React.useState(0);
|
||||
const [testing, setTesting] = React.useState(false);
|
||||
const [loaded, setLoaded] = React.useState(false);
|
||||
const [settingsLoaded, setSettingsLoaded] = React.useState(false);
|
||||
@@ -113,12 +84,6 @@ export default function SystemSettingsPage() {
|
||||
const [noaCompaction, setNoaCompaction] = React.useState(false);
|
||||
// 纯前端偏好:不走 /api/settings,直接读写 localStorage。
|
||||
const sendMode = useChatSendMode();
|
||||
const {
|
||||
enabled: showEgressIp,
|
||||
isLoading: egressProbeLoading,
|
||||
setEnabled: setShowEgressIp,
|
||||
probeEgress,
|
||||
} = useEgressIp();
|
||||
|
||||
const apply = React.useCallback((s: Settings) => {
|
||||
setCredentialAgent(!!s.credential_agent_enabled);
|
||||
@@ -137,21 +102,8 @@ export default function SystemSettingsPage() {
|
||||
setTavilyKeySet(!!s.tavily_key_set);
|
||||
setDeepSeekKeySet(!!s.deepseek_search_key_set);
|
||||
setProxyInput(s.web_search_proxy ?? "");
|
||||
const savedProxy = s.global_proxy ?? "";
|
||||
setGlobalProxyInput(savedProxy);
|
||||
setProxyPool(s.proxy_pool ?? []);
|
||||
setProxyPoolActiveId(s.proxy_pool_active_id ?? "");
|
||||
setProxyPoolTimed(!!s.proxy_rotate_timed_enabled);
|
||||
setProxyPoolInterval(String(s.proxy_rotate_interval_seconds ?? 30));
|
||||
setProxyPoolFailure(!!s.proxy_rotate_on_failure);
|
||||
setProxyPoolStrategy(s.proxy_rotate_strategy === "random" ? "random" : "sequential");
|
||||
setProxyPoolThreshold(String(s.proxy_health_fail_threshold ?? 3));
|
||||
setProxyPoolCooldown(String(s.proxy_health_cooldown_seconds ?? 60));
|
||||
setProxyPoolHealthInterval(String(s.proxy_health_check_interval_seconds ?? 30));
|
||||
setProxyPoolLogs(s.proxy_pool_switch_log ?? []);
|
||||
setProxyReconnectMax(String(s.proxy_reconnect_max_attempts ?? 5));
|
||||
setProxyReconnectInterval(String(s.proxy_reconnect_interval_seconds ?? 30));
|
||||
setEgressProbeUrl(s.egress_probe_url ?? "");
|
||||
setGlobalProxySummary(s.global_proxy ?? "");
|
||||
setProxyPoolCount((s.proxy_pool ?? []).length);
|
||||
setPyInterp(s.python_interpreter ?? "");
|
||||
setWorkers(String(s.workers ?? 3));
|
||||
setWorkerPools(s.worker_pools ?? []);
|
||||
@@ -242,14 +194,6 @@ export default function SystemSettingsPage() {
|
||||
.then((s) => {
|
||||
apply(s);
|
||||
setSettingsLoaded(true);
|
||||
void api
|
||||
.proxyPool()
|
||||
.then((pool) => {
|
||||
setProxyPool(pool.entries);
|
||||
setProxyPoolActiveId(pool.active_id);
|
||||
setProxyPoolLogs(pool.switch_log);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
})
|
||||
.catch(() => {
|
||||
setSettingsLoaded(false);
|
||||
@@ -272,8 +216,6 @@ export default function SystemSettingsPage() {
|
||||
.setSettings({ traffic_capture: v })
|
||||
.then((s) => {
|
||||
apply(s);
|
||||
// 捕获开关一变,② 的链路就变了,旧结果不能留。
|
||||
clearEgressReport();
|
||||
})
|
||||
.catch(() => setTrafficCapture(!v)) // revert on failure
|
||||
.finally(() => setSaving(false));
|
||||
@@ -484,174 +426,6 @@ export default function SystemSettingsPage() {
|
||||
.finally(() => setSavingProxy(false));
|
||||
};
|
||||
|
||||
const saveGlobalProxy = () => {
|
||||
if (proxyPool.length > 0) {
|
||||
toast.info(t("settings.poolOverridesProxy"));
|
||||
return;
|
||||
}
|
||||
setSavingGlobalProxy(true);
|
||||
api
|
||||
.setSettings({ global_proxy: globalProxyInput.trim() })
|
||||
.then((s) => {
|
||||
apply(s);
|
||||
// 保存后链路变了,旧结果(尤其"尚未保存")立刻失效。
|
||||
clearEgressReport();
|
||||
if (showEgressIp) void probeEgress().catch(() => undefined);
|
||||
toast.success(globalProxyInput.trim() ? t("settings.globalProxySaved") : t("settings.globalProxyCleared"));
|
||||
})
|
||||
.catch((e) => toast.error(t("settings.saveFailedPrefix") + localizedError(e, t)))
|
||||
.finally(() => setSavingGlobalProxy(false));
|
||||
};
|
||||
|
||||
const importProxyPool = () => {
|
||||
api
|
||||
.importProxyPool({ text: proxyPoolText })
|
||||
.then((r) => {
|
||||
setProxyPool(r.entries);
|
||||
setProxyPoolActiveId(r.active_id);
|
||||
setProxyPoolLogs(r.switch_log);
|
||||
setProxyPoolText("");
|
||||
if (r.errors.length)
|
||||
toast.error(
|
||||
r.errors.map((e) => t("settings.importLineError", { line: e.line, message: e.error })).join(";"),
|
||||
);
|
||||
else toast.success(t("settings.proxyPoolImported"));
|
||||
})
|
||||
.catch((e) => toast.error(t("settings.importFailedPrefix") + localizedError(e, t)));
|
||||
};
|
||||
const saveProxyPoolStrategy = () => {
|
||||
const interval = Number(proxyPoolInterval);
|
||||
if (!Number.isFinite(interval) || !Number.isInteger(interval) || interval < 3) {
|
||||
toast.error(t("settings.invalidRotationInterval"));
|
||||
return;
|
||||
}
|
||||
api
|
||||
.setSettings({
|
||||
proxy_rotate_timed_enabled: proxyPoolTimed,
|
||||
proxy_rotate_interval_seconds: Number(proxyPoolInterval),
|
||||
proxy_rotate_on_failure: proxyPoolFailure,
|
||||
proxy_rotate_strategy: proxyPoolStrategy,
|
||||
proxy_health_fail_threshold: Number(proxyPoolThreshold),
|
||||
proxy_health_cooldown_seconds: Number(proxyPoolCooldown),
|
||||
proxy_health_check_interval_seconds: Number(proxyPoolHealthInterval),
|
||||
})
|
||||
.then((s) => {
|
||||
apply(s);
|
||||
toast.success(t("settings.rotationSaved"));
|
||||
})
|
||||
.catch((e) => toast.error(t("settings.saveFailedPrefix") + localizedError(e, t)));
|
||||
};
|
||||
const testAllProxyPool = () =>
|
||||
api
|
||||
.testAllProxyPool()
|
||||
.then((r) => {
|
||||
setProxyPool(r.entries);
|
||||
setProxyPoolActiveId(r.active_id);
|
||||
setProxyPoolLogs(r.switch_log);
|
||||
toast.success(t("settings.allProxiesTested"));
|
||||
})
|
||||
.catch((e) => toast.error(t("settings.probeFailedPrefix") + localizedError(e, t)));
|
||||
const testOneProxyPool = (id: string) =>
|
||||
api
|
||||
.testProxyPoolEntry(id)
|
||||
.then(() => api.proxyPool())
|
||||
.then((r) => {
|
||||
setProxyPool(r.entries);
|
||||
setProxyPoolActiveId(r.active_id);
|
||||
setProxyPoolLogs(r.switch_log);
|
||||
})
|
||||
.catch((e) => toast.error(t("settings.probeFailedPrefix") + localizedError(e, t)));
|
||||
const refreshProxyPool = () =>
|
||||
api.proxyPool().then((r) => {
|
||||
setProxyPool(r.entries);
|
||||
setProxyPoolActiveId(r.active_id);
|
||||
setProxyPoolLogs(r.switch_log);
|
||||
});
|
||||
const toggleProxyPoolEntry = (entry: ProxyPoolEntry) =>
|
||||
api
|
||||
.updateProxyPool(entry.id, { enabled: !entry.enabled })
|
||||
.then(() => refreshProxyPool())
|
||||
.catch((e) => toast.error(t("settings.updateFailedPrefix") + localizedError(e, t)));
|
||||
const deleteProxyPoolEntry = (id: string) =>
|
||||
api
|
||||
.deleteProxyPool(id)
|
||||
.then(() => refreshProxyPool())
|
||||
.catch((e) => toast.error(t("settings.deleteFailedPrefix") + localizedError(e, t)));
|
||||
|
||||
const saveProxyReconnect = () => {
|
||||
api
|
||||
.setSettings({
|
||||
proxy_reconnect_max_attempts: Number(proxyReconnectMax),
|
||||
proxy_reconnect_interval_seconds: Number(proxyReconnectInterval),
|
||||
})
|
||||
.then((s) => {
|
||||
apply(s);
|
||||
toast.success(t("settings.reconnectSaved"));
|
||||
})
|
||||
.catch((e) => toast.error(t("settings.saveFailedPrefix") + localizedError(e, t)));
|
||||
};
|
||||
|
||||
const saveEgressProbeUrl = async () => {
|
||||
setSavingEgressProbeUrl(true);
|
||||
try {
|
||||
const settings = await api.setSettings({ egress_probe_url: egressProbeUrl.trim() });
|
||||
setEgressProbeUrl(settings.egress_probe_url ?? "");
|
||||
clearEgressReport();
|
||||
toast.success(settings.egress_probe_url ? t("settings.probeServiceSaved") : t("settings.probeServiceReset"));
|
||||
if (showEgressIp) void probeEgress().catch(() => undefined);
|
||||
} catch (e) {
|
||||
toast.error(t("settings.probeServiceSaveFailed", { message: localizedError(e, t) }));
|
||||
} finally {
|
||||
setSavingEgressProbeUrl(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 测表单里当前的值,不要求先保存;后端返回直连 / 经代理两条。
|
||||
const testEgress = () => {
|
||||
const seq = ++egressSeq.current;
|
||||
setEgressTesting(true);
|
||||
setEgressReport(null);
|
||||
api
|
||||
.testEgressProxy({
|
||||
global_proxy: globalProxyInput.trim(),
|
||||
resume: true,
|
||||
probe_url: egressProbeUrl.trim(),
|
||||
})
|
||||
.then((rep) => {
|
||||
if (seq !== egressSeq.current) return; // 期间改过配置,这份结果已经过期
|
||||
setEgressReport(rep);
|
||||
if (rep.ok) {
|
||||
// 先取 ②:直连那行永远成功,先命中它会把直连 IP 当成出口报出去。
|
||||
const hit =
|
||||
rep.checks.find((c) => c.key === "global" && !c.skipped && c.result.ok) ??
|
||||
rep.checks.find((c) => !c.skipped && c.result.ok);
|
||||
toast.success(
|
||||
hit?.result.exit_ip ? t("settings.egressResult", { ip: hit.result.exit_ip }) : t("settings.probeSucceeded"),
|
||||
);
|
||||
} else {
|
||||
toast.error(t("settings.egressFailed"));
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
if (seq === egressSeq.current) toast.error(t("settings.probeFailedPrefix") + localizedError(e, t));
|
||||
})
|
||||
.finally(() => {
|
||||
if (seq === egressSeq.current) setEgressTesting(false);
|
||||
});
|
||||
};
|
||||
|
||||
const toggleEgressVisibility = async (nextEnabled: boolean) => {
|
||||
setSavingEgressVisibility(true);
|
||||
try {
|
||||
await setShowEgressIp(nextEnabled);
|
||||
toast.success(nextEnabled ? t("settings.egressShown") : t("settings.egressHidden"));
|
||||
} catch (e) {
|
||||
toast.error(t("settings.egressVisibilityFailed") + localizedError(e, t));
|
||||
} finally {
|
||||
setSavingEgressVisibility(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Run a real "test" search ("test") against the CURRENT form values (backend +
|
||||
// proxy + entered key), falling back to saved values server-side. Toasts result.
|
||||
const runTest = () => {
|
||||
@@ -890,440 +664,27 @@ export default function SystemSettingsPage() {
|
||||
<Card
|
||||
className={`${isSettingVisible("traffic", "settings.keywords.globalProxy") ? "" : "hidden"} mb-4 break-inside-avoid md:mb-6`}
|
||||
>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<RadioTowerIcon className="size-4" />
|
||||
{t("settings.globalProxy")}
|
||||
</CardTitle>
|
||||
<CardDescription>{t("settings.globalProxyHelp")}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-5">
|
||||
<section className="space-y-2">
|
||||
<Label htmlFor="global-proxy" className="text-sm font-normal text-muted-foreground">
|
||||
{t("settings.proxyAddress")}
|
||||
</Label>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Input
|
||||
id="global-proxy"
|
||||
className="min-w-0 flex-1"
|
||||
autoComplete="off"
|
||||
placeholder={t("settings.globalProxyPlaceholder")}
|
||||
value={globalProxyInput}
|
||||
disabled={!loaded || savingGlobalProxy}
|
||||
onChange={(e) => {
|
||||
setGlobalProxyInput(e.target.value);
|
||||
// 旧结果对应的是上一次的地址,留着会让人以为新值已经测过。
|
||||
clearEgressReport();
|
||||
}}
|
||||
/>
|
||||
<Button type="button" onClick={saveGlobalProxy} disabled={!loaded || savingGlobalProxy}>
|
||||
{t("settings.save")}
|
||||
</Button>
|
||||
{/* 测表单里当前的值,不要求先保存。 */}
|
||||
<Button type="button" variant="outline" onClick={testEgress} disabled={!loaded || egressTesting}>
|
||||
{egressTesting ? t("settings.testing") : t("settings.testProxy")}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{globalProxyInput.trim() ? t("settings.proxyConfigured") : t("settings.proxyUnconfigured")}
|
||||
</p>
|
||||
<details className="text-xs">
|
||||
<summary className="text-muted-foreground cursor-pointer select-none">
|
||||
{t("settings.howProxyWorks")}
|
||||
</summary>
|
||||
<p className="text-muted-foreground mt-2 max-w-4xl leading-relaxed">
|
||||
{t("settings.howProxyWorksHelp")}
|
||||
</p>
|
||||
</details>
|
||||
</section>
|
||||
<details className="text-xs">
|
||||
<summary className="text-muted-foreground cursor-pointer select-none">
|
||||
{t("settings.reconnection")}
|
||||
</summary>
|
||||
<div className="mt-3 space-y-3 rounded-md border p-3 sm:p-4">
|
||||
<p className="text-muted-foreground">{t("settings.reconnectionHelp")}</p>
|
||||
<div className="grid grid-cols-1 items-end gap-3 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto]">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="proxy-reconnect-max">{t("settings.reconnectAttempts")}</Label>
|
||||
<Input
|
||||
id="proxy-reconnect-max"
|
||||
type="number"
|
||||
min={1}
|
||||
value={proxyReconnectMax}
|
||||
onChange={(e) => setProxyReconnectMax(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="proxy-reconnect-interval">{t("settings.reconnectInterval")}</Label>
|
||||
<Input
|
||||
id="proxy-reconnect-interval"
|
||||
type="number"
|
||||
min={1}
|
||||
value={proxyReconnectInterval}
|
||||
onChange={(e) => setProxyReconnectInterval(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<Button type="button" variant="outline" className="w-full sm:w-auto" onClick={saveProxyReconnect}>
|
||||
{t("settings.savePolicy")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
<div className="flex items-center justify-between gap-4 rounded-md border px-3 py-2">
|
||||
<div className="min-w-0">
|
||||
<Label htmlFor="show-egress-ip" className="text-sm font-normal">
|
||||
{t("settings.showEgress")}
|
||||
</Label>
|
||||
<p className="text-muted-foreground text-xs">{t("settings.showEgressHelp")}</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="show-egress-ip"
|
||||
checked={showEgressIp}
|
||||
disabled={!settingsLoaded || savingEgressVisibility || egressProbeLoading}
|
||||
onCheckedChange={(checked) => void toggleEgressVisibility(checked)}
|
||||
/>
|
||||
<CardHeader className="flex flex-row flex-wrap items-center justify-between gap-3">
|
||||
<div className="space-y-1">
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<RadioTowerIcon className="size-4" />
|
||||
{t("settings.globalProxy")}
|
||||
</CardTitle>
|
||||
<CardDescription>{t("settings.proxyMovedDesc")}</CardDescription>
|
||||
</div>
|
||||
{/* 紧贴结果区:用户看两行时正好需要它。细节放文档。 */}
|
||||
<details className="text-xs">
|
||||
<summary className="text-muted-foreground cursor-pointer select-none">
|
||||
{t("settings.egressTestDetails")}
|
||||
</summary>
|
||||
<p className="text-muted-foreground mt-2 leading-relaxed">{t("settings.egressTestHelp")}</p>
|
||||
</details>
|
||||
{/* 内网里公网回显不可达,两行都会失败——不是代理坏了。 */}
|
||||
<details className="text-xs">
|
||||
<summary className="text-muted-foreground cursor-pointer select-none">
|
||||
{t("settings.customProbe")}
|
||||
</summary>
|
||||
<div className="mt-2 flex flex-col gap-2">
|
||||
<Label htmlFor="egress-probe-url">{t("settings.probeUrl")}</Label>
|
||||
<div className="flex flex-col gap-2 sm:flex-row">
|
||||
<Input
|
||||
id="egress-probe-url"
|
||||
autoComplete="off"
|
||||
placeholder={t("settings.probePlaceholder")}
|
||||
value={egressProbeUrl}
|
||||
disabled={!settingsLoaded || savingEgressProbeUrl}
|
||||
onChange={(e) => {
|
||||
setEgressProbeUrl(e.target.value);
|
||||
clearEgressReport();
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={!settingsLoaded || savingEgressProbeUrl}
|
||||
onClick={() => void saveEgressProbeUrl()}
|
||||
>
|
||||
{savingEgressProbeUrl ? t("settings.saving") : t("settings.saveProbe")}
|
||||
</Button>
|
||||
</div>
|
||||
<span className="text-muted-foreground leading-relaxed">{t("settings.probePersistenceHelp")}</span>
|
||||
<span className="text-muted-foreground leading-relaxed">
|
||||
{t("settings.probeResponseStart")}
|
||||
<code>{'{"ip":"1.2.3.4"}'}</code>
|
||||
{t("settings.probeResponseEnd")}
|
||||
</span>
|
||||
</div>
|
||||
</details>
|
||||
{egressReport && (
|
||||
<div className="flex flex-col gap-1 text-xs">
|
||||
{egressReport.checks.map((c) => {
|
||||
// 经 MITM 时 via 是 HTTP(MITM 自己是代理),标出来会让人以为填错了。
|
||||
const viaCapture = !!c.path && c.path !== egressReport.configured;
|
||||
return (
|
||||
<div key={c.key} className="flex flex-wrap items-center gap-x-2">
|
||||
<span
|
||||
className={
|
||||
c.skipped
|
||||
? "text-muted-foreground"
|
||||
: c.result.ok
|
||||
? "text-emerald-600"
|
||||
: "text-destructive"
|
||||
}
|
||||
>
|
||||
{c.skipped ? "—" : c.result.ok ? "✓" : "✗"}
|
||||
</span>
|
||||
|
||||
<span
|
||||
className="w-56 shrink-0"
|
||||
title={
|
||||
c.key === "direct"
|
||||
? t("settings.directProbeHint")
|
||||
: viaCapture
|
||||
? t("settings.captureProbeHint", { path: c.path })
|
||||
: t("settings.proxyProbeHint")
|
||||
}
|
||||
>
|
||||
{t(`settings.egressCheck.${c.key}`, { defaultValue: c.label })}
|
||||
</span>
|
||||
{c.skipped ? (
|
||||
<span className="text-muted-foreground">
|
||||
{c.skip_code
|
||||
? t(`settings.egressSkip.${c.skip_code}`, { defaultValue: c.skip_reason })
|
||||
: c.skip_reason}
|
||||
</span>
|
||||
) : c.result.ok ? (
|
||||
<span className="font-mono">
|
||||
<span title={t("settings.outboundIpHint")}>{c.result.exit_ip}</span> ·{" "}
|
||||
<span title={t("settings.latencyHint")}>{c.result.latency_ms}ms</span>
|
||||
{c.result.via && c.result.via !== "direct" && !viaCapture && (
|
||||
<span className="text-muted-foreground">
|
||||
{" "}
|
||||
{t("settings.viaPrefix")}
|
||||
{c.result.via.toUpperCase()}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
) : (
|
||||
// 只显示第一个地址的原因:refused=代理没开,timeout=出不了网。
|
||||
<span className="text-destructive">
|
||||
{c.result.probes?.find((p) => p.error)?.error ?? c.result.error}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{(
|
||||
egressReport.warning_details ??
|
||||
egressReport.warnings?.map((message) => ({ code: "", message, params: {} }))
|
||||
)?.map((notice) => (
|
||||
<p key={notice.code || notice.message} className="text-amber-700">
|
||||
⚠{" "}
|
||||
{notice.code
|
||||
? t(`settings.egressWarning.${notice.code}`, {
|
||||
...notice.params,
|
||||
defaultValue: notice.message,
|
||||
})
|
||||
: notice.message}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<section className="space-y-3 border-t pt-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<div>
|
||||
<p className="text-sm font-medium">
|
||||
{t("settings.proxyPool")}{" "}
|
||||
<span className="text-muted-foreground font-normal">{proxyPool.length}</span>
|
||||
</p>
|
||||
<p className="text-muted-foreground mt-1 text-xs">
|
||||
{t("settings.currentProxyPrefix")}
|
||||
{proxyPool.find((entry) => entry.id === proxyPoolActiveId)?.name ??
|
||||
(proxyPoolActiveId ? t("settings.selectedProxy") : t("settings.direct"))}
|
||||
</p>
|
||||
</div>
|
||||
<Button type="button" variant="outline" size="sm" onClick={testAllProxyPool}>
|
||||
{t("settings.testAll")}
|
||||
</Button>
|
||||
</div>
|
||||
<details className="rounded-md border px-3 py-2 text-xs">
|
||||
<summary className="text-muted-foreground cursor-pointer select-none">
|
||||
{t("settings.importProxies")}
|
||||
</summary>
|
||||
<Textarea
|
||||
className="mt-3 font-mono"
|
||||
rows={3}
|
||||
placeholder={t("settings.importPlaceholder")}
|
||||
value={proxyPoolText}
|
||||
onChange={(e) => setProxyPoolText(e.target.value)}
|
||||
/>
|
||||
<div className="mt-2 flex flex-wrap items-center gap-2">
|
||||
<Button type="button" size="sm" onClick={importProxyPool} disabled={!proxyPoolText.trim()}>
|
||||
{t("settings.import")}
|
||||
</Button>
|
||||
<span className="text-muted-foreground">{t("settings.proxyCredentialsHidden")}</span>
|
||||
</div>
|
||||
</details>
|
||||
<div className="space-y-2">
|
||||
{proxyPool.length === 0 ? (
|
||||
<p className="text-muted-foreground text-xs">{t("settings.emptyProxyPool")}</p>
|
||||
) : (
|
||||
proxyPool.map((entry) => (
|
||||
<div
|
||||
key={entry.id}
|
||||
className="grid gap-3 rounded-md border p-3 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-center"
|
||||
>
|
||||
<div className="flex min-w-0 items-start gap-3">
|
||||
<Switch
|
||||
checked={entry.enabled}
|
||||
onCheckedChange={() => toggleProxyPoolEntry(entry)}
|
||||
aria-label={t("settings.enableProxy")}
|
||||
/>
|
||||
<div className="grid min-w-0 flex-1 gap-x-5 gap-y-2 text-xs sm:grid-cols-2">
|
||||
<div className="min-w-0">
|
||||
<p className="text-muted-foreground">{t("settings.proxyAddress")}</p>
|
||||
<p className="truncate font-mono" title={entry.url}>
|
||||
{entry.name ? `${entry.name} · ` : ""}
|
||||
{entry.url}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-muted-foreground">{t("settings.testOutboundIp")}</p>
|
||||
<p className="break-all font-mono">
|
||||
{entry.egress_ip ||
|
||||
(entry.last_error ? t("settings.probeFailed") : t("settings.notTested"))}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<span
|
||||
className={
|
||||
entry.health === "healthy"
|
||||
? "text-emerald-600"
|
||||
: entry.health === "disabled"
|
||||
? "text-muted-foreground"
|
||||
: "text-amber-600"
|
||||
}
|
||||
>
|
||||
{!entry.enabled
|
||||
? t("settings.disabled")
|
||||
: entry.health === "healthy"
|
||||
? t("settings.healthy")
|
||||
: entry.health === "unhealthy-cooling"
|
||||
? t("settings.coolingDown")
|
||||
: t("settings.pendingCheck")}
|
||||
</span>
|
||||
{entry.id === proxyPoolActiveId && (
|
||||
<span className="text-primary">{t("settings.activeProxy")}</span>
|
||||
)}
|
||||
<span className="text-muted-foreground">
|
||||
{t("settings.failureCount", { count: entry.consecutive_failures })}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-muted-foreground">
|
||||
{entry.latency_ms != null ? `${entry.latency_ms} ms` : t("settings.noLatency")}
|
||||
{entry.last_checked_at &&
|
||||
!entry.last_checked_at.startsWith("0001-") &&
|
||||
` · ${new Date(entry.last_checked_at).toLocaleTimeString(i18n.resolvedLanguage)}`}
|
||||
{entry.last_error && <span className="text-destructive"> · {entry.last_error}</span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end gap-1">
|
||||
<Button type="button" variant="ghost" size="sm" onClick={() => testOneProxyPool(entry.id)}>
|
||||
{t("settings.test")}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => deleteProxyPoolEntry(entry.id)}
|
||||
>
|
||||
{t("settings.delete")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
<details className="rounded-md border px-3 py-2 text-xs">
|
||||
<summary className="text-muted-foreground cursor-pointer select-none">
|
||||
{t("settings.rotationHealth")}
|
||||
</summary>
|
||||
<div className="mt-3 space-y-3">
|
||||
<p className="text-muted-foreground">{t("settings.rotationHealthHelp")}</p>
|
||||
<div className="flex flex-wrap items-center gap-x-8 gap-y-3 border-b pb-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<Label htmlFor="proxy-pool-timed">{t("settings.timedRotation")}</Label>
|
||||
<Switch id="proxy-pool-timed" checked={proxyPoolTimed} onCheckedChange={setProxyPoolTimed} />
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<Label htmlFor="proxy-pool-failure">{t("settings.failureRotation")}</Label>
|
||||
<Switch
|
||||
id="proxy-pool-failure"
|
||||
checked={proxyPoolFailure}
|
||||
onCheckedChange={setProxyPoolFailure}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid max-w-2xl grid-cols-1 gap-x-5 gap-y-4 sm:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="proxy-pool-strategy">{t("settings.rotationOrder")}</Label>
|
||||
<Select
|
||||
value={proxyPoolStrategy}
|
||||
onValueChange={(v) => setProxyPoolStrategy(v as "sequential" | "random")}
|
||||
>
|
||||
<SelectTrigger id="proxy-pool-strategy" className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="sequential">{t("settings.sequential")}</SelectItem>
|
||||
<SelectItem value="random">{t("settings.random")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="proxy-pool-interval">{t("settings.rotationInterval")}</Label>
|
||||
<Input
|
||||
id="proxy-pool-interval"
|
||||
type="number"
|
||||
min={3}
|
||||
value={proxyPoolInterval}
|
||||
onChange={(e) => setProxyPoolInterval(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="proxy-pool-threshold">{t("settings.failureThreshold")}</Label>
|
||||
<Input
|
||||
id="proxy-pool-threshold"
|
||||
type="number"
|
||||
min={1}
|
||||
value={proxyPoolThreshold}
|
||||
onChange={(e) => setProxyPoolThreshold(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="proxy-pool-cooldown">{t("settings.cooldown")}</Label>
|
||||
<Input
|
||||
id="proxy-pool-cooldown"
|
||||
type="number"
|
||||
min={1}
|
||||
value={proxyPoolCooldown}
|
||||
onChange={(e) => setProxyPoolCooldown(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="proxy-pool-health-interval">{t("settings.healthInterval")}</Label>
|
||||
<Input
|
||||
id="proxy-pool-health-interval"
|
||||
type="number"
|
||||
min={1}
|
||||
value={proxyPoolHealthInterval}
|
||||
onChange={(e) => setProxyPoolHealthInterval(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end border-t pt-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="w-full sm:w-auto"
|
||||
onClick={saveProxyPoolStrategy}
|
||||
>
|
||||
{t("settings.saveRotation")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
{proxyPoolLogs.length > 0 && (
|
||||
<details className="text-xs">
|
||||
<summary className="text-muted-foreground cursor-pointer select-none">
|
||||
{t("settings.switchHistory", { count: proxyPoolLogs.length })}
|
||||
</summary>
|
||||
<div className="mt-2 space-y-1">
|
||||
{proxyPoolLogs
|
||||
.slice(-5)
|
||||
.reverse()
|
||||
.map((log) => (
|
||||
<p key={`${log.at}-${log.to}`} className="text-muted-foreground">
|
||||
{new Date(log.at).toLocaleTimeString(i18n.resolvedLanguage)} ·{" "}
|
||||
{log.from || t("settings.direct")} → {log.to || t("settings.direct")} · {log.reason}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
</section>
|
||||
<Button type="button" variant="outline" size="sm" asChild>
|
||||
<Link href="/system/proxy" className="gap-1.5">
|
||||
{t("settings.openProxyPage")}
|
||||
<ExternalLinkIcon className="size-3.5" />
|
||||
</Link>
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent className="text-muted-foreground text-xs">
|
||||
{proxyPoolCount > 0
|
||||
? `${t("settings.proxyPool")} (${proxyPoolCount})`
|
||||
: globalProxySummary.trim()
|
||||
? t("settings.proxyConfigured")
|
||||
: t("settings.proxyUnconfigured")}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
|
||||
@@ -0,0 +1,618 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
|
||||
import {
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
GlobeIcon,
|
||||
Loader2Icon,
|
||||
NetworkIcon,
|
||||
RefreshCwIcon,
|
||||
SearchIcon,
|
||||
ShieldBanIcon,
|
||||
Trash2Icon,
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { useLiveTranslation } from "@/i18n/use-live-translation";
|
||||
import { api } from "@/lib/api";
|
||||
import type { TrafficDNSQuery, TrafficNetFlow } from "@/lib/types";
|
||||
|
||||
function fmtUnix(ts: number, locale?: string) {
|
||||
if (!ts) return "—";
|
||||
return new Date(ts * 1000).toLocaleString(locale, {
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
second: "2-digit",
|
||||
});
|
||||
}
|
||||
|
||||
function fmtBytes(n: number) {
|
||||
if (!n || 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 FlowSourceBadge({
|
||||
scope,
|
||||
ownerId,
|
||||
containerId,
|
||||
srcIp,
|
||||
isEn,
|
||||
}: {
|
||||
scope?: string;
|
||||
ownerId?: string;
|
||||
containerId?: string;
|
||||
srcIp?: string;
|
||||
isEn: boolean;
|
||||
}) {
|
||||
if (!scope && !ownerId && !containerId && !srcIp) {
|
||||
return <span className="text-muted-foreground text-xs">—</span>;
|
||||
}
|
||||
let label = isEn ? "Host" : "主进程";
|
||||
if (srcIp) label = srcIp;
|
||||
let variant: "default" | "secondary" | "outline" = "outline";
|
||||
if (scope === "task" && ownerId) {
|
||||
label = isEn ? `Task #${ownerId}` : `任务 #${ownerId}`;
|
||||
variant = "secondary";
|
||||
} else if (scope === "session" && ownerId) {
|
||||
label = isEn ? `Chat ${ownerId.slice(0, 8)}` : `对话 ${ownerId.slice(0, 8)}`;
|
||||
variant = "outline";
|
||||
}
|
||||
const details: string[] = [];
|
||||
if (srcIp) details.push(`IP: ${srcIp}`);
|
||||
if (containerId) details.push(`${isEn ? "Container" : "容器"}: ${containerId.slice(0, 12)}`);
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Badge variant={variant} className="max-w-[8.5rem] truncate font-mono text-[11px]">
|
||||
{label}
|
||||
</Badge>
|
||||
</TooltipTrigger>
|
||||
{details.length > 0 ? (
|
||||
<TooltipContent side="top" className="font-mono text-xs">
|
||||
{details.map((line) => (
|
||||
<div key={line}>{line}</div>
|
||||
))}
|
||||
</TooltipContent>
|
||||
) : null}
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
export function NonHTTPTrafficPanel({ mode, taskId }: { mode: "flows" | "dns"; taskId?: string }) {
|
||||
const { isEn, locale } = useLiveTranslation();
|
||||
const L = (zh: string, en: string) => (isEn ? en : zh);
|
||||
const formatUpstream = (raw?: string) => (!raw || raw === "direct" ? L("直连", "Direct") : raw);
|
||||
|
||||
const [page, setPage] = React.useState(0);
|
||||
const [size] = React.useState(50);
|
||||
const [query, setQuery] = React.useState("");
|
||||
const [queryDebounced, setQueryDebounced] = React.useState("");
|
||||
const [protoFilter, setProtoFilter] = React.useState("all");
|
||||
const [actionFilter, setActionFilter] = React.useState("all");
|
||||
const [qtypeFilter, setQtypeFilter] = React.useState("ALL");
|
||||
const [loading, setLoading] = React.useState(false);
|
||||
|
||||
const [flows, setFlows] = React.useState<TrafficNetFlow[]>([]);
|
||||
const [dnsRows, setDnsRows] = React.useState<TrafficDNSQuery[]>([]);
|
||||
const [total, setTotal] = React.useState(0);
|
||||
|
||||
const [selectedFlow, setSelectedFlow] = React.useState<TrafficNetFlow | null>(null);
|
||||
const [detailLoading, setDetailLoading] = React.useState(false);
|
||||
|
||||
React.useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
setQueryDebounced(query.trim());
|
||||
setPage(0);
|
||||
}, 250);
|
||||
return () => clearTimeout(timer);
|
||||
}, [query]);
|
||||
|
||||
React.useEffect(() => {
|
||||
void mode;
|
||||
void protoFilter;
|
||||
void actionFilter;
|
||||
void qtypeFilter;
|
||||
void taskId;
|
||||
setPage(0);
|
||||
}, [mode, protoFilter, actionFilter, qtypeFilter, taskId]);
|
||||
|
||||
const load = React.useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
if (mode === "flows") {
|
||||
const res = await api.trafficFlows({
|
||||
protocol: protoFilter,
|
||||
action: actionFilter,
|
||||
task_id: taskId,
|
||||
q: queryDebounced || undefined,
|
||||
page,
|
||||
size,
|
||||
});
|
||||
setFlows(res.flows ?? []);
|
||||
setTotal(res.total ?? 0);
|
||||
} else {
|
||||
const res = await api.trafficDNS({
|
||||
qtype: qtypeFilter,
|
||||
action: actionFilter,
|
||||
task_id: taskId,
|
||||
q: queryDebounced || undefined,
|
||||
page,
|
||||
size,
|
||||
});
|
||||
setDnsRows(res.queries ?? []);
|
||||
setTotal(res.total ?? 0);
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [mode, protoFilter, actionFilter, qtypeFilter, taskId, queryDebounced, page, size]);
|
||||
|
||||
React.useEffect(() => {
|
||||
void load();
|
||||
const interval = setInterval(() => {
|
||||
void load();
|
||||
}, 5000);
|
||||
return () => clearInterval(interval);
|
||||
}, [load]);
|
||||
|
||||
const openFlowDetail = async (row: TrafficNetFlow) => {
|
||||
setSelectedFlow(row);
|
||||
setDetailLoading(true);
|
||||
try {
|
||||
const full = await api.trafficFlowDetail(row.id);
|
||||
setSelectedFlow(full);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setDetailLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClear = async () => {
|
||||
try {
|
||||
if (mode === "flows") {
|
||||
const res = await api.deleteTrafficFlows(taskId);
|
||||
toast.success(L(`已清空 ${res.deleted} 条 TCP/UDP 流记录`, `Cleared ${res.deleted} TCP/UDP flow records`));
|
||||
} else {
|
||||
const res = await api.deleteTrafficDNS(taskId);
|
||||
toast.success(L(`已清空 ${res.deleted} 条 DNS 查询记录`, `Cleared ${res.deleted} DNS query records`));
|
||||
}
|
||||
setPage(0);
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
};
|
||||
|
||||
const pageCount = Math.max(1, Math.ceil(total / size));
|
||||
|
||||
const actionBadge = (action: string) => {
|
||||
switch (action) {
|
||||
case "block":
|
||||
return (
|
||||
<Badge variant="destructive" className="gap-1 font-mono text-[11px]">
|
||||
<ShieldBanIcon className="size-3" />
|
||||
{L("拦截", "BLOCK")}
|
||||
</Badge>
|
||||
);
|
||||
case "error":
|
||||
return (
|
||||
<Badge variant="outline" className="border-amber-500/40 font-mono text-[11px] text-amber-600">
|
||||
{L("错误", "ERROR")}
|
||||
</Badge>
|
||||
);
|
||||
case "passthrough":
|
||||
return (
|
||||
<Badge variant="secondary" className="font-mono text-[11px]">
|
||||
{L("透传", "PASS")}
|
||||
</Badge>
|
||||
);
|
||||
default:
|
||||
return (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="border-emerald-500/30 bg-emerald-500/10 font-mono text-[11px] text-emerald-600 dark:text-emerald-400"
|
||||
>
|
||||
{L("放行", "ALLOW")}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-3">
|
||||
{/* Filter toolbar */}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div className="relative min-w-[200px] max-w-sm flex-1">
|
||||
<SearchIcon className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder={
|
||||
mode === "flows"
|
||||
? L("搜索目标主机 / IP / 端口 / SNI / 来源 IP…", "Filter by host, IP, port, SNI, src IP…")
|
||||
: L("搜索查询域名 / 解析结果 IP / 来源 IP…", "Filter by domain, answer IP, src IP…")
|
||||
}
|
||||
className="h-8 pl-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{mode === "flows" ? (
|
||||
<Select value={protoFilter} onValueChange={setProtoFilter}>
|
||||
<SelectTrigger className="h-8 w-[120px] text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">{L("全部协议", "All protos")}</SelectItem>
|
||||
<SelectItem value="tcp">TCP</SelectItem>
|
||||
<SelectItem value="tls">TLS</SelectItem>
|
||||
<SelectItem value="udp">UDP</SelectItem>
|
||||
<SelectItem value="icmp">ICMP</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
) : (
|
||||
<Select value={qtypeFilter} onValueChange={setQtypeFilter}>
|
||||
<SelectTrigger className="h-8 w-[120px] text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="ALL">{L("全部类型", "All types")}</SelectItem>
|
||||
<SelectItem value="A">A</SelectItem>
|
||||
<SelectItem value="AAAA">AAAA</SelectItem>
|
||||
<SelectItem value="CNAME">CNAME</SelectItem>
|
||||
<SelectItem value="TXT">TXT</SelectItem>
|
||||
<SelectItem value="MX">MX</SelectItem>
|
||||
<SelectItem value="NS">NS</SelectItem>
|
||||
<SelectItem value="PTR">PTR</SelectItem>
|
||||
<SelectItem value="SRV">SRV</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
|
||||
<Select value={actionFilter} onValueChange={setActionFilter}>
|
||||
<SelectTrigger className="h-8 w-[120px] text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">{L("全部动作", "All actions")}</SelectItem>
|
||||
<SelectItem value="allow">{L("放行", "Allow")}</SelectItem>
|
||||
<SelectItem value="block">{L("拦截", "Blocked")}</SelectItem>
|
||||
{mode === "flows" ? <SelectItem value="passthrough">{L("透传", "Passthrough")}</SelectItem> : null}
|
||||
<SelectItem value="error">{L("错误", "Error")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<span className="text-muted-foreground text-xs tabular-nums">{L(`共 ${total} 条`, `${total} records`)}</span>
|
||||
<Button size="sm" variant="outline" className="h-8" onClick={() => void load()} disabled={loading}>
|
||||
<RefreshCwIcon className={`mr-1.5 size-3.5 ${loading ? "animate-spin" : ""}`} />
|
||||
{L("刷新", "Refresh")}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-8 text-destructive hover:text-destructive"
|
||||
disabled={total === 0}
|
||||
onClick={() => void handleClear()}
|
||||
>
|
||||
<Trash2Icon className="mr-1.5 size-3.5" />
|
||||
{L("清空", "Clear")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Table */}
|
||||
<Card className="min-h-0 flex-1 overflow-auto p-0">
|
||||
{mode === "flows" ? (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-[130px]">{L("时间", "Time")}</TableHead>
|
||||
<TableHead className="w-[70px]">{L("协议", "Proto")}</TableHead>
|
||||
<TableHead className="w-[84px]">{L("动作", "Action")}</TableHead>
|
||||
<TableHead className="w-[120px]">{L("来源", "Source")}</TableHead>
|
||||
<TableHead>{L("目标地址", "Destination")}</TableHead>
|
||||
<TableHead className="w-[130px]">{L("上下行流量", "TX / RX")}</TableHead>
|
||||
<TableHead className="w-[90px]">{L("耗时", "Duration")}</TableHead>
|
||||
<TableHead className="w-[160px]">{L("出口路径 / 原因", "Egress / Reason")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{flows.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={8} className="py-12 text-center text-muted-foreground text-sm">
|
||||
<div className="flex flex-col items-center gap-1.5">
|
||||
<NetworkIcon className="size-6 opacity-40" />
|
||||
<span>
|
||||
{L(
|
||||
"暂无 TCP/UDP 非 HTTP 流量(透明网关启用后将自动捕获 nmap / nc / 数据库 / SSH / 自定义 Socket)",
|
||||
"No TCP/UDP flows recorded yet (captured automatically when the transparent gateway is active)",
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
flows.map((f) => (
|
||||
<TableRow
|
||||
key={f.id}
|
||||
className="cursor-pointer hover:bg-muted/50"
|
||||
onClick={() => void openFlowDetail(f)}
|
||||
>
|
||||
<TableCell className="whitespace-nowrap font-mono text-muted-foreground text-xs">
|
||||
{fmtUnix(f.ts, locale)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline" className="font-mono text-[11px] uppercase">
|
||||
{f.protocol}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{actionBadge(f.action)}</TableCell>
|
||||
<TableCell>
|
||||
<FlowSourceBadge
|
||||
scope={f.sandbox_scope}
|
||||
ownerId={f.sandbox_owner_id}
|
||||
containerId={f.container_id}
|
||||
srcIp={f.src_ip}
|
||||
isEn={isEn}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="max-w-[300px] truncate font-mono text-xs">
|
||||
<div className="truncate font-medium">
|
||||
{f.dst_host && f.dst_host !== f.dst_ip
|
||||
? `${f.dst_host}:${f.dst_port}`
|
||||
: `${f.dst_ip}:${f.dst_port}`}
|
||||
</div>
|
||||
{f.dst_host && f.dst_host !== f.dst_ip ? (
|
||||
<div className="truncate text-[11px] text-muted-foreground">{f.dst_ip}</div>
|
||||
) : null}
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap font-mono text-xs tabular-nums">
|
||||
↑ {fmtBytes(f.bytes_tx)} / ↓ {fmtBytes(f.bytes_rx)}
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap font-mono text-muted-foreground text-xs tabular-nums">
|
||||
{f.duration_ms} ms
|
||||
</TableCell>
|
||||
<TableCell
|
||||
className="max-w-[200px] truncate font-mono text-muted-foreground text-xs"
|
||||
title={f.block_reason || f.error || formatUpstream(f.upstream_proxy)}
|
||||
>
|
||||
{f.block_reason || f.error || formatUpstream(f.upstream_proxy)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-[130px]">{L("时间", "Time")}</TableHead>
|
||||
<TableHead className="w-[70px]">{L("类型", "Type")}</TableHead>
|
||||
<TableHead className="w-[84px]">{L("动作", "Action")}</TableHead>
|
||||
<TableHead className="w-[120px]">{L("来源", "Source")}</TableHead>
|
||||
<TableHead>{L("查询域名", "Domain")}</TableHead>
|
||||
<TableHead className="w-[96px]">RCODE</TableHead>
|
||||
<TableHead>{L("解析结果 / 拦截原因", "Answers / Reason")}</TableHead>
|
||||
<TableHead className="w-[80px]">{L("耗时", "Time")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{dnsRows.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={8} className="py-12 text-center text-muted-foreground text-sm">
|
||||
<div className="flex flex-col items-center gap-1.5">
|
||||
<GlobeIcon className="size-6 opacity-40" />
|
||||
<span>
|
||||
{L(
|
||||
"暂无 DNS 查询记录(透明网关接管 UDP/TCP 53 后自动记录容器全部域名解析)",
|
||||
"No DNS queries recorded yet (captured automatically when the transparent gateway intercepts port 53)",
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
dnsRows.map((q) => (
|
||||
<TableRow key={q.id}>
|
||||
<TableCell className="whitespace-nowrap font-mono text-muted-foreground text-xs">
|
||||
{fmtUnix(q.ts, locale)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline" className="font-mono text-[11px]">
|
||||
{q.qtype}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{actionBadge(q.action)}</TableCell>
|
||||
<TableCell>
|
||||
<FlowSourceBadge
|
||||
scope={q.sandbox_scope}
|
||||
ownerId={q.sandbox_owner_id}
|
||||
containerId={q.container_id}
|
||||
srcIp={q.src_ip}
|
||||
isEn={isEn}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="max-w-[260px] truncate font-medium font-mono text-xs" title={q.qname}>
|
||||
{q.qname}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge
|
||||
variant={q.rcode === "NOERROR" ? "secondary" : "outline"}
|
||||
className="font-mono text-[11px]"
|
||||
>
|
||||
{q.rcode || "—"}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell
|
||||
className="max-w-[320px] truncate font-mono text-muted-foreground text-xs"
|
||||
title={q.block_reason || q.error || q.answers.join(", ")}
|
||||
>
|
||||
{q.block_reason || q.error || (q.answers.length > 0 ? q.answers.join(", ") : "—")}
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap font-mono text-muted-foreground text-xs tabular-nums">
|
||||
{q.duration_ms} ms
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* Pagination */}
|
||||
<div className="flex items-center justify-between text-muted-foreground text-xs">
|
||||
<span>{L(`第 ${page + 1} / ${pageCount} 页`, `Page ${page + 1} / ${pageCount}`)}</span>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 px-2"
|
||||
disabled={page <= 0}
|
||||
onClick={() => setPage((p) => Math.max(0, p - 1))}
|
||||
>
|
||||
<ChevronLeftIcon className="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 px-2"
|
||||
disabled={page + 1 >= pageCount}
|
||||
onClick={() => setPage((p) => p + 1)}
|
||||
>
|
||||
<ChevronRightIcon className="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Flow Detail Sheet */}
|
||||
<Sheet open={Boolean(selectedFlow)} onOpenChange={(o) => !o && setSelectedFlow(null)}>
|
||||
<SheetContent className="w-full overflow-y-auto sm:max-w-2xl">
|
||||
{selectedFlow ? (
|
||||
<>
|
||||
<SheetHeader>
|
||||
<SheetTitle className="flex items-center gap-2 font-mono text-sm">
|
||||
<Badge variant="outline" className="uppercase">
|
||||
{selectedFlow.protocol}
|
||||
</Badge>
|
||||
<span>
|
||||
{selectedFlow.dst_host || selectedFlow.dst_ip}:{selectedFlow.dst_port}
|
||||
</span>
|
||||
{actionBadge(selectedFlow.action)}
|
||||
</SheetTitle>
|
||||
<SheetDescription className="font-mono text-xs">
|
||||
{selectedFlow.src_ip || "?"}:{selectedFlow.src_port || 0} → {selectedFlow.dst_ip}:
|
||||
{selectedFlow.dst_port}
|
||||
{selectedFlow.sni ? ` (SNI: ${selectedFlow.sni})` : ""}
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
<div className="mt-4 space-y-4 px-4 pb-6 text-xs">
|
||||
<div className="grid grid-cols-2 gap-2 rounded-lg border bg-muted/30 p-3 font-mono">
|
||||
<div>
|
||||
<span className="text-muted-foreground">{L("ID:", "ID: ")}</span>
|
||||
{selectedFlow.id}
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">{L("耗时:", "Duration: ")}</span>
|
||||
{selectedFlow.duration_ms} ms
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">{L("发送:", "TX: ")}</span>
|
||||
{fmtBytes(selectedFlow.bytes_tx)}
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">{L("接收:", "RX: ")}</span>
|
||||
{fmtBytes(selectedFlow.bytes_rx)}
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<span className="text-muted-foreground">{L("出口代理:", "Upstream: ")}</span>
|
||||
{formatUpstream(selectedFlow.upstream_proxy)}
|
||||
</div>
|
||||
{selectedFlow.block_reason ? (
|
||||
<div className="col-span-2 text-destructive">
|
||||
<span>{L("拦截原因:", "Block reason: ")}</span>
|
||||
{selectedFlow.block_reason}
|
||||
</div>
|
||||
) : null}
|
||||
{selectedFlow.error ? (
|
||||
<div className="col-span-2 text-amber-600">
|
||||
<span>{L("错误:", "Error: ")}</span>
|
||||
{selectedFlow.error}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{detailLoading ? (
|
||||
<div className="flex items-center justify-center py-8 text-muted-foreground">
|
||||
<Loader2Icon className="mr-2 size-4 animate-spin" />
|
||||
{L("加载载荷预览…", "Loading payload preview…")}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-1.5">
|
||||
<div className="font-medium">
|
||||
{L("上行载荷预览 (TX, 最多 4KB)", "Outbound Payload Preview (TX, up to 4KB)")}
|
||||
</div>
|
||||
<pre className="max-h-60 overflow-auto whitespace-pre-wrap break-all rounded-md border bg-muted/40 p-3 font-mono text-[11px]">
|
||||
{selectedFlow.tx_preview_text || L("(空)", "(empty)")}
|
||||
</pre>
|
||||
{selectedFlow.tx_binary && selectedFlow.tx_preview_hex ? (
|
||||
<details className="rounded-md border p-2">
|
||||
<summary className="cursor-pointer text-muted-foreground">
|
||||
{L("Hex 转储 (TX)", "Hex Dump (TX)")}
|
||||
</summary>
|
||||
<pre className="mt-2 max-h-40 overflow-auto break-all font-mono text-[11px]">
|
||||
{selectedFlow.tx_preview_hex}
|
||||
</pre>
|
||||
</details>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<div className="font-medium">
|
||||
{L("下行载荷预览 (RX, 最多 4KB)", "Inbound Payload Preview (RX, up to 4KB)")}
|
||||
</div>
|
||||
<pre className="max-h-60 overflow-auto whitespace-pre-wrap break-all rounded-md border bg-muted/40 p-3 font-mono text-[11px]">
|
||||
{selectedFlow.rx_preview_text || L("(空)", "(empty)")}
|
||||
</pre>
|
||||
{selectedFlow.rx_binary && selectedFlow.rx_preview_hex ? (
|
||||
<details className="rounded-md border p-2">
|
||||
<summary className="cursor-pointer text-muted-foreground">
|
||||
{L("Hex 转储 (RX)", "Hex Dump (RX)")}
|
||||
</summary>
|
||||
<pre className="mt-2 max-h-40 overflow-auto break-all font-mono text-[11px]">
|
||||
{selectedFlow.rx_preview_hex}
|
||||
</pre>
|
||||
</details>
|
||||
) : null}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -63,6 +63,7 @@ export const messages = {
|
||||
"nav.asset-intercept": ["资产拦截", "Asset interception"],
|
||||
"nav.approvals": ["审批记录", "Approval history"],
|
||||
"nav.sandbox": ["沙箱容器", "Sandbox"],
|
||||
"nav.proxy": ["代理与出口", "Proxy & Egress"],
|
||||
"nav.logs": ["日志", "Logs"],
|
||||
"nav.settings": ["系统配置", "Settings"],
|
||||
"search.placeholder": ["搜索页面与功能…", "Search pages and features…"],
|
||||
@@ -251,6 +252,15 @@ export const messages = {
|
||||
"No findings eligible for AI auto-merge (at least 2 findings per task required)",
|
||||
],
|
||||
"findingsAutoMerge.failed": ["启动 AI 自动合并失败:{{message}}", "Failed to start AI auto-merge: {{message}}"],
|
||||
"traffic.source": ["来源归属", "Source"],
|
||||
"traffic.scopeAll": ["全部来源", "All sources"],
|
||||
"traffic.scopeTask": ["任务容器", "Task"],
|
||||
"traffic.scopeSession": ["对话容器", "Chat"],
|
||||
"traffic.ownerPlaceholder": ["归属 ID(任务/对话)…", "Owner ID (task/chat)…"],
|
||||
"traffic.containerPlaceholder": ["容器 ID 前缀…", "Container ID…"],
|
||||
"traffic.sourceTask": ["任务 #{{id}}", "Task #{{id}}"],
|
||||
"traffic.sourceSession": ["对话 {{id}}", "Chat {{id}}"],
|
||||
"traffic.sourceHost": ["宿主机", "Host"],
|
||||
} satisfies Record<string, readonly [string, string]>;
|
||||
|
||||
const statuses: Record<string, readonly (readonly [string, string, string])[]> = {
|
||||
|
||||
@@ -367,3 +367,41 @@ test("Repeater renders persisted drafts with translated default group and preser
|
||||
assert.equal(useRepeaterStore.getState().workspace.tabs[0].rawRequest, "GET / HTTP/1.1\nHost: example.test\n\n");
|
||||
useRepeaterStore.setState({ workspace: null });
|
||||
});
|
||||
|
||||
test("ContainerRoutesTab localizes effective egress without mixed Chinese/English", async () => {
|
||||
const { ContainerRoutesTab } = load(base + "/src/app/(main)/system/proxy/_components/container-routes-tab.tsx");
|
||||
const routesState = {
|
||||
global_proxy: "direct",
|
||||
routes: [],
|
||||
containers: [
|
||||
{
|
||||
scope: "session",
|
||||
owner_id: "conv-6",
|
||||
container_name: "artex-sbx-session-conv-6",
|
||||
state: "running",
|
||||
ip: "172.30.0.3",
|
||||
mode: "inherit",
|
||||
effective_proxy: "direct",
|
||||
},
|
||||
{
|
||||
scope: "task",
|
||||
owner_id: "42",
|
||||
container_name: "artex-sbx-task-42",
|
||||
state: "inactive",
|
||||
mode: "inherit",
|
||||
effective_proxy: "direct (全局)",
|
||||
},
|
||||
],
|
||||
gateway: { connected: true, embedded: false, udp_policy: "block_on_proxy", dns_upstream: "" },
|
||||
};
|
||||
await i18n.changeLanguage("en");
|
||||
const enHtml = visible(render(ContainerRoutesTab, { proxyPool: [], routesState, onRefresh: async () => undefined }));
|
||||
assert.doesNotMatch(enHtml, /[\p{Script=Han}]/u, enHtml);
|
||||
assert.match(enHtml, /Effective Egress/);
|
||||
assert.match(enHtml, /Direct \(Global\)/);
|
||||
|
||||
await i18n.changeLanguage("zh-CN");
|
||||
const zhHtml = visible(render(ContainerRoutesTab, { proxyPool: [], routesState, onRefresh: async () => undefined }));
|
||||
assert.match(zhHtml, /当前生效出口/);
|
||||
assert.match(zhHtml, /直连 \(全局\)/);
|
||||
});
|
||||
@@ -168,6 +168,11 @@ export const settingsMessages = {
|
||||
"沙箱 容器 隔离 docker 镜像 内存 cpu 进程 生命周期 停机 清理",
|
||||
"sandbox container isolation docker image memory cpu pids lifecycle stop prune",
|
||||
],
|
||||
"settings.proxyMovedDesc": [
|
||||
"全局出口代理、代理池轮换、出口黑名单与拦截审计已迁移至独立的「代理与出口」管理页。",
|
||||
"Global egress proxy, proxy pool rotation, egress blacklist and block audit have moved to the dedicated Proxy & Egress page.",
|
||||
],
|
||||
"settings.openProxyPage": ["前往代理与出口", "Open Proxy & Egress"],
|
||||
"settings.trafficCapture": ["流量捕获", "Traffic capture"],
|
||||
"settings.trafficCaptureHelp": [
|
||||
"开启后,所有 Agent 的 HTTP 流量经记录代理全量落库,并向 Agent 注入 traffic_search / traffic_get 工具与代理配置(提示词含代理说明)。",
|
||||
|
||||
@@ -2,13 +2,11 @@
|
||||
|
||||
import { enUS } from "date-fns/locale/en-US";
|
||||
import { zhCN } from "date-fns/locale/zh-CN";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { resolveLocale } from "./config";
|
||||
import { useLiveTranslation } from "./use-live-translation";
|
||||
|
||||
export function useDateLocale() {
|
||||
const { i18n } = useTranslation();
|
||||
const locale = resolveLocale(i18n.resolvedLanguage);
|
||||
const { locale } = useLiveTranslation();
|
||||
return {
|
||||
locale,
|
||||
dateLocale: locale === "en" ? enUS : zhCN,
|
||||
|
||||
@@ -9,7 +9,10 @@ import { useTranslation } from "react-i18next";
|
||||
// language change; it reads the current language when each callback runs.
|
||||
export function useLiveTranslation() {
|
||||
const translation = useTranslation();
|
||||
const { i18n } = translation;
|
||||
const { t, i18n } = translation;
|
||||
const liveT = useMemo(() => i18n.t.bind(i18n), [i18n]);
|
||||
return { ...translation, liveT };
|
||||
// Read reactive `t` so React Compiler invalidates memo caches on language switches.
|
||||
const isEn = t.length >= 0 && /^en(?:-|$)/i.test(i18n.resolvedLanguage ?? i18n.language ?? "");
|
||||
const locale = isEn ? "en" : "zh-CN";
|
||||
return { ...translation, liveT, locale, isEn };
|
||||
}
|
||||
+105
-5
@@ -24,6 +24,7 @@ import type {
|
||||
Company,
|
||||
CompanyScopeMutation,
|
||||
CompanyScopeRule,
|
||||
ContainerProxyRoute,
|
||||
Conversation,
|
||||
ConvTokenSummary,
|
||||
CoverageAssetRefs,
|
||||
@@ -33,6 +34,8 @@ import type {
|
||||
DeleteTaskOptions,
|
||||
DeleteTaskResult,
|
||||
Edge,
|
||||
EgressBlacklistRule,
|
||||
EgressBlacklistState,
|
||||
EgressReport,
|
||||
EvidenceBodyPreview,
|
||||
ExplorationNodePage,
|
||||
@@ -80,9 +83,13 @@ import type {
|
||||
PromptVar,
|
||||
PromptVersion,
|
||||
ProxyPoolEntry,
|
||||
ProxyRoutesState,
|
||||
ProxySwitchLog,
|
||||
RepeaterSendRequest,
|
||||
RepeaterSendResponse,
|
||||
SandboxContainerInfo,
|
||||
SandboxGlobalStatus,
|
||||
SandboxRuntimeOverrides,
|
||||
SessionTokenUsage,
|
||||
Settings,
|
||||
Severity,
|
||||
@@ -112,15 +119,15 @@ import type {
|
||||
Tool,
|
||||
ToolStat,
|
||||
TrafficDetail,
|
||||
TrafficDNSResp,
|
||||
TrafficEvidenceRef,
|
||||
TrafficEvidenceRole,
|
||||
TrafficHost,
|
||||
TrafficNetFlow,
|
||||
TrafficNetFlowsResp,
|
||||
TrafficResp,
|
||||
UpdateCheck,
|
||||
UpdateSettings,
|
||||
SandboxContainerInfo,
|
||||
SandboxGlobalStatus,
|
||||
SandboxRuntimeOverrides,
|
||||
UsageStats,
|
||||
WorkspaceFile,
|
||||
WorkspaceListing,
|
||||
@@ -1163,6 +1170,9 @@ export const api = {
|
||||
q = "",
|
||||
opts: {
|
||||
taskId?: string;
|
||||
scope?: string;
|
||||
ownerId?: string;
|
||||
containerId?: string;
|
||||
body?: string;
|
||||
path?: string;
|
||||
status?: string;
|
||||
@@ -1175,6 +1185,9 @@ export const api = {
|
||||
get<TrafficResp>(
|
||||
`/traffic?page=${page}&size=${size}` +
|
||||
(opts.taskId ? `&task_id=${encodeURIComponent(opts.taskId)}` : "") +
|
||||
(opts.scope && opts.scope !== "all" ? `&scope=${encodeURIComponent(opts.scope)}` : "") +
|
||||
(opts.ownerId ? `&owner_id=${encodeURIComponent(opts.ownerId)}` : "") +
|
||||
(opts.containerId ? `&container_id=${encodeURIComponent(opts.containerId)}` : "") +
|
||||
(host ? `&host=${encodeURIComponent(host)}` : "") +
|
||||
(method && method !== "all" ? `&method=${encodeURIComponent(method)}` : "") +
|
||||
(q ? `&q=${encodeURIComponent(q)}` : "") +
|
||||
@@ -1818,8 +1831,7 @@ export const api = {
|
||||
rollbackUpdate: () => post<{ ok: boolean }>(`/update/rollback`),
|
||||
|
||||
// ---- Sandbox container isolation ----
|
||||
sandboxStatus: (withStats = false) =>
|
||||
get<SandboxGlobalStatus>(`/sandbox/status${withStats ? "?stats=1" : ""}`),
|
||||
sandboxStatus: (withStats = false) => get<SandboxGlobalStatus>(`/sandbox/status${withStats ? "?stats=1" : ""}`),
|
||||
updateSandboxSettings: (ov: SandboxRuntimeOverrides) => put<SandboxGlobalStatus>("/sandbox/settings", ov),
|
||||
pruneSandboxContainers: () => post<{ removed: number }>("/sandbox/prune"),
|
||||
sandboxContainer: (scope: string, ownerID: string, withStats = true) =>
|
||||
@@ -1849,4 +1861,92 @@ export const api = {
|
||||
post<SandboxContainerInfo>(`/tasks/${encodeURIComponent(taskID)}/sandbox/stop`, { pause_task: pauseTask }),
|
||||
recreateTaskSandbox: (taskID: string, opts?: { pause_task?: boolean; clear_workspace?: boolean }) =>
|
||||
post<SandboxContainerInfo>(`/tasks/${encodeURIComponent(taskID)}/sandbox/recreate`, opts ?? {}),
|
||||
|
||||
// ---- Proxy Egress Blacklist (#218) ----
|
||||
egressBlacklist: () => get<EgressBlacklistState>("/proxy/blacklist"),
|
||||
updateEgressBlacklistSettings: (syncAssetIntercept: boolean) =>
|
||||
put<EgressBlacklistState>("/proxy/blacklist/settings", { sync_asset_intercept: syncAssetIntercept }),
|
||||
createEgressBlacklistRule: (rule: {
|
||||
enabled?: boolean;
|
||||
kind: string;
|
||||
pattern: string;
|
||||
port?: number;
|
||||
note?: string;
|
||||
}) => post<EgressBlacklistRule>("/proxy/blacklist/rules", rule),
|
||||
updateEgressBlacklistRule: (
|
||||
id: string,
|
||||
patch: { enabled?: boolean; kind?: string; pattern?: string; port?: number; note?: string },
|
||||
) => put<EgressBlacklistRule>(`/proxy/blacklist/rules/${encodeURIComponent(id)}`, patch),
|
||||
deleteEgressBlacklistRule: (id: string) =>
|
||||
del<{ deleted: string }>(`/proxy/blacklist/rules/${encodeURIComponent(id)}`),
|
||||
clearEgressBlockEvents: () => del<{ cleared: boolean }>("/proxy/blacklist/events"),
|
||||
|
||||
// ---- Non-HTTP Traffic (TCP/UDP Flows & DNS Queries, #218 Phase 3/4) ----
|
||||
trafficFlows: (params?: {
|
||||
protocol?: string;
|
||||
action?: string;
|
||||
task_id?: string;
|
||||
scope?: string;
|
||||
owner_id?: string;
|
||||
container_id?: string;
|
||||
q?: string;
|
||||
page?: number;
|
||||
size?: number;
|
||||
}) => {
|
||||
const qs = new URLSearchParams();
|
||||
if (params?.protocol && params.protocol !== "all") qs.set("protocol", params.protocol);
|
||||
if (params?.action && params.action !== "all") qs.set("action", params.action);
|
||||
if (params?.task_id) qs.set("task_id", params.task_id);
|
||||
if (params?.scope) qs.set("scope", params.scope);
|
||||
if (params?.owner_id) qs.set("owner_id", params.owner_id);
|
||||
if (params?.container_id) qs.set("container_id", params.container_id);
|
||||
if (params?.q) qs.set("q", params.q);
|
||||
if (params?.page !== undefined) qs.set("page", String(params.page));
|
||||
if (params?.size !== undefined) qs.set("size", String(params.size));
|
||||
const suffix = qs.toString() ? `?${qs.toString()}` : "";
|
||||
return get<TrafficNetFlowsResp>(`/traffic/flows${suffix}`);
|
||||
},
|
||||
trafficFlowDetail: (id: string) => get<TrafficNetFlow>(`/traffic/flows/${encodeURIComponent(id)}`),
|
||||
deleteTrafficFlows: (taskId?: string) =>
|
||||
del<{ deleted: number }>(`/traffic/flows${taskId ? `?task_id=${encodeURIComponent(taskId)}` : ""}`),
|
||||
trafficDNS: (params?: {
|
||||
qtype?: string;
|
||||
rcode?: string;
|
||||
action?: string;
|
||||
task_id?: string;
|
||||
scope?: string;
|
||||
owner_id?: string;
|
||||
container_id?: string;
|
||||
q?: string;
|
||||
page?: number;
|
||||
size?: number;
|
||||
}) => {
|
||||
const qs = new URLSearchParams();
|
||||
if (params?.qtype && params.qtype !== "ALL") qs.set("qtype", params.qtype);
|
||||
if (params?.rcode && params.rcode !== "ALL") qs.set("rcode", params.rcode);
|
||||
if (params?.action && params.action !== "all") qs.set("action", params.action);
|
||||
if (params?.task_id) qs.set("task_id", params.task_id);
|
||||
if (params?.scope) qs.set("scope", params.scope);
|
||||
if (params?.owner_id) qs.set("owner_id", params.owner_id);
|
||||
if (params?.container_id) qs.set("container_id", params.container_id);
|
||||
if (params?.q) qs.set("q", params.q);
|
||||
if (params?.page !== undefined) qs.set("page", String(params.page));
|
||||
if (params?.size !== undefined) qs.set("size", String(params.size));
|
||||
const suffix = qs.toString() ? `?${qs.toString()}` : "";
|
||||
return get<TrafficDNSResp>(`/traffic/dns${suffix}`);
|
||||
},
|
||||
deleteTrafficDNS: (taskId?: string) =>
|
||||
del<{ deleted: number }>(`/traffic/dns${taskId ? `?task_id=${encodeURIComponent(taskId)}` : ""}`),
|
||||
|
||||
// ---- Per-Container Proxy Routes & Transparent Gateway (#218 Phase 3/4) ----
|
||||
proxyRoutes: () => get<ProxyRoutesState>("/proxy/routes"),
|
||||
putProxyRoute: (
|
||||
scope: string,
|
||||
ownerId: string,
|
||||
body: { mode: string; proxy_pool_id?: string; proxy_url?: string; note?: string },
|
||||
) => put<ContainerProxyRoute>(`/proxy/routes/${encodeURIComponent(scope)}/${encodeURIComponent(ownerId)}`, body),
|
||||
deleteProxyRoute: (scope: string, ownerId: string) =>
|
||||
del<{ deleted: string }>(`/proxy/routes/${encodeURIComponent(scope)}/${encodeURIComponent(ownerId)}`),
|
||||
updateGatewaySettings: (body: { udp_policy: string; dns_upstream: string }) =>
|
||||
put<{ udp_policy: string; dns_upstream: string }>("/proxy/gateway/settings", body),
|
||||
};
|
||||
@@ -961,6 +961,12 @@ export interface TrafficExchange {
|
||||
status: number;
|
||||
content_type: string;
|
||||
resp_len: number;
|
||||
sandbox_scope?: string;
|
||||
sandbox_owner_id?: string;
|
||||
container_id?: string;
|
||||
session_id?: string;
|
||||
intent_id?: number;
|
||||
src_ip?: string;
|
||||
}
|
||||
|
||||
export interface TrafficResp {
|
||||
@@ -2057,3 +2063,144 @@ export interface SandboxRuntimeOverrides {
|
||||
auto_stop_on_complete?: boolean;
|
||||
session_idle_minutes?: number;
|
||||
}
|
||||
|
||||
// ---- Proxy Egress Blacklist (#218) ----
|
||||
export interface EgressBlacklistRule {
|
||||
id: string;
|
||||
enabled: boolean;
|
||||
kind: "domain" | "suffix" | "ip" | "cidr" | string;
|
||||
pattern: string;
|
||||
port?: number;
|
||||
note?: string;
|
||||
source?: "custom" | "asset_intercept" | string;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
export interface EgressBlockEvent {
|
||||
at: string;
|
||||
host: string;
|
||||
port?: string;
|
||||
method?: string;
|
||||
url?: string;
|
||||
src_ip?: string;
|
||||
scope?: string;
|
||||
owner_id?: string;
|
||||
reason: string;
|
||||
rule_kind?: string;
|
||||
rule_id?: string;
|
||||
pattern?: string;
|
||||
source?: "ssrf_guard" | "custom" | "asset_intercept" | string;
|
||||
}
|
||||
|
||||
export interface EgressBlacklistState {
|
||||
rules: EgressBlacklistRule[];
|
||||
synced_rules: EgressBlacklistRule[];
|
||||
sync_asset_intercept: boolean;
|
||||
events: EgressBlockEvent[];
|
||||
}
|
||||
|
||||
// ---- Non-HTTP Traffic (TCP/UDP/TLS Flows & DNS Queries, #218 Phase 3/4) ----
|
||||
export interface TrafficNetFlow {
|
||||
id: string;
|
||||
ts: number;
|
||||
ended_at?: number;
|
||||
duration_ms: number;
|
||||
protocol: "tcp" | "tls" | "udp" | string;
|
||||
dst_ip: string;
|
||||
dst_port: number;
|
||||
dst_host?: string;
|
||||
sni?: string;
|
||||
action: "allow" | "block" | "error" | "passthrough" | string;
|
||||
block_reason?: string;
|
||||
upstream_proxy?: string;
|
||||
bytes_tx: number;
|
||||
bytes_rx: number;
|
||||
tx_preview_text?: string;
|
||||
tx_preview_hex?: string;
|
||||
tx_binary?: boolean;
|
||||
rx_preview_text?: string;
|
||||
rx_preview_hex?: string;
|
||||
rx_binary?: boolean;
|
||||
sandbox_scope?: string;
|
||||
sandbox_owner_id?: string;
|
||||
container_id?: string;
|
||||
session_id?: string;
|
||||
intent_id?: number;
|
||||
src_ip?: string;
|
||||
src_port?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface TrafficNetFlowsResp {
|
||||
enabled: boolean;
|
||||
count: number;
|
||||
total: number;
|
||||
page: number;
|
||||
size: number;
|
||||
flows: TrafficNetFlow[];
|
||||
}
|
||||
|
||||
export interface TrafficDNSQuery {
|
||||
id: string;
|
||||
ts: number;
|
||||
duration_ms: number;
|
||||
qname: string;
|
||||
qtype: string;
|
||||
rcode: string;
|
||||
answers: string[];
|
||||
action: "allow" | "block" | "error" | string;
|
||||
block_reason?: string;
|
||||
upstream?: string;
|
||||
sandbox_scope?: string;
|
||||
sandbox_owner_id?: string;
|
||||
container_id?: string;
|
||||
session_id?: string;
|
||||
intent_id?: number;
|
||||
src_ip?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface TrafficDNSResp {
|
||||
enabled: boolean;
|
||||
count: number;
|
||||
total: number;
|
||||
page: number;
|
||||
size: number;
|
||||
queries: TrafficDNSQuery[];
|
||||
}
|
||||
|
||||
// ---- Per-Container Proxy Routes & Transparent Gateway (#218 Phase 3/4) ----
|
||||
export interface ContainerProxyRoute {
|
||||
scope: "task" | "session" | string;
|
||||
owner_id: string;
|
||||
mode: "inherit" | "direct" | "proxy" | string;
|
||||
proxy_pool_id?: string;
|
||||
proxy_url?: string;
|
||||
note?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
export interface ContainerRouteStatusItem extends ContainerProxyRoute {
|
||||
container_name?: string;
|
||||
container_id?: string;
|
||||
state?: string;
|
||||
ip?: string;
|
||||
effective_proxy: string;
|
||||
}
|
||||
|
||||
export interface TransparentGatewayStatus {
|
||||
connected: boolean;
|
||||
embedded: boolean;
|
||||
gateway_id?: string;
|
||||
last_seen?: string;
|
||||
udp_policy: "block_on_proxy" | "block" | "direct" | string;
|
||||
dns_upstream?: string;
|
||||
}
|
||||
|
||||
export interface ProxyRoutesState {
|
||||
global_proxy: string;
|
||||
routes: ContainerProxyRoute[];
|
||||
containers: ContainerRouteStatusItem[];
|
||||
gateway: TransparentGatewayStatus;
|
||||
}
|
||||
@@ -97,6 +97,7 @@ export const sidebarItems: NavGroup[] = [
|
||||
{ id: "asset-intercept", title: "资产拦截", url: "/system/intercept/assets", icon: Ban },
|
||||
{ id: "approvals", title: "审批记录", url: "/system/intercept/approvals", icon: ClipboardList },
|
||||
{ id: "sandbox", title: "沙箱容器", url: "/system/sandbox", icon: Box },
|
||||
{ id: "proxy", title: "代理与出口", url: "/system/proxy", icon: Radio },
|
||||
{ id: "logs", title: "日志", url: "/system/logs", icon: ScrollText },
|
||||
{ id: "settings", title: "系统配置", url: "/system/settings", icon: Settings2 },
|
||||
],
|
||||
|
||||
Reference in new issue
Block a user