diff --git a/web/package.json b/web/package.json index e37dc6099..70e9c00fc 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.mjs new file mode 100644 index 000000000..31ef1315f --- /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.tsx new file mode 100644 index 000000000..1034d58f7 --- /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; + source: string; + }; +} + +export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: TrafficExchange[] }) { + const [hooks, setHooks] = React.useState([]); + const [enabledByEnv, setEnabledByEnv] = React.useState(true); + const [loading, setLoading] = React.useState(true); + const [loadError, setLoadError] = React.useState(null); + const [togglingId, setTogglingId] = React.useState(null); + + // Create / Edit dialog state + const [editor, setEditor] = React.useState(null); + const [saving, setSaving] = React.useState(false); + const [formError, setFormError] = React.useState(null); + + // Delete confirmation + const [deleteTarget, setDeleteTarget] = React.useState(null); + const [deleting, setDeleting] = React.useState(false); + + // Versions sheet + const [versionsHook, setVersionsHook] = React.useState(null); + const [versions, setVersions] = React.useState([]); + const [versionsLoading, setVersionsLoading] = React.useState(false); + const [expandedVersion, setExpandedVersion] = React.useState(null); + const [rollbackTarget, setRollbackTarget] = React.useState(null); + const [rollingBack, setRollingBack] = React.useState(false); + + // Dry-run sheet + const [dryRunTarget, setDryRunTarget] = React.useState(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(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(null); + const [dryRunResult, setDryRunResult] = React.useState(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 ( +
+ {!enabledByEnv && ( + + + + {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.", + )} + + + )} + + {loadError && ( + + {loadError} + + )} + +
+

+ {t( + "Operator-only Go-subset tampering hooks run after declarative rewrite rules per phase and fail open on error.", + )} +

+
+ + +
+
+ + + + + + {t("Name")} + {t("Phase")} + {t("Priority")} + {t("Version")} + {t("Enabled")} + {t("Last error")} + {t("Actions")} + + + + {loading && hooks.length === 0 ? ( + + + + {t("Loading hooks…")} + + + ) : hooks.length === 0 ? ( + + + {t("No tampering hooks configured yet.")} + + + ) : ( + hooks.map((hook) => ( + + +
{hook.name}
+ {hook.note &&
{hook.note}
} +
+ + + {hook.phase} + + + {hook.priority} + v{hook.version} + + void handleToggle(hook, checked)} + /> + + + {hook.load_error ? ( + + + + + {t("load_error")} + + + {hook.load_error} + + ) : hook.last_error ? ( + + + + + {hook.last_error.class} ({hook.last_error.count}) + + + + {t("Last seen at {time}", { time: fmtDateTime(hook.last_error.at) })} + + + ) : ( + + + {t("None")} + + )} + + +
+ + + + +
+
+
+ )) + )} +
+
+
+ + {/* Create / Edit Dialog */} + { + if (!open) { + setEditor(null); + setFormError(null); + } + }} + > + + + {editor?.mode === "edit" ? t("Edit tampering hook") : t("New tampering hook")} + + {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.")} + + + + {editor && ( +
+ {formError && ( + + + {formError} + + )} + +
+
+ + setEditor({ ...editor, name: e.target.value })} + /> +
+
+ + +
+
+ + setEditor({ ...editor, priority: e.target.value })} + /> +
+
+ +
+ + setEditor({ ...editor, note: e.target.value })} + /> +
+ + {/* Matchers */} +
+
+ {t("Matchers (prefilter — empty matches all)")} +
+
+
+ + setEditor({ ...editor, methods: e.target.value })} + /> +
+
+ + setEditor({ ...editor, host: e.target.value })} + /> +
+
+ + setEditor({ ...editor, urlRegex: e.target.value })} + /> +
+
+ + setEditor({ ...editor, bodyRegex: e.target.value })} + /> +
+
+
+ +