-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhunt.js
More file actions
1256 lines (1157 loc) · 63.7 KB
/
hunt.js
File metadata and controls
1256 lines (1157 loc) · 63.7 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
// PenScope v6.2 — Hunt Mode (autonomous attacker + report drafter)
//
// Orchestrates the existing PenScope engine pieces (probe, stack packs, auth matrix,
// chain analyzer) into an autonomous "set scope and forget" workflow. When the chain
// analyzer surfaces a Critical or High chain, Hunt Mode composes a full
// HackerOne-format report draft, fires a Chrome notification, and persists the draft
// to chrome.storage.local under the host bucket.
//
// State model:
// - SOURCE_TAB_ID — the tab being hunted (passed in URL hash)
// - hunt config + state lives in the foreground page (this file) for v6.2.
// If the user closes the tab, the hunt aborts. Background-driven persistence
// across tab close comes in v6.2.1.
// - reports persist in chrome.storage.local keyed by host (survive tab close + SW restart)
const params = new URLSearchParams(location.search);
const SOURCE_TAB_ID = parseInt(params.get('source')) || null;
let activeSubtab = 'setup';
let TARGET_URL = '';
let TARGET_HOST = '';
let HUNT_STATE = null; // null = idle; { running, startTime, config, steps, currentStepIdx, ... } when running
let SAVED_REPORTS = [];
let CURRENT_VIEWING_REPORT = null;
// -------------------------------------------------------------------
// Utility
// -------------------------------------------------------------------
function $(id) { return document.getElementById(id); }
function esc(s) { return String(s == null ? '' : s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"'); }
function toast(msg) {
const t = $('toast');
t.textContent = msg;
t.classList.add('show');
clearTimeout(toast._t);
toast._t = setTimeout(() => t.classList.remove('show'), 2200);
}
function fmtTime(ms) {
const s = Math.floor(ms / 1000);
if (s < 60) return s + 's';
const m = Math.floor(s / 60);
if (m < 60) return m + 'm ' + (s % 60) + 's';
return Math.floor(m / 60) + 'h ' + (m % 60) + 'm';
}
function copyClip(text, label) {
navigator.clipboard.writeText(text || '').then(() => toast('Copied' + (label ? ' ' + label : '')), () => toast('Clipboard blocked'));
}
// Glob → RegExp. Supports * (any chars within a path segment) and ** (any chars including /).
// Used to filter endpoints by in/out scope rules.
function globToRegex(pattern) {
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&');
const withWild = escaped.replace(/\*\*/g, '@@DOUBLEWILD@@').replace(/\*/g, '[^/]*').replace(/@@DOUBLEWILD@@/g, '.*');
return new RegExp('^' + withWild + '$');
}
function pathMatchesAny(path, patterns) {
for (const p of patterns) {
try { if (globToRegex(p).test(path)) return true; } catch (e) {}
}
return false;
}
// -------------------------------------------------------------------
// Bootstrap
// -------------------------------------------------------------------
document.addEventListener('DOMContentLoaded', async () => {
document.querySelectorAll('.nav-btn').forEach(btn => btn.addEventListener('click', () => switchSubtab(btn.dataset.subtab)));
if (!SOURCE_TAB_ID) {
document.querySelector('.main').innerHTML = `
<div style="padding:80px 24px;text-align:center;color:var(--t2)">
<div style="font-size:36px;margin-bottom:14px;opacity:.5">⚠</div>
<div style="font-size:14px">No source tab specified.</div>
<div style="font-size:11px;color:var(--t3);margin-top:8px">Open Hunt Mode from the PenScope popup.</div>
</div>`;
return;
}
// Pull the source tab URL for the target pill + auto-fill
try {
const tab = await chrome.tabs.get(SOURCE_TAB_ID);
if (tab && tab.url) {
TARGET_URL = tab.url;
try { TARGET_HOST = new URL(tab.url).hostname; } catch (e) {}
$('targetUrl').textContent = tab.url;
$('cfgTarget').value = tab.url;
}
} catch (e) { /* tab closed */ }
// Wire setup pills (radio behavior)
document.querySelectorAll('#cfgAggro .pill-btn').forEach(b => {
b.addEventListener('click', () => {
document.querySelectorAll('#cfgAggro .pill-btn').forEach(x => { x.classList.toggle('active', x === b); x.setAttribute('aria-checked', x === b); });
});
});
document.querySelectorAll('#cfgBudget .pill-btn').forEach(b => {
b.addEventListener('click', () => {
document.querySelectorAll('#cfgBudget .pill-btn').forEach(x => { x.classList.toggle('active', x === b); x.setAttribute('aria-checked', x === b); });
});
});
$('huntStartBtn').addEventListener('click', startHunt);
$('huntStopBtn').addEventListener('click', stopHunt);
$('reportsRefresh').addEventListener('click', loadReports);
$('reportsExportAll').addEventListener('click', exportAllReports);
$('reportsClearAll').addEventListener('click', clearAllReports);
// Modal
$('modalCloseBtn').addEventListener('click', () => $('reportModal').classList.remove('show'));
$('reportModal').addEventListener('click', e => { if (e.target.id === 'reportModal') $('reportModal').classList.remove('show'); });
$('modalCopyBtn').addEventListener('click', () => { if (CURRENT_VIEWING_REPORT) copyClip(CURRENT_VIEWING_REPORT.markdown, 'report'); });
$('modalExportBtn').addEventListener('click', () => { if (CURRENT_VIEWING_REPORT) exportSingleReport(CURRENT_VIEWING_REPORT); });
$('modalDeleteBtn').addEventListener('click', () => { if (CURRENT_VIEWING_REPORT) deleteReport(CURRENT_VIEWING_REPORT.id); });
// Initial: load any persisted reports for this host
await loadReports();
// v6.2.4 — Pre-flight indicator. Shows the engine state before the user clicks
// Start, so they know whether they have enough captured surface for a productive
// hunt. Auto-refreshes when the user returns to the Setup tab. The Refresh button
// re-pulls in case the user browsed the target between opening Hunt Mode and
// clicking Start.
$('pfRefresh').addEventListener('click', refreshPreflight);
await refreshPreflight();
// If a hunt is already running (e.g. user refreshed the page), refuse to restart;
// background isn't tracking it (foreground orchestrator), so we just reset to idle.
setStatus('idle', 'Idle');
});
async function refreshPreflight() {
try {
const state = await wbGetTabData();
const wbState = await new Promise(resolve => {
chrome.runtime.sendMessage({ action: 'wbGetState', tabId: SOURCE_TAB_ID }, r => {
void chrome.runtime.lastError;
resolve(r || {});
});
});
const epCount = (state.endpoints || []).length;
const secretsCount = (state.secrets || []).length;
const techCount = (state.techStack || []).length;
const authCtxCount = ((wbState.auth && wbState.auth.list) || []).length;
$('pfEndpoints').textContent = epCount;
$('pfSecrets').textContent = secretsCount;
$('pfTech').textContent = techCount;
$('pfAuthCtx').textContent = authCtxCount;
// Warning thresholds. Below 20 endpoints means the probe will have very thin
// surface to test against — this is the #1 reason a hunt finishes with 0 reports.
// The DOM-crawl step (added in v6.2.4) will harvest more URLs at hunt time, but
// the user should know upfront if their starting position is weak.
const warningEl = $('preflightWarning');
const warnings = [];
if (epCount < 20) {
warnings.push(`Only <strong>${epCount}</strong> endpoint${epCount===1?'':'s'} captured passively. Hunt Mode will run a DOM crawl step to harvest more from the page, but for the richest hunt: <strong>browse the target site for 30+ seconds</strong> (click links, log in, navigate routes, expand menus) before clicking Start. Then click ↻ to refresh this panel.`);
}
if (authCtxCount < 2) {
warnings.push(`Only <strong>${authCtxCount}</strong> auth context${authCtxCount===1?'':'s'} saved. Authorization Matrix needs 2+ contexts to surface IDOR/BAC anomalies — set them up in Workbench → Auth Contexts (log in as User A, save cookies; log in as Admin, save cookies). Then enable "Run Authorization Matrix sweep" in this Setup.`);
}
if (warnings.length) {
warningEl.style.display = '';
warningEl.innerHTML = '⚠ ' + warnings.join('<br><br>⚠ ');
} else {
warningEl.style.display = 'none';
}
} catch (e) { /* tab may have closed */ }
}
function switchSubtab(name) {
activeSubtab = name;
document.querySelectorAll('.nav-btn').forEach(b => {
const on = b.dataset.subtab === name;
b.classList.toggle('active', on);
b.setAttribute('aria-selected', on);
});
document.querySelectorAll('.subtab').forEach(s => s.classList.toggle('active', s.id === 'sub-' + name));
if (name === 'reports') loadReports();
// v6.2.4 — Refresh pre-flight indicator when the user returns to Setup. They may
// have browsed the target between hunts, picking up more endpoints.
if (name === 'setup' && typeof refreshPreflight === 'function') refreshPreflight();
}
function setStatus(kind, text) {
const pill = $('statusPill');
pill.classList.remove('live', 'done', 'error');
if (kind === 'live') pill.classList.add('live');
else if (kind === 'done') pill.classList.add('done');
else if (kind === 'error') pill.classList.add('error');
$('statusText').textContent = text;
}
// -------------------------------------------------------------------
// Configuration
// -------------------------------------------------------------------
function readConfig() {
const aggroBtn = document.querySelector('#cfgAggro .pill-btn.active');
const budgetBtn = document.querySelector('#cfgBudget .pill-btn.active');
return {
target: $('cfgTarget').value.trim() || TARGET_URL,
inScope: $('cfgInScope').value.split('\n').map(s => s.trim()).filter(Boolean),
outScope: $('cfgOutScope').value.split('\n').map(s => s.trim()).filter(Boolean),
aggro: aggroBtn ? aggroBtn.dataset.aggro : 'medium',
budgetMin: budgetBtn ? parseInt(budgetBtn.dataset.budget) : 15,
runProbes: $('cfgProbes').checked,
runStackPacks: $('cfgStackPacks').checked,
runAuthMatrix: $('cfgAuthMatrix').checked,
chainOnly: $('cfgChainOnly').checked,
notify: $('cfgNotify').checked,
};
}
// -------------------------------------------------------------------
// Hunt orchestration — runs the engine pieces in sequence
// -------------------------------------------------------------------
const HUNT_STEPS = [
{ id: 'init', label: 'Bootstrap engine + capture passive state', weight: 5 },
{ id: 'deep', label: 'Enable Deep mode (CDP debugger)', weight: 3 },
{ id: 'wait', label: 'Wait for passive scan to settle', weight: 5 },
{ id: 'crawl', label: 'DOM crawl — harvest URLs from anchors/forms/iframes', weight: 4 },
{ id: 'probe', label: 'Run 36-step probe pipeline', weight: 43 },
{ id: 'matrix', label: 'Run Authorization Matrix sweep', weight: 20 },
{ id: 'analyze', label: 'Run chain correlator + aggregate findings', weight: 5 },
{ id: 'report', label: 'Draft HackerOne-format reports for High+ findings', weight: 10 },
{ id: 'finish', label: 'Save drafts + fire notifications', weight: 5 },
];
async function startHunt() {
const cfg = readConfig();
if (!cfg.target) { toast('Target URL required'); return; }
if (HUNT_STATE && HUNT_STATE.running) { toast('Hunt already running'); return; }
HUNT_STATE = {
running: true,
startTime: Date.now(),
config: cfg,
currentStepIdx: 0,
findings: [],
chains: [],
reports: [],
abortRequested: false,
feed: [],
};
$('huntStartBtn').style.display = 'none';
$('huntStopBtn').style.display = '';
setStatus('live', 'Hunting');
switchSubtab('live');
renderSteps();
feedLine('info', 'Hunt started · target ' + cfg.target + ' · aggression ' + cfg.aggro + ' · budget ' + cfg.budgetMin + ' min');
// Time budget timer
HUNT_STATE.budgetTimer = setTimeout(() => {
if (HUNT_STATE && HUNT_STATE.running) {
feedLine('info', 'Time budget reached — stopping hunt');
stopHunt();
}
}, cfg.budgetMin * 60 * 1000);
// Live progress ticker
HUNT_STATE.tickInterval = setInterval(updateProgress, 500);
try {
await runHuntLoop();
if (HUNT_STATE && HUNT_STATE.running) {
finishHunt('done');
}
} catch (e) {
feedLine('crit', 'Hunt error: ' + (e.message || e));
finishHunt('error');
}
}
function stopHunt() {
if (!HUNT_STATE) return;
HUNT_STATE.abortRequested = true;
feedLine('info', 'Stop requested — finishing current step then stopping');
finishHunt('stopped');
}
function finishHunt(reason) {
if (!HUNT_STATE) return;
HUNT_STATE.running = false;
if (HUNT_STATE.budgetTimer) clearTimeout(HUNT_STATE.budgetTimer);
if (HUNT_STATE.tickInterval) clearInterval(HUNT_STATE.tickInterval);
$('huntStartBtn').style.display = '';
$('huntStopBtn').style.display = 'none';
if (reason === 'done') setStatus('done', 'Done');
else if (reason === 'error') setStatus('error', 'Error');
else if (reason === 'stopped') setStatus('done', 'Stopped');
const elapsed = Date.now() - HUNT_STATE.startTime;
const reportCount = (HUNT_STATE.reports || []).length;
feedLine('info', `Hunt finished — ${fmtTime(elapsed)} · ${reportCount} report${reportCount===1?'':'s'} drafted`);
// v6.2.3 — "Why no reports?" diagnostic. The single most-confusing UX moment is
// "Hunt says Done but I see 0 reports". This block walks the diagnostic counters we
// accumulated through the loop and explains in plain English where every potential
// report got dropped, with concrete suggestions for what to change.
if (reportCount === 0 && HUNT_STATE._diagnostics) {
const d = HUNT_STATE._diagnostics;
feedLine('crit', '────────────────────────────────────────');
feedLine('crit', ' Why no reports were drafted:');
feedLine('crit', '────────────────────────────────────────');
if (d.rawChainCount === 0) {
feedLine('info', ` · Chain analyzer produced 0 chains. Chains form when probe results combine with secrets/endpoints/auth context — empty means no compound exploit paths were detected.`);
} else {
feedLine('info', ` · Chain analyzer produced ${d.rawChainCount} chain${d.rawChainCount===1?'':'s'} (${d.rawSeverityDist.critical} crit, ${d.rawSeverityDist.high} high, ${d.rawSeverityDist.medium} med, ${d.rawSeverityDist.low} low)`);
}
if (d.scopeDropped > 0) {
feedLine('info', ` · Scope filter dropped ${d.scopeDropped} chain${d.scopeDropped===1?'':'s'} (paths matched ${HUNT_STATE.config.outScope.length?'out-of-scope':'no in-scope'} rules)`);
}
if (d.passiveFindingsCount === 0 && d.secretsTotal > 0) {
feedLine('info', ` · Passive findings: ${d.secretsTotal} secret${d.secretsTotal===1?'':'s'} found, but ALL are below high severity → ineligible for individual-finding fallback (which only drafts critical/high)`);
} else if (d.passiveFindingsCount === 0) {
feedLine('info', ` · No high-severity passive findings (no exposed secrets, JWT alg=none, or confirmed SSTI/XXE/CRLF in scope)`);
}
if (HUNT_STATE.config.runAuthMatrix && d.matrixAdded === 0) {
feedLine('info', ` · Authorization Matrix added 0 anomalies — either no anomalies found, or matrix didn't run (need 2+ saved auth contexts)`);
} else if (!HUNT_STATE.config.runAuthMatrix) {
feedLine('info', ` · Authorization Matrix is disabled in this hunt (huge IDOR/BAC source — enable it in Setup if you have saved auth contexts)`);
}
feedLine('crit', '────────────────────────────────────────');
feedLine('crit', ' Try one of:');
feedLine('crit', '────────────────────────────────────────');
if (HUNT_STATE.config.chainOnly) {
feedLine('info', ` → Uncheck "Only Critical + High severity" in Setup to include medium/low findings`);
}
if (!HUNT_STATE.config.runAuthMatrix) {
feedLine('info', ` → Save 2+ auth contexts in Workbench → Auth Contexts, then re-hunt with the matrix enabled (catches IDOR/BAC)`);
}
if (HUNT_STATE.config.aggro === 'careful') {
feedLine('info', ` → Try aggression: Medium or Full Send (more probe steps run, more chains form). Check the bug bounty program's TOS first.`);
}
if (d.rawChainCount === 0 && (d.secretsTotal === 0)) {
feedLine('info', ` → Browse the target more before hunting (click links, log in, navigate routes) — PenScope only knows about endpoints it has captured passively`);
}
feedLine('info', ` → Open Classic mode to see the full unfiltered scan data, including everything below the report threshold`);
}
loadReports();
}
async function runHuntLoop() {
const cfg = HUNT_STATE.config;
// ---- Step 0: init ----
setStep('init', 'live');
feedLine('info', 'Connecting to background engine...');
const initialState = await wbGetTabData();
setStep('init', 'done', `${initialState.endpoints.length} endpoints captured passively`);
if (HUNT_STATE.abortRequested) return;
// ---- Step 0.5: Auto-enable Deep mode (CDP debugger). The probe step requires this;
// without it the user gets "Probe error: Deep mode required" and the hunt produces
// zero results. The debugger.attach API is granted at install time via the manifest
// permission, so enableDeep just works without user interaction. If the source tab
// is on a chrome:// page or the debugger is already attached by another extension,
// attach fails — we surface the error but continue (passive findings still useful). ----
setStep('deep', 'live');
const deepRes = await new Promise(resolve => {
chrome.runtime.sendMessage({ action: 'enableDeep', tabId: SOURCE_TAB_ID }, r => {
void chrome.runtime.lastError;
resolve(r || {});
});
});
if (deepRes.ok) {
setStep('deep', 'done', 'CDP attached — probe will run');
feedLine('info', 'Deep mode auto-enabled. Probe pipeline will have full capabilities.');
} else {
setStep('deep', 'done', 'failed — passive only');
feedLine('crit', 'Deep mode failed to attach (already attached by another extension, or source tab is internal). Probe will be skipped, but passive findings will still be drafted as reports.');
}
if (HUNT_STATE.abortRequested) return;
// ---- Step 1: wait for passive scan to settle ----
setStep('wait', 'live');
await chrome.runtime.sendMessage({ action: 'runScan', tabId: SOURCE_TAB_ID }).catch(() => {});
await delay(4000); // give the content-script scan time to flush
const afterScan = await wbGetTabData();
setStep('wait', 'done', `${afterScan.endpoints.length} endpoints, ${afterScan.secrets.length} secrets, ${afterScan.techStack.length} tech detected`);
if (HUNT_STATE.abortRequested) return;
// ---- Step 1.5: DOM auto-crawl (v6.2.4). PenScope's recursive probe step (#30)
// chains URLs found in API responses, but it doesn't read the actual page DOM.
// If the user opens a target's dashboard with 50 sidebar links, those URLs never
// make it into PenScope's discovery list — the probe has nothing to test against.
// This step injects a script that walks every <a href>, <form action>, <iframe src>,
// and SPA-router-style attributes ([routerLink], [ng-href], [to], [data-href]),
// filters to same-origin URLs, and feeds them into tab.discoveredRoutes so the
// probe step picks them up. Pure URL extraction — no clicking, no navigation, no
// session-changing side effects. ----
setStep('crawl', 'live');
feedLine('info', 'Crawling DOM for same-origin URLs (anchors, forms, iframes, SPA route attrs)...');
const crawlRes = await new Promise(resolve => {
chrome.runtime.sendMessage({ action: 'huntDomCrawl', tabId: SOURCE_TAB_ID }, r => {
void chrome.runtime.lastError;
resolve(r || {});
});
});
if (crawlRes.ok) {
const added = crawlRes.added || 0;
const total = crawlRes.totalSeen || 0;
setStep('crawl', 'done', `${added} new URL${added===1?'':'s'} added (${total} found in DOM)`);
feedLine('info', `DOM crawl: ${total} URLs found in page DOM, ${added} new (rest already known to PenScope)`);
} else {
setStep('crawl', 'done', 'failed: ' + (crawlRes.error || 'unknown'));
feedLine('crit', 'DOM crawl failed: ' + (crawlRes.error || 'unknown') + ' (continuing — probe will use existing endpoints only)');
}
if (HUNT_STATE.abortRequested) return;
// ---- Step 2: probe pipeline ----
if (cfg.runProbes) {
setStep('probe', 'live');
feedLine('info', 'Firing probe — this is the long step');
const probeRes = await runProbeViaBackground(cfg);
if (probeRes && probeRes.ok) {
const r = probeRes.results || {};
const reqs = r.requests || 0;
// Break down what the probe actually found by category. If reqs > 0 but every
// count below is 0, the user knows the probe ran but nothing was exploitable.
const breakdown = summarizeProbeResults(r);
setStep('probe', 'done', `${reqs} requests · ${breakdown.totalConfirmed} confirmed findings`);
feedLine('info', `Probe complete — ${reqs} requests fired`);
if (breakdown.totalConfirmed > 0) {
breakdown.lines.forEach(line => feedLine('info', ' · ' + line));
} else {
feedLine('info', ' · 0 confirmed exploitable findings from probe (target is well-secured, or aggression too low to trigger them)');
}
} else {
setStep('probe', 'done', 'failed: ' + (probeRes?.error || 'unknown'));
feedLine('crit', 'Probe error: ' + (probeRes?.error || 'unknown') + ' (continuing with what we have)');
}
} else {
setStep('probe', 'done', 'skipped (disabled in config)');
feedLine('info', 'Probe skipped — only passive findings will be drafted');
}
if (HUNT_STATE.abortRequested) return;
// ---- Step 3: auth matrix ----
if (cfg.runAuthMatrix) {
setStep('matrix', 'live');
const matrixRes = await runAuthMatrixSweep();
setStep('matrix', 'done', matrixRes.message);
} else {
setStep('matrix', 'done', 'skipped (disabled in config)');
}
if (HUNT_STATE.abortRequested) return;
// ---- Step 4: chain analyzer + finding aggregator ----
// The chain correlator surfaces compound exploit paths (the killer feature). But on
// sites where Deep mode failed or the probe found nothing, the analyzer might emit
// 0 chains while we still have legitimate high-severity passive findings (exposed
// secrets, JWT tokens, etc.) that absolutely warrant a bounty report. Fall back to
// wrapping those individual findings as chain-shaped objects so the report composer
// can draft them.
//
// Every filter step below logs its before/after counts so users can see exactly why
// an item didn't make it to a report. The most common confusing outcome — "hunt
// says done but 0 reports" — is almost always the severity filter dropping mediums.
setStep('analyze', 'live');
const finalState = await wbGetTabData();
const rawChains = finalState.chains || [];
feedLine('info', `Chain analyzer produced ${rawChains.length} compound chain${rawChains.length===1?'':'s'} from probe + passive data`);
if (rawChains.length === 0) {
feedLine('info', ' (chains form when probe results combine with secrets/endpoints/auth context — empty means no compound exploit paths detected)');
} else {
const sevDist = severityCounts(rawChains);
feedLine('info', ` Severity breakdown: ${sevDist.critical} critical · ${sevDist.high} high · ${sevDist.medium} medium · ${sevDist.low} low · ${sevDist.info} info`);
}
// Scope filter — silent in v6.2.x; now logs how many items were dropped and why
let chains = filterChainsByScope(rawChains, cfg);
const scopeDropped = rawChains.length - chains.length;
if (scopeDropped > 0) {
feedLine('info', `Scope filter: dropped ${scopeDropped} chain${scopeDropped===1?'':'s'} (paths matched ${cfg.outScope.length?'out-of-scope':'not in-scope'} rules)`);
} else if (rawChains.length > 0) {
feedLine('info', `Scope filter: all ${rawChains.length} chains in scope`);
}
// Add HUNT_STATE-internal matrix anomalies (synthesized by runAuthMatrixSweep)
const matrixChains = (HUNT_STATE.chains || []).filter(c => c && c.findingType === 'authz-matrix');
let matrixAdded = 0;
matrixChains.forEach(mc => {
if (!chains.find(x => x.id === mc.id)) { chains.push(mc); matrixAdded++; }
});
if (matrixAdded > 0) feedLine('info', `Authorization Matrix added ${matrixAdded} authz-disagreement finding${matrixAdded===1?'':'s'}`);
// Fallback: synthesize chain-shaped objects for individual high/critical findings
// that aren't already represented in a chain. This catches the "Deep mode failed +
// 3 passive secrets sitting there" case where the chain count is 0 but reportable
// findings exist. Same scope filter applies.
const passiveFindings = collectIndividualFindings(finalState, cfg);
if (passiveFindings.length > 0) {
const passSev = severityCounts(passiveFindings);
feedLine('info', `Individual findings (passive): ${passiveFindings.length} found · ${passSev.critical} critical · ${passSev.high} high (${(finalState.secrets||[]).length} total secrets in scope, only critical/high are eligible)`);
} else if ((finalState.secrets || []).length > 0) {
feedLine('info', `Individual findings: 0 high-severity (${(finalState.secrets||[]).length} secrets exist but all are below high severity, won't be drafted)`);
}
passiveFindings.forEach(f => chains.push(f));
// Severity filter: when chainOnly is on, restrict to Critical + High. Otherwise
// include everything (some hunters prefer a full draft queue).
const beforeSev = chains.length;
if (cfg.chainOnly) {
chains = chains.filter(c => c.severity === 'critical' || c.severity === 'high');
const sevDropped = beforeSev - chains.length;
if (sevDropped > 0) {
feedLine('info', `Severity filter (Critical+High only): kept ${chains.length}, dropped ${sevDropped} medium/low${beforeSev > 0 && chains.length === 0 ? ' — uncheck "Only Critical + High" in Setup to include them' : ''}`);
}
} else {
feedLine('info', `Severity filter: off — including all severities (${chains.length} items)`);
}
// Final dedupe by id so a real chain and its corresponding individual finding don't
// both produce reports.
const beforeDedup = chains.length;
const seenIds = new Set();
chains = chains.filter(c => {
if (!c.id) return true;
if (seenIds.has(c.id)) return false;
seenIds.add(c.id);
return true;
});
const dedupDropped = beforeDedup - chains.length;
if (dedupDropped > 0) feedLine('info', `Dedupe: removed ${dedupDropped} duplicate${dedupDropped===1?'':'s'} (chain + individual finding for same root)`);
HUNT_STATE.chains = chains;
HUNT_STATE._diagnostics = {
rawChainCount: rawChains.length,
rawSeverityDist: severityCounts(rawChains),
scopeDropped,
matrixAdded,
passiveFindingsCount: passiveFindings.length,
sevDropped: cfg.chainOnly ? (beforeSev - (cfg.chainOnly ? chains.length + dedupDropped : chains.length + dedupDropped)) : 0,
final: chains.length,
secretsTotal: (finalState.secrets || []).length,
matrixContexts: ((finalState.authContexts || []).length) || null,
};
setStep('analyze', 'done', `${chains.length} reportable item${chains.length===1?'':'s'}`);
if (chains.length === 0) {
feedLine('crit', `0 items survived all filters — see "Why no reports?" diagnostic at hunt completion below`);
} else {
feedLine('info', `✓ ${chains.length} item${chains.length===1?'':'s'} ready for report drafting`);
}
if (HUNT_STATE.abortRequested) return;
// ---- Step 5: draft reports ----
setStep('report', 'live');
const reports = [];
for (const chain of chains) {
if (HUNT_STATE.abortRequested) break;
const report = composeReport(chain, finalState, cfg);
reports.push(report);
HUNT_STATE.reports = reports;
feedLine(severityFeedKind(chain.severity), `Drafted: [${(chain.severity || 'info').toUpperCase()}] ${chain.title}`);
if (cfg.notify && (chain.severity === 'critical' || chain.severity === 'high')) {
fireNotification(chain, report);
}
updateProgress();
}
setStep('report', 'done', `${reports.length} reports composed`);
// ---- Step 6: persist ----
setStep('finish', 'live');
await persistReports(reports);
setStep('finish', 'done', 'saved to local storage');
feedLine('info', 'All reports saved · view in Reports tab');
}
// Synthesize chain-shaped objects from individual passive findings. Used as a fallback
// when the chain correlator emits few/no chains (e.g. Deep mode failed and probe didn't
// run). Each returned object has the same shape as a real chain — composeReport doesn't
// have to know the difference.
//
// Sources walked: secrets (high+), exposed-env probe results, JWT findings with weak
// algorithms, source map URLs (medium-severity). Extend conservatively — we don't want
// to draft 200 reports for medium-severity info leaks.
function collectIndividualFindings(state, cfg) {
const out = [];
const inP = cfg.inScope || [];
const outP = cfg.outScope || [];
function pathInScope(path) {
if (!path) return true;
if (outP.length && pathMatchesAny(path, outP)) return false;
if (inP.length && !pathMatchesAny(path, inP)) return false;
return true;
}
// Secrets — high & critical severity only. The content scan and probe both populate
// this list. Each becomes a wrapped finding with a real curl repro.
(state.secrets || []).forEach((s, idx) => {
if (!s || (s.severity !== 'critical' && s.severity !== 'high')) return;
if (!pathInScope(s.source || '')) return;
const valuePreview = String(s.value || '').substring(0, 80);
out.push({
id: 'secret-' + (s.type || 'unk').toLowerCase().replace(/[^a-z0-9]+/g, '-') + '-' + idx,
severity: s.severity,
title: `Exposed ${s.type || 'secret'}`,
summary: `PenScope detected an exposed ${s.type || 'secret'} during recon. Source: \`${s.source || 'unknown source'}\`. Value preview: \`${valuePreview}${(s.value || '').length > 80 ? '…' : ''}\`. ${s.context ? 'Context: ' + s.context.substring(0, 200) : ''} Hardcoded secrets in shipped code/responses are immediately exploitable — assume the credential is compromised the moment it's served.`,
findings: [{ type: s.type || 'exposed-secret', source: s.source, evidence: valuePreview, path: s.source || '' }],
reproCmd: s.source && /^https?:/i.test(s.source)
? `curl -i "${s.source}" | grep -i "${(s.type || '').split(' ')[0].toLowerCase()}"`
: `# Verify the exposed secret is reachable\n# Source: ${s.source || '(unknown)'}\n# Value: ${valuePreview}`,
nextSteps: [
'Confirm the secret is valid by testing it against the corresponding API',
'Determine the blast radius (what does this credential authorize?)',
'Notify the program — exposed secrets are typically high-severity even before exploitation',
],
confidence: 0.85,
findingType: 'exposed-secret',
});
});
// JWT findings with alg=none or weak algorithms — these are immediately exploitable
// for auth bypass. Promote to chain-shape for report drafting.
(state.probeData?.jwtAlgResults || []).forEach((j, idx) => {
if (!j.confirmed) return;
if (!pathInScope(j.path || '')) return;
out.push({
id: 'jwt-alg-' + idx,
severity: 'critical',
title: `JWT alg=none accepted on ${j.path || 'endpoint'}`,
summary: `The server at \`${j.path}\` accepts JWTs with \`alg=none\` (unsigned). Any attacker can forge a token with arbitrary claims (including \`role: admin\`) and the server will trust it. This is a complete authentication bypass.`,
findings: [{ type: 'jwt-alg-none', path: j.path, evidence: j.note || 'server accepted unsigned token' }],
reproCmd: `# Forge an alg=none token (use PenScope Workbench → Encoder → JWT card)\nheader='{"alg":"none","typ":"JWT"}'\npayload='{"sub":"admin","role":"admin","exp":9999999999}'\ntoken="$(echo -n $header|base64|tr '+/' '-_'|tr -d '=').$(echo -n $payload|base64|tr '+/' '-_'|tr -d '=')."\ncurl -i -H "Authorization: Bearer $token" "${j.path}"`,
nextSteps: ['Verify by sending a forged token to a privileged endpoint', 'Check the impact (what can the forged role do?)', 'Submit immediately — this is critical'],
confidence: 0.95,
findingType: 'jwt-alg-none',
});
});
// Confirmed SSTI / XXE / CRLF / IDOR / BAC findings from the probe. The chain
// correlator usually wraps these into chains, but if the chain analyzer skipped
// them for some reason, we still want to draft.
const promote = (results, kind, sev, label, fixHint) => {
(results || []).forEach((r, idx) => {
if (!r.confirmed) return;
if (!pathInScope(r.path || '')) return;
out.push({
id: kind + '-' + idx,
severity: sev,
title: `${label} on ${r.path || 'endpoint'}`,
summary: `Confirmed ${label.toLowerCase()} on \`${r.path}\`. ${r.evidence ? 'Evidence: ' + String(r.evidence).substring(0, 200) : ''} ${fixHint}`,
findings: [{ type: kind, path: r.path, evidence: r.evidence || '' }],
reproCmd: `# Re-test ${label.toLowerCase()} on the affected endpoint\ncurl -i "${r.path}"`,
nextSteps: ['Re-verify with a clean session', 'Determine the impact', 'Document for the report'],
confidence: 0.9,
findingType: kind,
});
});
};
promote(state.probeData?.sstiResults, 'ssti', 'critical', 'Server-side template injection', 'SSTI usually means RCE.');
promote(state.probeData?.xxeResults, 'xxe', 'critical', 'XML External Entity injection', 'XXE allows file disclosure, SSRF, sometimes RCE.');
promote(state.probeData?.crlfResults, 'crlf', 'high', 'CRLF injection', 'Enables response splitting, cache poisoning, header injection.');
return out;
}
// v6.2.3 — Diagnostic helpers for the live feed. The user reported "Hunt says done
// but no reports" multiple times — the issue was always silent filter drops. These
// helpers feed the rich logging in runHuntLoop and the "Why no reports?" diagnostic
// in finishHunt.
// Count chains by severity. Returns an object keyed by severity name.
function severityCounts(items) {
const c = { critical: 0, high: 0, medium: 0, low: 0, info: 0 };
(items || []).forEach(it => {
const s = (it && it.severity) || 'info';
if (c[s] !== undefined) c[s]++;
else c.info++;
});
return c;
}
// Walk a probeData object and count "interesting" findings per category. Each probe
// type has a different shape for "this is exploitable" so we centralize the logic.
// Returns { totalConfirmed, lines: [string,...] } — lines are human-readable per-cat.
function summarizeProbeResults(probeData) {
const lines = [];
let total = 0;
const add = (label, count) => {
if (count > 0) { lines.push(`${count} ${label}`); total += count; }
};
// authRemoval: severity-based (critical/high mean confirmed bypass)
const ar = (probeData.authRemovalResults || []).filter(r => r.severity === 'critical' || r.severity === 'high').length;
add('confirmed auth bypass', ar);
// BAC: vulnerable flag
const bac = (probeData.bacResults || []).filter(b => b.vulnerable).length;
add('confirmed BAC (broken access control)', bac);
// IDOR: sameBody === true means the auto-test confirmed identical responses across IDs
const idor = (probeData.idorAutoResults || []).filter(r => r.sameBody).length;
add('confirmed IDOR', idor);
// CORS: reflected origin + credentials = full SOP bypass
const cors = (probeData.corsResults || []).filter(r => r.reflected && r.allowsCredentials).length;
add('CORS reflection w/ credentials', cors);
// CSRF: medium+ severity = exploitable gap
const csrf = (probeData.csrfResults || []).filter(r => r.severity === 'critical' || r.severity === 'high' || r.severity === 'medium').length;
add('CSRF validation gaps', csrf);
// JWT alg=none confirmed
const jwt = (probeData.jwtAlgResults || []).filter(r => r.confirmed).length;
add('JWT alg=none accepts', jwt);
// SSTI / XXE / CRLF / proto pollution all use confirmed flag
add('confirmed SSTI', (probeData.sstiResults || []).filter(r => r.confirmed).length);
add('confirmed XXE', (probeData.xxeResults || []).filter(r => r.confirmed).length);
add('confirmed CRLF injection', (probeData.crlfResults || []).filter(r => r.confirmed).length);
add('confirmed prototype pollution', (probeData.protoPollution || []).filter(r => r.severity === 'critical' || r.severity === 'high').length);
// Open redirects
add('confirmed open redirect', (probeData.openRedirects || []).filter(r => r.confirmed).length);
// Recursive probe findings (any severity)
const rp = probeData.recursiveProbe || {};
const recFindings = ((rp.wave1 || []).concat(rp.wave2 || [], rp.wave3 || [])).flatMap(r => r.findings || []).filter(f => f.severity === 'critical' || f.severity === 'high').length;
add('high-severity findings in recursive probe responses', recFindings);
// Stack-attack pack hits (confirmed)
const stack = (probeData.stackAttacks || []).filter(a => a.confirmed && (a.severity === 'critical' || a.severity === 'high')).length;
add('confirmed stack-pack hits', stack);
return { totalConfirmed: total, lines };
}
// Filter chains by scope rules. A chain is in scope if any of its findings'
// paths match the inScope patterns AND none match the outScope patterns.
// If inScope is empty, all paths are considered in (just exclude outScope).
function filterChainsByScope(chains, cfg) {
const inP = cfg.inScope || [];
const outP = cfg.outScope || [];
if (!inP.length && !outP.length) return chains;
return chains.filter(chain => {
const findings = chain.findings || [];
if (!findings.length) return true; // no path data — don't filter out
const paths = findings.map(f => f.path || '').filter(Boolean);
if (!paths.length) return true;
if (outP.length && paths.every(p => pathMatchesAny(p, outP))) return false;
if (inP.length && !paths.some(p => pathMatchesAny(p, inP))) return false;
return true;
});
}
// -------------------------------------------------------------------
// Sub-step runners (wrap existing background message handlers)
// -------------------------------------------------------------------
function wbGetTabData() {
return new Promise(resolve => {
chrome.runtime.sendMessage({ action: 'getData', tabId: SOURCE_TAB_ID }, data => {
// Touch lastError to silence channel-closed warnings
void chrome.runtime.lastError;
const d = data || {};
resolve({
endpoints: d.endpoints || [],
secrets: d.secrets || [],
techStack: d.techStack || [],
chains: d.exploitChains || [],
probeData: d.probeData || null,
cookies: d.cookies || [],
url: d.url || '',
});
});
});
}
function runProbeViaBackground(cfg) {
// Note: the background's startProbe requires deep mode (debugger). The user must
// have enabled Deep before launching Hunt. We surface the error if not.
return new Promise(resolve => {
chrome.runtime.sendMessage({
action: 'startProbe',
tabId: SOURCE_TAB_ID,
aggroLevel: cfg.aggro,
customHeaders: {},
recursive: true,
stealth: false,
}, r => {
void chrome.runtime.lastError;
resolve(r || { ok: false, error: 'no response' });
});
});
}
// Authorization Matrix sweep. Pulls the saved auth contexts from background, then
// runs a bounded matrix scan. We call wbSendRequest per (endpoint, ctx) cell.
async function runAuthMatrixSweep() {
const state = await new Promise(resolve => {
chrome.runtime.sendMessage({ action: 'wbGetState', tabId: SOURCE_TAB_ID }, r => {
void chrome.runtime.lastError;
resolve(r || {});
});
});
const auth = state.auth || { list: [] };
const contexts = auth.list || [];
if (contexts.length < 2) {
return { message: 'need 2+ auth contexts (set up in Workbench → Auth)' };
}
const data = state.data || {};
// Pick up to 25 unique target endpoints (in-scope only) for the matrix
const cfg = HUNT_STATE.config;
const seen = new Set();
const targets = [];
for (const ep of (data.endpoints || [])) {
const key = (ep.method || 'GET') + ' ' + (ep.path || ep.url || '');
if (seen.has(key)) continue;
seen.add(key);
// Filter by scope
const path = ep.path || '';
if (cfg.outScope.length && pathMatchesAny(path, cfg.outScope)) continue;
if (cfg.inScope.length && !pathMatchesAny(path, cfg.inScope)) continue;
targets.push(ep);
if (targets.length >= 25) break;
}
if (!targets.length) return { message: 'no in-scope endpoints for matrix' };
feedLine('info', `Authorization Matrix: ${targets.length} endpoints × ${contexts.length} contexts = ${targets.length * contexts.length} requests`);
let anomalies = 0;
const grid = {};
for (const ep of targets) {
if (HUNT_STATE.abortRequested) break;
const epKey = (ep.method || 'GET') + ' ' + (ep.path || ep.url);
grid[epKey] = {};
const statuses = [];
for (const ctx of contexts) {
const resp = await new Promise(resolve => {
chrome.runtime.sendMessage({
action: 'wbSendRequest',
tabId: SOURCE_TAB_ID,
req: { method: ep.method || 'GET', url: ep.url || ep.path, headers: {}, body: '', ctxName: ctx.name },
}, r => { void chrome.runtime.lastError; resolve(r || {}); });
});
grid[epKey][ctx.name] = { status: resp.status || 0, size: resp.size || 0 };
statuses.push(resp.status || 0);
}
if (new Set(statuses).size > 1) {
anomalies++;
// Synthesize a synthetic chain-like object for matrix anomalies and add to chains
const findingsList = contexts.map(c => ({ ctx: c.name, status: grid[epKey][c.name].status }));
HUNT_STATE.chains = HUNT_STATE.chains || [];
HUNT_STATE.chains.push({
id: 'matrix-' + epKey.replace(/[^a-z0-9]+/gi, '-').substring(0, 60),
severity: detectMatrixSeverity(grid[epKey], contexts),
title: `Authorization disagreement: ${ep.method || 'GET'} ${ep.path || ''}`,
summary: `Different auth contexts return different responses for ${ep.method || 'GET'} ${ep.path || ''}. Statuses: ${contexts.map(c => `${c.name}=${grid[epKey][c.name].status}`).join(', ')}. Likely IDOR or broken access control.`,
findings: [{ type: 'authz-matrix-anomaly', path: ep.path || ep.url, method: ep.method || 'GET', evidence: JSON.stringify(findingsList) }],
reproCmd: contexts.slice(0, 2).map(c => `# As ${c.name}\ncurl -i "${ep.url || ep.path}" # adapt cookies/headers per context`).join('\n'),
nextSteps: ['Verify the response bodies actually differ', 'Confirm with a burner account', 'Check whether the lower-priv user is seeing the higher-priv user\'s data'],
confidence: 0.8,
findingType: 'authz-matrix',
});
feedLine('high', `Matrix anomaly: ${ep.method || 'GET'} ${ep.path || ''} → ${contexts.map(c => grid[epKey][c.name].status).join('/')}`);
}
}
return { message: `${targets.length * contexts.length} requests, ${anomalies} anomalies` };
}
// Heuristic severity for matrix anomalies. If a "lower" privilege context (Anonymous
// or named with "guest"/"user") returns 200 and a higher one returns 200 too, that
// might mean lower-priv can access higher-priv data → high. If contexts disagree
// only on 401/403, that's expected → low.
function detectMatrixSeverity(row, contexts) {
const statuses = contexts.map(c => row[c.name].status);
const has2xx = statuses.some(s => s >= 200 && s < 300);
const has4xx = statuses.some(s => s >= 400 && s < 500);
const anonIdx = contexts.findIndex(c => /anon|public/i.test(c.name));
if (anonIdx >= 0) {
const anonStatus = row[contexts[anonIdx].name].status;
if (anonStatus >= 200 && anonStatus < 300 && contexts.some(c => c !== contexts[anonIdx] && row[c.name].status >= 400)) {
// Anonymous gets in but other contexts don't — weird but probably not a bug
return 'medium';
}
if (anonStatus >= 400 && contexts.some(c => c !== contexts[anonIdx] && row[c.name].status >= 200 && row[c.name].status < 300)) {
// Anonymous denied, others allowed — expected. Check for low-priv vs high-priv leak instead
const others = contexts.filter((_, i) => i !== anonIdx);
const allOthers200 = others.every(c => row[c.name].status >= 200 && row[c.name].status < 300);
if (allOthers200 && others.length >= 2) return 'high'; // multiple privilege levels all see same data
return 'medium';
}
}
if (has2xx && has4xx) return 'high';
return 'low';
}
// -------------------------------------------------------------------
// Report composer — full HackerOne-format markdown
// -------------------------------------------------------------------
function composeReport(chain, state, cfg) {
const sev = (chain.severity || 'medium').toLowerCase();
const sevLabel = sev.toUpperCase();
const cvssRange = { critical: '9.0–10.0', high: '7.0–8.9', medium: '4.0–6.9', low: '0.1–3.9', info: 'N/A' }[sev] || '4.0–6.9';
const conf = Math.round((chain.confidence || 0.5) * 100);
const target = state.url || cfg.target || '';
let host = '';
try { host = new URL(target).hostname; } catch (e) {}
// Suggested fix from blue-fixes mapping (if loaded). Falls back to generic.
const fix = generateFixHint(chain);
// Steps to reproduce — derive from chain.reproCmd
const steps = chain.reproCmd
? chain.reproCmd.split('\n').filter(Boolean)
: [`curl -i "${target}${(chain.findings && chain.findings[0] && chain.findings[0].path) || '/'}"`];
const md = `# ${chain.title || 'Security finding'}
**Severity:** ${sevLabel} _(CVSS estimate: ${cvssRange})_
**Confidence:** ${conf}%
**Target:** ${target}
**Discovered:** ${new Date().toISOString()}
**Detected by:** PenScope v6.2 Hunt Mode (chain pattern: \`${chain.findingType || chain.id || 'compound'}\`)
---
## Summary
${chain.summary || 'PenScope detected a compound exploit chain combining multiple findings into an exploitable path.'}
${(chain.findings || []).length ? `\nThis chain combines **${(chain.findings || []).length} signal${(chain.findings || []).length === 1 ? '' : 's'}** observed during recon:\n${(chain.findings || []).slice(0, 6).map(f => `- ${f.type || 'finding'}${f.path ? ' on \`' + f.path + '\`' : ''}${f.evidence ? ': ' + String(f.evidence).substring(0, 120) : ''}`).join('\n')}\n` : ''}
## Steps to reproduce
\`\`\`bash
${steps.join('\n')}
\`\`\`
${chain.nextSteps && chain.nextSteps.length ? `Additional verification steps:\n${chain.nextSteps.slice(0, 6).map(s => `1. ${s}`).join('\n')}\n` : ''}
## Impact
${impactStatement(chain, sev)}
${fix.section}
## Detection methodology
PenScope's chain correlator surfaced this compound finding by combining outputs from multiple subsystems:
${(chain.findings || []).slice(0, 4).map(f => `- ${f.type || 'finding'}${f.source ? ' (source: ' + f.source + ')' : ''}`).join('\n') || '- Multiple chain inputs (see attached scan data)'}
The combination meets PenScope's pattern \`${chain.findingType || chain.id || 'compound'}\` with confidence ${conf}%. Severity assigned per the chain analyzer's severity × confidence ranking.
## References
- [OWASP Top 10 2021](https://owasp.org/Top10/)
- [CWE List](https://cwe.mitre.org/data/index.html)
${fix.references.map(r => `- ${r}`).join('\n')}
---
_Report drafted automatically by PenScope Hunt Mode. Verify each finding manually before submitting to a bounty program._`;
return {
id: 'r-' + Date.now() + '-' + Math.floor(Math.random() * 9999),
chainId: chain.id || null,
severity: sev,
title: chain.title || 'Security finding',
host,
target,
timestamp: Date.now(),
confidence: conf,
chain,
markdown: md,
};
}
function impactStatement(chain, sev) {
const sevImpact = {
critical: "Successful exploitation enables an attacker to bypass core security controls, gain unauthorized access to sensitive functionality or data, and pivot to broader compromise. This is a credible breach path warranting immediate remediation.",
high: "Successful exploitation bypasses intended access controls and exposes sensitive data or operations to unauthorized actors. Should be remediated as a priority.",
medium: "Exploitation weakens the security posture and provides a foothold for further attacks. Should be addressed in the next sprint.",
low: "Minor issue that hardens the security posture if remediated. Low priority but worth tracking.",
};
const generic = sevImpact[sev] || sevImpact.medium;
// If chain summary explicitly mentions specific impact, append context
const specifics = [];
if (/admin|privilege|escalat/i.test(chain.summary || '')) specifics.push('privilege escalation to administrator');
if (/idor|other user|cross.user/i.test(chain.summary || '')) specifics.push('access to other users\' data (IDOR)');
if (/rce|code execution|shell/i.test(chain.summary || '')) specifics.push('remote code execution');
if (/data leak|secret|credential|token/i.test(chain.summary || '')) specifics.push('exposure of credentials or sensitive data');
if (/csrf|forgery/i.test(chain.summary || '')) specifics.push('cross-site request forgery enabling state-changing actions');
const tail = specifics.length ? `\n\nSpecifically, this chain enables: ${specifics.join(', ')}.` : '';
return generic + tail;
}
// Pull a remediation hint. If background ever exposes blue-fixes, route through it.
// For now use a small inline mapping covering common chain types.
function generateFixHint(chain) {
const sec = (key) => '\n## Suggested fix\n\n' + key;
const findingType = (chain.findingType || chain.id || '').toLowerCase();
const summary = (chain.summary || '').toLowerCase();
if (/auth.?bypass|auth.?removal/.test(findingType + summary)) return {
section: sec("Enforce server-side authentication on every endpoint that returns sensitive data. The fact that PenScope received a 200 with no cookies means the authorization middleware is missing or disabled for this route.\n\n```\n// Express\nfunction requireAuth(req, res, next) { if (!req.user) return res.status(401).end(); next(); }\napp.get('/api/admin/users', requireAuth, handler);\n```"),
references: ['https://owasp.org/Top10/A01_2021-Broken_Access_Control/']
};
if (/idor|same.body/.test(findingType + summary)) return {
section: sec("Scope every database query by the authenticated user, not just by the resource ID. Verify resource ownership before returning data.\n\n```\n// BAD\nconst order = await Order.findById(req.params.id);\n// GOOD\nconst order = await Order.findOne({ _id: req.params.id, userId: req.user.id });\nif (!order) return res.status(404).end();\n```"),
references: ['https://cwe.mitre.org/data/definitions/639.html']
};
if (/jwt.?(none|alg)/.test(findingType + summary)) return {
section: sec("Pin the allowed JWT algorithm explicitly when verifying tokens. Never let the JWT itself dictate the algorithm.\n\n```\n// jsonwebtoken (Node)\njwt.verify(token, secret, { algorithms: ['HS256'] });\n// PyJWT\njwt.decode(token, secret, algorithms=['HS256'])\n```"),
references: ['https://cwe.mitre.org/data/definitions/347.html']
};
if (/cors/.test(findingType + summary)) return {
section: sec("Replace any wildcard or reflected `Access-Control-Allow-Origin` with an explicit allowlist. Especially do not combine reflected origin with `Access-Control-Allow-Credentials: true`.\n\n```\nconst ALLOW = new Set(['https://app.example.com']);\napp.use((req, res, next) => {\n const o = req.headers.origin;\n if (ALLOW.has(o)) {\n res.setHeader('Access-Control-Allow-Origin', o);\n res.setHeader('Access-Control-Allow-Credentials', 'true');\n }\n next();\n});\n```"),
references: ['https://cwe.mitre.org/data/definitions/942.html']
};
if (/csrf/.test(findingType + summary)) return {
section: sec("Add CSRF tokens to every state-changing form. SameSite=Strict cookies help but tokens remain the standard defense.\n\n```\nconst csurf = require('csurf');\napp.use(csurf({ cookie: true }));\n```"),