Repository navigation
Expand file tree
/
Copy pathdashboard.js
More file actions
1956 lines (1834 loc) · 83.3 KB
/
Copy pathdashboard.js
File metadata and controls
1956 lines (1834 loc) · 83.3 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
'use strict';
/* global HTTP, Workbench, Workflow, Lab, workflowState, bindWorkflow, renderSiteMap, renderCollections, renderInspector, renderRunner, workspaceVariableText, labState, bindLab, queueLocalSave, renderAssertionResults, renderSecurity, renderWorkspace, renderWebSockets, captureWebSocket */
const $ = (s) => document.querySelector(s);
const $$ = (s) => [...document.querySelectorAll(s)];
function applyShortcutHints(platform) {
const mac = /^mac(?:os|intel|intosh)?$/i.test(String(platform || ''));
const modifier = mac ? '⌘' : 'Ctrl';
const spokenModifier = mac ? 'Command' : 'Control';
const ariaModifier = mac ? 'Meta' : 'Control';
for (const hint of $$('[data-shortcut]')) {
hint.textContent = `${modifier} + ${hint.dataset.shortcut}`;
hint.setAttribute('aria-label', `${spokenModifier} + ${hint.dataset.shortcut}`);
}
for (const button of $$('[data-shortcut-title]')) {
button.title = `${modifier} + ${button.dataset.shortcutTitle}`;
button.setAttribute('aria-keyshortcuts', `${ariaModifier}+${button.dataset.shortcutTitle}`);
}
}
async function configureShortcutHints() {
const fallback = navigator.userAgentData?.platform || navigator.platform || '';
applyShortcutHints(fallback);
try { applyShortcutHints((await chrome.runtime.getPlatformInfo()).os); }
catch { /* the local platform fallback remains visible */ }
}
const shortcutHintsReady = configureShortcutHints();
let dashboardPort;
let closingDashboard = false;
function connectDashboard() {
dashboardPort = chrome.runtime.connect({ name: 'dashboard' });
dashboardPort.onDisconnect.addListener(() => {
if (!closingDashboard) setTimeout(connectDashboard, 250);
});
}
const MAX_HISTORY = 2500;
const MAX_BODY_CHARS = 750_000; // characters kept per captured body
const MAX_HISTORY_CHARS = 64_000_000; // approximate total text budget
const MAX_REPEATER_BYTES = 4_000_000;
const MAX_DISPLAY_CHARS = 200_000; // bounded visible preview; copy/export retains stored text
const STATIC_TYPES = new Set(['Image', 'Font', 'Stylesheet', 'Media']);
const STATIC_EXT = /\.(png|jpe?g|gif|webp|avif|svg|ico|bmp|css|woff2?|ttf|otf|eot|mp4|webm|mp3|wav|ogg|map)$/i;
const STD_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS', 'CONNECT'];
const state = {
tabId: null,
attached: false,
settings: {
requests: true, responses: false, skipStatic: true, filter: '',
disableCache: false, historyHideStatic: false, historySearchContent: true,
prettyJson: true, repPretty: true, repRemember: true, comparePretty: true,
autoMode: false, autoRules: [{ param: HTTP.DEFAULT_PARAMS, value: '1' }],
autoInclude: '', autoExclude: '',
},
interceptOn: false,
queue: [], // paused Fetch items
selectedQueueId: null,
forceResponse: new Set(), // Fetch requestIds whose response we want to pause
history: [],
selectedHistoryId: null,
autoLog: [], // auto-mode rewrites
autoCount: 0,
seq: 0,
repeaters: [],
activeRepeaterId: null,
repSeq: 0,
compare: { left: '', right: '', leftLabel: '', rightLabel: '', unified: '' },
};
// ======================================================================
// Utilities
// ======================================================================
const escapeHtml = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
let toastTimer;
function toast(msg, kind = 'info') {
const t = $('#toast');
t.textContent = msg;
t.className = `toast show ${kind}`;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => (t.className = 'toast'), kind === 'error' ? 5000 : 2200);
}
function fmtSize(n) {
if (n == null || n < 0) return '';
if (n < 1024) return `${n} B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
return `${(n / 1024 / 1024).toFixed(2)} MB`;
}
const fmtMs = (ms) => (ms == null ? '' : ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(2)} s`);
function limitBody(text, label = 'body') {
text = String(text || '');
if (text.length <= MAX_BODY_CHARS) return text;
return text.slice(0, MAX_BODY_CHARS) + `\n[… ${label} truncated; ${fmtSize(text.length)} total]`;
}
function entryChars(entry) {
const headers = [...(entry.reqHeaders || []), ...(entry.resHeaders || [])]
.reduce((n, h) => n + String(h.name).length + String(h.value).length, 0);
return headers + String(entry.url || '').length + String(entry.reqBody || '').length + String(entry.resBody || '').length;
}
function pruneHistory() {
let total = 0;
let keepFrom = state.history.length;
for (let i = state.history.length - 1; i >= 0; i--) {
total += entryChars(state.history[i]);
if (total > MAX_HISTORY_CHARS || state.history.length - i > MAX_HISTORY) break;
keepFrom = i;
}
if (keepFrom > 0) {
const removed = state.history.splice(0, keepFrom);
for (const entry of removed) {
if (netMap.get(entry.requestId) === entry) netMap.delete(entry.requestId);
}
if (removed.some((e) => e.id === state.selectedHistoryId)) state.selectedHistoryId = null;
}
}
async function copyText(text, what = 'Copied') {
try {
await navigator.clipboard.writeText(text);
toast(what);
} catch (e) {
toast(`Copy failed: ${e.message}`, 'error');
}
}
function shortUrl(url) {
try {
const u = new URL(url);
return u.host + u.pathname + u.search;
} catch {
return url;
}
}
function isStatic(type, url) {
if (STATIC_TYPES.has(type)) return true;
try { return STATIC_EXT.test(new URL(url).pathname); } catch { return false; }
}
/** Text filter: plain substring (case-insensitive) or /regex/flags. */
function compileMatcher(str) {
const s = (str || '').trim();
if (!s) return { test: () => true, valid: true };
const m = /^\/(.+)\/([gimsuy]*)$/.exec(s);
if (m) {
try {
const re = new RegExp(m[1], m[2].replace(/[gy]/g, ''));
return { test: (v) => re.test(v), valid: true };
} catch { /* fall through to substring */ }
return { test: (v) => v.toLowerCase().includes(s.toLowerCase()), valid: false };
}
return { test: (v) => v.toLowerCase().includes(s.toLowerCase()), valid: true };
}
function highlightHttp(text) {
let note = '';
if (text.length > MAX_DISPLAY_CHARS) {
note = `\n\n[… truncated for display: ${fmtSize(text.length)} total. Use "Copy" to get everything.]`;
text = text.slice(0, MAX_DISPLAY_CHARS);
}
const idx = text.indexOf('\n\n');
const head = idx < 0 ? text : text.slice(0, idx);
const lines = head.split('\n');
let html = `<span class="h-first">${escapeHtml(lines[0])}</span>`;
for (const l of lines.slice(1)) {
const i = l.indexOf(':');
html += '\n' + (i > 0 ? `<span class="h-name">${escapeHtml(l.slice(0, i))}</span>:${escapeHtml(l.slice(i + 1))}` : escapeHtml(l));
}
if (idx >= 0) html += '\n\n' + escapeHtml(text.slice(idx + 2));
if (note) html += `<span class="h-note">${escapeHtml(note)}</span>`;
return html;
}
function setRaw(pre, text) {
pre.innerHTML = text ? highlightHttp(text) : '';
}
/** Body of a CDP Network.Request / Fetch request. */
function requestBodyFromCdp(req) {
return HTTP.requestBodyText(req);
}
// ======================================================================
// Settings persistence
// ======================================================================
/** Bring an older stored `settings` object up to the current shape. */
function normalizeSettings(s) {
if (!s) return;
if (!Array.isArray(s.autoRules)) {
// Migrate the old single-parameter format.
s.autoRules = s.autoParam
? [{ param: String(s.autoParam), value: s.autoValue ?? '1' }]
: [{ param: HTTP.DEFAULT_PARAMS, value: '1' }];
}
if (s.autoScope !== 'tab' && s.autoScope !== 'all') s.autoScope = 'all';
s.autoInclude = String(s.autoInclude || '');
s.autoExclude = String(s.autoExclude || '');
delete s.autoParam;
delete s.autoValue;
}
async function loadSettings() {
try {
const [{ settings }, session] = await Promise.all([
chrome.storage.local.get('settings'),
chrome.storage.session.get('autoTabId'),
]);
normalizeSettings(settings);
Object.assign(state.settings, settings || {});
state.settings.autoTabId = typeof session.autoTabId === 'number' ? session.autoTabId : null;
if (state.settings.autoScope === 'tab' && state.settings.autoTabId == null) state.settings.autoMode = false;
} catch { /* defaults */ }
}
function saveSettings() {
queueLocalSave();
const settings = { ...state.settings };
delete settings.autoTabId;
chrome.storage.local.set({ settings }).catch(() => {});
}
// ======================================================================
// Debugger / CDP plumbing
// ======================================================================
function cdp(method, params = {}) {
if (!state.attached) return Promise.reject(new Error('Not attached'));
return chrome.debugger.sendCommand({ tabId: state.tabId }, method, params);
}
async function refreshTabs() {
const sel = $('#tabSelect');
const prev = sel.value;
const tabs = await chrome.tabs.query({});
const usable = tabs.filter((t) => /^(https?|file):/i.test(t.url || t.pendingUrl || ''));
sel.innerHTML = '';
if (!usable.length) {
const o = document.createElement('option');
o.textContent = 'No web tabs open — open your app in another tab';
o.value = '';
sel.append(o);
return;
}
usable.sort((a, b) => (b.lastAccessed || 0) - (a.lastAccessed || 0));
for (const t of usable) {
const o = document.createElement('option');
o.value = String(t.id);
const url = t.url || t.pendingUrl;
o.textContent = `${(t.title || url).slice(0, 60)} — ${shortUrl(url).slice(0, 80)}`;
sel.append(o);
}
const want = state.attached ? String(state.tabId) : prev;
if (want && usable.some((t) => String(t.id) === want)) sel.value = want;
}
/** Ask the background worker to release a tab from Auto mode before we attach. */
async function claimTab(tabId) {
try { await chrome.storage.session.set({ dashboardTabId: tabId }); } catch { /* ignore */ }
try { await chrome.runtime.sendMessage({ type: 'claimTab', tabId }); } catch { /* worker asleep; storage change covers it */ }
}
async function releaseTab(tabId) {
try { await chrome.storage.session.set({ dashboardTabId: null }); } catch { /* ignore */ }
try { await chrome.runtime.sendMessage({ type: 'releaseTab', tabId }); } catch { /* ignore */ }
}
/** Turn Chrome's terse debugger errors into something actionable. */
function attachErrorMessage(msg, host) {
if (/already attached|Another debugger/i.test(msg)) {
return 'Another debugger is already on this tab. Close its DevTools (F12) or any other debugging extension, then try again.';
}
if (/different extension|chrome-extension|Cannot access|Cannot attach/i.test(msg)) {
return `Chrome won't let Interceptor attach to this tab: another extension has put its own page here — a redirect, or an injected iframe/overlay (common on payment pages). Disable other extensions for ${host || 'this site'}, or use a clean browser profile with only Interceptor, then Attach again.`;
}
return `Could not attach: ${msg}`;
}
async function attach() {
if (labState.restoring) return toast('Wait for workspace restore to finish.', 'error');
if (!await Disclosure.accepted()) return;
const tabId = Number($('#tabSelect').value);
if (!tabId) return toast('Pick a tab to attach to first.', 'error');
// Re-read the tab's CURRENT url — it may have navigated/redirected since the list was built.
let liveTab;
try { liveTab = await chrome.tabs.get(tabId); }
catch { await refreshTabs(); return toast('That tab is gone — I refreshed the list. Pick your site tab again.', 'error'); }
const liveUrl = liveTab.url || liveTab.pendingUrl || '';
let liveHost = '';
try { liveHost = new URL(liveUrl).host; } catch { /* ignore */ }
if (!/^https?:|^file:/i.test(liveUrl)) {
await refreshTabs();
return toast(
'That tab is not a normal web page right now (it may have been redirected by another extension to a chrome-extension/chrome page). Reload your site in the tab, then pick it again.',
'error',
);
}
await claimTab(tabId); // hand the tab off from Auto mode so there's no debugger conflict
try {
await chrome.debugger.attach({ tabId }, '1.3');
} catch (e) {
await releaseTab(tabId);
return toast(attachErrorMessage(e.message, liveHost), 'error');
}
state.tabId = tabId;
state.attached = true;
try {
const tab = await chrome.tabs.get(tabId);
state.attachedHost = new URL(tab.url || tab.pendingUrl).host;
} catch { state.attachedHost = ''; }
try {
await cdp('Network.enable', { maxPostDataSize: 20 * 1024 * 1024 });
await cdp('Network.setCacheDisabled', { cacheDisabled: state.settings.disableCache });
await applyFetch();
toast('Attached. Traffic from this tab is now recorded.');
} catch (e) {
toast(`Attached, but setup failed: ${e.message}`, 'error');
}
updateStatus();
}
async function detach() {
if (!state.attached) return;
const tabId = state.tabId;
await releaseAll(false);
try { await chrome.debugger.detach({ tabId }); } catch { /* already gone */ }
onDetached();
}
function onDetached(reason) {
if (!state.attached) return;
const tabId = state.tabId;
state.attached = false;
state.tabId = null;
state.queue = [];
state.selectedQueueId = null;
state.forceResponse.clear();
netMap.clear();
// Chrome's Cancel button is an explicit stop; disable Auto before handing
// ownership back so the worker cannot immediately reattach the same tab.
if (reason === 'canceled_by_user') {
state.settings.autoMode = false;
queueLocalSave();
const settings = { ...state.settings, autoMode: false };
delete settings.autoTabId;
chrome.storage.local.set({ settings })
.then(() => tabId != null && releaseTab(tabId)).catch(() => {});
} else if (tabId != null) releaseTab(tabId); // let Auto mode reclaim the tab
renderQueue();
loadEditor();
updateStatus();
if (reason === 'canceled_by_user') toast('Debugging was cancelled from the browser bar — detached.', 'error');
else if (reason === 'target_closed') toast('Target tab was closed — detached.', 'error');
else if (reason) toast(`Detached (${reason}).`);
}
function updateStatus() {
const pill = $('#status');
const btn = $('#attachBtn');
$('#tabSelect').disabled = state.attached;
$('#reloadTabBtn').disabled = !state.attached;
btn.textContent = state.attached ? 'Detach' : 'Attach';
btn.classList.toggle('primary', !state.attached);
if (!state.attached) {
pill.className = 'pill off';
pill.textContent = 'Not attached';
} else if (state.interceptOn) {
pill.className = 'pill hot';
pill.textContent = 'Attached · intercepting';
} else {
pill.className = 'pill on';
pill.textContent = 'Attached · recording';
}
const t = $('#interceptToggle');
t.textContent = state.interceptOn ? 'Intercept is ON' : 'Intercept is OFF';
t.classList.toggle('on', state.interceptOn);
const bar = $('#autoBar');
if (autoModeOn()) {
bar.classList.remove('hidden');
const scope = state.settings.autoScope === 'tab' ? 'this-tab-only' : 'all tabs';
const here = state.attached && !autoActive() ? ' · not this tab (handled per-tab scope)' : '';
$('#autoBarText').textContent = `Auto mode ON (${scope}) — ${autoRuleSummary()} · ${state.autoCount} rewritten${here}`;
} else {
bar.classList.add('hidden');
}
// Publish attach state so the popup can show it.
chrome.storage.session.set({ attachedTabId: state.attached, attachedHost: state.attachedHost || '' }).catch(() => {});
}
/** Enable/disable Fetch interception according to the current settings.
* Calls are serialized so a stale Fetch.disable can't land after a newer Fetch.enable. */
let fetchChain = Promise.resolve();
function applyFetch() {
const run = fetchChain.then(applyFetchNow);
fetchChain = run.catch(() => {});
return run;
}
async function applyFetchNow() {
if (!state.attached) return;
const patterns = [];
// Enable the request stage for manual capture OR for Auto mode (independently),
// so Auto mode keeps working even when "Capture requests" is off.
if ((state.interceptOn && state.settings.requests) || autoActive()) {
patterns.push({ urlPattern: '*', requestStage: 'Request' });
}
if (state.interceptOn && state.settings.responses) {
patterns.push({ urlPattern: '*', requestStage: 'Response' });
}
if (patterns.length) {
await cdp('Fetch.enable', { patterns });
} else {
await releaseAll(true);
await cdp('Fetch.disable').catch(() => {});
}
}
chrome.debugger.onEvent.addListener((source, method, params) => {
if (!state.attached || source.tabId !== state.tabId || source.sessionId) return;
switch (method) {
case 'Network.webSocketCreated':
case 'Network.webSocketClosed':
case 'Network.webSocketFrameSent':
case 'Network.webSocketFrameReceived': captureWebSocket(method, params); break;
case 'Fetch.requestPaused': onRequestPaused(params); break;
case 'Network.requestWillBeSent': onRequestWillBeSent(params); break;
case 'Network.requestWillBeSentExtraInfo': onRequestExtra(params); break;
case 'Network.responseReceived': onResponseReceived(params); break;
case 'Network.responseReceivedExtraInfo': onResponseExtra(params); break;
case 'Network.loadingFinished': onLoadingFinished(params); break;
case 'Network.loadingFailed': onLoadingFailed(params); break;
}
});
chrome.debugger.onDetach.addListener((source, reason) => {
if (state.attached && source.tabId === state.tabId) onDetached(reason);
});
// ======================================================================
// Intercept (Fetch domain)
// ======================================================================
function inScope(url, type) {
if (/^(data|blob|chrome-extension|about):/i.test(url)) return false;
if (state.settings.skipStatic && isStatic(type, url)) return false;
return compileMatcher(state.settings.filter).test(url);
}
function continuePlain(requestId) {
return cdp('Fetch.continueRequest', { requestId }).catch(() => {});
}
const autoNames = () => (state.settings.autoRules || []).flatMap((r) => HTTP.splitNames(r.param));
const autoModeOn = () => !!(
state.settings.autoMode && autoNames().length &&
!HTTP.urlInScope('https://interceptor.invalid/', state.settings.autoInclude, state.settings.autoExclude).errors.length
);
// Whether Auto mode applies to the tab THIS dashboard is attached to.
function autoActive() {
if (!autoModeOn()) return false;
if ((state.settings.autoScope === 'tab' ? 'tab' : 'all') === 'all') return true;
return state.settings.autoTabId === state.tabId;
}
function autoInScope(url, type) {
if (/^(data|blob|chrome-extension|about):/i.test(url)) return false;
return !isStatic(type, url) && HTTP.urlInScope(url, state.settings.autoInclude, state.settings.autoExclude).allowed;
}
function autoRuleSummary() {
const parts = (state.settings.autoRules || []).map((r) => {
const names = HTTP.splitNames(r.param);
if (!names.length) return '';
const shown = names.length <= 3 ? names.join(', ') : `${names.slice(0, 2).join(', ')} +${names.length - 2} more`;
return `${shown} → ${r.value}`;
}).filter(Boolean);
const includeCount = HTTP.splitPatterns(state.settings.autoInclude).length;
const excludeCount = HTTP.splitPatterns(state.settings.autoExclude).length;
const scope = includeCount || excludeCount
? ` · URL scope ${includeCount || 'all'} include / ${excludeCount} exclude`
: '';
return `forcing ${parts.join(' ; ') || '(nothing)'}${scope}`;
}
async function onRequestPaused(p) {
const isResponse = 'responseStatusCode' in p || 'responseErrorReason' in p;
const forced = isResponse && state.forceResponse.delete(p.requestId);
const req = p.request;
let manualWant;
if (!state.interceptOn) manualWant = false;
else if (isResponse) {
const ct = HTTP.getHeader(HTTP.headersToList(p.responseHeaders), 'content-type') || '';
const streaming = /text\/event-stream/i.test(ct) || p.resourceType === 'EventSource' || p.resourceType === 'WebSocket';
manualWant = !p.responseErrorReason && !streaming && (forced || (state.settings.responses && inScope(req.url, p.resourceType)));
} else {
manualWant = state.settings.requests && inScope(req.url, p.resourceType);
}
// Auto mode: rewrite the configured parameter on requests.
let mod = null;
const reqBody = requestBodyFromCdp(req);
const reqBodyTooLarge = reqBody.text.length > MAX_BODY_CHARS;
if (!isResponse && autoActive() && autoInScope(req.url, p.resourceType)) {
try {
const textBody = reqBody.binary || !reqBody.known || reqBodyTooLarge ? '' : reqBody.text;
const m = HTTP.applyParamRules(
{ method: req.method, url: req.url, headers: req.headers, body: textBody },
state.settings.autoRules,
);
if (m.changes.length) mod = m;
} catch (e) {
console.warn('auto rule failed, passing request through:', e);
}
}
// Not wanted by manual intercept: auto-forward (with rewrite if any) or pass through.
if (!manualWant) {
if (mod) return autoForward(p, req, reqBody, mod);
return continuePlain(p.requestId);
}
const item = {
id: p.requestId,
networkId: p.networkId,
stage: isResponse ? 'response' : 'request',
method: req.method,
url: req.url,
resourceType: p.resourceType,
warn: '',
autoNote: '',
};
const historyRequest = isResponse ? netMap.get(p.networkId) : null;
const editableBody = reqBody.known && !reqBody.binary && !reqBodyTooLarge && reqBody.text
? reqBody.text
: isResponse && historyRequest && historyRequest.reqBodyComplete !== false && !HTTP.isUnavailableRequestBody(historyRequest.reqBody)
? historyRequest.reqBody : '';
item.requestBodyComplete = isResponse && historyRequest
? historyRequest.reqBodyComplete !== false && !HTTP.isUnavailableRequestBody(historyRequest.reqBody)
: reqBody.known && !reqBody.binary && !reqBodyTooLarge;
item.requestRaw = HTTP.serializeRequest({
method: req.method,
url: req.url,
headers: historyRequest ? historyRequest.reqHeaders : req.headers,
body: editableBody || '',
});
if (!isResponse) {
item.originalBody = editableBody;
if (reqBody.binary) item.warn = `Request body is binary (${fmtSize(reqBody.size)}) and is not shown. Leave the body empty to send the original bytes unchanged.`;
else if (reqBodyTooLarge) item.warn = `Request body exceeds ${fmtSize(MAX_BODY_CHARS)} and is not shown. Leave the body empty to send the original bytes unchanged.`;
else if (!reqBody.known) item.warn = 'Request body is not fully available (large upload / file). Leave the body empty to send the original body unchanged.';
item.originalRaw = item.requestRaw;
// Pre-fill the auto-rewrite so the paused request already shows the tampered value.
if (mod) {
item.autoRaw = HTTP.serializeRequest({ method: req.method, url: mod.url, headers: req.headers, body: reqBody.binary || !reqBody.known || reqBodyTooLarge ? '' : mod.body });
item.autoNote = `Auto mode pre-applied: ${describeChanges(mod.changes)}`;
}
} else {
item.status = p.responseStatusCode;
let bodyText = '';
item.originalBodyB64 = null;
try {
const r = await cdp('Fetch.getResponseBody', { requestId: p.requestId });
if (r.body.length > MAX_BODY_CHARS * (r.base64Encoded ? 4 / 3 : 1)) {
toast('Oversized response passed through unchanged.');
return continuePlain(p.requestId);
}
if (r.base64Encoded) {
item.originalBodyB64 = r.body;
const d = HTTP.decodeBody(HTTP.b64ToBytes(r.body));
if (d.binary) {
item.warn = `Response body is binary (${fmtSize(d.size)}) and is not shown. Leave the body empty to keep the original bytes.`;
} else bodyText = d.text;
} else {
bodyText = r.body;
}
} catch {
// e.g. redirects have no body
}
item.originalBody = bodyText;
item.originalRaw = HTTP.serializeResponse({
status: p.responseStatusCode, statusText: p.responseStatusText,
headers: await withSetCookies(p.networkId, HTTP.headersToList(p.responseHeaders)), body: bodyText,
});
}
if (!state.attached) return; // detached while awaiting
item.raw = item.autoRaw || item.originalRaw;
state.queue.push(item);
if (!state.selectedQueueId) {
state.selectedQueueId = item.id;
loadEditor();
}
renderQueue();
}
function describeChanges(changes) {
return changes.map((c) => `${c.key}: ${c.from} → ${c.to} (${c.where})`).join(', ');
}
/** Forward a request with the auto-rewrite applied, without pausing it. */
async function autoForward(p, req, reqBody, mod) {
const headers = HTTP.headersToList(req.headers).filter((h) => h.name.toLowerCase() !== 'content-length');
const params = { requestId: p.requestId, url: mod.url, method: req.method, headers };
const canBody = reqBody && !reqBody.binary && reqBody.known && reqBody.text.length <= MAX_BODY_CHARS;
const bodyChanged = canBody && HTTP.norm(mod.body) !== HTTP.norm(reqBody.text);
if (bodyChanged) params.postData = HTTP.utf8ToB64(mod.body);
try {
await cdp('Fetch.continueRequest', params);
} catch (e) {
await continuePlain(p.requestId);
return;
}
recordAuto(p, req, mod, bodyChanged);
}
/** Log an auto-rewrite and mark the matching history row edited. */
function recordAuto(p, req, mod, bodyChanged) {
queueLocalSave();
state.autoCount++;
chrome.runtime.sendMessage({ type: 'incrementAutoCount' }).then((result) => {
if (typeof result?.count === 'number') { state.autoCount = result.count; updateStatus(); renderAutoLog(); }
}).catch(() => {});
const entry = {
id: ++state.seq,
method: req.method,
url: mod.url,
changes: mod.changes,
seqNo: state.autoCount,
};
state.autoLog.unshift(entry);
if (state.autoLog.length > 500) state.autoLog.length = 500;
const e = netMap.get(p.networkId) || state.history.find((h) => h.requestId === p.networkId);
if (e) {
e.edited = true;
e.url = mod.url;
if (bodyChanged) e.reqBody = mod.body;
e.note = `auto: ${mod.changes.map((c) => `${c.key} ${c.from}→${c.to}`).join(', ')}`;
touchHistory(e);
}
renderAutoLog();
updateStatus();
}
/** Record an auto-rewrite that the background worker made on another tab. */
function recordAutoExternal(entry) {
queueLocalSave();
state.autoCount = typeof entry.count === 'number' ? entry.count : state.autoCount + 1;
state.autoLog.unshift({
id: ++state.seq,
method: entry.method,
url: entry.url,
changes: entry.changes || [],
seqNo: state.autoCount,
external: true,
});
if (state.autoLog.length > 500) state.autoLog.length = 500;
renderAutoLog();
updateStatus();
}
/** Chrome hides Set-Cookie from Fetch.requestPaused; recover it from the Network
* domain's raw headers so an edited (fulfilled) response doesn't lose cookies. */
async function withSetCookies(networkId, headers) {
if (headers.some((h) => h.name.toLowerCase() === 'set-cookie')) return headers;
const find = () => {
const e = netMap.get(networkId);
if (e && e.resExtra) return e.resHeaders;
const x = extraRes.get(networkId);
return x ? HTTP.headersToList(x.headers) : null;
};
let raw = find();
for (let i = 0; !raw && i < 5; i++) {
await new Promise((r) => setTimeout(r, 20));
raw = find();
}
const cookies = (raw || []).filter((h) => h.name.toLowerCase() === 'set-cookie');
return cookies.length ? [...headers, ...cookies] : headers;
}
const currentItem = () => state.queue.find((i) => i.id === state.selectedQueueId) || null;
function renderQueue() {
const ul = $('#queueList');
ul.innerHTML = '';
for (const item of state.queue) {
const li = document.createElement('li');
li.className = 'qitem' + (item.id === state.selectedQueueId ? ' selected' : '');
li.innerHTML =
`<span class="stage ${item.stage}">${item.stage === 'request' ? 'REQ' : 'RES'}</span>` +
`<span class="m m-${escapeHtml(item.method)}">${escapeHtml(item.method)}</span>` +
(item.stage === 'response' ? `<span class="s${String(item.status)[0]}">${escapeHtml(item.status)}</span>` : '') +
`<span class="url" title="${escapeHtml(item.url)}">${escapeHtml(shortUrl(item.url))}</span>`;
li.addEventListener('click', () => {
state.selectedQueueId = item.id;
loadEditor();
renderQueue();
});
ul.append(li);
}
const n = state.queue.length;
$('#queueEmpty').classList.toggle('hidden', n > 0);
$('#queueCount').textContent = String(n);
const badge = $('#queueBadge');
badge.textContent = String(n);
badge.classList.toggle('hidden', n === 0);
document.title = n ? `(${n}) Interceptor` : 'Interceptor';
// The toolbar badge is owned by the background worker (Auto-mode "ON").
const cur = currentItem();
$('#fwdBtn').disabled = !cur || !!cur.busy;
$('#dropBtn').disabled = !cur || !!cur.busy;
$('#fwdRespBtn').disabled = !cur || !!cur.busy || cur.stage !== 'request';
$('#toRepeaterFromIntercept').disabled = !cur;
$('#fwdAllBtn').disabled = n === 0;
}
function renderAutoLog() {
const ul = $('#autoLogList');
ul.innerHTML = '';
for (const e of state.autoLog) {
const li = document.createElement('li');
li.className = 'alog';
li.innerHTML =
`<div class="top"><span class="n">#${e.seqNo}</span>` +
`<span class="m m-${escapeHtml(e.method)}">${escapeHtml(e.method)}</span>` +
`<span class="url" title="${escapeHtml(e.url)}">${escapeHtml(shortUrl(e.url))}</span></div>` +
`<div class="chg">${escapeHtml(describeChanges(e.changes))}</div>`;
ul.append(li);
}
$('#autoLogCount').textContent = String(state.autoCount);
$('#autoLogEmpty').classList.toggle('hidden', state.autoLog.length > 0);
}
function loadEditor() {
const ed = $('#interceptEditor');
const cur = currentItem();
const warn = $('#editorWarn');
if (!cur) {
ed.value = '';
ed.disabled = true;
$('#editorTitle').textContent = 'No intercepted item selected';
$('#editorHint').textContent = '';
warn.classList.add('hidden');
return;
}
ed.disabled = false;
ed.value = cur.raw;
$('#editorTitle').textContent = cur.stage === 'request' ? 'Intercepted request' : `Intercepted response (${cur.status})`;
$('#editorHint').textContent = `${cur.resourceType || ''} · ${shortUrl(cur.url)}`;
const msg = [cur.autoNote, cur.warn].filter(Boolean).join(' • ');
warn.textContent = msg;
warn.classList.toggle('hidden', !msg);
warn.classList.toggle('auto', !!cur.autoNote && !cur.warn);
}
$('#interceptEditor').addEventListener('input', (e) => {
const cur = currentItem();
if (cur) cur.raw = e.target.value;
});
const isUnchanged = (item) => HTTP.norm(item.raw) === HTTP.norm(item.originalRaw);
/** Build the CDP command that releases a paused item, applying the user's edits. */
function buildRelease(item, catchResponse = false) {
if (item.stage === 'request') {
const params = { requestId: item.id };
if (catchResponse) params.interceptResponse = true;
if (isUnchanged(item)) return { method: 'Fetch.continueRequest', params, edited: false };
const p = HTTP.parseRequest(item.raw, item.url);
params.method = p.method;
params.url = p.url;
params.headers = p.headers.filter((h) => h.name.toLowerCase() !== 'content-length');
const bodyChanged = HTTP.norm(p.body) !== HTTP.norm(item.originalBody);
if (bodyChanged) params.postData = HTTP.utf8ToB64(p.body);
return { method: 'Fetch.continueRequest', params, edited: true, parsed: p, bodyChanged };
}
if (isUnchanged(item)) return { method: 'Fetch.continueRequest', params: { requestId: item.id }, edited: false };
const r = HTTP.parseResponse(item.raw);
const bodyChanged = HTTP.norm(r.body) !== HTTP.norm(item.originalBody);
const body = !bodyChanged
? item.originalBodyB64 ?? HTTP.utf8ToB64(item.originalBody)
: HTTP.utf8ToB64(r.body);
const params = {
requestId: item.id,
responseCode: r.status,
// The body we hold is already decoded, so drop encoding/length headers.
responseHeaders: r.headers.filter((h) => !/^(content-length|content-encoding|transfer-encoding)$/i.test(h.name)),
body,
};
if (r.statusText) params.responsePhrase = r.statusText;
return { method: 'Fetch.fulfillRequest', params, edited: true };
}
function removeFromQueue(id) {
const idx = state.queue.findIndex((i) => i.id === id);
if (idx === -1) return;
state.queue.splice(idx, 1);
if (state.selectedQueueId === id) {
const next = state.queue[idx] || state.queue[idx - 1] || null;
state.selectedQueueId = next ? next.id : null;
loadEditor();
}
renderQueue();
}
async function forwardItem(item, catchResponse = false) {
if (item.busy) return false;
let rel;
try {
rel = buildRelease(item, catchResponse);
} catch (e) {
toast(`Can't forward: ${e.message}`, 'error');
return false;
}
if (catchResponse) state.forceResponse.add(item.id);
item.busy = true;
renderQueue();
try {
await cdp(rel.method, rel.params);
removeFromQueue(item.id);
if (rel.edited) markHistoryEdited(item, rel);
} catch (e) {
state.forceResponse.delete(item.id);
if (/Invalid InterceptionId/i.test(e.message)) {
removeFromQueue(item.id);
toast('That request is no longer pending (page navigated or request was cancelled).', 'error');
} else {
toast(`Forward failed: ${e.message}. Fix the edit and try again.`, 'error');
}
return false;
} finally {
item.busy = false;
renderQueue();
}
return true;
}
async function dropItem(item) {
if (item.busy) return;
removeFromQueue(item.id);
try {
await cdp('Fetch.failRequest', { requestId: item.id, errorReason: 'BlockedByClient' });
} catch { /* already gone */ }
const e = netMap.get(item.networkId);
if (e) { e.note = 'dropped'; scheduleHistoryRender(); }
}
/** Release everything in the queue (used by Forward all / intercept off / detach). */
async function releaseAll(applyEdits) {
const items = state.queue.filter((item) => !item.busy);
state.queue = state.queue.filter((item) => item.busy);
state.selectedQueueId = null;
loadEditor();
renderQueue();
await Promise.all(items.map(async (item) => {
if (applyEdits) {
try {
const rel = buildRelease(item);
await cdp(rel.method, rel.params);
if (rel.edited) markHistoryEdited(item, rel);
return;
} catch { /* fall back to unchanged */ }
}
await continuePlain(item.id);
}));
}
function toggleIntercept() {
state.interceptOn = !state.interceptOn;
if (state.interceptOn && !state.attached) toast('Intercept is ON — now attach to a tab to start catching requests.');
// Turning intercept off must release any queued items, even when Auto mode
// keeps the Fetch domain enabled (so they don't hang waiting for Forward).
if (!state.interceptOn && state.queue.length) {
releaseAll(true).then(() => applyFetch()).catch((e) => toast(e.message, 'error'));
} else {
applyFetch().catch((e) => toast(e.message, 'error'));
}
updateStatus();
}
// ======================================================================
// HTTP History (Network domain)
// ======================================================================
const netMap = new Map(); // Network requestId -> live history entry
const extraReq = new Map(); // requestWillBeSentExtraInfo that arrived early
const extraRes = new Map(); // responseReceivedExtraInfo that arrived early
function applyResponse(e, r) {
e.status = r.status;
e.statusText = r.statusText || '';
e.mime = r.mimeType || '';
e.httpVersion = /^h2|http\/2/i.test(r.protocol || '') ? 'HTTP/2' : /^h3/i.test(r.protocol || '') ? 'HTTP/3' : 'HTTP/1.1';
if (!e.resExtra) e.resHeaders = HTTP.headersToList(r.headers);
}
function onRequestWillBeSent(p) {
if (!Lab.historyUrlAllowed(p.request.url)) return;
const prev = netMap.get(p.requestId);
if (prev && p.redirectResponse) {
applyResponse(prev, p.redirectResponse);
prev.state = 'done';
prev.duration = (p.timestamp - prev.ts) * 1000;
prev.resBody = '';
netMap.delete(p.requestId);
touchHistory(prev);
}
const body = requestBodyFromCdp(p.request);
const e = {
id: ++state.seq,
requestId: p.requestId,
method: p.request.method,
url: p.request.url,
reqHeaders: HTTP.headersToList(p.request.headers),
reqBody: body.binary ? `[binary request body, ${fmtSize(body.size)}]` : !body.known ? '[request body unavailable: full upload bytes were not captured]' : limitBody(body.text, 'request body'),
reqBodyComplete: body.known && !body.binary && body.text.length <= MAX_BODY_CHARS,
type: p.type || 'Other',
wallTime: p.wallTime ? p.wallTime * 1000 : Date.now(),
ts: p.timestamp,
status: null, statusText: '', resHeaders: [], resBody: null, httpVersion: 'HTTP/1.1',
size: null, duration: null, state: 'pending', error: null, mime: '', note: '',
reqExtra: false, resExtra: false, edited: false,
};
const x = extraReq.get(p.requestId);
if (x) { e.reqHeaders = HTTP.headersToList(x.headers); e.reqExtra = true; extraReq.delete(p.requestId); }
if (!body.known && !body.binary) {
cdp('Network.getRequestPostData', { requestId: p.requestId }).then((r) => {
// CDP omits file bytes from multipart post data. A fallback string is not
// proof that an upload with missing entries was captured completely.
const ct = HTTP.getHeader(e.reqHeaders, 'content-type') || '';
const missingEntry = p.request.postDataEntries?.some((entry) => typeof entry.bytes !== 'string');
if (missingEntry || /^multipart\//i.test(ct)) return;
const recovered = r.base64Encoded ? HTTP.decodeBody(HTTP.b64ToBytes(r.postData)) : { text: r.postData, binary: false };
if (recovered.binary || typeof recovered.text !== 'string') return;
e.reqBody = limitBody(recovered.text, 'request body');
e.reqBodyComplete = recovered.text.length <= MAX_BODY_CHARS;
pruneHistory();
touchHistory(e);
}).catch(() => {});
}
netMap.set(p.requestId, e);
state.history.push(e);
pruneHistory();
scheduleHistoryRender();
}
function onRequestExtra(p) {
const e = netMap.get(p.requestId);
if (e && !e.reqExtra) {
if (!e.edited) e.reqHeaders = HTTP.headersToList(p.headers);
e.reqExtra = true;
touchHistory(e);
} else {
extraReq.set(p.requestId, p);
if (extraReq.size > 500) extraReq.delete(extraReq.keys().next().value);
}
}
function onResponseReceived(p) {
const e = netMap.get(p.requestId);
if (!e) return;
const x = extraRes.get(p.requestId);
if (x) { e.resHeaders = HTTP.headersToList(x.headers); e.resExtra = true; extraRes.delete(p.requestId); }
applyResponse(e, p.response);
e.type = p.type || e.type;
touchHistory(e);
}
function onResponseExtra(p) {
const e = netMap.get(p.requestId);
if (e) {
e.resHeaders = HTTP.headersToList(p.headers);
e.resExtra = true;
if (p.statusCode && e.status == null) e.status = p.statusCode;
touchHistory(e);
} else {
extraRes.set(p.requestId, p);
if (extraRes.size > 500) extraRes.delete(extraRes.keys().next().value);
}
}
async function onLoadingFinished(p) {
const e = netMap.get(p.requestId);
if (!e) return;
e.size = p.encodedDataLength;
e.duration = (p.timestamp - e.ts) * 1000;
e.state = 'done';
touchHistory(e);
try {
if (p.encodedDataLength > MAX_BODY_CHARS * 2) {
e.resBody = `[body not captured: encoded response is ${fmtSize(p.encodedDataLength)}]`;
} else {
const r = await cdp('Network.getResponseBody', { requestId: p.requestId });
if (r.base64Encoded) {
const bytes = HTTP.b64ToBytes(r.body);
const d = HTTP.decodeBody(bytes);
e.resBody = d.binary ? `[binary ${e.mime || 'data'}, ${fmtSize(d.size)} — not shown]` : d.text;