Repository navigation
Expand file tree
/
Copy pathproxy.js
More file actions
2668 lines (2475 loc) · 133 KB
/
Copy pathproxy.js
File metadata and controls
2668 lines (2475 loc) · 133 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const HELP_TEXT = [
"Ares Proxy - standalone inspection and forwarding proxy",
"",
"Usage: node proxy.js [options]",
"",
"Options:",
" -h, --help Show this help and exit",
" --listen HOST:PORT Proxy listener (default 127.0.0.1:8787)",
" --gui [HOST:PORT] Enable GUI (default 127.0.0.1:8790)",
" --forward HOST:PORT Override the gateway destination",
" --forwarding Use --forward as an upstream HTTP proxy",
"",
"Forwarding modes:",
" --forward alone overrides origin-form gateway destinations.",
" --forwarding chains all HTTP, HTTPS, and CONNECT traffic through",
" the unauthenticated HTTP proxy specified by --forward/FORWARD_TARGET.",
"",
"Environment:",
" PROXY_HOST, PROXY_PORT, GUI, GUI_BIND, FORWARD_TARGET, FORWARDING",
" DEFAULT_PROVIDER, ANTHROPIC_ENDPOINT, OPENAI_ENDPOINT,",
" OPENAI_CHATGPT_ENDPOINT, NEXT_HOP_ENDPOINT",
" ANTHROPIC_API_KEY, OPENAI_API_KEY, API_KEY",
" DATA_LOG, BODY_DIR, BODY_CAP, BODY_KEEP, RULES_FILE",
" GUI_CONFIG_FILE, DEBUG_BODIES, DEBUG_CAP, DUMP_PROMPT,",
" DISABLE_UPSTREAM_WS",
"",
"Precedence: CLI > environment > persisted GUI config > defaults.",
"",
"Examples:",
" node proxy.js",
" node proxy.js --gui",
" node proxy.js --forward 10.13.37.5:8080",
" node proxy.js --forward 10.13.37.5:8080 --forwarding",
"",
"WARNING: The GUI has no authentication. Keep its default loopback bind",
"unless you intentionally accept exposure on a trusted network."
].join("\n");
function isHelpRequest(argv) {
return argv.includes("--help") || argv.includes("-h");
}
function unknownCliOption(argv) {
const exact = new Set(["-h", "--help", "--listen", "--gui", "--forward", "--forwarding"]);
return argv.find((arg) =>
arg.startsWith("-") &&
!exact.has(arg) &&
!arg.startsWith("--listen=") &&
!arg.startsWith("--gui=") &&
!arg.startsWith("--forward=")
) || null;
}
if (require.main === module) {
const earlyArgv = process.argv.slice(2);
if (isHelpRequest(earlyArgv)) {
process.stdout.write(HELP_TEXT + "\n");
process.exit(0);
}
const unknown = unknownCliOption(earlyArgv);
if (unknown) {
process.stderr.write("Unknown option: " + unknown + "\nUse --help for usage.\n");
process.exit(1);
}
}
const http = require("http");
const https = require("https");
const net = require("net");
const path = require("path");
const tls = require("tls");
const fs = require("fs");
function runtimeStoragePath(explicit, privilegedPath, localName, options = {}) {
if (explicit) return explicit;
const cwd = options.cwd || process.cwd();
const canWrite = options.canWrite || ((candidate) => {
try {
const probe = fs.existsSync(candidate) ? candidate : path.dirname(candidate);
fs.accessSync(probe, fs.constants.W_OK);
return true;
} catch (_) {
return false;
}
});
return canWrite(privilegedPath)
? privilegedPath
: path.resolve(cwd, localName);
}
// --- Option parsing ------------------------------------------------
class OptionError extends Error {
constructor(message) {
super(message);
this.name = "OptionError";
}
}
function parsePort(value, label) {
const port = Number(value);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new OptionError(label + " has an invalid port: \"" + value + "\"");
}
return port;
}
function parseAddress(spec, defaults = { host: "127.0.0.1", port: 0 }) {
if (typeof spec !== "string" || !spec.trim()) {
throw new OptionError("Address must be a non-empty HOST:PORT value");
}
const value = spec.trim();
let host;
let portText;
if (value.startsWith("[")) {
const match = value.match(/^\[([^\]]+)\]:(\d+)$/);
if (!match) throw new OptionError("Invalid bracketed IPv6 address: \"" + value + "\"");
host = match[1];
portText = match[2];
} else {
const colonCount = (value.match(/:/g) || []).length;
if (colonCount > 1) {
throw new OptionError("IPv6 addresses must use bracket notation: \"" + value + "\"");
}
if (colonCount === 0) {
host = defaults.host;
portText = value;
} else {
const parts = value.split(":");
const left = parts[0];
const right = parts[1];
if (!left && right) {
host = defaults.host;
portText = right;
} else if (/^\d+$/.test(left) && right && !/^\d+$/.test(right)) {
host = right;
portText = left;
} else {
host = left;
portText = right;
}
}
}
if (!host || !portText) throw new OptionError("Invalid address: \"" + value + "\"");
if (/\s/.test(host) || /[/?#]/.test(host)) {
throw new OptionError("Invalid host in address: \"" + value + "\"");
}
return { host, port: parsePort(portText, "Address \"" + value + "\"") };
}
function parseBoolean(value, label) {
if (typeof value === "boolean") return value;
const normalized = String(value).trim().toLowerCase();
if (["1", "true", "yes", "on"].includes(normalized)) return true;
if (["0", "false", "no", "off", ""].includes(normalized)) return false;
throw new OptionError(label + " must be a boolean (1/0, true/false, yes/no, on/off)");
}
function loadPersistedConfig(filename) {
try {
const parsed = JSON.parse(fs.readFileSync(filename, "utf8"));
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
} catch (_) {
return {};
}
}
function readCli(argv) {
const cli = {};
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
const takeValue = (name) => {
const value = argv[index + 1];
if (!value || value.startsWith("--")) {
throw new OptionError(name + " requires an address");
}
index += 1;
return value;
};
if (arg === "--listen") cli.listen = takeValue("--listen");
else if (arg.startsWith("--listen=")) cli.listen = arg.slice(9);
else if (arg === "--gui") {
cli.guiEnabled = true;
if (argv[index + 1] && !argv[index + 1].startsWith("--")) {
cli.guiBind = argv[index + 1];
index += 1;
}
} else if (arg.startsWith("--gui=")) {
cli.guiEnabled = true;
cli.guiBind = arg.slice(6);
} else if (arg === "--forward") cli.forwardTarget = takeValue("--forward");
else if (arg.startsWith("--forward=")) cli.forwardTarget = arg.slice(10);
else if (arg === "--forwarding") cli.forwarding = true;
else throw new OptionError("Unknown option: " + arg);
}
return cli;
}
function parseProxyOptions(argv = [], env = {}, persisted = {}) {
const cli = readCli(argv);
const envListenSet = env.PROXY_HOST !== undefined || env.PROXY_PORT !== undefined;
const listenBase = {
host: env.PROXY_HOST || "127.0.0.1",
port: parsePort(env.PROXY_PORT || 8787, "PROXY_PORT"),
};
const listen = cli.listen ? parseAddress(cli.listen, listenBase) : listenBase;
const envGuiSet = env.GUI !== undefined || env.GUI_BIND !== undefined;
const guiEnabled = cli.guiEnabled !== undefined
? cli.guiEnabled
: env.GUI !== undefined ? parseBoolean(env.GUI, "GUI") : false;
const guiSpec = cli.guiBind || env.GUI_BIND || "127.0.0.1:8790";
const guiBind = parseAddress(guiSpec, { host: "127.0.0.1", port: 8790 });
const envForwardSet = env.FORWARD_TARGET !== undefined;
const forwardSpec = cli.forwardTarget !== undefined
? cli.forwardTarget
: envForwardSet ? env.FORWARD_TARGET : persisted.forwardTarget;
const forwardTarget = forwardSpec
? parseAddress(forwardSpec, { host: "127.0.0.1", port: 8080 })
: null;
const envForwardingSet = env.FORWARDING !== undefined;
const forwarding = cli.forwarding !== undefined
? cli.forwarding
: envForwardingSet
? parseBoolean(env.FORWARDING, "FORWARDING")
: parseBoolean(persisted.forwarding || false, "persisted forwarding");
if (forwarding && !forwardTarget) {
throw new OptionError("Forwarding mode requires --forward or FORWARD_TARGET");
}
return {
listen,
gui: { enabled: guiEnabled, ...guiBind },
forwardTarget,
forwarding,
guiConfigFile: env.GUI_CONFIG_FILE || path.resolve(process.cwd(), "proxy-gui-config.json"),
locks: {
listen: cli.listen !== undefined || envListenSet,
gui: cli.guiEnabled !== undefined || envGuiSet,
forwardTarget: cli.forwardTarget !== undefined || envForwardSet,
forwarding: cli.forwarding !== undefined || envForwardingSet,
},
};
}
// --- Runtime forwarding ------------------------------------------------
function copyTarget(target) {
return target ? { host: target.host, port: Number(target.port) } : null;
}
function createRuntimeConfig(initial = {}) {
let state = {
forwardTarget: copyTarget(initial.forwardTarget),
forwarding: Boolean(initial.forwarding),
};
return {
snapshot() {
return { ...state, forwardTarget: copyTarget(state.forwardTarget) };
},
update(patch = {}) {
const next = { ...state };
if (Object.prototype.hasOwnProperty.call(patch, "forwardTarget")) {
next.forwardTarget = copyTarget(patch.forwardTarget);
}
if (Object.prototype.hasOwnProperty.call(patch, "forwarding")) {
next.forwarding = Boolean(patch.forwarding);
}
if (next.forwarding && !next.forwardTarget) {
throw new Error("Forwarding mode requires a forward target");
}
state = next;
return this.snapshot();
},
};
}
function selectHttpDispatch({ target, providerTarget, runtime }) {
const config = runtime.snapshot();
if (target.isGateway && config.forwardTarget && !config.forwarding) {
return {
...config.forwardTarget,
client: http,
path: target.path,
isGateway: true,
provider: providerTarget.provider,
forwardMode: "destination",
logicalDest: providerTarget.host,
};
}
return {
...providerTarget,
forwardMode: config.forwardTarget && config.forwarding ? "chain" : "automatic",
logicalDest: providerTarget.host,
};
}
function formatAuthority(host, port) {
const printableHost = host.includes(":") ? "[" + host + "]" : host;
return printableHost + ":" + port;
}
// --- HTTP proxy chaining ------------------------------------------------
function authority(host, port) {
return (host.includes(":") ? "[" + host + "]" : host) + ":" + port;
}
function absoluteUrl(target, requestPath) {
const scheme = target.client === https ? "https" : "http";
const defaultPort = scheme === "https" ? 443 : 80;
const host = target.port === defaultPort ? target.host : authority(target.host, target.port);
const path = requestPath.startsWith("/") ? requestPath : "/" + requestPath;
return scheme + "://" + host + path;
}
function connectThroughHttpProxy(proxy, targetAuthority, callback) {
let settled = false;
const done = (error, socket, head) => {
if (settled) {
if (socket) socket.destroy();
return;
}
settled = true;
callback(error, socket, head);
};
const req = http.request({
hostname: proxy.host,
port: proxy.port,
method: "CONNECT",
path: targetAuthority,
headers: { host: targetAuthority },
});
req.on("connect", (res, socket, head) => {
if (res.statusCode < 200 || res.statusCode >= 300) {
socket.destroy();
const error = new Error("Upstream proxy rejected CONNECT with " + res.statusCode);
error.statusCode = res.statusCode;
done(error);
return;
}
done(null, socket, head);
});
req.on("error", (error) => done(error));
req.end();
return req;
}
function requestThroughHttpProxy(proxy, target, options, onResponse) {
if (target.client !== https) {
return http.request({
hostname: proxy.host,
port: proxy.port,
method: options.method,
path: absoluteUrl(target, options.path),
headers: options.headers,
}, onResponse);
}
const agent = new https.Agent({ keepAlive: false });
agent.createConnection = (_options, callback) => {
const targetAuthority = authority(target.host, target.port);
connectThroughHttpProxy(proxy, targetAuthority, (error, socket, head) => {
if (error) return callback(error);
if (head && head.length) socket.unshift(head);
const secure = tls.connect({
socket,
servername: net.isIP(target.host) ? undefined : target.host,
});
secure.once("secureConnect", () => callback(null, secure));
secure.once("error", callback);
});
};
return https.request({
hostname: target.host,
port: target.port,
method: options.method,
path: options.path,
headers: options.headers,
agent,
}, onResponse);
}
function requestClient(target, runtime) {
const config = runtime.snapshot();
if (!config.forwarding || !config.forwardTarget) return target.client;
return {
request(options, onResponse) {
return requestThroughHttpProxy(config.forwardTarget, target, options, onResponse);
},
};
}
function installConnectHandler(server, runtime, logger = console.error) {
server.on("connect", (req, clientSocket, head) => {
const targetAuthority = req.url || "";
const split = targetAuthority.lastIndexOf(":");
const host = split === -1 ? targetAuthority : targetAuthority.slice(0, split);
const port = split === -1 ? 443 : Number(targetAuthority.slice(split + 1)) || 443;
if (!host) {
clientSocket.end("HTTP/1.1 400 Bad Request\r\n\r\n");
return;
}
let upstream;
let established = false;
const teardown = (error) => {
if (error) logger("tunnel error " + host + ":" + port + ": " + error.message);
if (!established && clientSocket.writable) {
clientSocket.end("HTTP/1.1 502 Bad Gateway\r\n\r\n");
} else {
clientSocket.destroy();
}
if (upstream) upstream.destroy();
};
const connected = (socket, proxyHead) => {
upstream = socket;
established = true;
if (proxyHead && proxyHead.length) upstream.unshift(proxyHead);
clientSocket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
if (head && head.length) upstream.write(head);
upstream.pipe(clientSocket);
clientSocket.pipe(upstream);
upstream.on("error", teardown);
upstream.on("close", () => clientSocket.destroy());
};
const config = runtime.snapshot();
if (config.forwarding && config.forwardTarget) {
connectThroughHttpProxy(config.forwardTarget, authority(host, port), (error, socket, proxyHead) => {
if (error) teardown(error);
else connected(socket, proxyHead);
});
} else {
upstream = net.connect(port, host, () => connected(upstream));
upstream.on("error", teardown);
}
clientSocket.on("error", teardown);
clientSocket.on("close", () => { if (upstream) upstream.destroy(); });
});
}
// --- GUI API server ------------------------------------------------
const BODY_KINDS = new Set(["req", "res", "sys", "syso", "usr", "usro", "out"]);
const JSON_LIMIT = 64 * 1024;
function json(res, status, value) {
const body = JSON.stringify(value);
res.writeHead(status, {
"content-type": "application/json; charset=utf-8",
"content-length": Buffer.byteLength(body),
"cache-control": "no-store",
});
res.end(body);
}
function apiError(res, status, code, message) {
json(res, status, { error: { code, message } });
}
function readJson(req) {
return new Promise((resolve, reject) => {
let size = 0;
const chunks = [];
req.on("data", (chunk) => {
size += chunk.length;
if (size > JSON_LIMIT) {
const error = new Error("JSON body exceeds 64 KiB");
error.code = "BODY_TOO_LARGE";
reject(error);
req.destroy();
return;
}
chunks.push(chunk);
});
req.on("end", () => {
try {
const text = Buffer.concat(chunks).toString("utf8");
resolve(text ? JSON.parse(text) : {});
} catch (_) {
const error = new Error("Request body must be valid JSON");
error.code = "INVALID_JSON";
reject(error);
}
});
req.on("error", reject);
});
}
function printableAddress(target) {
if (!target) return null;
const host = target.host.includes(":") ? "[" + target.host + "]" : target.host;
return host + ":" + target.port;
}
function readSessions(filename, limit = 400) {
let lines;
try {
lines = fs.readFileSync(filename, "utf8").trim().split("\n").filter(Boolean).slice(-limit * 3);
} catch (_) {
return [];
}
const sessions = new Map();
for (const line of lines) {
let entry;
try { entry = JSON.parse(line); } catch (_) { continue; }
if (!entry || !entry.sid) continue;
const current = sessions.get(entry.sid) || { sid: entry.sid, request: null, response: null };
if (entry.dir === "req") current.request = entry;
if (entry.dir === "res") current.response = entry;
current.ts = entry.ts || current.ts;
sessions.set(entry.sid, current);
}
return Array.from(sessions.values()).slice(-limit).reverse();
}
function readRules(filename) {
try {
const rules = JSON.parse(fs.readFileSync(filename, "utf8"));
return Array.isArray(rules) ? rules : [];
} catch (_) {
return [];
}
}
function validateRules(rules) {
if (!Array.isArray(rules) || rules.length > 1000) {
throw new Error("rules must be an array containing at most 1000 entries");
}
return rules.map((rule, index) => {
if (!rule || typeof rule !== "object" || Array.isArray(rule)) {
throw new Error("rule " + index + " must be an object");
}
const match = String(rule.match || "");
if (!match || match.length > 10000) throw new Error("rule " + index + " has an invalid match value");
if (rule.regex) {
try { new RegExp(match, "g"); }
catch (error) { throw new Error("rule " + index + " has invalid regex: " + error.message); }
}
if (rule.scope !== undefined && !["all", "system", "user"].includes(rule.scope)) throw new Error("rule " + index + " has an invalid scope");
if (rule.provider !== undefined && !["both", "anthropic", "openai"].includes(rule.provider)) throw new Error("rule " + index + " has an invalid provider");
return {
id: String(rule.id || (Date.now().toString(36) + "-" + index)).slice(0, 80),
match,
replace: String(rule.replace || "").slice(0, 10000),
...(rule.scope !== undefined ? { scope: rule.scope } : {}),
...(rule.provider !== undefined ? { provider: rule.provider } : {}),
...(rule.regex !== undefined ? { regex: Boolean(rule.regex) } : {}),
enabled: rule.enabled !== false,
};
});
}
const GUI_HTML = String.raw`<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="dark">
<title>Ares Proxy Console</title>
<link rel="stylesheet" href="/assets/app.css">
</head>
<body>
<div class="scanlines" aria-hidden="true"></div>
<header class="app-header">
<a class="brand" href="#console" aria-label="Ares Proxy home">
<span class="brand-mark" aria-hidden="true">A</span>
<span><strong>ARES PROXY</strong><small>STANDALONE INSPECTION</small></span>
</a>
<nav class="tabs" aria-label="Primary">
<button id="console-tab" class="tab active" role="tab" aria-selected="true" aria-controls="console-panel">Console</button>
<button id="command-tab" class="tab" role="tab" aria-selected="false" aria-controls="command-panel">Command Center</button>
</nav>
<div class="header-status mono" aria-label="Listener status">
<span><small>PROXY</small><b id="proxy-bind">—</b><i class="live-dot"></i></span>
<span><small>GUI BIND</small><b id="gui-bind">—</b><i class="live-dot"></i></span>
</div>
</header>
<main>
<section id="console-panel" class="tab-panel console-grid" role="tabpanel" aria-labelledby="console-tab">
<aside class="operations panel">
<div class="panel-title"><span>OPERATIONS</span><small>LIVE SIGNAL</small></div>
<div id="traffic-radar" class="radar" aria-label="Animated traffic radar">
<span class="radar-axis north">000</span><span class="radar-axis east">090</span>
<span class="radar-axis south">180</span><span class="radar-axis west">270</span>
<div id="radar-contacts" class="radar-contacts" aria-live="polite"></div>
<div class="radar-sweep" aria-hidden="true"></div>
</div>
<dl class="metrics mono">
<div><dt>REQUESTS</dt><dd id="metric-requests">0</dd></div>
<div><dt>ACTIVE</dt><dd id="metric-active">0</dd></div>
<div><dt>FAILURES</dt><dd id="metric-failures">0</dd></div>
<div><dt>LATENCY P50</dt><dd id="metric-latency">—</dd></div>
</dl>
<div class="mini-section"><h3>RECENT FAILURES</h3><ol id="failure-list" class="failure-list mono"><li>No failures detected</li></ol></div>
<div class="health mono"><span><small>ENGINE</small><b>ONLINE</b></span><span><small>CAPTURE</small><b id="capture-state">FOLLOW</b></span></div>
</aside>
<section class="traffic panel">
<div class="traffic-heading">
<div><small>INTERCEPTED COMMUNICATIONS</small><h1>LIVE TRAFFIC STREAM</h1></div>
<span id="stream-count" class="count mono">0 SESSIONS</span>
</div>
<div class="stream-tools">
<label class="search"><span class="sr-only">Filter sessions</span><input id="session-filter" type="search" placeholder="Filter method, path, model, status, destination or content…"></label>
<button id="follow-toggle" class="btn signal" type="button" aria-pressed="true">● FOLLOW</button>
<label class="sort-control mono">SORT<select id="session-sort-field"><option value="time">TIME</option><option value="status">STATUS</option><option value="latency">LATENCY</option><option value="method">METHOD</option><option value="provider">PROVIDER / MODEL</option></select></label>
<button id="session-sort-direction" class="btn" type="button" aria-label="Descending">DESC</button>
<button id="export-sessions" class="btn" type="button">EXPORT</button>
<button id="clear-sessions" class="btn danger" type="button">CLEAR</button>
</div>
<div class="session-head mono" aria-hidden="true"><span>TIME</span><span>METHOD</span><span>PATH / DESTINATION</span><span>STATUS</span><span>DURATION</span></div>
<div id="session-stream" class="session-stream" aria-live="polite"><div class="empty-state">Awaiting intercepted traffic<span>Radar acquisition is active</span></div></div>
</section>
<aside class="context panel">
<div class="panel-title"><span>CONTEXT</span><small>ROUTING</small></div>
<section><h3>FORWARDING TARGET</h3><dl class="context-list mono"><div><dt>TARGET</dt><dd id="context-target">AUTOMATIC</dd></div><div><dt>MODE</dt><dd id="context-mode">PROVIDER ROUTING</dd></div><div><dt>STATE</dt><dd id="context-state" class="signal-text">ACTIVE</dd></div></dl></section>
<section><h3>PROVIDER ROUTES</h3><dl id="context-providers" class="context-list mono"></dl></section>
<div class="context-note"><b>CONFIGURATION</b><p>Edit destinations, forwarding behavior, inspection retention and rewrite rules in Command Center.</p><button class="text-action" data-open-command type="button">OPEN COMMAND CENTER →</button></div>
</aside>
</section>
<section id="command-panel" class="tab-panel command" role="tabpanel" aria-labelledby="command-tab" hidden>
<div id="app-status" class="announcement" role="status" aria-live="polite"><span>●</span><p>Configuration interface ready.</p></div>
<div class="command-grid">
<section class="settings-panel network"><div class="section-head"><h2>NETWORK</h2><small>RESTART BOUND</small></div><div class="field-row"><label>Proxy listener</label><input id="listener-display" class="mono" readonly><span class="lock">READ ONLY</span></div><div class="field-row"><label>GUI bind</label><input id="gui-display" class="mono" readonly><span class="lock">READ ONLY</span></div><p class="help">Listener and GUI bind changes require a process restart. Supply them through CLI or environment options.</p></section>
<section class="settings-panel forwarding"><div class="section-head"><h2>FORWARDING</h2><small id="forward-lock-state">RUNTIME EDITABLE</small></div>
<div class="mode-line"><span>Mode</span><div id="forwarding-mode" class="segmented" role="group" aria-label="Forwarding mode"><button type="button" data-mode="destination" class="active">DESTINATION OVERRIDE</button><button type="button" data-mode="chain">UPSTREAM PROXY CHAIN</button></div></div>
<div class="target-line"><label for="forward-target">Target (IP or hostname:port)</label><div><input id="forward-target" class="mono" placeholder="10.13.37.5:8080"><button id="test-forward" class="btn" type="button">TEST CONNECTION</button></div></div>
<p id="mode-description" class="help">Origin-form API requests are sent directly to this target. Absolute-form and CONNECT traffic retain client-selected destinations.</p>
<div class="actions"><button id="apply-config" class="btn primary" type="button">APPLY CONFIGURATION</button><button id="disable-forward" class="btn danger" type="button">DISABLE FORWARDING</button></div>
</section>
<section id="provider-settings" class="settings-panel providers"><div class="section-head"><h2>PROVIDERS</h2><small>NO KEYS EXPOSED</small></div><label>Anthropic endpoint<input id="provider-anthropic" class="mono" type="url"></label><label>OpenAI endpoint<input id="provider-openai" class="mono" type="url"></label><label>ChatGPT Codex endpoint<input id="provider-chatgpt" class="mono" type="url"></label><p class="help">Endpoint changes affect subsequent gateway requests. Credentials remain environment-only.</p></section>
<section id="inspection-settings" class="settings-panel inspection"><div class="section-head"><h2>INSPECTION</h2><small>CAPTURE POLICY</small></div><div class="switch-line"><span><b>Debug body logging</b><small>Write full redacted headers and bodies to the process log.</small></span><button id="debug-toggle" class="switch" type="button" role="switch" aria-checked="false"><i></i></button></div><label>Body size cap (bytes)<input id="body-cap" class="mono" type="number" min="1024"></label><label>Retained body files<input id="body-keep" class="mono" type="number" min="1"></label><dl class="paths mono"><div><dt>DATA LOG</dt><dd id="data-log-path">—</dd></div><div><dt>BODY STORE</dt><dd id="body-dir-path">—</dd></div><div><dt>RULES FILE</dt><dd id="rules-file-path">—</dd></div></dl></section>
<section class="settings-panel rules"><div class="rules-toolbar"><div class="section-head"><h2>REWRITE RULES</h2><small id="rules-count">0 RULES</small></div><div><button id="add-rule" class="btn" type="button">+ ADD RULE</button><button id="import-rules" class="btn" type="button">IMPORT</button><button id="export-rules" class="btn" type="button">EXPORT</button><input id="rules-file-input" type="file" accept="application/json,.json" hidden></div></div>
<div class="table-wrap"><table id="rules-table"><thead><tr><th>ENABLED</th><th>PROVIDER</th><th>SCOPE</th><th>FIND</th><th>REPLACE</th><th>TYPE</th><th></th></tr></thead><tbody></tbody></table></div>
<div id="rule-editor" class="rule-editor" hidden><label>Find<input id="rule-match" class="mono"></label><label>Replace<input id="rule-replace" class="mono"></label><label>Provider<select id="rule-provider"><option value="both">Both</option><option value="anthropic">Anthropic</option><option value="openai">OpenAI</option></select></label><label>Scope<select id="rule-scope"><option value="all">All prompts</option><option value="system">System</option><option value="user">User</option></select></label><label class="check"><input id="rule-regex" type="checkbox"> Regex</label><button id="save-rule" class="btn primary" type="button">SAVE RULE</button><button id="cancel-rule" class="btn" type="button">CANCEL</button></div>
</section>
</div>
</section>
</main>
<div id="toast-region" class="toasts" aria-live="polite"></div>
<script src="/assets/app.js" defer></script>
</body>
</html>
`;
const GUI_CSS = String.raw`:root{--bg:#050607;--surface:#090b0d;--surface-2:#0d1012;--surface-3:#111416;--line:#342027;--line-hot:#8a202e;--signal:#ff3349;--signal-soft:#ff6576;--text:#eee8e9;--muted:#8f8588;--dim:#5d5658;--ok:#ff5266;--shadow:0 0 28px rgba(255,31,58,.12);--mono:"Cascadia Mono","SFMono-Regular",Consolas,monospace;--sans:Inter,"Segoe UI",system-ui,sans-serif}
[hidden]{display:none!important}*{box-sizing:border-box}html,body{min-height:100%;margin:0;background:var(--bg);color:var(--text);font-family:var(--sans)}body{background-image:radial-gradient(circle at 12% 16%,rgba(128,11,28,.13),transparent 27%),linear-gradient(rgba(255,255,255,.012) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,.012) 1px,transparent 1px);background-size:auto,28px 28px,28px 28px}.scanlines{position:fixed;inset:0;pointer-events:none;z-index:90;background:repeating-linear-gradient(0deg,transparent 0 3px,rgba(255,31,54,.018) 4px);mix-blend-mode:screen}.mono{font-family:var(--mono)}button,input,select{font:inherit;color:inherit}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
.app-header{height:72px;display:flex;align-items:stretch;border-bottom:1px solid var(--line-hot);background:rgba(7,8,9,.96);position:sticky;top:0;z-index:50;box-shadow:0 10px 35px rgba(0,0,0,.45)}.brand{width:310px;padding:0 24px;display:flex;gap:14px;align-items:center;color:var(--text);text-decoration:none;border-right:1px solid var(--line)}.brand-mark{width:36px;height:40px;display:grid;place-items:center;color:var(--signal);font:900 31px/1 var(--mono);transform:skew(-8deg);text-shadow:0 0 20px rgba(255,35,63,.5)}.brand strong{font:800 19px/1.1 var(--mono);letter-spacing:.12em}.brand small{display:block;color:var(--signal-soft);font:700 11px/1.8 var(--mono);letter-spacing:.13em}.tabs{display:flex;margin-left:32px}.tab{min-width:176px;border:0;border-left:1px solid transparent;border-right:1px solid transparent;background:transparent;color:#aaa1a3;font:700 12px var(--mono);letter-spacing:.07em;cursor:pointer}.tab:hover{color:#fff;background:#100c0e}.tab.active{color:var(--signal-soft);border-color:var(--line-hot);background:linear-gradient(180deg,rgba(101,17,31,.22),rgba(22,10,13,.2));box-shadow:inset 0 -2px var(--signal),0 0 28px rgba(255,36,61,.1)}.header-status{margin-left:auto;display:flex;align-items:center}.header-status>span{min-width:190px;height:44px;padding:3px 22px;display:grid;grid-template-columns:1fr auto;align-content:center;border-left:1px solid var(--line);position:relative}.header-status small{grid-column:1/-1;color:var(--muted);font-size:11px;letter-spacing:.13em}.header-status b{font-size:11px;margin-top:4px}.live-dot{width:7px;height:7px;border-radius:50%;background:var(--signal);align-self:center;box-shadow:0 0 9px var(--signal)}
.tab-panel{min-height:calc(100vh - 72px)}.console-grid{display:grid;grid-template-columns:282px minmax(520px,1fr) 276px;gap:10px;padding:10px}.panel,.settings-panel{background:linear-gradient(145deg,rgba(14,16,18,.97),rgba(7,8,9,.97));border:1px solid var(--line);box-shadow:0 10px 35px rgba(0,0,0,.22)}.panel-title,.section-head{display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid var(--line);padding:14px 16px;color:var(--signal-soft);font:800 12px var(--mono);letter-spacing:.12em}.panel-title small,.section-head small{color:var(--dim);font-size:10px}
.operations{padding-bottom:12px}.radar{width:218px;aspect-ratio:1;margin:22px auto 20px;border:1px solid #7a2230;border-radius:50%;position:relative;overflow:visible;background:repeating-radial-gradient(circle,transparent 0 31px,rgba(187,31,49,.28) 32px 33px),linear-gradient(90deg,transparent 49.5%,rgba(173,28,46,.34) 50%,transparent 50.5%),linear-gradient(transparent 49.5%,rgba(173,28,46,.34) 50%,transparent 50.5%);box-shadow:inset 0 0 38px rgba(255,20,47,.1),0 0 28px rgba(255,20,47,.08)}.radar:before,.radar:after{content:"";position:absolute;inset:23px;border:1px dashed rgba(255,55,76,.18);border-radius:50%}.radar:after{inset:68px}.radar-sweep{position:absolute;inset:2px;border-radius:50%;background:conic-gradient(from 2deg,transparent 0 315deg,rgba(255,33,57,.02) 330deg,rgba(255,40,64,.3) 353deg,var(--signal) 359.5deg,transparent 360deg);animation:radar-sweep 4.2s linear infinite}.radar-axis{position:absolute;color:var(--signal);font:700 10px var(--mono);z-index:2}.radar-axis.north{top:-16px;left:48%}.radar-axis.east{right:-21px;top:48%}.radar-axis.south{bottom:-17px;left:47%}.radar-axis.west{left:-21px;top:48%}.radar-contacts{position:absolute;inset:0;z-index:3;pointer-events:none}.radar-contact{position:absolute;width:6px;height:6px;border-radius:50%;transform:translate(-50%,-50%);background:var(--signal-soft);box-shadow:0 0 9px var(--signal);transition:opacity .35s}.radar-contact.active{width:8px;height:8px;background:#fff0f2;box-shadow:0 0 8px #fff,0 0 20px var(--signal);animation:contact-pulse 1.2s ease-in-out infinite}.radar-contact.error{background:#ff1638;box-shadow:0 0 6px #fff,0 0 18px #ff1638}@keyframes radar-sweep{to{transform:rotate(360deg)}}@keyframes contact-pulse{50%{transform:translate(-50%,-50%) scale(1.7);filter:brightness(1.4)}}.metrics{margin:0 10px;border-top:1px solid var(--line)}.metrics div{display:flex;justify-content:space-between;padding:10px 8px;border-bottom:1px solid #24171b}.metrics dt{font-size:11px;color:var(--muted)}.metrics dd{margin:0;color:var(--signal-soft);font-size:11px}.mini-section{padding:15px 18px}.mini-section h3,.context h3{font:800 11px var(--mono);letter-spacing:.1em;color:var(--signal);margin:0 0 12px}.failure-list{padding-left:0;list-style:none;color:#9c8b8f;font-size:11px;line-height:2}.health{margin:0 10px;display:grid;grid-template-columns:1fr 1fr;border:1px solid var(--line)}.health span{padding:11px}.health span+span{border-left:1px solid var(--line)}.health small{display:block;color:var(--dim);font-size:10px}.health b{color:var(--signal-soft);font-size:11px}
.traffic{min-width:0;overflow:hidden}.traffic-heading{height:66px;display:flex;justify-content:space-between;align-items:center;padding:12px 18px;border-bottom:1px solid var(--line)}.traffic-heading small{color:var(--signal);font:700 10px var(--mono);letter-spacing:.12em}.traffic-heading h1{font:800 17px var(--mono);letter-spacing:.06em;margin:3px 0}.count{font-size:11px;color:var(--muted)}.stream-tools{display:grid;grid-template-columns:minmax(220px,1fr) auto auto auto auto auto;gap:7px;padding:11px;border-bottom:1px solid var(--line)}.sort-control{display:flex;align-items:center;gap:7px;color:#776b6e;font:700 10px var(--mono)}.sort-control select{height:34px;min-width:108px;border:1px solid #3a292e;background:#07090a;color:#c7bec0;padding:0 8px;font:700 10px var(--mono)}.search input,.field-row input,.target-line input,.providers input,.inspection input,.rule-editor input,.rule-editor select{width:100%;height:36px;border:1px solid #3a292e;background:#07090a;color:var(--text);padding:0 11px;outline:none;font-size:12px}.search input:focus,input:focus,select:focus,button:focus-visible{border-color:var(--signal)!important;box-shadow:0 0 0 2px rgba(255,42,67,.18),var(--shadow);outline:none}.btn{height:34px;padding:0 12px;border:1px solid #423036;background:#111416;color:#c7bec0;font:700 11px var(--mono);letter-spacing:.06em;cursor:pointer}.btn:hover{border-color:#92505b;color:#fff;background:#171113}.btn.signal,.btn.primary{border-color:#a32436;color:#ff8795;background:#300e16;box-shadow:0 0 18px rgba(255,31,56,.09)}.btn.danger{color:#c87581}.session-head,.session-row{display:grid;grid-template-columns:84px 68px minmax(200px,1fr) 70px 76px;gap:10px;align-items:center}.session-head{padding:10px 18px;color:#766b6d;font-size:10px;border-bottom:1px solid var(--line)}.session-stream{height:calc(100vh - 232px);min-height:460px;overflow:auto}.session{border-bottom:1px solid #2b1b20}.session-row{width:100%;padding:13px 18px;border:0;background:transparent;color:#cfc5c7;text-align:left;font:12px var(--mono);cursor:pointer}.session-row:hover,.session[open]>.session-row{background:#160d10}.session-row .method,.session-row .status{color:var(--signal-soft);font-weight:700}.session-row .route{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.session-detail{display:grid;grid-template-columns:1fr 1fr;border-top:1px solid #3b2027;background:#080a0b}.payload{min-width:0;padding:14px}.payload+.payload{border-left:1px solid var(--line)}.payload h3{display:flex;justify-content:space-between;gap:8px;margin:0 0 10px;color:var(--signal);font:800 11px var(--mono)}.payload:nth-child(n+3){border-top:1px solid var(--line)}.payload:nth-child(odd){border-left:0}.change-state{font-size:10px;color:#766b6e}.change-state.changed{color:var(--signal-soft);text-shadow:0 0 8px rgba(255,51,73,.45)}.payload pre{max-height:260px;overflow:auto;white-space:pre-wrap;word-break:break-word;color:#b8adaf;font:11px/1.7 var(--mono);margin:0}.empty-state{height:100%;display:grid;place-content:center;text-align:center;color:#776b6e;font:700 11px var(--mono);letter-spacing:.08em}.empty-state span{display:block;font-size:10px;margin-top:8px;color:#51484a}
.context{padding-bottom:18px}.context section{padding:18px;border-bottom:1px solid var(--line)}.context-list{margin:0}.context-list div{padding:8px 0}.context-list dt{color:var(--dim);font-size:10px}.context-list dd{margin:4px 0 0;color:#c8bec0;font-size:11px;word-break:break-all}.signal-text{color:var(--signal-soft)!important}.context-note{margin:18px;border:1px solid var(--line-hot);padding:14px;background:rgba(79,12,23,.12)}.context-note b{font:800 11px var(--mono);color:var(--signal)}.context-note p{color:#8f8184;font-size:12px;line-height:1.5}.text-action{border:0;background:none;padding:0;color:var(--signal-soft);font:700 10px var(--mono);cursor:pointer}
.command{padding:12px}.announcement{min-height:40px;display:flex;align-items:center;gap:10px;border:1px solid var(--line-hot);background:rgba(70,12,22,.2);padding:0 14px;margin-bottom:10px;color:#c8bec0;font:12px var(--mono)}.announcement span{color:var(--signal)}.command-grid{display:grid;grid-template-columns:1fr 1.7fr;gap:10px}.settings-panel{padding:0 16px 16px}.settings-panel .section-head{margin:0 -16px 15px}.network{grid-column:1}.forwarding{grid-column:2}.providers{grid-column:1}.inspection{grid-column:2}.rules{grid-column:1/-1}.field-row{display:grid;grid-template-columns:140px 1fr 88px;gap:8px;align-items:center;margin:9px 0;font-size:12px}.field-row input{height:32px}.lock{font:700 10px var(--mono);color:#6d6265;border:1px solid #38272c;padding:7px;text-align:center}.help{color:#817679;font-size:11px;line-height:1.6;margin:12px 0 0}.mode-line,.target-line{margin-bottom:14px}.mode-line{display:flex;align-items:center;gap:28px;font-size:12px}.segmented{display:flex}.segmented button{height:34px;padding:0 17px;border:1px solid #3d2c31;background:#0a0c0d;color:#8f8587;font:700 10px var(--mono);cursor:pointer}.segmented button+button{border-left:0}.segmented button.active{color:#ff8896;border-color:#9f2939;background:#2f0e15;box-shadow:var(--shadow)}.target-line>label{display:block;font-size:11px;margin-bottom:7px;color:#aaa0a2}.target-line>div{display:grid;grid-template-columns:1fr auto;gap:8px}.actions{display:flex;gap:8px;margin-top:14px}.providers label,.inspection>label{display:grid;grid-template-columns:150px 1fr;align-items:center;margin:9px 0;color:#aaa0a2;font-size:11px}.providers input,.inspection input{height:32px}.switch-line{display:flex;justify-content:space-between;align-items:center;margin:10px 0}.switch-line b{font-size:11px}.switch-line small{display:block;color:#6f6668;font-size:10px;margin-top:4px}.switch{width:39px;height:20px;border:1px solid #4c343a;background:#0a0b0c;padding:2px;cursor:pointer}.switch i{display:block;width:14px;height:14px;background:#756c6e;transition:transform .2s,background .2s}.switch[aria-checked="true"]{border-color:var(--signal)}.switch[aria-checked="true"] i{transform:translateX(17px);background:var(--signal);box-shadow:0 0 10px var(--signal)}.paths{margin:14px 0 0;border-top:1px solid var(--line);font-size:10px}.paths div{display:grid;grid-template-columns:90px 1fr;padding:7px;border-bottom:1px solid #25191d}.paths dt{color:#6d6265}.paths dd{margin:0;color:#9c9093;overflow:hidden;text-overflow:ellipsis}.rules-toolbar{display:flex;justify-content:space-between;align-items:center}.rules-toolbar .section-head{border:0;margin-bottom:0}.table-wrap{overflow:auto;border:1px solid var(--line)}table{width:100%;border-collapse:collapse;font:11px var(--mono)}th{text-align:left;color:#706669;background:#0b0d0e;padding:9px;border-bottom:1px solid var(--line)}td{padding:9px;border-bottom:1px solid #25191d;color:#b7abad}td code{color:#ddd0d2}.rule-actions{display:flex;gap:6px;white-space:nowrap}.rule-editor{display:grid;grid-template-columns:1fr 1fr 130px 130px 130px auto auto;gap:8px;align-items:end;padding:12px;border:1px solid var(--line-hot);margin-top:9px}.rule-editor label{font-size:10px;color:#827679}.rule-editor input,.rule-editor select{display:block;margin-top:5px}.check{height:36px;display:flex;align-items:center;gap:8px;padding:0 10px;margin-top:5px;border:1px solid #3a292e;background:#07090a;cursor:pointer}.check input[type="checkbox"]{width:16px;height:16px;flex:0 0 16px;margin:0;padding:0;accent-color:var(--signal);box-shadow:none}.toasts{position:fixed;right:18px;bottom:18px;z-index:100;display:grid;gap:8px}.toast{border:1px solid var(--line-hot);background:#140c0f;padding:11px 14px;box-shadow:var(--shadow);font:11px var(--mono);color:#e3d9db}
@media(max-width:1120px){.console-grid{grid-template-columns:230px 1fr}.context{display:none}.brand{width:250px}.header-status>span{min-width:155px}.command-grid{grid-template-columns:1fr}.network,.forwarding,.providers,.inspection,.rules{grid-column:1}.rule-editor{grid-template-columns:1fr 1fr 1fr}}
@media(max-width:760px){.app-header{height:auto;min-height:64px;flex-wrap:wrap}.brand{width:100%;height:58px;border-bottom:1px solid var(--line)}.tabs{margin:0;order:3;width:100%;height:46px}.tab{flex:1;min-width:0}.header-status{display:none}.header-status>span{min-width:130px;padding:3px 10px}.console-grid{grid-template-columns:1fr;padding:7px}.operations{display:none}.stream-tools{grid-template-columns:1fr 1fr}.search{grid-column:1/-1}.session-head,.session-row{grid-template-columns:68px 54px minmax(130px,1fr) 54px}.session-head span:last-child,.session-row span:last-child{display:none}.session-stream{height:calc(100vh - 280px)}.session-detail{grid-template-columns:1fr}.payload+.payload{border-left:0;border-top:1px solid var(--line)}.command{padding:7px}.field-row,.providers label,.inspection>label{grid-template-columns:1fr}.rule-editor{grid-template-columns:1fr}.command-grid{display:block}.settings-panel{margin-bottom:8px}}
@media(prefers-reduced-motion:reduce){*,*::before,*::after{scroll-behavior:auto!important;animation-duration:.001ms!important;animation-iteration-count:1!important;transition-duration:.001ms!important}.radar-sweep{animation:none;transform:rotate(38deg)}}
`;
const GUI_JS = String.raw`"use strict";
const $ = (id) => document.getElementById(id);
const state = { status: null, sessions: [], rules: [], editingRuleId: null, follow: true, sortField: "time", sortDirection: "desc", mode: "destination", timer: null, openSessions: new Set() };
async function api(route, options = {}) {
const response = await fetch(route, {
...options,
headers: options.body ? { "content-type": "application/json", ...(options.headers || {}) } : options.headers,
});
const type = response.headers.get("content-type") || "";
const data = type.includes("application/json") ? await response.json() : await response.text();
if (!response.ok) throw new Error(data && data.error ? data.error.message : "Request failed with " + response.status);
return data;
}
function address(target) {
if (!target) return "";
const host = target.host.includes(":") ? "[" + target.host + "]" : target.host;
return host + ":" + target.port;
}
function setStatus(message, error = false) {
$("app-status").querySelector("p").textContent = message;
$("app-status").classList.toggle("error", error);
}
function toast(message) {
const item = document.createElement("div");
item.className = "toast";
item.textContent = message;
$("toast-region").append(item);
setTimeout(() => item.remove(), 3600);
}
function setTab(name) {
const consoleActive = name === "console";
$("console-panel").hidden = !consoleActive;
$("command-panel").hidden = consoleActive;
$("console-tab").classList.toggle("active", consoleActive);
$("command-tab").classList.toggle("active", !consoleActive);
$("console-tab").setAttribute("aria-selected", String(consoleActive));
$("command-tab").setAttribute("aria-selected", String(!consoleActive));
$("traffic-radar").classList.toggle("paused", !consoleActive);
history.replaceState(null, "", consoleActive ? "#console" : "#command");
}
function populateStatus(data) {
state.status = data;
$("proxy-bind").textContent = address(data.listen);
$("gui-bind").textContent = address(data.gui);
$("listener-display").value = address(data.listen);
$("gui-display").value = address(data.gui);
const config = data.forwarding || {};
$("forward-target").value = address(config.forwardTarget);
state.mode = config.forwarding ? "chain" : "destination";
updateModeUi();
$("context-target").textContent = config.forwardTarget ? address(config.forwardTarget) : "AUTOMATIC";
$("context-mode").textContent = !config.forwardTarget ? "PROVIDER ROUTING" : config.forwarding ? "UPSTREAM PROXY CHAIN" : "DESTINATION OVERRIDE";
$("context-state").textContent = "ACTIVE";
const providers = data.providers || {};
$("provider-anthropic").value = providers.anthropic || "";
$("provider-openai").value = providers.openai || "";
$("provider-chatgpt").value = providers.openai_chatgpt || "";
const providerList = $("context-providers");
providerList.replaceChildren();
for (const [name, endpoint] of Object.entries(providers)) {
const row = document.createElement("div");
const dt = document.createElement("dt");
const dd = document.createElement("dd");
dt.textContent = name.replace("openai_chatgpt", "CHATGPT CODEX").toUpperCase();
dd.textContent = endpoint;
row.append(dt, dd);
providerList.append(row);
}
$("debug-toggle").setAttribute("aria-checked", String(Boolean(data.inspection && data.inspection.debugBodies)));
$("body-cap").value = data.inspection && data.inspection.bodyCap || "";
$("body-keep").value = data.inspection && data.inspection.bodyKeep || "";
$("data-log-path").textContent = data.files && data.files.dataLog || "—";
$("body-dir-path").textContent = data.files && data.files.bodyDir || "—";
$("rules-file-path").textContent = data.files && data.files.rulesFile || "—";
const locks = data.locks || {};
$("forward-target").disabled = Boolean(locks.forwardTarget);
$("forward-lock-state").textContent = locks.forwardTarget || locks.forwarding ? "CLI / ENV LOCKED" : "RUNTIME EDITABLE";
document.querySelectorAll("[data-mode]").forEach((button) => { button.disabled = Boolean(locks.forwarding); });
}
function updateModeUi() {
document.querySelectorAll("[data-mode]").forEach((button) => button.classList.toggle("active", button.dataset.mode === state.mode));
$("mode-description").textContent = state.mode === "chain"
? "All outbound HTTP and HTTPS traffic is routed through this upstream HTTP proxy. CONNECT tunnels are chained through it."
: "Origin-form API requests are sent directly to this target. Absolute-form and CONNECT traffic retain client-selected destinations.";
}
function sessionSearchText(session) {
return JSON.stringify(session).toLowerCase();
}
function sessionSortValue(session, field) {
const req = session.request || {};
const res = session.response || {};
if (field === "status") {
const value = Number(res.status);
return Number.isFinite(value) ? value : Number.MAX_SAFE_INTEGER;
}
if (field === "latency") {
const value = Number(res.time_ms);
return Number.isFinite(value) ? value : Number.MAX_SAFE_INTEGER;
}
if (field === "method") return String(req.method || "").toLowerCase();
if (field === "provider") return (String(req.provider || "") + " " + String(req.model || "")).trim().toLowerCase();
const value = Date.parse(req.ts || res.ts || session.ts || "");
return Number.isFinite(value) ? value : 0;
}
function visibleSessions(sessions, filter, field, direction) {
const needle = String(filter || "").trim().toLowerCase();
const factor = direction === "asc" ? 1 : -1;
return (sessions || [])
.filter((session) => !needle || sessionSearchText(session).includes(needle))
.slice()
.sort((a, b) => {
const av = sessionSortValue(a, field);
const bv = sessionSortValue(b, field);
let compared;
if (typeof av === "number" && typeof bv === "number") compared = av - bv;
else compared = String(av).localeCompare(String(bv));
return compared * factor || String(a.sid || "").localeCompare(String(b.sid || ""));
});
}
function hashSessionId(sid) {
let hash = 2166136261;
for (const char of String(sid || "")) {
hash ^= char.charCodeAt(0);
hash = Math.imul(hash, 16777619);
}
return hash >>> 0;
}
function isSessionActive(session) {
const response = session && session.response;
return !response || Boolean(response.streaming && !response.stream_complete);
}
function radarContact(session, now = Date.now()) {
if (!session || !session.sid) return null;
const req = session.request || {};
const res = session.response || null;
const active = isSessionActive(session);
let completedAt = null;
if (!active) {
const parsed = Date.parse(res.ts || session.ts || req.ts || "");
if (!Number.isFinite(parsed)) return null;
completedAt = parsed;
if (now - completedAt > 60000) return null;
}
const hash = hashSessionId(session.sid);
const angle = (hash % 360) * Math.PI / 180;
const ringRadius = 28 + ((hash >>> 9) % 58);
const distance = ringRadius * 0.5;
const status = Number(res && res.status);
const failed = Boolean(res && (status >= 400 || res.error));
const age = active ? 0 : Math.max(0, now - completedAt);
const opacity = active ? 1 : Math.max(failed ? 0.35 : 0.18, 1 - age / 60000);
const route = req.path || req.dest || "unknown route";
const method = req.method || "REQUEST";
return {
sid: String(session.sid),
left: (50 + Math.cos(angle) * distance).toFixed(2) + "%",
top: (50 + Math.sin(angle) * distance).toFixed(2) + "%",
state: active ? "active" : failed ? "error" : "success",
opacity,
sortTime: active ? Number.MAX_SAFE_INTEGER : completedAt,
label: method + " " + route + " — " + (active ? "active" : failed ? "failed " + (res.status || "") : "completed " + (res.status || "")),
};
}
function selectRadarContacts(sessions, now = Date.now()) {
return (sessions || [])
.map((session) => radarContact(session, now))
.filter(Boolean)
.sort((a, b) => {
if (a.state === "active" && b.state !== "active") return -1;
if (a.state !== "active" && b.state === "active") return 1;
return b.sortTime - a.sortTime || a.sid.localeCompare(b.sid);
})
.slice(0, 24);
}
function renderRadar(now = Date.now()) {
const layer = $("radar-contacts");
const contacts = selectRadarContacts(state.sessions, now);
const existing = new Map(Array.from(layer.children).map((item) => [item.dataset.sid, item]));
const keep = new Set();
for (const contact of contacts) {
let item = existing.get(contact.sid);
if (!item) {
item = document.createElement("span");
item.dataset.sid = contact.sid;
item.setAttribute("role", "img");
layer.append(item);
}
keep.add(contact.sid);
item.className = "radar-contact " + contact.state;
item.style.left = contact.left;
item.style.top = contact.top;
item.style.opacity = String(contact.opacity);
item.setAttribute("aria-label", contact.label);
item.title = contact.label;
}
for (const [sid, item] of existing) if (!keep.has(sid)) item.remove();
}
function textBlock(title, value, changeState) {
const section = document.createElement("section");
section.className = "payload";
const heading = document.createElement("h3");
const pre = document.createElement("pre");
heading.textContent = title;
if (changeState) {
const badge = document.createElement("span");
badge.className = "change-state " + changeState.toLowerCase();
badge.textContent = changeState;
heading.append(badge);
}
pre.textContent = value || "No captured content";
section.append(heading, pre);
return section;
}
async function loadBody(sid, kind, pre) {
pre.textContent = "Loading stored content…";
try {
pre.textContent = await api("/api/body?sid=" + encodeURIComponent(sid) + "&kind=" + encodeURIComponent(kind));
pre.dataset.loaded = kind;
} catch (error) {
delete pre.dataset.loaded;
pre.textContent = "Unavailable — " + error.message;
throw error;
}
}
function updateOpenSessions(openSessions, sid, open) {
if (open) openSessions.add(sid);
else openSessions.delete(sid);
return openSessions;
}
function needsSessionBodies(open, loaded) {
return Boolean(open && !loaded);
}
function reconcileSessionNodes(existingNodes, sessions, createNode, updateNode) {
const existing = new Map(Array.from(existingNodes || []).map((node) => [node.dataset.sid, node]));
return (sessions || []).map((session) => {
const node = existing.get(String(session.sid));
if (!node) return createNode(session);
updateNode(node, session);
return node;
});
}
function syncChildOrder(container, desiredNodes) {
desiredNodes.forEach((node, index) => {
const current = container.children[index] || null;
if (current !== node) container.insertBefore(node, current);
});
while (container.children.length > desiredNodes.length) {
container.removeChild(container.lastElementChild);
}
}
function panelsForSession(session) {
const req = session.request || {};
const res = session.response || {};
const systemState = req.sys_changed ? "CHANGED" : (req.system_original != null || req.system != null) ? "UNCHANGED" : "";
const userState = req.usr_changed ? "CHANGED" : (req.input_original != null || req.input != null) ? "UNCHANGED" : "";
return [
{ title: "RAW REQUEST", preview: JSON.stringify(req, null, 2), kind: "req", stored: req.has_req_body },
{ title: "RAW / STREAMED RESPONSE", preview: res.output || res.error || JSON.stringify(res, null, 2), kind: "res", stored: res.has_res_body },
{ title: "SYSTEM ORIGINAL", preview: req.system_original, kind: "sys", stored: req.sys_full, state: systemState },
{ title: "SYSTEM TRANSFORMED", preview: req.system, kind: "syso", stored: req.syso_full, state: systemState },
{ title: "USER ORIGINAL", preview: req.input_original, kind: "usr", stored: req.usr_full, state: userState },
{ title: "USER TRANSFORMED", preview: req.input, kind: "usro", stored: req.usro_full, state: userState },
];
}
function updatePanel(section, panel) {
const heading = section.querySelector("h3");
const pre = section.querySelector("pre");
const headingKey = panel.title + "\n" + (panel.state || "");
if (section.dataset.headingKey !== headingKey) {
heading.textContent = panel.title;
if (panel.state) {
const badge = document.createElement("span");
badge.className = "change-state " + panel.state.toLowerCase();
badge.textContent = panel.state;
heading.append(badge);
}
section.dataset.headingKey = headingKey;
}
const preview = panel.preview || "No captured content";
if (!(panel.stored && pre.dataset.loaded === panel.kind) && pre.textContent !== preview) {
pre.textContent = preview;
}
if (!panel.stored) delete pre.dataset.loaded;
}
async function loadSessionPanels(details) {
if (!details.open) return;
const session = details._aresSession;
const panels = details._aresPanels || [];
const blocks = details.querySelectorAll(".session-detail pre");
const jobs = panels.map((panel, index) => panel.stored
&& blocks[index].dataset.loaded !== panel.kind
? loadBody(session.sid, panel.kind, blocks[index])
: Promise.resolve());
await Promise.allSettled(jobs);
}
function updateSessionElement(details, session) {
const fingerprint = JSON.stringify(session);