ARTEX - AI autonomous penetration testing system (English translation; upstream: Autumn-27/ARTEX, AGPL-3.0)
Go aiai-agentsautonomous-agentsbug-bountydockergolanglinuxllmmcpnextjspenetration-testingpentestpostgresqlreareactred-teamsecuritysecurity-automationsqlitetypescript
feat(web): add Traffic > Hooks admin panel, versions/rollback, and dry-run UI (P4.2 PR2)
BaaRaie712c05ccd29
diff --git a/web/package.json b/web/package.jsonindex e37dc60..70e9c00 100644--- a/web/package.json+++ b/web/package.json@@ -15,6 +15,7 @@"generate:presets": "ts-node -P tsconfig.scripts.json src/scripts/generate-theme-presets.ts","test:polling": "node --test scripts/polling.test.mjs","test:replay": "node --test scripts/replay.test.mjs",+ "test:tamper-hooks": "node --test scripts/tamper-hooks.test.mjs","test:upload": "node --test scripts/upload.test.mjs","test:i18n": "node scripts/check-i18n.mjs && node --test scripts/i18n.test.mjs","test:bash": "node --test src/lib/bash-exit-status.test.mjs"diff --git a/web/scripts/tamper-hooks.test.mjs b/web/scripts/tamper-hooks.test.mjsnew file mode 100644index 0000000..31ef131--- /dev/null+++ b/web/scripts/tamper-hooks.test.mjs@@ -0,0 +1,106 @@+import ts from "typescript";++import assert from "node:assert/strict";+import fs from "node:fs";+import path from "node:path";+import { test } from "node:test";+import { fileURLToPath } from "node:url";+import vm from "node:vm";++const web = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");++function loadTsModule(relPath, deps = {}) {+ const output = ts.transpileModule(fs.readFileSync(path.join(web, relPath), "utf8"), {+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },+ }).outputText;+ const exports = {};+ const require = (id) => {+ if (deps[id]) return deps[id];+ throw new Error(`Unexpected require(${id})`);+ };+ vm.runInNewContext(output, { exports, require, atob, TextDecoder });+ return exports;+}++const replay = loadTsModule("src/lib/replay.ts");+const hooks = loadTsModule("src/lib/tamper-hooks.ts", { "./replay": replay });+const plain = (v) => JSON.parse(JSON.stringify(v));++test("parseRawResponse parses status, multi-value headers, and body", () => {+ const r = hooks.parseRawResponse(+ 'HTTP/1.1 201 Created\r\nContent-Type: application/json\r\nSet-Cookie: a=1\r\nSet-Cookie: b=2\r\n\r\n{"id":42}',+ );+ assert.equal(r.status, 201);+ assert.deepEqual(plain(r.headers), {+ "Content-Type": ["application/json"],+ "Set-Cookie": ["a=1", "b=2"],+ });+ assert.equal(r.body, '{"id":42}');+ assert.equal(r.binary, false);+ assert.equal(r.bodyPreviewOnly, false);+});++test("exchangeDetailToDryRunIO derives URL from Host header and strips Host from headers map", () => {+ const conv = hooks.exchangeDetailToDryRunIO({+ req: 'POST /api/v1/test?x=1 HTTP/1.1\r\nHost: api.example.test\r\nX-Token: secret\r\n\r\n{"a":1}',+ resp: 'HTTP/1.1 200 OK\r\nX-Resp: ok\r\n\r\n{"b":2}',+ });+ assert.equal(conv.io.request.method, "POST");+ assert.equal(conv.io.request.url, "https://api.example.test/api/v1/test?x=1");+ assert.deepEqual(plain(conv.io.request.headers), { "X-Token": ["secret"] });+ assert.equal(conv.io.request.body, '{"a":1}');+ assert.equal(conv.io.response.status, 200);+ assert.deepEqual(plain(conv.io.response.headers), { "X-Resp": ["ok"] });+ assert.equal(conv.io.response.body, '{"b":2}');+});++test("parseHeaderMatcherLines handles presence-only and regex header matchers", () => {+ const m = hooks.parseHeaderMatcherLines("X-Api-Key\nContent-Type: ^application/json\n");+ assert.deepEqual(plain(m), [{ name: "X-Api-Key" }, { name: "Content-Type", value_regex: "^application/json" }]);+ assert.equal(hooks.formatHeaderMatcherLines(m), "X-Api-Key\nContent-Type: ^application/json");+});++test("buildMatchers omits response-only matchers for request phase", () => {+ const m = hooks.buildMatchers({+ phase: "request",+ methods: "post, get",+ host: "*.example.test",+ urlRegex: "^/api",+ headers: "X-Auth",+ bodyRegex: "role",+ status: "200, 4xx",+ respHeaders: "X-Resp",+ respBodyRegex: "secret",+ });+ assert.deepEqual(plain(m), {+ methods: ["POST", "GET"],+ host: "*.example.test",+ url_regex: "^/api",+ headers: [{ name: "X-Auth" }],+ body_regex: "role",+ });+});++test("decodeTraceAfter decodes base64 UTF-8 and isTraceLineMasked flags HMAC-masked fields", () => {+ assert.equal(hooks.decodeTraceAfter(Buffer.from("hello-hook", "utf8").toString("base64")), "hello-hook");+ assert.equal(hooks.decodeTraceAfter(null), null);++ assert.equal(+ hooks.isTraceLineMasked({+ Outcome: "applied",+ After: null,+ BeforeHash: "0123456789abcdef0123456789abcdef",+ AfterHash: "fedcba9876543210fedcba9876543210",+ }),+ true,+ );+ assert.equal(+ hooks.isTraceLineMasked({+ Outcome: "applied",+ After: Buffer.from("ok", "utf8").toString("base64"),+ BeforeHash: "a".repeat(64),+ AfterHash: "b".repeat(64),+ }),+ false,+ );+});diff --git a/web/src/app/(main)/function/traffic/_components/tamper-hooks-panel.tsx b/web/src/app/(main)/function/traffic/_components/tamper-hooks-panel.tsxnew file mode 100644index 0000000..1034d58--- /dev/null+++ b/web/src/app/(main)/function/traffic/_components/tamper-hooks-panel.tsx@@ -0,0 +1,1243 @@+"use client";++import * as React from "react";++import {+ AlertTriangleIcon,+ Code2Icon,+ HistoryIcon,+ Loader2Icon,+ PencilIcon,+ PlayIcon,+ PlusIcon,+ RefreshCwIcon,+ RotateCcwIcon,+ ShieldAlertIcon,+ ShieldCheckIcon,+ Trash2Icon,+} from "lucide-react";+import { toast } from "sonner";++import { Alert, AlertDescription } from "@/components/ui/alert";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { Card } from "@/components/ui/card";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";+import { Switch } from "@/components/ui/switch";+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";+import { Textarea } from "@/components/ui/textarea";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { intlLocale, t } from "@/i18n";+import { api } from "@/lib/api";+import {+ buildMatchers,+ DEFAULT_REQUEST_HOOK_SOURCE,+ DEFAULT_RESPONSE_HOOK_SOURCE,+ decodeTraceAfter,+ exchangeDetailToDryRunIO,+ formatHeaderLines,+ formatHeaderMatcherLines,+ isTraceLineMasked,+ parseHeaderLines,+} from "@/lib/tamper-hooks";+import type {+ TamperDryRunRequest,+ TamperDryRunResult,+ TamperHook,+ TamperHookPhase,+ TamperHookVersion,+ TrafficExchange,+} from "@/lib/types";++function fmtDateTime(ts: string) {+ if (!ts) return "";+ return new Date(ts).toLocaleString(intlLocale, {+ month: "2-digit",+ day: "2-digit",+ hour: "2-digit",+ minute: "2-digit",+ second: "2-digit",+ });+}++interface EditorState {+ mode: "create" | "edit";+ id?: number;+ enabled: boolean;+ name: string;+ phase: TamperHookPhase;+ priority: string;+ note: string;+ methods: string;+ host: string;+ urlRegex: string;+ headers: string;+ bodyRegex: string;+ status: string;+ respHeaders: string;+ respBodyRegex: string;+ source: string;+}++function emptyEditor(phase: TamperHookPhase = "request"): EditorState {+ return {+ mode: "create",+ enabled: false,+ name: "",+ phase,+ priority: "100",+ note: "",+ methods: "",+ host: "",+ urlRegex: "",+ headers: "",+ bodyRegex: "",+ status: "",+ respHeaders: "",+ respBodyRegex: "",+ source: phase === "response" ? DEFAULT_RESPONSE_HOOK_SOURCE : DEFAULT_REQUEST_HOOK_SOURCE,+ };+}++function editorFromHook(h: TamperHook): EditorState {+ return {+ mode: "edit",+ id: h.id,+ enabled: h.enabled,+ name: h.name,+ phase: h.phase,+ priority: String(h.priority),+ note: h.note ?? "",+ methods: (h.matchers?.methods ?? []).join(", "),+ host: h.matchers?.host ?? "",+ urlRegex: h.matchers?.url_regex ?? "",+ headers: formatHeaderMatcherLines(h.matchers?.headers),+ bodyRegex: h.matchers?.body_regex ?? "",+ status: (h.matchers?.status ?? []).join(", "),+ respHeaders: formatHeaderMatcherLines(h.matchers?.resp_headers),+ respBodyRegex: h.matchers?.resp_body_regex ?? "",+ source: h.source,+ };+}++interface DryRunTarget {+ label: string;+ hookId?: number;+ inline?: {+ name: string;+ phase: TamperHookPhase;+ matchers: ReturnType<typeof buildMatchers>;+ source: string;+ };+}++export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: TrafficExchange[] }) {+ const [hooks, setHooks] = React.useState<TamperHook[]>([]);+ const [enabledByEnv, setEnabledByEnv] = React.useState<boolean>(true);+ const [loading, setLoading] = React.useState(true);+ const [loadError, setLoadError] = React.useState<string | null>(null);+ const [togglingId, setTogglingId] = React.useState<number | null>(null);++ // Create / Edit dialog state+ const [editor, setEditor] = React.useState<EditorState | null>(null);+ const [saving, setSaving] = React.useState(false);+ const [formError, setFormError] = React.useState<string | null>(null);++ // Delete confirmation+ const [deleteTarget, setDeleteTarget] = React.useState<TamperHook | null>(null);+ const [deleting, setDeleting] = React.useState(false);++ // Versions sheet+ const [versionsHook, setVersionsHook] = React.useState<TamperHook | null>(null);+ const [versions, setVersions] = React.useState<TamperHookVersion[]>([]);+ const [versionsLoading, setVersionsLoading] = React.useState(false);+ const [expandedVersion, setExpandedVersion] = React.useState<number | null>(null);+ const [rollbackTarget, setRollbackTarget] = React.useState<TamperHookVersion | null>(null);+ const [rollingBack, setRollingBack] = React.useState(false);++ // Dry-run sheet+ const [dryRunTarget, setDryRunTarget] = React.useState<DryRunTarget | null>(null);+ const [dryRunInputMode, setDryRunInputMode] = React.useState<"synthetic" | "exchange">("synthetic");+ const [dryRunExchangeId, setDryRunExchangeId] = React.useState("");+ const [dryRunLoadingExchange, setDryRunLoadingExchange] = React.useState(false);+ const [dryRunExchangeWarning, setDryRunExchangeWarning] = React.useState<string | null>(null);+ const [dryRunMethod, setDryRunMethod] = React.useState("GET");+ const [dryRunUrl, setDryRunUrl] = React.useState("https://example.test/api/v1/items");+ const [dryRunReqHeaders, setDryRunReqHeaders] = React.useState("Accept: application/json");+ const [dryRunReqBody, setDryRunReqBody] = React.useState("");+ const [dryRunStatus, setDryRunStatus] = React.useState("200");+ const [dryRunRespHeaders, setDryRunRespHeaders] = React.useState("Content-Type: application/json");+ const [dryRunRespBody, setDryRunRespBody] = React.useState('{"ok":true}');+ const [dryRunRunning, setDryRunRunning] = React.useState(false);+ const [dryRunError, setDryRunError] = React.useState<string | null>(null);+ const [dryRunResult, setDryRunResult] = React.useState<TamperDryRunResult | null>(null);++ const loadHooks = React.useCallback(async () => {+ setLoading(true);+ setLoadError(null);+ try {+ const res = await api.trafficHooks();+ setHooks(res.hooks ?? []);+ setEnabledByEnv(Boolean(res.enabled_by_env));+ } catch (e) {+ setLoadError((e as Error).message);+ } finally {+ setLoading(false);+ }+ }, []);++ React.useEffect(() => {+ void loadHooks();+ }, [loadHooks]);++ const handleToggle = async (hook: TamperHook, next: boolean) => {+ setTogglingId(hook.id);+ try {+ const updated = await api.toggleTrafficHook(hook.id, next);+ setHooks((prev) => prev.map((h) => (h.id === hook.id ? updated : h)));+ toast.success(+ next ? t('Hook "{name}" enabled', { name: hook.name }) : t('Hook "{name}" disabled', { name: hook.name }),+ );+ } catch (e) {+ toast.error((e as Error).message);+ } finally {+ setTogglingId(null);+ }+ };++ const handleSave = async () => {+ if (!editor) return;+ setFormError(null);+ const priority = Number.parseInt(editor.priority, 10);+ if (Number.isNaN(priority)) {+ setFormError(t("Priority must be an integer"));+ return;+ }+ const payload = {+ name: editor.name.trim(),+ enabled: editor.mode === "create" ? false : editor.enabled,+ phase: editor.phase,+ priority,+ matchers: buildMatchers(editor),+ source: editor.source,+ note: editor.note.trim(),+ };+ setSaving(true);+ try {+ if (editor.mode === "create") {+ await api.createTrafficHook(payload);+ toast.success(t("Hook created (disabled by default)"));+ } else if (editor.id !== undefined) {+ await api.updateTrafficHook(editor.id, payload);+ toast.success(t("Hook updated"));+ }+ setEditor(null);+ await loadHooks();+ } catch (e) {+ setFormError((e as Error).message);+ } finally {+ setSaving(false);+ }+ };++ const handleDelete = async () => {+ if (!deleteTarget) return;+ setDeleting(true);+ try {+ await api.deleteTrafficHook(deleteTarget.id);+ toast.success(t("Hook deleted"));+ setDeleteTarget(null);+ await loadHooks();+ } catch (e) {+ toast.error((e as Error).message);+ } finally {+ setDeleting(false);+ }+ };++ const openVersions = async (hook: TamperHook) => {+ setVersionsHook(hook);+ setVersions([]);+ setExpandedVersion(null);+ setVersionsLoading(true);+ try {+ const res = await api.trafficHookVersions(hook.id);+ setVersions(res.versions ?? []);+ } catch (e) {+ toast.error((e as Error).message);+ } finally {+ setVersionsLoading(false);+ }+ };++ const handleRollback = async () => {+ if (!versionsHook || !rollbackTarget) return;+ setRollingBack(true);+ try {+ const updated = await api.rollbackTrafficHook(versionsHook.id, rollbackTarget.version);+ toast.success(+ t("Rolled back to v{version} (now v{current})", { version: rollbackTarget.version, current: updated.version }),+ );+ setRollbackTarget(null);+ setVersionsHook(updated);+ await loadHooks();+ const res = await api.trafficHookVersions(updated.id);+ setVersions(res.versions ?? []);+ } catch (e) {+ toast.error((e as Error).message);+ } finally {+ setRollingBack(false);+ }+ };++ const openDryRunForHook = (hook: TamperHook) => {+ setDryRunTarget({ label: `${hook.name} (v${hook.version}, ${hook.phase})`, hookId: hook.id });+ setDryRunError(null);+ setDryRunResult(null);+ setDryRunExchangeWarning(null);+ };++ const openDryRunForDraft = () => {+ if (!editor) return;+ setDryRunTarget({+ label: t("Draft: {name} ({phase})", { name: editor.name.trim() || t("untitled"), phase: editor.phase }),+ inline: {+ name: editor.name.trim() || "dry-run",+ phase: editor.phase,+ matchers: buildMatchers(editor),+ source: editor.source,+ },+ });+ setDryRunError(null);+ setDryRunResult(null);+ setDryRunExchangeWarning(null);+ };++ const loadExchangeIntoDryRun = async (id: string) => {+ const trimmed = id.trim();+ if (!trimmed) return;+ setDryRunLoadingExchange(true);+ setDryRunError(null);+ setDryRunExchangeWarning(null);+ try {+ const detail = await api.trafficExchange(trimmed);+ const matched = recentExchanges.find((ex) => ex.id === trimmed);+ const converted = exchangeDetailToDryRunIO(detail, matched?.url);+ setDryRunMethod(converted.io.request.method);+ setDryRunUrl(converted.io.request.url);+ setDryRunReqHeaders(formatHeaderLines(converted.io.request.headers));+ setDryRunReqBody(converted.io.request.body);+ setDryRunStatus(String(converted.io.response.status));+ setDryRunRespHeaders(formatHeaderLines(converted.io.response.headers));+ setDryRunRespBody(converted.io.response.body);+ const warnings: string[] = [];+ if (converted.reqBinary || converted.respBinary) {+ warnings.push(t("Binary body detected; binary bodies are skipped by hooks in 0.7."));+ }+ if (converted.reqPreviewOnly || converted.respPreviewOnly) {+ warnings.push(t("Body was truncated in the recorded preview; only the inline preview was loaded."));+ }+ if (warnings.length) setDryRunExchangeWarning(warnings.join(" "));+ toast.success(t("Loaded exchange {id}", { id: trimmed }));+ } catch (e) {+ setDryRunError((e as Error).message);+ } finally {+ setDryRunLoadingExchange(false);+ }+ };++ const runDryRun = async () => {+ if (!dryRunTarget) return;+ setDryRunRunning(true);+ setDryRunError(null);+ setDryRunResult(null);+ const statusNum = Number.parseInt(dryRunStatus, 10);+ const body: TamperDryRunRequest = {+ ...(dryRunTarget.hookId+ ? { hook_id: dryRunTarget.hookId }+ : {+ name: dryRunTarget.inline?.name,+ phase: dryRunTarget.inline?.phase,+ matchers: dryRunTarget.inline?.matchers,+ source: dryRunTarget.inline?.source,+ }),+ request: {+ method: dryRunMethod.trim().toUpperCase() || "GET",+ url: dryRunUrl.trim() || "https://example.test/",+ headers: parseHeaderLines(dryRunReqHeaders),+ body: dryRunReqBody,+ },+ response: {+ status: Number.isNaN(statusNum) ? 200 : statusNum,+ headers: parseHeaderLines(dryRunRespHeaders),+ body: dryRunRespBody,+ },+ };+ try {+ const res = await api.dryRunTrafficHook(body);+ setDryRunResult(res);+ } catch (e) {+ setDryRunError((e as Error).message);+ } finally {+ setDryRunRunning(false);+ }+ };++ return (+ <div className="flex min-h-0 flex-1 flex-col gap-4">+ {!enabledByEnv && (+ <Alert className="border-amber-500/40 bg-amber-500/10 py-2.5">+ <AlertTriangleIcon className="size-4 text-amber-500" />+ <AlertDescription className="text-xs">+ {t(+ "Live hook execution is disabled (ARTEX_TAMPER_HOOKS_ENABLED is off). You can create, edit, version, and dry-run hooks, but none will run on live proxy traffic until enabled.",+ )}+ </AlertDescription>+ </Alert>+ )}++ {loadError && (+ <Alert variant="destructive" className="py-2">+ <AlertDescription className="text-xs">{loadError}</AlertDescription>+ </Alert>+ )}++ <div className="flex flex-wrap items-center justify-between gap-2">+ <p className="text-xs text-muted-foreground">+ {t(+ "Operator-only Go-subset tampering hooks run after declarative rewrite rules per phase and fail open on error.",+ )}+ </p>+ <div className="flex items-center gap-2">+ <Button variant="outline" size="sm" className="h-8" onClick={() => void loadHooks()} disabled={loading}>+ <RefreshCwIcon className={`size-3.5 ${loading ? "animate-spin" : ""}`} />+ {t("Refresh")}+ </Button>+ <Button+ size="sm"+ className="h-8"+ onClick={() => {+ setFormError(null);+ setEditor(emptyEditor("request"));+ }}+ >+ <PlusIcon className="size-3.5" />+ {t("New hook")}+ </Button>+ </div>+ </div>++ <Card className="min-h-0 flex-1 overflow-auto p-0">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>{t("Name")}</TableHead>+ <TableHead className="w-28">{t("Phase")}</TableHead>+ <TableHead className="w-24">{t("Priority")}</TableHead>+ <TableHead className="w-24">{t("Version")}</TableHead>+ <TableHead className="w-24">{t("Enabled")}</TableHead>+ <TableHead className="w-44">{t("Last error")}</TableHead>+ <TableHead className="w-48 text-right">{t("Actions")}</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {loading && hooks.length === 0 ? (+ <TableRow>+ <TableCell colSpan={7} className="py-10 text-center text-sm text-muted-foreground">+ <Loader2Icon className="mx-auto mb-2 size-5 animate-spin" />+ {t("Loading hooks…")}+ </TableCell>+ </TableRow>+ ) : hooks.length === 0 ? (+ <TableRow>+ <TableCell colSpan={7} className="py-10 text-center text-sm text-muted-foreground">+ {t("No tampering hooks configured yet.")}+ </TableCell>+ </TableRow>+ ) : (+ hooks.map((hook) => (+ <TableRow key={hook.id}>+ <TableCell>+ <div className="font-medium">{hook.name}</div>+ {hook.note && <div className="line-clamp-1 text-xs text-muted-foreground">{hook.note}</div>}+ </TableCell>+ <TableCell>+ <Badge variant="outline" className="font-mono text-xs">+ {hook.phase}+ </Badge>+ </TableCell>+ <TableCell className="font-mono text-xs tabular-nums">{hook.priority}</TableCell>+ <TableCell className="font-mono text-xs tabular-nums">v{hook.version}</TableCell>+ <TableCell>+ <Switch+ checked={hook.enabled}+ disabled={togglingId === hook.id}+ aria-label={t("Toggle hook {name}", { name: hook.name })}+ onCheckedChange={(checked) => void handleToggle(hook, checked)}+ />+ </TableCell>+ <TableCell>+ {hook.load_error ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge variant="destructive" className="gap-1 font-mono text-xs">+ <ShieldAlertIcon className="size-3" />+ {t("load_error")}+ </Badge>+ </TooltipTrigger>+ <TooltipContent className="max-w-xs font-mono text-xs">{hook.load_error}</TooltipContent>+ </Tooltip>+ ) : hook.last_error ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge variant="destructive" className="gap-1 font-mono text-xs">+ <AlertTriangleIcon className="size-3" />+ {hook.last_error.class} ({hook.last_error.count})+ </Badge>+ </TooltipTrigger>+ <TooltipContent className="text-xs">+ {t("Last seen at {time}", { time: fmtDateTime(hook.last_error.at) })}+ </TooltipContent>+ </Tooltip>+ ) : (+ <Badge variant="secondary" className="gap-1 text-xs text-muted-foreground">+ <ShieldCheckIcon className="size-3" />+ {t("None")}+ </Badge>+ )}+ </TableCell>+ <TableCell className="text-right">+ <div className="flex items-center justify-end gap-1">+ <Button+ variant="ghost"+ size="icon-xs"+ title={t("Dry-run")}+ aria-label={t("Dry-run")}+ onClick={() => openDryRunForHook(hook)}+ >+ <PlayIcon className="size-3.5" />+ </Button>+ <Button+ variant="ghost"+ size="icon-xs"+ title={t("Versions")}+ aria-label={t("Versions")}+ onClick={() => void openVersions(hook)}+ >+ <HistoryIcon className="size-3.5" />+ </Button>+ <Button+ variant="ghost"+ size="icon-xs"+ title={t("Edit")}+ aria-label={t("Edit")}+ onClick={() => {+ setFormError(null);+ setEditor(editorFromHook(hook));+ }}+ >+ <PencilIcon className="size-3.5" />+ </Button>+ <Button+ variant="ghost"+ size="icon-xs"+ title={t("Delete")}+ aria-label={t("Delete")}+ className="text-destructive hover:text-destructive"+ onClick={() => setDeleteTarget(hook)}+ >+ <Trash2Icon className="size-3.5" />+ </Button>+ </div>+ </TableCell>+ </TableRow>+ ))+ )}+ </TableBody>+ </Table>+ </Card>++ {/* Create / Edit Dialog */}+ <Dialog+ open={editor !== null}+ onOpenChange={(open) => {+ if (!open) {+ setEditor(null);+ setFormError(null);+ }+ }}+ >+ <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-3xl">+ <DialogHeader>+ <DialogTitle>{editor?.mode === "edit" ? t("Edit tampering hook") : t("New tampering hook")}</DialogTitle>+ <DialogDescription>+ {editor?.mode === "create"+ ? t("New hooks are created disabled. Save and dry-run before enabling.")+ : t("Saving creates a new version in history. Source and matchers are sealed at rest.")}+ </DialogDescription>+ </DialogHeader>++ {editor && (+ <div className="space-y-4 py-2">+ {formError && (+ <Alert variant="destructive">+ <AlertTriangleIcon className="size-4" />+ <AlertDescription className="font-mono text-xs whitespace-pre-wrap">{formError}</AlertDescription>+ </Alert>+ )}++ <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">+ <div className="space-y-1.5 sm:col-span-1">+ <Label htmlFor="hook-name">{t("Name")}</Label>+ <Input+ id="hook-name"+ value={editor.name}+ placeholder="sign-api-requests"+ onChange={(e) => setEditor({ ...editor, name: e.target.value })}+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="hook-phase">{t("Phase")}</Label>+ <Select+ value={editor.phase}+ onValueChange={(val) => {+ const nextPhase = val as TamperHookPhase;+ const shouldSwapTemplate =+ editor.mode === "create" &&+ (editor.source.trim() === DEFAULT_REQUEST_HOOK_SOURCE.trim() ||+ editor.source.trim() === DEFAULT_RESPONSE_HOOK_SOURCE.trim());+ setEditor({+ ...editor,+ phase: nextPhase,+ source: shouldSwapTemplate+ ? nextPhase === "response"+ ? DEFAULT_RESPONSE_HOOK_SOURCE+ : DEFAULT_REQUEST_HOOK_SOURCE+ : editor.source,+ });+ }}+ >+ <SelectTrigger id="hook-phase">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="request">request</SelectItem>+ <SelectItem value="response">response</SelectItem>+ </SelectContent>+ </Select>+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="hook-priority">{t("Priority")}</Label>+ <Input+ id="hook-priority"+ type="number"+ value={editor.priority}+ onChange={(e) => setEditor({ ...editor, priority: e.target.value })}+ />+ </div>+ </div>++ <div className="space-y-1.5">+ <Label htmlFor="hook-note">{t("Note")}</Label>+ <Input+ id="hook-note"+ value={editor.note}+ placeholder={t("Optional operator note")}+ onChange={(e) => setEditor({ ...editor, note: e.target.value })}+ />+ </div>++ {/* Matchers */}+ <div className="space-y-3 rounded-md border p-3">+ <div className="text-xs font-medium text-muted-foreground">+ {t("Matchers (prefilter — empty matches all)")}+ </div>+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">+ <div className="space-y-1">+ <Label htmlFor="m-methods" className="text-xs">+ {t("Methods (comma-separated)")}+ </Label>+ <Input+ id="m-methods"+ className="h-8 font-mono text-xs"+ value={editor.methods}+ placeholder="POST, PUT"+ onChange={(e) => setEditor({ ...editor, methods: e.target.value })}+ />+ </div>+ <div className="space-y-1">+ <Label htmlFor="m-host" className="text-xs">+ {t("Host (exact or *.suffix)")}+ </Label>+ <Input+ id="m-host"+ className="h-8 font-mono text-xs"+ value={editor.host}+ placeholder="*.example.test"+ onChange={(e) => setEditor({ ...editor, host: e.target.value })}+ />+ </div>+ <div className="space-y-1">+ <Label htmlFor="m-url" className="text-xs">+ {t("URL regex")}+ </Label>+ <Input+ id="m-url"+ className="h-8 font-mono text-xs"+ value={editor.urlRegex}+ placeholder="^/api/v1/"+ onChange={(e) => setEditor({ ...editor, urlRegex: e.target.value })}+ />+ </div>+ <div className="space-y-1">+ <Label htmlFor="m-body" className="text-xs">+ {t("Request body regex")}+ </Label>+ <Input+ id="m-body"+ className="h-8 font-mono text-xs"+ value={editor.bodyRegex}+ placeholder="token"+ onChange={(e) => setEditor({ ...editor, bodyRegex: e.target.value })}+ />+ </div>+ </div>+ <div className="space-y-1">+ <Label htmlFor="m-headers" className="text-xs">+ {t("Request headers (one per line: Name or Name: value_regex)")}+ </Label>+ <Textarea+ id="m-headers"+ rows={2}+ className="font-mono text-xs"+ value={editor.headers}+ placeholder={"Content-Type: application/json\nX-Api-Key"}+ onChange={(e) => setEditor({ ...editor, headers: e.target.value })}+ />+ </div>++ {editor.phase === "response" && (+ <div className="grid grid-cols-1 gap-3 border-t pt-3 sm:grid-cols-2">+ <div className="space-y-1">+ <Label htmlFor="m-status" className="text-xs">+ {t("Status codes (comma-separated, e.g. 200, 4xx)")}+ </Label>+ <Input+ id="m-status"+ className="h-8 font-mono text-xs"+ value={editor.status}+ placeholder="200, 2xx"+ onChange={(e) => setEditor({ ...editor, status: e.target.value })}+ />+ </div>+ <div className="space-y-1">+ <Label htmlFor="m-resp-body" className="text-xs">+ {t("Response body regex")}+ </Label>+ <Input+ id="m-resp-body"+ className="h-8 font-mono text-xs"+ value={editor.respBodyRegex}+ onChange={(e) => setEditor({ ...editor, respBodyRegex: e.target.value })}+ />+ </div>+ <div className="space-y-1 sm:col-span-2">+ <Label htmlFor="m-resp-headers" className="text-xs">+ {t("Response headers (one per line: Name or Name: value_regex)")}+ </Label>+ <Textarea+ id="m-resp-headers"+ rows={2}+ className="font-mono text-xs"+ value={editor.respHeaders}+ placeholder="Content-Type: application/json"+ onChange={(e) => setEditor({ ...editor, respHeaders: e.target.value })}+ />+ </div>+ </div>+ )}+ </div>++ {/* Source editor */}+ <div className="space-y-1.5">+ <div className="flex items-center justify-between">+ <Label htmlFor="hook-source" className="flex items-center gap-1.5">+ <Code2Icon className="size-3.5" />+ {t("Go-subset source")}+ </Label>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="h-6 px-2 text-xs"+ onClick={() =>+ setEditor({+ ...editor,+ source:+ editor.phase === "response" ? DEFAULT_RESPONSE_HOOK_SOURCE : DEFAULT_REQUEST_HOOK_SOURCE,+ })+ }+ >+ {t("Reset template")}+ </Button>+ </div>+ <Textarea+ id="hook-source"+ rows={12}+ spellCheck={false}+ className="font-mono text-xs leading-relaxed"+ value={editor.source}+ onChange={(e) => setEditor({ ...editor, source: e.target.value })}+ />+ <p className="text-xs text-muted-foreground">+ {editor.phase === "response"+ ? t("Entrypoint: package hook · func OnResponse(req *Request, resp *Response) error")+ : t("Entrypoint: package hook · func OnRequest(req *Request) error")}+ </p>+ </div>+ </div>+ )}++ <DialogFooter className="gap-2 sm:justify-between">+ <Button type="button" variant="outline" size="sm" onClick={openDryRunForDraft} disabled={!editor}>+ <PlayIcon className="size-3.5" />+ {t("Dry-run draft")}+ </Button>+ <div className="flex items-center gap-2">+ <Button type="button" variant="outline" onClick={() => setEditor(null)} disabled={saving}>+ {t("Cancel")}+ </Button>+ <Button type="button" onClick={() => void handleSave()} disabled={saving}>+ {saving && <Loader2Icon className="size-3.5 animate-spin" />}+ {editor?.mode === "edit" ? t("Save changes") : t("Create hook")}+ </Button>+ </div>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ {/* Delete confirmation */}+ <AlertDialog open={deleteTarget !== null} onOpenChange={(open) => !open && setDeleteTarget(null)}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t("Delete tampering hook?")}</AlertDialogTitle>+ <AlertDialogDescription>+ {t('This permanently removes "{name}" and its stored version history.', {+ name: deleteTarget?.name ?? "",+ })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={deleting}>{t("Cancel")}</AlertDialogCancel>+ <AlertDialogAction+ onClick={(e) => {+ e.preventDefault();+ void handleDelete();+ }}+ disabled={deleting}+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"+ >+ {deleting && <Loader2Icon className="size-3.5 animate-spin" />}+ {t("Delete")}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>++ {/* Versions Sheet */}+ <Sheet open={versionsHook !== null} onOpenChange={(open) => !open && setVersionsHook(null)}>+ <SheetContent className="w-full overflow-y-auto sm:max-w-2xl">+ <SheetHeader>+ <SheetTitle>{t("Versions: {name}", { name: versionsHook?.name ?? "" })}</SheetTitle>+ <SheetDescription>+ {t("Up to 20 newest revisions are retained. Rolling back creates a new monotonic version.")}+ </SheetDescription>+ </SheetHeader>++ <div className="mt-4 space-y-3">+ {versionsLoading ? (+ <div className="py-10 text-center text-sm text-muted-foreground">+ <Loader2Icon className="mx-auto mb-2 size-5 animate-spin" />+ {t("Loading versions…")}+ </div>+ ) : versions.length === 0 ? (+ <div className="py-8 text-center text-sm text-muted-foreground">{t("No stored versions.")}</div>+ ) : (+ versions.map((v) => {+ const isCurrent = versionsHook?.version === v.version;+ const isExpanded = expandedVersion === v.version;+ return (+ <Card key={v.id} className="space-y-2 p-3">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="flex items-center gap-2">+ <Badge variant={isCurrent ? "default" : "outline"} className="font-mono text-xs">+ v{v.version}+ </Badge>+ {isCurrent && <Badge variant="secondary">{t("Current")}</Badge>}+ <Badge variant="outline" className="font-mono text-xs">+ {v.phase}+ </Badge>+ <span className="font-mono text-xs text-muted-foreground">+ {t("prio {n}", { n: v.priority })} · {v.source_sha256.slice(0, 12)}+ </span>+ </div>+ <span className="text-xs text-muted-foreground">{fmtDateTime(v.created_at)}</span>+ </div>+ {v.note && <p className="text-xs text-muted-foreground">{v.note}</p>}+ <div className="flex items-center justify-between gap-2 pt-1">+ <Button+ variant="ghost"+ size="sm"+ className="h-7 px-2 text-xs"+ onClick={() => setExpandedVersion(isExpanded ? null : v.version)}+ >+ <Code2Icon className="size-3.5" />+ {isExpanded ? t("Hide source") : t("View source")}+ </Button>+ {!isCurrent && (+ <Button+ variant="outline"+ size="sm"+ className="h-7 px-2.5 text-xs"+ onClick={() => setRollbackTarget(v)}+ >+ <RotateCcwIcon className="size-3.5" />+ {t("Rollback to v{version}", { version: v.version })}+ </Button>+ )}+ </div>+ {isExpanded && (+ <pre className="max-h-72 overflow-auto rounded-md border bg-muted/40 p-2.5 font-mono text-xs">+ {v.source}+ </pre>+ )}+ </Card>+ );+ })+ )}+ </div>+ </SheetContent>+ </Sheet>++ {/* Rollback confirmation */}+ <AlertDialog open={rollbackTarget !== null} onOpenChange={(open) => !open && setRollbackTarget(null)}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ {t("Rollback hook to v{version}?", { version: rollbackTarget?.version ?? 0 })}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {t('This restores the matchers and source from v{version} as a new version on "{name}".', {+ version: rollbackTarget?.version ?? 0,+ name: versionsHook?.name ?? "",+ })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={rollingBack}>{t("Cancel")}</AlertDialogCancel>+ <AlertDialogAction+ onClick={(e) => {+ e.preventDefault();+ void handleRollback();+ }}+ disabled={rollingBack}+ >+ {rollingBack && <Loader2Icon className="size-3.5 animate-spin" />}+ {t("Rollback")}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>++ {/* Dry-run Sheet */}+ <Sheet open={dryRunTarget !== null} onOpenChange={(open) => !open && setDryRunTarget(null)}>+ <SheetContent className="w-full overflow-y-auto sm:max-w-3xl">+ <SheetHeader>+ <SheetTitle>{t("Dry-run: {target}", { target: dryRunTarget?.label ?? "" })}</SheetTitle>+ <SheetDescription>+ {t(+ "Runs the hook in the sandbox against a recorded exchange or synthetic HTTP message without touching live traffic.",+ )}+ </SheetDescription>+ </SheetHeader>++ <div className="mt-4 space-y-4">+ <Tabs value={dryRunInputMode} onValueChange={(v) => setDryRunInputMode(v as "synthetic" | "exchange")}>+ <TabsList className="grid w-full grid-cols-2">+ <TabsTrigger value="exchange">{t("From exchange ID")}</TabsTrigger>+ <TabsTrigger value="synthetic">{t("Synthetic input")}</TabsTrigger>+ </TabsList>++ <TabsContent value="exchange" className="space-y-3 pt-2">+ <div className="flex items-end gap-2">+ <div className="flex-1 space-y-1">+ <Label htmlFor="dryrun-ex-id" className="text-xs">+ {t("Exchange ID")}+ </Label>+ <Input+ id="dryrun-ex-id"+ className="h-8 font-mono text-xs"+ value={dryRunExchangeId}+ placeholder={t("Paste a recorded exchange ID")}+ onChange={(e) => setDryRunExchangeId(e.target.value)}+ />+ </div>+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="h-8"+ disabled={dryRunLoadingExchange || !dryRunExchangeId.trim()}+ onClick={() => void loadExchangeIntoDryRun(dryRunExchangeId)}+ >+ {dryRunLoadingExchange && <Loader2Icon className="size-3.5 animate-spin" />}+ {t("Load exchange")}+ </Button>+ </div>++ {recentExchanges.length > 0 && (+ <div className="space-y-1">+ <Label className="text-xs text-muted-foreground">{t("Or pick a recent captured exchange")}</Label>+ <Select+ value=""+ onValueChange={(id) => {+ setDryRunExchangeId(id);+ void loadExchangeIntoDryRun(id);+ }}+ >+ <SelectTrigger className="h-8 font-mono text-xs">+ <SelectValue placeholder={t("Select recent exchange…")} />+ </SelectTrigger>+ <SelectContent>+ {recentExchanges.slice(0, 20).map((ex) => (+ <SelectItem key={ex.id} value={ex.id} className="font-mono text-xs">+ {ex.method} {ex.host}+ {ex.url.replace(/^https?:\/\/[^/]+/, "").slice(0, 48)} ({ex.status})+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ )}++ {dryRunExchangeWarning && (+ <Alert className="border-amber-500/40 bg-amber-500/10 py-2">+ <AlertTriangleIcon className="size-4 text-amber-500" />+ <AlertDescription className="text-xs">{dryRunExchangeWarning}</AlertDescription>+ </Alert>+ )}+ </TabsContent>++ <TabsContent value="synthetic" className="pt-1">+ <p className="text-xs text-muted-foreground">+ {t("Edit the synthetic request and response below, then click Run dry-run.")}+ </p>+ </TabsContent>+ </Tabs>++ {/* Editable Request / Response fields (also populated when an exchange is loaded) */}+ <div className="grid grid-cols-1 gap-3 rounded-md border p-3 sm:grid-cols-2">+ <div className="space-y-2">+ <div className="text-xs font-medium">{t("Request")}</div>+ <div className="flex gap-2">+ <Input+ className="h-8 w-24 font-mono text-xs"+ value={dryRunMethod}+ onChange={(e) => setDryRunMethod(e.target.value)}+ aria-label={t("Method")}+ />+ <Input+ className="h-8 flex-1 font-mono text-xs"+ value={dryRunUrl}+ onChange={(e) => setDryRunUrl(e.target.value)}+ aria-label={t("URL")}+ />+ </div>+ <Textarea+ rows={3}+ className="font-mono text-xs"+ value={dryRunReqHeaders}+ placeholder="Header: value"+ onChange={(e) => setDryRunReqHeaders(e.target.value)}+ />+ <Textarea+ rows={3}+ className="font-mono text-xs"+ value={dryRunReqBody}+ placeholder={t("Request body")}+ onChange={(e) => setDryRunReqBody(e.target.value)}+ />+ </div>++ <div className="space-y-2">+ <div className="text-xs font-medium">{t("Response")}</div>+ <Input+ className="h-8 w-28 font-mono text-xs"+ type="number"+ value={dryRunStatus}+ onChange={(e) => setDryRunStatus(e.target.value)}+ aria-label={t("Status")}+ />+ <Textarea+ rows={3}+ className="font-mono text-xs"+ value={dryRunRespHeaders}+ placeholder="Header: value"+ onChange={(e) => setDryRunRespHeaders(e.target.value)}+ />+ <Textarea+ rows={3}+ className="font-mono text-xs"+ value={dryRunRespBody}+ placeholder={t("Response body")}+ onChange={(e) => setDryRunRespBody(e.target.value)}+ />+ </div>+ </div>++ <div className="flex justify-end">+ <Button type="button" size="sm" onClick={() => void runDryRun()} disabled={dryRunRunning}>+ {dryRunRunning ? <Loader2Icon className="size-3.5 animate-spin" /> : <PlayIcon className="size-3.5" />}+ {t("Run dry-run")}+ </Button>+ </div>++ {dryRunError && (+ <Alert variant="destructive">+ <AlertTriangleIcon className="size-4" />+ <AlertDescription className="font-mono text-xs whitespace-pre-wrap">{dryRunError}</AlertDescription>+ </Alert>+ )}++ {dryRunResult && (+ <div className="space-y-3 border-t pt-3">+ <div className="flex items-center justify-between">+ <span className="text-sm font-medium">{t("Dry-run result")}</span>+ <Badge variant={dryRunResult.changed ? "default" : "secondary"}>+ {dryRunResult.changed ? t("Modified") : t("Unchanged")}+ </Badge>+ </div>++ {/* Trace lines */}+ <div className="space-y-1.5">+ <div className="text-xs font-medium text-muted-foreground">+ {t("Trace lines ({count})", { count: dryRunResult.lines?.length ?? 0 })}+ </div>+ {!dryRunResult.lines || dryRunResult.lines.length === 0 ? (+ <p className="text-xs text-muted-foreground">+ {t("No trace lines recorded (matcher did not match or hook made no changes).")}+ </p>+ ) : (+ <div className="overflow-x-auto rounded-md border">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="text-xs">{t("Field")}</TableHead>+ <TableHead className="text-xs">{t("Outcome")}</TableHead>+ <TableHead className="text-xs">{t("After / Masked")}</TableHead>+ <TableHead className="text-xs">{t("Hashes")}</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {dryRunResult.lines.map((line, idx) => {+ const masked = isTraceLineMasked(line);+ const decodedAfter = decodeTraceAfter(line.After);+ return (+ <TableRow key={`${line.Field}-${line.Outcome}-${idx}`}>+ <TableCell className="font-mono text-xs">+ <div>{line.Field || "—"}</div>+ <div className="text-[11px] text-muted-foreground">+ {line.Phase} · {line.Action}+ </div>+ </TableCell>+ <TableCell className="text-xs">+ <Badge+ variant={+ line.Outcome === "error"+ ? "destructive"+ : line.Outcome === "applied"+ ? "default"+ : "secondary"+ }+ className="font-mono text-[11px]"+ >+ {line.Outcome}+ </Badge>+ {line.Reason && (+ <div className="mt-1 font-mono text-[11px] text-muted-foreground">+ {line.Reason}+ </div>+ )}+ </TableCell>+ <TableCell className="max-w-xs font-mono text-xs">+ {masked ? (+ <Badge+ variant="outline"+ className="border-amber-500/50 text-amber-600 dark:text-amber-400"+ >+ {t("Masked (HMAC)")}+ </Badge>+ ) : decodedAfter !== null ? (+ <span className="break-all">{decodedAfter.slice(0, 160)}</span>+ ) : (+ <span className="text-muted-foreground">—</span>+ )}+ </TableCell>+ <TableCell className="font-mono text-[11px] text-muted-foreground">+ {line.BeforeHash && <div>{line.BeforeHash.slice(0, 12)}</div>}+ {line.AfterHash && <div>→ {line.AfterHash.slice(0, 12)}</div>}+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ </div>+ )}+ </div>++ {/* Output preview */}+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">+ <div className="space-y-1">+ <div className="text-xs font-medium text-muted-foreground">{t("Resulting request")}</div>+ <pre className="max-h-48 overflow-auto rounded-md border bg-muted/40 p-2 font-mono text-xs">+ {`${dryRunResult.request.method} ${dryRunResult.request.url}\n${formatHeaderLines(dryRunResult.request.headers)}${dryRunResult.request.body ? `\n\n${dryRunResult.request.body}` : ""}`}+ </pre>+ </div>+ <div className="space-y-1">+ <div className="text-xs font-medium text-muted-foreground">{t("Resulting response")}</div>+ <pre className="max-h-48 overflow-auto rounded-md border bg-muted/40 p-2 font-mono text-xs">+ {`HTTP ${dryRunResult.response.status}\n${formatHeaderLines(dryRunResult.response.headers)}${dryRunResult.response.body ? `\n\n${dryRunResult.response.body}` : ""}`}+ </pre>+ </div>+ </div>+ </div>+ )}+ </div>+ </SheetContent>+ </Sheet>+ </div>+ );+}diff --git a/web/src/app/(main)/function/traffic/page.tsx b/web/src/app/(main)/function/traffic/page.tsxindex 4cbb009..7e7ae5e 100644--- a/web/src/app/(main)/function/traffic/page.tsx+++ b/web/src/app/(main)/function/traffic/page.tsx@@ -54,6 +54,7 @@ import { intlLocale, t } from "@/i18n";import { ReplayPanel } from "./_components/replay-panel";import { StreamMessagesPanel } from "./_components/stream-messages";+import { TamperHooksPanel } from "./_components/tamper-hooks-panel";function fmtTime(ts: string) {return new Date(ts).toLocaleString(intlLocale, {@@ -121,6 +122,7 @@ const SORT_STORAGE_KEY = "traffic-sort";const STATUS_BUCKETS = ["2xx", "3xx", "4xx", "5xx"];export default function TrafficPage() {+ const [viewTab, setViewTab] = React.useState<"exchanges" | "hooks">("exchanges");const [selectedFlows, setSelectedFlows] = React.useState<Set<string>>(() => new Set());const [linking, setLinking] = React.useState(false);const [page, setPage] = React.useState(0);@@ -507,6 +509,22 @@ export default function TrafficPage() {</div></div>+ <Tabs+ value={viewTab}+ onValueChange={(v) => setViewTab(v as "exchanges" | "hooks")}+ className="flex min-h-0 flex-1 flex-col gap-4"+ >+ <TabsList className="w-fit">+ <TabsTrigger value="exchanges">{t("Exchanges")}</TabsTrigger>+ <TabsTrigger value="hooks">{t("Hooks")}</TabsTrigger>+ </TabsList>++ <TabsContent value="hooks" className="mt-0 flex min-h-0 flex-1 flex-col gap-4">+ <TamperHooksPanel recentExchanges={exchanges} />+ </TabsContent>++ <TabsContent value="exchanges" className="mt-0 flex min-h-0 flex-1 flex-col gap-4">+{harError ? (<Alert variant="destructive" className="flex items-center justify-between gap-2 py-2"><AlertDescription className="text-xs">{harError}</AlertDescription>@@ -1098,6 +1116,8 @@ export default function TrafficPage() {</AlertDialogFooter></AlertDialogContent></AlertDialog>+ </TabsContent>+ </Tabs></div>);}diff --git a/web/src/i18n/locales/tr.json b/web/src/i18n/locales/tr.jsonindex f557b67..7158f79 100644--- a/web/src/i18n/locales/tr.json+++ b/web/src/i18n/locales/tr.json@@ -2619,5 +2619,91 @@"You can control at most 100 tasks at once": "Tek seferde en fazla 100 görevi yönetebilirsiniz","You can control injection into the <b>planner</b> and the <b>worker</b> separately; both are on by default. Switching takes effect immediately (read on the next turn) without rebuilding agents. When off, the agent no longer sees the constraints.": "<b>Planlayıcıya</b> ve <b>çalışana</b> eklemeyi ayrı ayrı denetleyebilirsiniz; ikisi de varsayılan olarak açıktır. Geçiş, ajanlar yeniden oluşturulmadan hemen geçerli olur (bir sonraki turda okunur). Kapalıyken ajan kısıtları artık görmez.","You have read all the terms": "Tüm koşulları okudunuz",- "You must comply on your own with all laws and regulations of your country or region on cybersecurity, data security and personal-information protection, computer crime, and the like (for example, laws on unauthorized access to computer systems, on personal-data protection, and on the responsibilities of security researchers and penetration testers in your jurisdiction).": "Ülkenizin veya bölgenizin siber güvenlik, veri güvenliği ve kişisel verilerin korunması, bilişim suçları ve benzeri konulardaki tüm yasa ve yönetmeliklerine kendi sorumluluğunuzda uymanız gerekir (örneğin bilişim sistemlerine yetkisiz erişime, kişisel verilerin korunmasına ve yargı bölgenizdeki güvenlik araştırmacıları ile sızma testi uzmanlarının sorumluluklarına ilişkin yasalar)."+ "You must comply on your own with all laws and regulations of your country or region on cybersecurity, data security and personal-information protection, computer crime, and the like (for example, laws on unauthorized access to computer systems, on personal-data protection, and on the responsibilities of security researchers and penetration testers in your jurisdiction).": "Ülkenizin veya bölgenizin siber güvenlik, veri güvenliği ve kişisel verilerin korunması, bilişim suçları ve benzeri konulardaki tüm yasa ve yönetmeliklerine kendi sorumluluğunuzda uymanız gerekir (örneğin bilişim sistemlerine yetkisiz erişime, kişisel verilerin korunmasına ve yargı bölgenizdeki güvenlik araştırmacıları ile sızma testi uzmanlarının sorumluluklarına ilişkin yasalar).",+ "Exchanges": "Değişimler",+ "Hooks": "Kancalar (Hooks)",+ "Hook \"{name}\" enabled": "\"{name}\" kancası etkinleştirildi",+ "Hook \"{name}\" disabled": "\"{name}\" kancası devre dışı bırakıldı",+ "Priority must be an integer": "Öncelik bir tam sayı olmalıdır",+ "Hook created (disabled by default)": "Kanca oluşturuldu (varsayılan olarak devre dışı)",+ "Hook updated": "Kanca güncellendi",+ "Hook deleted": "Kanca silindi",+ "Rolled back to v{version} (now v{current})": "v{version} sürümüne geri alındı (şimdi v{current})",+ "Draft: {name} ({phase})": "Taslak: {name} ({phase})",+ "untitled": "adsız",+ "Binary body detected; binary bodies are skipped by hooks in 0.7.": "İkili gövde algılandı; 0.7 sürümünde ikili gövdeler kancalar tarafından atlanır.",+ "Body was truncated in the recorded preview; only the inline preview was loaded.": "Kayıtlı önizlemede gövde kırpılmış; yalnızca satır içi önizleme yüklendi.",+ "Loaded exchange {id}": "{id} değişimi yüklendi",+ "Live hook execution is disabled (ARTEX_TAMPER_HOOKS_ENABLED is off). You can create, edit, version, and dry-run hooks, but none will run on live proxy traffic until enabled.": "Canlı kanca yürütme devre dışı (ARTEX_TAMPER_HOOKS_ENABLED kapalı). Kancaları oluşturabilir, düzenleyebilir, sürümleyebilir ve deneme çalıştırması yapabilirsiniz, ancak etkinleştirilene kadar canlı proxy trafiğinde çalışmazlar.",+ "Operator-only Go-subset tampering hooks run after declarative rewrite rules per phase and fail open on error.": "Yalnızca operatöre özel Go alt kümesi değiştirme kancaları her aşamada bildirimsel yeniden yazma kurallarından sonra çalışır ve hata durumunda açık başarısız olur.",+ "New hook": "Yeni kanca",+ "Phase": "Aşama",+ "Version": "Sürüm",+ "Last error": "Son hata",+ "Loading hooks…": "Kancalar yükleniyor…",+ "No tampering hooks configured yet.": "Henüz yapılandırılmış değiştirme kancası yok.",+ "Toggle hook {name}": "{name} kancasını aç/kapat",+ "load_error": "yükleme hatası",+ "Last seen at {time}": "Son görülme: {time}",+ "None": "Yok",+ "Dry-run": "Deneme çalıştırması",+ "Versions": "Sürümler",+ "Edit tampering hook": "Değiştirme kancasını düzenle",+ "New tampering hook": "Yeni değiştirme kancası",+ "New hooks are created disabled. Save and dry-run before enabling.": "Yeni kancalar devre dışı oluşturulur. Etkinleştirmeden önce kaydedin ve deneme çalıştırması yapın.",+ "Saving creates a new version in history. Source and matchers are sealed at rest.": "Kaydetme geçmişte yeni bir sürüm oluşturur. Kaynak kod ve eşleştiriciler durgun halde şifrelenir.",+ "Optional operator note": "İsteğe bağlı operatör notu",+ "Matchers (prefilter — empty matches all)": "Eşleştiriciler (ön filtre — boş ise tümüyle eşleşir)",+ "Methods (comma-separated)": "Yöntemler (virgülle ayrılmış)",+ "Host (exact or *.suffix)": "Ana bilgisayar (tam veya *.sonek)",+ "URL regex": "URL düzenli ifadesi",+ "Request body regex": "İstek gövdesi düzenli ifadesi",+ "Request headers (one per line: Name or Name: value_regex)": "İstek başlıkları (satır başına bir: Ad veya Ad: değer_regex)",+ "Status codes (comma-separated, e.g. 200, 4xx)": "Durum kodları (virgülle ayrılmış, örn. 200, 4xx)",+ "Response body regex": "Yanıt gövdesi düzenli ifadesi",+ "Response headers (one per line: Name or Name: value_regex)": "Yanıt başlıkları (satır başına bir: Ad veya Ad: değer_regex)",+ "Go-subset source": "Go alt kümesi kaynak kodu",+ "Reset template": "Şablonu sıfırla",+ "Entrypoint: package hook · func OnResponse(req *Request, resp *Response) error": "Giriş noktası: package hook · func OnResponse(req *Request, resp *Response) error",+ "Entrypoint: package hook · func OnRequest(req *Request) error": "Giriş noktası: package hook · func OnRequest(req *Request) error",+ "Dry-run draft": "Taslağı dene",+ "Create hook": "Kanca oluştur",+ "Delete tampering hook?": "Değiştirme kancası silinsin mi?",+ "This permanently removes \"{name}\" and its stored version history.": "Bu işlem \"{name}\" kancasını ve kayıtlı sürüm geçmişini kalıcı olarak siler.",+ "Versions: {name}": "Sürümler: {name}",+ "Up to 20 newest revisions are retained. Rolling back creates a new monotonic version.": "En yeni 20 revizyona kadar saklanır. Geri alma yeni bir monoton sürüm oluşturur.",+ "Loading versions…": "Sürümler yükleniyor…",+ "No stored versions.": "Kayıtlı sürüm yok.",+ "prio {n}": "öncelik {n}",+ "Hide source": "Kaynağı gizle",+ "View source": "Kaynağı görüntüle",+ "Rollback to v{version}": "v{version} sürümüne geri al",+ "Rollback hook to v{version}?": "Kanca v{version} sürümüne geri alınsın mı?",+ "This restores the matchers and source from v{version} as a new version on \"{name}\".": "Bu işlem v{version} sürümündeki eşleştiricileri ve kaynak kodu \"{name}\" üzerinde yeni bir sürüm olarak geri yükler.",+ "Rollback": "Geri al",+ "Dry-run: {target}": "Deneme çalıştırması: {target}",+ "Runs the hook in the sandbox against a recorded exchange or synthetic HTTP message without touching live traffic.": "Kancayı canlı trafiğe dokunmadan kayıtlı bir değişime veya sentetik bir HTTP iletisine karşı korumalı alanda çalıştırır.",+ "From exchange ID": "Değişim kimliğinden",+ "Synthetic input": "Sentetik girdi",+ "Exchange ID": "Değişim kimliği",+ "Paste a recorded exchange ID": "Kayıtlı bir değişim kimliği yapıştırın",+ "Load exchange": "Değişimi yükle",+ "Or pick a recent captured exchange": "Veya yakın zamanda yakalanmış bir değişim seçin",+ "Select recent exchange…": "Yakın zamandaki değişimi seçin…",+ "Edit the synthetic request and response below, then click Run dry-run.": "Aşağıdaki sentetik istek ve yanıtı düzenleyin, ardından Denemeyi çalıştır'a tıklayın.",+ "URL": "URL",+ "Request body": "İstek gövdesi",+ "Response body": "Yanıt gövdesi",+ "Run dry-run": "Denemeyi çalıştır",+ "Dry-run result": "Deneme çalıştırması sonucu",+ "Unchanged": "Değişmedi",+ "Trace lines ({count})": "İz satırları ({count})",+ "No trace lines recorded (matcher did not match or hook made no changes).": "İz satırı kaydedilmedi (eşleştirici eşleşmedi veya kanca değişiklik yapmadı).",+ "Field": "Alan",+ "Outcome": "Sonuç",+ "After / Masked": "Sonra / Maskeli",+ "Hashes": "Özetler",+ "Masked (HMAC)": "Maskeli (HMAC)",+ "Resulting request": "Ortaya çıkan istek",+ "Resulting response": "Ortaya çıkan yanıt"}diff --git a/web/src/i18n/locales/zh-CN.json b/web/src/i18n/locales/zh-CN.jsonindex ca94ab6..cddee14 100644--- a/web/src/i18n/locales/zh-CN.json+++ b/web/src/i18n/locales/zh-CN.json@@ -2619,5 +2619,91 @@"You can control at most 100 tasks at once": "一次最多控制 100 个任务","You can control injection into the <b>planner</b> and the <b>worker</b> separately; both are on by default. Switching takes effect immediately (read on the next turn) without rebuilding agents. When off, the agent no longer sees the constraints.": "可分别控制是否注入<b>规划器</b>和<b>执行器</b>,两者默认开启。切换立即生效(下一轮读取),无需重建智能体。关闭后,智能体将不再看到这些约束。","You have read all the terms": "您已浏览全部条款",- "You must comply on your own with all laws and regulations of your country or region on cybersecurity, data security and personal-information protection, computer crime, and the like (for example, laws on unauthorized access to computer systems, on personal-data protection, and on the responsibilities of security researchers and penetration testers in your jurisdiction).": "您必须自行遵守所在国家或地区有关网络安全、数据安全、个人信息保护、计算机犯罪等方面的全部法律法规(例如所在司法管辖区关于未授权访问计算机系统、个人数据保护,以及安全研究人员和渗透测试人员责任的规定)。"+ "You must comply on your own with all laws and regulations of your country or region on cybersecurity, data security and personal-information protection, computer crime, and the like (for example, laws on unauthorized access to computer systems, on personal-data protection, and on the responsibilities of security researchers and penetration testers in your jurisdiction).": "您必须自行遵守所在国家或地区有关网络安全、数据安全、个人信息保护、计算机犯罪等方面的全部法律法规(例如所在司法管辖区关于未授权访问计算机系统、个人数据保护,以及安全研究人员和渗透测试人员责任的规定)。",+ "Exchanges": "请求记录",+ "Hooks": "篡改钩子 (Hooks)",+ "Hook \"{name}\" enabled": "已启用钩子 \"{name}\"",+ "Hook \"{name}\" disabled": "已禁用钩子 \"{name}\"",+ "Priority must be an integer": "优先级必须为整数",+ "Hook created (disabled by default)": "钩子已创建(默认禁用)",+ "Hook updated": "钩子已更新",+ "Hook deleted": "钩子已删除",+ "Rolled back to v{version} (now v{current})": "已回滚到 v{version}(当前为 v{current})",+ "Draft: {name} ({phase})": "草稿:{name} ({phase})",+ "untitled": "未命名",+ "Binary body detected; binary bodies are skipped by hooks in 0.7.": "检测到二进制报文体;0.7 版本中钩子会跳过二进制报文体。",+ "Body was truncated in the recorded preview; only the inline preview was loaded.": "已记录的预览中报文体被截断;仅加载了内联预览内容。",+ "Loaded exchange {id}": "已加载流量记录 {id}",+ "Live hook execution is disabled (ARTEX_TAMPER_HOOKS_ENABLED is off). You can create, edit, version, and dry-run hooks, but none will run on live proxy traffic until enabled.": "实时钩子执行已关闭(ARTEX_TAMPER_HOOKS_ENABLED 未启用)。您可以创建、编辑、查看版本和演练钩子,但在启用前不会对实时代理流量生效。",+ "Operator-only Go-subset tampering hooks run after declarative rewrite rules per phase and fail open on error.": "仅限操作员使用的 Go 子集篡改钩子在每个阶段的声明式改写规则之后运行,出错时默认放行。",+ "New hook": "新建钩子",+ "Phase": "阶段",+ "Version": "版本",+ "Last error": "最近错误",+ "Loading hooks…": "正在加载钩子…",+ "No tampering hooks configured yet.": "尚未配置任何篡改钩子。",+ "Toggle hook {name}": "切换钩子 {name} 状态",+ "load_error": "加载错误",+ "Last seen at {time}": "最近出现于 {time}",+ "None": "无",+ "Dry-run": "演练",+ "Versions": "版本历史",+ "Edit tampering hook": "编辑篡改钩子",+ "New tampering hook": "新建篡改钩子",+ "New hooks are created disabled. Save and dry-run before enabling.": "新建钩子默认为禁用状态。请先保存并演练后再启用。",+ "Saving creates a new version in history. Source and matchers are sealed at rest.": "保存会在历史中创建新版本。源码和匹配器在静态存储时加密密封。",+ "Optional operator note": "可选操作员备注",+ "Matchers (prefilter — empty matches all)": "匹配器(预过滤 — 留空匹配全部)",+ "Methods (comma-separated)": "方法(逗号分隔)",+ "Host (exact or *.suffix)": "主机名(精确匹配或 *.后缀)",+ "URL regex": "URL 正则",+ "Request body regex": "请求体正则",+ "Request headers (one per line: Name or Name: value_regex)": "请求头(每行一条:Name 或 Name: value_regex)",+ "Status codes (comma-separated, e.g. 200, 4xx)": "状态码(逗号分隔,如 200, 4xx)",+ "Response body regex": "响应体正则",+ "Response headers (one per line: Name or Name: value_regex)": "响应头(每行一条:Name 或 Name: value_regex)",+ "Go-subset source": "Go 子集源码",+ "Reset template": "重置模板",+ "Entrypoint: package hook · func OnResponse(req *Request, resp *Response) error": "入口:package hook · func OnResponse(req *Request, resp *Response) error",+ "Entrypoint: package hook · func OnRequest(req *Request) error": "入口:package hook · func OnRequest(req *Request) error",+ "Dry-run draft": "演练草稿",+ "Create hook": "创建钩子",+ "Delete tampering hook?": "删除篡改钩子?",+ "This permanently removes \"{name}\" and its stored version history.": "此操作将永久删除 \"{name}\" 及其保存的版本历史。",+ "Versions: {name}": "版本历史:{name}",+ "Up to 20 newest revisions are retained. Rolling back creates a new monotonic version.": "最多保留最新 20 个修订版本。回滚会创建一个新的递增版本号。",+ "Loading versions…": "正在加载版本…",+ "No stored versions.": "暂无保存的版本。",+ "prio {n}": "优先级 {n}",+ "Hide source": "隐藏源码",+ "View source": "查看源码",+ "Rollback to v{version}": "回滚到 v{version}",+ "Rollback hook to v{version}?": "将钩子回滚到 v{version}?",+ "This restores the matchers and source from v{version} as a new version on \"{name}\".": "此操作会将 v{version} 的匹配器和源码恢复为 \"{name}\" 上的新版本。",+ "Rollback": "回滚",+ "Dry-run: {target}": "演练:{target}",+ "Runs the hook in the sandbox against a recorded exchange or synthetic HTTP message without touching live traffic.": "在沙箱中针对已记录的流量或合成 HTTP 报文运行钩子,不影响实时流量。",+ "From exchange ID": "从流量记录 ID",+ "Synthetic input": "合成输入",+ "Exchange ID": "流量记录 ID",+ "Paste a recorded exchange ID": "粘贴已记录的流量 ID",+ "Load exchange": "加载流量",+ "Or pick a recent captured exchange": "或选择最近捕获的流量记录",+ "Select recent exchange…": "选择最近的流量记录…",+ "Edit the synthetic request and response below, then click Run dry-run.": "在下方编辑合成请求和响应,然后点击运行演练。",+ "URL": "URL",+ "Request body": "请求体",+ "Response body": "响应体",+ "Run dry-run": "运行演练",+ "Dry-run result": "演练结果",+ "Unchanged": "未修改",+ "Trace lines ({count})": "追踪记录 ({count})",+ "No trace lines recorded (matcher did not match or hook made no changes).": "未产生追踪记录(匹配器未命中或钩子未做修改)。",+ "Field": "字段",+ "Outcome": "结果",+ "After / Masked": "修改后 / 已脱敏",+ "Hashes": "哈希",+ "Masked (HMAC)": "已脱敏 (HMAC)",+ "Resulting request": "结果请求",+ "Resulting response": "结果响应"}diff --git a/web/src/lib/api.ts b/web/src/lib/api.tsindex 339d541..790be32 100644--- a/web/src/lib/api.ts+++ b/web/src/lib/api.ts@@ -83,6 +83,12 @@ import type {SSProject,SSTask,Stats,+ TamperDryRunRequest,+ TamperDryRunResult,+ TamperHook,+ TamperHookInput,+ TamperHooksListResp,+ TamperHookVersion,Task,TaskArchive,TaskArchivePage,@@ -966,6 +972,16 @@ export const api = {// index handed back to the filesystem. Evidence bound to findings is kept.trafficDeleteAll: () => del<{ deleted: number; reclaimed: number }>(`/traffic/all`),+ // ---- capture-proxy constrained Go tampering hooks (P4.2, admin-only) ----+ trafficHooks: () => get<TamperHooksListResp>(`/traffic/hooks`),+ createTrafficHook: (body: TamperHookInput) => post<TamperHook>(`/traffic/hooks`, { ...body, enabled: false }),+ updateTrafficHook: (id: number, body: TamperHookInput) => put<TamperHook>(`/traffic/hooks/${id}`, body),+ deleteTrafficHook: (id: number) => del<{ deleted: boolean }>(`/traffic/hooks/${id}`),+ toggleTrafficHook: (id: number, enabled: boolean) => post<TamperHook>(`/traffic/hooks/${id}/toggle`, { enabled }),+ trafficHookVersions: (id: number) => get<{ versions: TamperHookVersion[] }>(`/traffic/hooks/${id}/versions`),+ rollbackTrafficHook: (id: number, version: number) => post<TamperHook>(`/traffic/hooks/${id}/rollback`, { version }),+ dryRunTrafficHook: (body: TamperDryRunRequest) => post<TamperDryRunResult>(`/traffic/hooks/dry-run`, body),+// ---- app settings (runtime toggles) ----settings: () => get<Settings>(`/settings`),setSettings: (patch: Partial<Settings>) => put<Settings>(`/settings`, patch),diff --git a/web/src/lib/tamper-hooks.ts b/web/src/lib/tamper-hooks.tsnew file mode 100644index 0000000..795d7f7--- /dev/null+++ b/web/src/lib/tamper-hooks.ts@@ -0,0 +1,236 @@+// Helpers for the Traffic > Hooks panel (P4.2 PR2):+// - Parse raw recorded HTTP responses and turn a recorded exchange into dry-run I/O+// - Parse/format header maps, header matchers, and CSV lists+// - Decode trace line After payloads and detect HMAC-masked fields++import { parseRawRequest } from "./replay";+import type { TamperDryRunIO, TamperHookHeaderMatcher, TamperHookMatchers, TamperTraceLine } from "./types";++export const DEFAULT_REQUEST_HOOK_SOURCE = `package hook++func OnRequest(req *Request) error {+\treq.SetHeader("X-Artex-Hook", "1")+\treturn nil+}+`;++export const DEFAULT_RESPONSE_HOOK_SOURCE = `package hook++func OnResponse(req *Request, resp *Response) error {+\tresp.SetHeader("X-Artex-Hook", "1")+\treturn nil+}+`;++const BLOB_MARKER = /\n?…\[truncated\] @blob sha256:[0-9a-f]{64} \(len=\d+\)$/;++export interface ParsedRawResponse {+ status: number;+ headers: Record<string, string[]>;+ body: string;+ binary: boolean;+ bodyPreviewOnly: boolean;+}++export function parseRawResponse(raw: string): ParsedRawResponse {+ if (!raw.trim()) {+ return { status: 200, headers: {}, body: "", binary: false, bodyPreviewOnly: false };+ }+ const separator = /\r?\n\r?\n/.exec(raw);+ const head = separator ? raw.slice(0, separator.index) : raw;+ let body = separator ? raw.slice(separator.index + separator[0].length) : "";+ const [statusLine = "", ...lines] = head.split(/\r?\n/);+ const statusMatch = /^HTTP\/\S+\s+(\d{3})\b/i.exec(statusLine.trim());+ const status = statusMatch ? Number.parseInt(statusMatch[1], 10) : 200;+ const headers: Record<string, string[]> = {};+ for (const line of lines) {+ const colon = line.indexOf(":");+ if (colon <= 0) continue;+ const name = line.slice(0, colon).trim();+ const value = line.slice(colon + 1).trim();+ if (!name) continue;+ if (!headers[name]) headers[name] = [];+ headers[name].push(value);+ }+ const bodyPreviewOnly = BLOB_MARKER.test(body);+ if (bodyPreviewOnly) body = body.replace(BLOB_MARKER, "");+ return {+ status,+ headers,+ body,+ binary: raw.includes("\u0000"),+ bodyPreviewOnly,+ };+}++export interface ExchangeDryRunConversion {+ io: TamperDryRunIO;+ reqBinary: boolean;+ respBinary: boolean;+ reqPreviewOnly: boolean;+ respPreviewOnly: boolean;+}++export function exchangeDetailToDryRunIO(+ detail: { req: string; resp: string },+ fallbackUrl?: string,+): ExchangeDryRunConversion {+ const req = parseRawRequest(detail.req || "");+ const resp = parseRawResponse(detail.resp || "");++ const reqHeaders: Record<string, string[]> = {};+ let hostHeader = "";+ for (const h of req.headers) {+ if (!h.name) continue;+ if (h.name.toLowerCase() === "host") {+ if (!hostHeader) hostHeader = h.value;+ continue;+ }+ if (!reqHeaders[h.name]) reqHeaders[h.name] = [];+ reqHeaders[h.name].push(h.value);+ }++ let url = fallbackUrl?.trim() || "";+ if (!url) {+ const target = req.target || "/";+ if (/^https?:\/\//i.test(target)) {+ url = target;+ } else {+ const host = hostHeader || "example.test";+ const path = target.startsWith("/") ? target : `/${target}`;+ url = `https://${host}${path}`;+ }+ }++ return {+ io: {+ request: {+ method: req.method || "GET",+ url,+ headers: reqHeaders,+ body: req.body,+ },+ response: {+ status: resp.status || 200,+ headers: resp.headers,+ body: resp.body,+ },+ },+ reqBinary: req.binary,+ respBinary: resp.binary,+ reqPreviewOnly: req.bodyPreviewOnly,+ respPreviewOnly: resp.bodyPreviewOnly,+ };+}++export function parseHeaderLines(text: string): Record<string, string[]> {+ const out: Record<string, string[]> = {};+ for (const rawLine of text.split(/\r?\n/)) {+ const line = rawLine.trim();+ if (!line) continue;+ const colon = line.indexOf(":");+ if (colon <= 0) continue;+ const name = line.slice(0, colon).trim();+ const value = line.slice(colon + 1).trim();+ if (!name) continue;+ if (!out[name]) out[name] = [];+ out[name].push(value);+ }+ return out;+}++export function formatHeaderLines(headers?: Record<string, string[]> | null): string {+ if (!headers) return "";+ const lines: string[] = [];+ for (const name of Object.keys(headers).sort()) {+ const vals = headers[name] ?? [];+ for (const v of vals) {+ lines.push(`${name}: ${v}`);+ }+ }+ return lines.join("\n");+}++export function parseHeaderMatcherLines(text: string): TamperHookHeaderMatcher[] {+ const out: TamperHookHeaderMatcher[] = [];+ for (const rawLine of text.split(/\r?\n/)) {+ const line = rawLine.trim();+ if (!line) continue;+ const colon = line.indexOf(":");+ if (colon < 0) {+ out.push({ name: line });+ continue;+ }+ const name = line.slice(0, colon).trim();+ const valueRegex = line.slice(colon + 1).trim();+ if (!name) continue;+ out.push(valueRegex ? { name, value_regex: valueRegex } : { name });+ }+ return out;+}++export function formatHeaderMatcherLines(matchers?: TamperHookHeaderMatcher[]): string {+ if (!matchers?.length) return "";+ return matchers.map((m) => (m.value_regex ? `${m.name}: ${m.value_regex}` : m.name)).join("\n");+}++export function parseCsvList(text: string, upper = false): string[] {+ return text+ .split(",")+ .map((s) => (upper ? s.trim().toUpperCase() : s.trim()))+ .filter(Boolean);+}++export function buildMatchers(fields: {+ methods: string;+ host: string;+ urlRegex: string;+ headers: string;+ bodyRegex: string;+ status: string;+ respHeaders: string;+ respBodyRegex: string;+ phase: "request" | "response";+}): TamperHookMatchers {+ const out: TamperHookMatchers = {};+ const methods = parseCsvList(fields.methods, true);+ if (methods.length) out.methods = methods;+ if (fields.host.trim()) out.host = fields.host.trim();+ if (fields.urlRegex.trim()) out.url_regex = fields.urlRegex.trim();+ const headers = parseHeaderMatcherLines(fields.headers);+ if (headers.length) out.headers = headers;+ if (fields.bodyRegex.trim()) out.body_regex = fields.bodyRegex.trim();+ if (fields.phase === "response") {+ const status = parseCsvList(fields.status, false);+ if (status.length) out.status = status;+ const respHeaders = parseHeaderMatcherLines(fields.respHeaders);+ if (respHeaders.length) out.resp_headers = respHeaders;+ if (fields.respBodyRegex.trim()) out.resp_body_regex = fields.respBodyRegex.trim();+ }+ return out;+}++// Decode Go's JSON-marshaled []byte (base64 string) into UTF-8 text.+export function decodeTraceAfter(after: string | null | undefined): string | null {+ if (after === null || after === undefined) return null;+ if (after === "") return "";+ try {+ const binary = atob(after);+ const bytes = new Uint8Array(binary.length);+ for (let i = 0; i < binary.length; i++) {+ bytes[i] = binary.charCodeAt(i);+ }+ return new TextDecoder("utf-8", { fatal: false }).decode(bytes);+ } catch {+ return after;+ }+}++// A trace line is masked/tainted when:+// - Outcome is "applied" and After is null (plaintext suppressed), OR+// - BeforeHash/AfterHash is a 128-bit keyed HMAC fingerprint (32 hex chars) instead of SHA-256 (64 hex chars).+export function isTraceLineMasked(line: TamperTraceLine): boolean {+ const isHmac = (h: string) => /^[0-9a-f]{32}$/i.test(h);+ if (isHmac(line.BeforeHash) || isHmac(line.AfterHash)) return true;+ return line.Outcome === "applied" && line.After === null;+}diff --git a/web/src/lib/types.ts b/web/src/lib/types.tsindex 10e6e03..798b5a3 100644--- a/web/src/lib/types.ts+++ b/web/src/lib/types.ts@@ -1750,3 +1750,117 @@ export interface InterceptExecution {seq: number;items: Activity[];}++// ---- capture-proxy constrained Go tampering hooks (P4.2) ----+export type TamperHookPhase = "request" | "response";++export interface TamperHookHeaderMatcher {+ name: string;+ value_regex?: string;+}++export interface TamperHookMatchers {+ methods?: string[];+ host?: string;+ url_regex?: string;+ headers?: TamperHookHeaderMatcher[];+ body_regex?: string;+ status?: string[];+ resp_headers?: TamperHookHeaderMatcher[];+ resp_body_regex?: string;+}++export interface TamperHookLastError {+ class: string;+ at: string;+ count: number;+}++export interface TamperHook {+ id: number;+ name: string;+ enabled: boolean;+ phase: TamperHookPhase;+ priority: number;+ matchers: TamperHookMatchers;+ source: string;+ source_sha256: string;+ version: number;+ note: string;+ created_at: string;+ updated_at: string;+ load_error?: string;+ last_error?: TamperHookLastError | null;+}++export interface TamperHooksListResp {+ hooks: TamperHook[];+ enabled_by_env: boolean;+}++export interface TamperHookVersion {+ id: number;+ hook_id: number;+ version: number;+ name: string;+ phase: TamperHookPhase;+ priority: number;+ matchers: TamperHookMatchers;+ source: string;+ source_sha256: string;+ note: string;+ created_at: string;+}++export interface TamperHookInput {+ name: string;+ enabled?: boolean;+ phase: TamperHookPhase;+ priority: number;+ matchers: TamperHookMatchers;+ source: string;+ note?: string;+}++export interface TamperDryRunIO {+ request: {+ method: string;+ url: string;+ headers: Record<string, string[]>;+ body: string;+ };+ response: {+ status: number;+ headers: Record<string, string[]>;+ body: string;+ };+}++export interface TamperDryRunRequest extends TamperDryRunIO {+ hook_id?: number;+ name?: string;+ phase?: TamperHookPhase;+ matchers?: TamperHookMatchers;+ source?: string;+}++export interface TamperTraceLine {+ Phase: string;+ SourceKind: string;+ RuleID: number;+ HookID: number;+ HookVersion: number;+ RuleSnapshot: string;+ Action: string;+ Field: string;+ Outcome: string;+ Reason: string;+ BeforeHash: string;+ AfterHash: string;+ After: string | null;+}++export interface TamperDryRunResult extends TamperDryRunIO {+ changed: boolean;+ lines: TamperTraceLine[] | null;+}