-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathscan-detail.js
More file actions
1427 lines (1329 loc) · 83.1 KB
/
Copy pathscan-detail.js
File metadata and controls
1427 lines (1329 loc) · 83.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(() => {
const esc = (...args) => (typeof window.esc === 'function' ? window.esc(...args) : String(args[0] ?? ''));
const apiFetch = (...args) => window.apiFetch(...args);
const navigateTo = (...args) => window.navigateTo(...args);
const showToast = (...args) => window.showToast(...args);
const API = '';
const apiPost = (...args) => window.apiPost(...args);
const fmtSize = (...args) => window.fmtSize(...args);
const getFileTypeFromName = (...args) => window.getFileTypeFromName(...args);
const getFileTypeIcon = (...args) => window.getFileTypeIcon(...args);
const detectModuleFromFileName = (...args) => window.detectModuleFromFileName(...args);
const getModuleDisplayInfo = (...args) => window.getModuleDisplayInfo(...args);
const scanNoArtifactsMessage = (...args) => window.scanNoArtifactsMessage(...args);
const escAttr = (...args) => window.escAttr(...args);
const copyToClipboard = (...args) => window.copyToClipboard(...args);
// showReportModal renders generated AI report text in a copyable overlay.
function showReportModal(title, text) {
document.getElementById('ai-report-modal')?.remove();
const overlay = document.createElement('div');
overlay.id = 'ai-report-modal';
overlay.style.cssText = 'position:fixed;inset:0;z-index:10000;background:rgba(2,6,23,.72);display:flex;align-items:center;justify-content:center;padding:24px;backdrop-filter:blur(2px)';
overlay.innerHTML = `
<div style="background:var(--bg-card,#0b1220);border:1px solid var(--border,rgba(255,255,255,.12));border-radius:12px;max-width:860px;width:100%;max-height:86vh;display:flex;flex-direction:column;box-shadow:0 20px 60px rgba(0,0,0,.5)">
<div style="display:flex;align-items:center;gap:12px;padding:14px 18px;border-bottom:1px solid var(--border,rgba(255,255,255,.1))">
<div style="font-weight:600;font-size:14px;color:var(--text-primary,#fff);flex:1">${esc(title)}</div>
<button type="button" id="ai-report-copy" style="padding:6px 12px;background:rgba(52,211,153,.12);border:1px solid rgba(52,211,153,.4);border-radius:6px;color:#34d399;font-size:12px;cursor:pointer">Copy</button>
<button type="button" id="ai-report-close" style="padding:6px 12px;background:rgba(255,255,255,.06);border:1px solid var(--border,rgba(255,255,255,.15));border-radius:6px;color:var(--text-secondary,#cbd5e1);font-size:12px;cursor:pointer">Close</button>
</div>
<pre id="ai-report-body" style="margin:0;padding:18px;overflow:auto;white-space:pre-wrap;word-break:break-word;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12.5px;line-height:1.55;color:var(--text-primary,#e2e8f0)"></pre>
</div>`;
overlay.querySelector('#ai-report-body').textContent = text;
const close = () => overlay.remove();
overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); });
overlay.querySelector('#ai-report-close').addEventListener('click', close);
overlay.querySelector('#ai-report-copy').addEventListener('click', async () => {
try { await copyToClipboard(text); showToast('success', 'Copied', 'Report copied to clipboard'); }
catch (e) { showToast('error', 'Copy failed', e.message || String(e)); }
});
const onKey = (e) => { if (e.key === 'Escape') { close(); document.removeEventListener('keydown', onKey); } };
document.addEventListener('keydown', onKey);
document.body.appendChild(overlay);
}
// ── State for Scan Detail Page ──────────────────────────────────────────
window._scanDetailKnownFiles = new Set();
window._scanDetailRefreshTimer = null;
window._scanDetailRefreshId = null;
let _assetsCache = null;
let _assetsLoading = false;
async function renderScanDetailView(scanId) {
_assetsCache = null;
_assetsLoading = false;
const container = document.getElementById('scan-detail-container');
const sub = document.getElementById('scan-detail-sub');
const apiA = document.getElementById('scan-detail-api');
if (!container) return;
const ui = window.state.scanDetailUI;
// Show modern loading skeleton
container.innerHTML = `
<div class="scan-detail-modern">
<div class="scan-summary-stats">
${[1, 2, 3, 4].map(() => `
<div class="skeleton-card">
<div class="skeleton-line skeleton-title"></div>
<div class="skeleton-line skeleton-text"></div>
</div>
`).join('')}
</div>
<div class="skeleton-card">
<div class="skeleton-line skeleton-title"></div>
<div class="skeleton-line skeleton-text"></div>
<div class="skeleton-line skeleton-text"></div>
</div>
</div>`;
try {
const sum = await apiFetch(
`/api/scans/${encodeURIComponent(scanId)}/results/summary?page=${ui.filesPage}&per_page=${ui.filesPerPage}`
);
const manifestResp = await fetchScanManifest(scanId);
const scan = sum.scan;
const target = scan.target || scan.Target || '';
const st = scan.scan_type || scan.ScanType || '';
const stat = scan.status || scan.Status || '';
const statLower = stat.toLowerCase();
const titleEl = document.getElementById('scan-detail-title');
if (titleEl) titleEl.textContent = target || 'Scan results';
// Render scan type + status with live badge if running
if (sub) {
const isActive = /running|starting|paused|cancelling/i.test(stat);
if (isActive) {
const isCancelling = /cancelling/i.test(stat);
const isPaused = /paused/i.test(stat);
const liveBadge = isPaused
? `<span class="badge badge-starting" style="font-size:10px;padding:2px 8px;margin-left:8px"> paused</span>`
: isCancelling
? `<span class="badge badge-starting" style="font-size:10px;padding:2px 8px;margin-left:8px">⋯ stopping</span>`
: `<span class="badge badge-running" style="font-size:10px;padding:2px 8px;margin-left:8px;animation:pulse 1.4s ease-in-out infinite">* live</span>`;
sub.innerHTML = `${esc(st)} · ${esc(statLower)}${liveBadge}`;
} else {
sub.textContent = `${st} · ${statLower}`;
}
}
if (apiA) apiA.style.display = 'none';
const r2DetailBtn = document.getElementById('scan-detail-r2-btn');
if (r2DetailBtn) {
if (st) {
r2DetailBtn.style.display = 'inline-flex';
if (target) {
r2DetailBtn.disabled = false;
r2DetailBtn.title = 'Browse scan artifacts in R2';
r2DetailBtn.onclick = () => window.browseR2ForScan(target, st);
} else {
r2DetailBtn.disabled = true;
r2DetailBtn.title = 'Target is unavailable for this scan record';
r2DetailBtn.onclick = null;
}
} else {
r2DetailBtn.style.display = 'none';
r2DetailBtn.disabled = false;
r2DetailBtn.title = '';
r2DetailBtn.onclick = null;
}
}
const rescanDetailBtn = document.getElementById('scan-detail-rescan-btn');
if (rescanDetailBtn) {
const isActive = /running|starting|paused|cancelling/i.test(stat);
if (!isActive) {
rescanDetailBtn.style.display = 'inline-flex';
rescanDetailBtn._rescan = () => window.rescanScan(scanId);
} else {
rescanDetailBtn.style.display = 'none';
rescanDetailBtn._rescan = null;
}
}
const deleteDetailBtn = document.getElementById('scan-detail-delete-btn');
if (deleteDetailBtn) {
deleteDetailBtn.onclick = async () => {
await window.deleteScan(scanId, target);
navigateTo('overview');
};
}
const clearCacheBtn = document.getElementById('scan-detail-clear-cache-btn');
if (clearCacheBtn) {
const isApkx = /apkx/i.test(String(st || ''));
clearCacheBtn.style.display = isApkx ? 'inline-flex' : 'none';
clearCacheBtn.onclick = isApkx ? () => clearApkxCacheForScan(scan) : null;
}
const files = sum.files || [];
const total = sum.total || 0;
const statNorm = String(stat || '').trim();
const finishedOk = /^(completed|done|success)$/i.test(statNorm);
const stillRunning = /^(running|pending|queued|active|in_progress|starting)$/i.test(statNorm);
const failedish = /fail|error|cancel/i.test(statNorm);
const zipURL = scan.result_url || scan.ResultURL || '';
const zipBanner = zipURL
? `<div class="modern-card" style="padding:18px">
<div style="display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap">
<div>
<div style="font-size:14px;font-weight:600;color:var(--text-primary);margin-bottom:4px"> Full Scan Archive</div>
<div style="font-size:12px;color:var(--text-muted)">Download complete scan results as ZIP</div>
</div>
<a href="${esc(zipURL)}" target="_blank" rel="noopener" class="btn btn-primary">Download ZIP</a>
</div>
</div>`
: '';
const manifestCard = renderScanManifestCard(manifestResp?.manifest || null, scan);
let emptyBanner = '';
if (!files.length) {
let emptyMsg;
if (finishedOk) {
emptyMsg = `<div class="scan-no-results-banner">${esc(scanNoArtifactsMessage(st, target))}</div>
<p class="scan-asm-muted" style="margin-top:12px">No files were indexed for this scan. Confirm uploads and artifact indexing.</p>`;
} else if (stillRunning) {
emptyMsg = '<div style="text-align:center;padding:20px"><div style="font-size:40px;margin-bottom:12px">...</div><div style="font-size:14px;color:var(--text-secondary)">Scan is still running or processing. Check back soon for results.</div></div>';
} else if (failedish) {
emptyMsg = `<div style="text-align:center;padding:20px"><div style="font-size:40px;margin-bottom:12px">X</div><div style="font-size:14px;color:var(--accent-red)">No result files indexed. Status: ${esc(statNorm)}</div></div>`;
} else {
emptyMsg = '<div style="text-align:center;padding:20px"><div style="font-size:40px;margin-bottom:12px"></div><div style="font-size:14px;color:var(--text-muted)">No indexed artifacts for this scan yet.</div></div>';
}
emptyBanner = `<div class="modern-card" style="padding:20px">${emptyMsg}</div>`;
}
let html;
if (!files.length) {
html = `
<div class="scan-detail-modern">
${zipBanner}
${manifestCard}
${emptyBanner}
<div class="modern-card" style="padding:20px">
<div style="text-align:center;color:var(--text-muted)">No files to preview.</div>
</div>
</div>`;
} else {
html = `
<div class="scan-detail-modern">
${zipBanner}
${manifestCard}
${emptyBanner}
<div class="modern-card">
<div class="card-header">
<div class="card-title"><span class="card-title-icon"></span>Results</div>
<span class="badge badge-running" id="unified-parsed-badge">${total} files</span>
</div>
<div id="unified-parsed-results" style="padding:16px">
<div style="text-align:center;padding:20px;color:var(--text-muted)">Loading all results...</div>
</div>
</div>
</div>`;
}
container.innerHTML = html;
// Wire manifest pipeline row clicks after DOM insertion.
const manifestCardEl = container.querySelector('.modern-card');
if (manifestCardEl) {
window.ScanDetailManifest.wireManifestRowClicks(manifestCardEl);
}
window.wireScanFileRows(container, scanId);
window.wireScanDetailFilters(scanId, files);
loadReconUnifiedTable(scanId, files, 'unified-parsed-results', scan);
if (files.length) {
window.loadScanDetailVulnerabilityInsights(scanId, files);
}
if (ui.selectedFileName) {
requestAnimationFrame(() => {
window.loadScanFilePreview(scanId, ui.selectedFileName, { retainPage: true });
});
}
if (stillRunning) {
scheduleScanDetailRefresh(scanId);
} else {
clearScanDetailRefreshTimer();
}
} catch (e) {
container.innerHTML = `<div class="modern-card" style="padding:20px;border-color:var(--accent-red)"><div style="color:var(--accent-red)">${esc(e.message || String(e))}</div></div>`;
}
}
async function clearApkxCacheForScan(scan) {
const target = String(scan?.target || scan?.Target || '').trim();
const looksLikePackage = /^[a-zA-Z0-9_]+(?:\.[a-zA-Z0-9_]+)+$/.test(target);
const scopeLabel = looksLikePackage ? `package cache for ${target}` : 'ALL APK cache';
if (!confirm(`Clear ${scopeLabel}?`)) return;
try {
const body = looksLikePackage ? { package: target } : { all: true };
const res = await apiPost('/api/apkx/cache/clear', body);
const localN = Number(res?.local_removed || 0);
const r2N = Number(res?.r2_removed || 0);
const r2Err = String(res?.r2_error || '').trim();
window.showToast('success', 'APK cache cleared', `Local: ${localN}, R2: ${r2N}${r2Err ? ' (R2 warning)' : ''}`);
} catch (e) {
window.showToast('error', 'Failed to clear APK cache', e.message || String(e));
}
}
function clearScanDetailRefreshTimer() {
if (window._scanDetailRefreshTimer) {
clearTimeout(window._scanDetailRefreshTimer);
window._scanDetailRefreshTimer = null;
}
}
function scheduleScanDetailRefresh(scanId, ms = 4000) {
clearScanDetailRefreshTimer();
window._scanDetailRefreshId = scanId;
window._scanDetailRefreshTimer = setTimeout(() => doScanDetailRefresh(scanId), ms);
}
async function doScanDetailRefresh(scanId) {
if (window.state.view !== 'scan-detail' || window.state.scanDetailId !== scanId) return;
try {
const sum = await apiFetch(`/api/scans/${encodeURIComponent(scanId)}/results/summary?page=1&per_page=200`);
const scan = sum.scan || {};
const stat = String(scan.status || scan.Status || '').toLowerCase();
const files = sum.files || [];
const stillRunning = /^(running|pending|queued|active|in_progress|starting)$/.test(stat);
const sub = document.getElementById('scan-detail-sub');
if (sub) {
if (stillRunning) {
const isCancelling = /cancelling/.test(stat);
const isPaused = /paused/.test(stat);
const scanType = scan.scan_type || '';
const liveBadge = isPaused
? `<span class="badge badge-starting" style="font-size:10px;padding:2px 8px;margin-left:8px"> paused</span>`
: isCancelling
? `<span class="badge badge-starting" style="font-size:10px;padding:2px 8px;margin-left:8px">⋯ stopping</span>`
: `<span class="badge badge-running" style="font-size:10px;padding:2px 8px;margin-left:8px;animation:pulse 1.4s ease-in-out infinite">* live</span>`;
sub.innerHTML = `${esc(scanType)} · ${esc(stat)}${liveBadge}`;
} else {
sub.textContent = `${scan.scan_type || ''} · ${stat}`;
}
}
refreshScanManifestCard(scanId, scan);
const badge = document.getElementById('unified-parsed-badge');
if (badge) {
const countStr = `${files.length} files`;
if (badge.textContent !== countStr) badge.textContent = countStr;
}
const newFiles = files.filter(f => !window._scanDetailKnownFiles.has(f.file_name));
if (newFiles.length) {
newFiles.forEach(f => window._scanDetailKnownFiles.add(f.file_name));
const unifiedRoot = document.getElementById('unified-parsed-results');
if (unifiedRoot) {
loadReconUnifiedTable(scanId, files, 'unified-parsed-results');
_assetsCache = null;
}
}
if (stillRunning) {
scheduleScanDetailRefresh(scanId, 4500);
} else {
clearScanDetailRefreshTimer();
_assetsCache = null; // Reset cache on auto-refresh to pick up new assets
await renderScanDetailView(scanId);
}
} catch (e) {
scheduleScanDetailRefresh(scanId, 8000);
}
}
// ── Manifest helpers — delegated to scan-detail-manifest.js ──────────────
const fetchScanManifest = (id) => window.ScanDetailManifest.fetchScanManifest(id);
const renderScanManifestCard = (m, s) => window.ScanDetailManifest.renderScanManifestCard(m, s);
const refreshScanManifestCard = (id, s) => window.ScanDetailManifest.refreshScanManifestCard(id, s);
const manifestStatusBadge = (st) => window.ScanDetailManifest.manifestStatusBadge(st);
const manifestArtifactLabel = (e) => window.ScanDetailManifest.manifestArtifactLabel(e);
const manifestStartedLabel = (e) => window.ScanDetailManifest.manifestStartedLabel(e);
// ── Unified Findings Table Implementation ──────────────────────────────────
async function loadReconUnifiedTable(scanId, allFiles, containerId, scanRecord) {
const root = document.getElementById(containerId);
if (!root) return;
let wrap = null;
const stNorm = String(scanRecord?.scan_type || scanRecord?.ScanType || '').toLowerCase();
const isAPKScan = stNorm.includes('apkx');
const badge = document.getElementById('unified-parsed-badge') || document.getElementById('recon-parsed-badge');
if (!allFiles || !allFiles.length) {
if (badge) badge.textContent = '0 artifacts';
root.innerHTML = '<div style="text-align:center;padding:20px;color:var(--text-muted)">No artifacts found.</div>';
return;
}
root.innerHTML = '<div style="text-align:center;padding:20px;color:var(--text-muted)">Loading all results…</div>';
let allRows = [];
try {
const parsed = await apiFetch(`/api/scans/${encodeURIComponent(scanId)}/results/parsed?section=all&limit=5000`);
if (Array.isArray(parsed.rows)) {
allRows = parsed.rows;
}
} catch (e) {
console.warn('[scan detail] parsed recon api fallback', e);
}
if (!allRows.length) {
for (const f of allFiles) {
try {
const data = await apiFetch(`/api/scans/${encodeURIComponent(scanId)}/results/file?file_name=${encodeURIComponent(f.file_name)}&page=1&per_page=500`);
const rows = window.previewDataToFlatRows(data, f).map((r) => ({
...r,
kind: window.detectModuleFromFileName(r.file, r.module),
category: window.categorizeScanArtifactFile(r.file),
}));
allRows.push(...rows);
} catch (e) {
allRows.push({
file: f.file_name,
module: detectModuleFromFileName(f.file_name, f.module),
source: f.source || '—',
category: window.categorizeScanArtifactFile(f.file_name),
kind: window.detectModuleFromFileName(f.file_name, f.module),
severity: '—',
target: '—',
finding: `[Error reading file] ${e.message || e}`,
});
}
}
}
if (badge) {
badge.textContent = `${allRows.length} rows · ${allFiles.length} files`;
}
if (!allRows.length) {
root.innerHTML = '<div style="text-align:center;padding:20px;color:var(--text-muted)">No parseable findings.</div>';
return;
}
if (isAPKScan) {
const hasJsonRows = allRows.some((r) => String(r.file || '').toLowerCase().endsWith('.json'));
if (hasJsonRows) {
allRows = allRows.filter((r) => String(r.file || '').toLowerCase().endsWith('.json'));
}
}
allRows = allRows
.map((r) => {
let kind = String(r.kind || window.detectModuleFromFileName(r.file, r.module) || 'other').toLowerCase().trim();
const file = String(r.file || '').toLowerCase();
const target = String(r.target || r.host || '').toLowerCase();
const finding = String(r.title || r.finding || '').trim();
const moduleNorm = window.normalizeModuleKey(r.module);
if (kind === 'js-urls') kind = 'js_urls';
if (kind === 'unknown' || kind === 'unknowns') kind = 'other';
const looksLikeJSMatcher = (/^\s*\[[^\]]+\].*->/i.test(finding) || (file.includes('js-') && !file.includes('trufflehog') && !file.includes('github'))) && !file.includes('trufflehog') && !file.includes('github-secrets');
const looksLikeJSURL = file.includes('js-url') || /\.m?jsx?(\?|$)/i.test(target);
const looksLikeJSEndpoints = file.includes('js-endpoint') || moduleNorm === 'js-endpoints';
const looksLikeKatana = file.includes('katana') || moduleNorm === 'katana-crawler' || moduleNorm === 'katana';
const looksLikeGitHub = (file.includes('github') || file.includes('trufflehog') || file.includes('secrets_table') || file.includes('github-secrets') || (file.includes('secrets') && file.endsWith('.json'))) && !file.startsWith('js-');
if (looksLikeGitHub) kind = 'github-scan';
else if (looksLikeJSEndpoints) kind = 'js-endpoints';
else if (looksLikeKatana) kind = 'katana-crawler';
else if (looksLikeJSMatcher) kind = 'js-analysis';
else if (looksLikeJSURL && kind === 'other') kind = 'js_urls';
if (isAPKScan) kind = 'apkx';
// Do not treat GitHub/TruffleHog rows as JS just because the blob URL ends in .js
const isJS = kind !== 'github-scan' && kind !== 'js-endpoints' && kind !== 'katana-crawler' && (kind === 'js_urls' || looksLikeJSURL);
if (kind === 'js_urls') kind = 'urls';
let normalizedModule = isAPKScan ? 'apkx' : moduleNorm;
if (kind === 'github-scan') {
normalizedModule = 'github-scan';
} else if (kind === 'js-endpoints') {
normalizedModule = 'js-endpoints';
} else if (kind === 'katana-crawler') {
normalizedModule = 'katana-crawler';
} else if (moduleNorm === 'unknown' && (kind === 'js-analysis' || isJS)) {
normalizedModule = 'js-analysis';
}
return {
...r,
kind,
module: normalizedModule,
is_js: isJS || r.is_js || false,
};
})
.filter((r) => {
const finding = String(r.title || r.finding || '').trim().toLowerCase();
const target = String(r.target || r.host || '').trim();
if (finding === 'no findings found' && (target === '' || target === '-' || target === '—')) {
return false;
}
if (isAPKScan) {
if ((target === '' || target === '-' || target === '—') && (finding === '' || finding === '—' || finding === 'autoar' || finding === 'apkx')) {
return false;
}
}
return true;
});
const VULN_KINDS = new Set(['vuln', 'nuclei', 'reflection', 'ports', 'buckets', 'backup', 'zerodays', 'aem', 'misconfig', 's3', 'gf', 'ffuf', 'dns', 'github-scan', 'github', 'sqlmap', 'aem-findings']);
const totalVuln = allRows.filter(r => VULN_KINDS.has(r.kind)).length;
const isReconScan = stNorm === 'recon' || stNorm === 'lite' || stNorm === 'domain_scan' || stNorm === 'subdomain_scan' || stNorm === 'subdomain_run' || stNorm === 'domain_run';
const isGitHubScan = /github/.test(stNorm) || allRows.some(r => r.module === 'github-scan' || r.module === 'github');
let activeKind = isReconScan ? 'assets' : 'urls';
if (totalVuln === 0 && !isReconScan && (allRows.some(r => r.kind === 'urls'))) activeKind = 'urls';
if (!isReconScan && isGitHubScan && allRows.some(r => window.normalizeModuleKey(r.module) === 'github-scan')) {
activeKind = 'mod:github-scan';
}
let searchHost = '';
let searchTitle = '';
let searchModule = 'all';
let filterSeverity = 'any';
const _kindCounts = {};
for (const r of allRows) _kindCounts[r.kind || 'other'] = (_kindCounts[r.kind || 'other'] || 0) + 1;
const HIDDEN_KINDS = new Set(['logs', 'log']);
const TAB_LABELS = {
assets: ' Assets',
urls: ' Links',
'js-analysis': ' JS Secrets',
'js-endpoints': ' JS Endpoints',
'katana-crawler': ' Katana',
'gf-patterns': ' GF Patterns',
nuclei: ' Nuclei',
ffuf: ' FFUF',
buckets: ' S3 Buckets',
ports: ' Ports',
reflection: ' Reflection',
'xss-detection': ' XSS (Dalfox)',
'github-scan': ' GitHub Secrets',
other: ' Other',
github: ' GitHub Secrets',
};
const dynamicKinds = [...new Set(allRows.map(r => r.kind || 'other'))];
const DATASET_TABS = [];
if (isReconScan || allRows.some(r => r.kind === 'subdomains' || r.kind === 'assets')) {
DATASET_TABS.push(['assets', TAB_LABELS.assets]);
}
dynamicKinds.forEach(k => {
if (k === 'subdomains' || k === 'assets' || k === 'vuln' || VULN_KINDS.has(k) || k === 'github-scan') {
if (['js-analysis', 'js-endpoints', 'katana-crawler', 'gf-patterns', 'nuclei', 'ffuf', 'reflection', 'xss-detection', 'github-scan', 'github'].includes(k)) {
DATASET_TABS.push([k, TAB_LABELS[k] || k]);
}
return;
}
if (k === 'urls') {
DATASET_TABS.push(['urls', TAB_LABELS.urls]);
return;
}
if (!['logs', 'log', 'tech'].includes(k)) {
DATASET_TABS.push([k, TAB_LABELS[k] || k]);
}
});
const seenTabs = new Set();
let UNIQUE_TABS = DATASET_TABS.filter(t => {
if (seenTabs.has(t[0])) return false;
seenTabs.add(t[0]);
return true;
});
const preferredModuleOrder = [
'nuclei', 'gf-patterns', 'misconfig', 'ffuf-fuzzing', 'dns-takeover',
'backup-detection', 'js-analysis', 'js-endpoints', 'katana-crawler', 'xss-detection', 'sql-detection',
's3-scan', 'port-scan', 'zerodays', 'aem', 'github-scan'
];
const usedModulesRaw = [...new Set(allRows.map(r => window.normalizeModuleKey(r.module)).filter(Boolean))];
const usedModules = usedModulesRaw.sort((a, b) => {
const ai = preferredModuleOrder.indexOf(a);
const bi = preferredModuleOrder.indexOf(b);
if (ai !== -1 && bi !== -1) return ai - bi;
if (ai !== -1) return -1;
if (bi !== -1) return 1;
return a.localeCompare(b);
});
const excludedModuleTabs = new Set(['autoar', 'unknown']);
const hasUrlsDatasetTab = UNIQUE_TABS.some((t) => t[0] === 'urls');
if (hasUrlsDatasetTab) excludedModuleTabs.add('url-collection');
const hasApkxDatasetTab = UNIQUE_TABS.some((t) => t[0] === 'apkx');
if (hasApkxDatasetTab) excludedModuleTabs.add('apkx');
// Build a set of kinds already covered by dataset tabs so we don't
// create duplicate mod: tabs for the same module.
// Also include normalized aliases — e.g. if the dataset has 'ffuf',
// 'ffuf-fuzzing' is covered too, and vice versa.
const coveredDatasetKinds = new Set(UNIQUE_TABS.map(t => t[0]));
for (const k of [...coveredDatasetKinds]) {
const norm = window.normalizeModuleKey(k);
if (norm !== k) coveredDatasetKinds.add(norm);
}
const moduleTabs = usedModules.filter((mod) => {
if (excludedModuleTabs.has(mod)) return false;
if (coveredDatasetKinds.has(mod)) return false;
if (coveredDatasetKinds.has(window.normalizeModuleKey(mod))) return false;
return true;
}).map((mod) => {
const info = getModuleDisplayInfo(mod);
return [`mod:${mod}`, `${info.icon} ${info.name}`];
});
UNIQUE_TABS = [...UNIQUE_TABS, ...moduleTabs].filter((t, i, arr) => arr.findIndex(x => x[0] === t[0]) === i);
const pinnedKinds = ['assets'];
UNIQUE_TABS = [
...pinnedKinds.map((k) => UNIQUE_TABS.find((t) => t[0] === k)).filter(Boolean),
...UNIQUE_TABS.filter((t) => !pinnedKinds.includes(t[0])),
];
if (!UNIQUE_TABS.some((t) => t[0] === activeKind)) {
activeKind = UNIQUE_TABS[0]?.[0] || 'assets';
}
let _assetsLoading = false;
let _currentPage = 1;
const isGitHubTableKind = (k) => {
const kk = String(k || '').toLowerCase();
return kk === 'github-scan' || kk === 'mod:github-scan' || kk === 'github';
};
const pageSizeForKind = () => isGitHubTableKind(activeKind) ? 1200 : 250;
const parseStatusCode = (v) => {
const m = String(v || '').match(/\b([1-5][0-9]{2})\b/);
return m ? Number(m[1]) : null;
};
const attachRowIndex = (rowHtml, rowIdx) => {
if (!rowHtml) return rowHtml;
// Ensure every interactive findings row can be resolved back to source data.
if (/\bdata-row-index=/.test(rowHtml)) return rowHtml;
return rowHtml.replace(
/<tr class="findings-row([^"]*)"/,
`<tr class="findings-row$1" data-row-index="${rowIdx}"`
);
};
const parseTitle = (v) => {
const s = String(v || '').trim();
if (!s || s === '—') return '-';
return s.length > 120 ? `${s.slice(0, 117)}...` : s;
};
const rowToGrid = (r) => {
const host = String(r.target || '—');
const code = parseStatusCode(`${r.target || ''} ${r.finding || ''}`);
const status = code && code < 400 ? 'Alive' : (code ? 'Issue' : '-');
const title = parseTitle(r.finding);
const tech = String(r.module || '').replace(/-/g, ' ') || '-';
return { ...r, host, code, status, title, tech };
};
allRows = allRows.map(rowToGrid);
const trufflehogSource = (raw) => {
const r = raw && typeof raw === 'object' ? raw : {};
const meta = r.SourceMetadata || r.source_metadata || {};
const data = (meta && typeof meta === 'object') ? (meta.Data || meta.data || {}) : {};
const git = (data && typeof data === 'object') ? (data.Git || data.git || {}) : {};
const fs = (data && typeof data === 'object') ? (data.Filesystem || data.filesystem || {}) : {};
const link = String(data.Link || data.link || git.Link || git.link || '').trim();
const file = String(data.File || data.file || git.File || git.file || git.Path || git.path || fs.File || fs.file || fs.Path || fs.path || '').trim();
const line = String(data.Line || data.line || git.Line || git.line || fs.Line || fs.line || '').trim();
return { link, file, line };
};
const dynamicValue = (r, key) => {
const raw = r && r.raw && typeof r.raw === 'object' ? r.raw : {};
const lk = String(key || '').toLowerCase();
if (lk === 'source_file' || lk === 'file') {
return trufflehogSource(raw).file || '';
}
if (lk === 'source_line' || lk === 'line') {
return trufflehogSource(raw).line || '';
}
if (lk === 'source_link' || lk === 'link' || lk === 'url') {
return trufflehogSource(raw).link || '';
}
const direct = raw[key];
if (direct != null && direct !== '') return direct;
const keys = Object.keys(raw);
const matched = keys.find((k) => String(k).toLowerCase() === lk);
if (!matched) return '';
return raw[matched];
};
const toCellText = (v) => {
if (v == null) return '';
if (typeof v === 'string') {
const s = v.trim();
if (s === '' || s === '<nil>' || s === 'null') return '';
return s;
}
if (typeof v === 'number' || typeof v === 'boolean') return String(v);
try { return JSON.stringify(v); } catch (_) { return String(v); }
};
const titleCase = (s) => String(s || '').replace(/[_-]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
const collectDynamicColumns = (rows) => {
const preferred = ['DetectorName', 'severity', 'Verified', 'Redacted', 'source_file', 'source_line', 'source_link'];
const discovered = [];
rows.forEach((r) => {
if (!r || !r.raw || typeof r.raw !== 'object') return;
Object.keys(r.raw).forEach((k) => {
if (!discovered.includes(k)) discovered.push(k);
});
});
const low = new Set(discovered.map((k) => String(k).toLowerCase()));
const out = [];
preferred.forEach((k) => {
if (k.startsWith('source_')) {
out.push(k);
return;
}
const m = discovered.find((x) => String(x).toLowerCase() === String(k).toLowerCase());
if (m) out.push(m);
});
discovered.forEach((k) => {
const lk = String(k).toLowerCase();
if (['sourcemetadata', 'source_metadata', 'raw'].includes(lk)) return;
if (!out.includes(k)) out.push(k);
});
return out.slice(0, 8);
};
const renderDynamicRawRow = (r, rowIdx, sevMeta, cols) => {
const cells = cols.map((k) => {
const val = toCellText(dynamicValue(r, k));
const short = val.length > 90 ? `${val.slice(0, 87)}...` : val;
const isLink = (String(k).toLowerCase().includes('link') || String(k).toLowerCase().includes('url')) && /^https?:\/\//i.test(val);
if (isLink) {
return `<td style="padding:7px 10px;max-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><a href="${esc(val)}" target="_blank" rel="noopener" onclick="event.stopPropagation()" style="color:var(--accent-cyan);font-family:var(--font-mono,monospace);font-size:11px">${esc(short)}</a></td>`;
}
return `<td style="padding:7px 10px;max-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><span title="${esc(val || '—')}" style="font-family:var(--font-mono,monospace);font-size:11px;color:var(--text-secondary)">${esc(short || '—')}</span></td>`;
}).join('');
return `<tr class="findings-row" data-row-index="${rowIdx}" style="cursor:pointer;${rowIdx % 2 ? 'background:rgba(255,255,255,.012)' : ''}">
<td style="padding:7px 10px;width:36px;text-align:center"><input type="checkbox" class="finding-chk" style="width:14px;height:14px;accent-color:var(--accent-cyan);cursor:pointer" onclick="event.stopPropagation()"></td>
<td style="padding:7px 8px;text-align:center;white-space:nowrap"><span style="display:inline-block;background:${sevMeta.bg};border:1px solid ${sevMeta.color}44;color:${sevMeta.color};font-size:9px;font-weight:800;letter-spacing:.7px;padding:2px 7px;border-radius:4px;min-width:34px;">${esc(sevMeta.label)}</span></td>
${cells}
</tr>`;
};
const renderGitHubExpandedRow = (r, rowIdx, sevMeta) => {
const raw = r.raw && typeof r.raw === 'object' ? r.raw : {};
const detector = String(raw.DetectorName || raw.detector_name || raw.detector || r.finding || 'Unknown').replace(/\s+—\s+.*$/, '').trim();
const redacted = String(raw.Redacted || raw.redacted || '').trim();
const verified = String(raw.Verified ?? raw.verified ?? '').toLowerCase() === 'true';
const { link, file, line } = trufflehogSource(raw);
const sourceFile = file || '—';
const sourceLine = line || '—';
const sourceLink = link || '—';
const redactedShort = redacted.length > 80 ? `${redacted.slice(0, 77)}...` : redacted || '—';
const linkLabel = sourceLink.length > 70 ? `${sourceLink.slice(0, 67)}...` : sourceLink;
const fileLabel = sourceFile.length > 60 ? `${sourceFile.slice(0, 57)}...` : sourceFile;
return `<tr class="findings-row" data-row-index="${rowIdx}" style="cursor:pointer;${rowIdx % 2 ? 'background:rgba(255,255,255,.012)' : ''}">
<td style="padding:7px 10px;width:36px;text-align:center"><input type="checkbox" class="finding-chk" style="width:14px;height:14px;accent-color:var(--accent-cyan);cursor:pointer" onclick="event.stopPropagation()"></td>
<td style="padding:7px 10px;max-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><span title="${esc(detector)}" style="font-family:var(--font-mono,monospace);font-size:11.5px;color:var(--text-primary);font-weight:600">${esc(detector || '—')}</span></td>
<td style="padding:7px 8px;text-align:center;white-space:nowrap"><span style="display:inline-block;background:${sevMeta.bg};border:1px solid ${sevMeta.color}44;color:${sevMeta.color};font-size:9px;font-weight:800;letter-spacing:.7px;padding:2px 7px;border-radius:4px;min-width:34px;">${esc(sevMeta.label)}</span></td>
<td style="padding:7px 10px;text-align:center"><span style="font-size:11px;font-family:var(--font-mono,monospace);color:${verified ? '#22c55e' : '#94a3b8'};font-weight:700">${verified ? 'true' : 'false'}</span></td>
<td style="padding:7px 10px;max-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><span title="${esc(redacted || '—')}" style="font-family:var(--font-mono,monospace);font-size:11px;color:var(--text-secondary)">${esc(redactedShort)}</span></td>
<td style="padding:7px 10px;max-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><span title="${esc(sourceFile)}" style="font-family:var(--font-mono,monospace);font-size:11px;color:var(--text-secondary)">${esc(fileLabel)}</span></td>
<td style="padding:7px 10px;text-align:center"><span style="font-family:var(--font-mono,monospace);font-size:11px;color:var(--text-secondary)">${esc(sourceLine)}</span></td>
<td style="padding:7px 10px;max-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${sourceLink !== '—' ? `<a href="${esc(sourceLink)}" target="_blank" rel="noopener" onclick="event.stopPropagation()" style="color:var(--accent-cyan);font-family:var(--font-mono,monospace);font-size:11px">${esc(linkLabel)}</a>` : `<span style="font-family:var(--font-mono,monospace);font-size:11px;color:var(--text-muted)">—</span>`}</td>
</tr>`;
};
const extractApkPackageInfo = (rows) => {
const info = {};
const consumed = new Set();
const aliases = {
package_name: 'package_name', package: 'package_name', packageid: 'package_name', package_id: 'package_name',
applicationid: 'package_name', application_id: 'package_name', appid: 'package_name',
app_name: 'app_name', appname: 'app_name', name: 'app_name',
version: 'version', version_name: 'version', versionname: 'version',
version_code: 'version_code', versioncode: 'version_code',
min_sdk: 'min_sdk', minsdk: 'min_sdk', minsdkversion: 'min_sdk',
target_sdk: 'target_sdk', targetsdk: 'target_sdk', targetsdkversion: 'target_sdk',
compile_sdk: 'compile_sdk', compilesdk: 'compile_sdk', compilesdkversion: 'compile_sdk',
};
const takeKV = (k, v) => {
const key = String(k || '').trim().toLowerCase().replace(/[^a-z0-9_]/g, '');
const mapped = aliases[key];
if (!mapped) return;
const val = String(v ?? '').trim();
if (!val) return;
if (!info[mapped]) info[mapped] = val;
};
rows.forEach((r, idx) => {
const target = String(r.target || '');
const finding = String(r.finding || '').trim();
if (!/[{]/.test(finding) && !/(package|version|sdk|app_name|application_id)/i.test(`${target} ${finding}`)) return;
let consumedRow = false;
try {
const parsed = JSON.parse(finding);
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
Object.entries(parsed).forEach(([k, v]) => takeKV(k, v));
consumedRow = Object.keys(parsed).length > 0;
}
} catch (_) { }
const kvs = finding.match(/"?([A-Za-z_][A-Za-z0-9_ ]*)"?\s*:\s*"?([^,"}]+)"?/g) || [];
kvs.forEach((frag) => {
const m = frag.match(/"?([A-Za-z_][A-Za-z0-9_ ]*)"?\s*:\s*"?([^,"}]+)"?/);
if (m) takeKV(m[1], m[2]);
});
if (kvs.length) consumedRow = true;
if (consumedRow) consumed.add(idx);
});
return { info, rows: rows.filter((_, idx) => !consumed.has(idx)) };
};
let apkPackageInfo = null;
if (isAPKScan) {
const extracted = extractApkPackageInfo(allRows);
allRows = extracted.rows;
apkPackageInfo = extracted.info;
if (!apkPackageInfo.package_name) {
const tgt = String(scanRecord?.target || scanRecord?.Target || '').trim();
if (tgt) apkPackageInfo.package_name = tgt;
}
apiFetch(`/api/scans/${encodeURIComponent(scanId)}/results/apk-meta`)
.then((meta) => {
if (!meta) return;
if (meta.package_name) apkPackageInfo.package_name = meta.package_name;
if (meta.version) apkPackageInfo.version = meta.version;
if (meta.version_code) apkPackageInfo.version_code = meta.version_code;
if (meta.min_sdk) apkPackageInfo.min_sdk = meta.min_sdk;
if (meta.target_sdk) apkPackageInfo.target_sdk = meta.target_sdk;
if (meta.task_hijacking_risk) apkPackageInfo.task_hijacking_risk = meta.task_hijacking_risk;
if (apkMetaBar && isAPKScan) renderAPKMetaBar();
}).catch(() => { });
}
const apkCategoryKey = (r) => {
const explicit = String(r.category_name || r.apk_category || '').trim();
if (explicit) return explicit;
const t = String(r.target || '').trim();
if (t && t !== '-' && t !== '—') return t;
const f = String(r.finding || '').trim();
const idx = f.indexOf(':');
if (idx > 0) return f.slice(0, idx).trim();
return '';
};
const slugifyApkCategory = (s) => String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
const apkCategoryCounts = {};
if (isAPKScan) {
allRows = allRows.map((r) => {
const cat = apkCategoryKey(r);
const slug = slugifyApkCategory(cat);
if (slug) {
apkCategoryCounts[slug] = apkCategoryCounts[slug] || { label: cat, count: 0 };
apkCategoryCounts[slug].count += 1;
}
return { ...r, apk_category: cat, apk_category_slug: slug };
});
const apkCategoryTabs = Object.entries(apkCategoryCounts)
.sort((a, b) => b[1].count - a[1].count)
.slice(0, 30)
.map(([slug, meta]) => [`apkcat:${slug}`, ` ${meta.label}`]);
if (apkCategoryTabs.length) {
const baseTabs = UNIQUE_TABS.filter(([k]) => k !== 'apkx');
UNIQUE_TABS = [['apkx', TAB_LABELS.apkx], ...apkCategoryTabs, ...baseTabs]
.filter((t, i, arr) => arr.findIndex(x => x[0] === t[0]) === i);
}
}
const kindCounts = {};
for (const r of allRows) kindCounts[r.kind || 'other'] = (kindCounts[r.kind || 'other'] || 0) + 1;
const datasetCount = (k) => (k === 'all' ? allRows.length : (kindCounts[k] || 0));
let searchJsOnly = false;
let presetMode = 'smart';
let railSearch = '';
let currentRenderedRows = [];
let _virtualScrollTop = 0;
// Per-scan id so a saved "Assets" tab from a domain recon does not blank GitHub / other scans.
const uiStateKey = `autoar.recon.uistate.${encodeURIComponent(scanId)}`;
const colStateKey = `autoar.recon.colwidths.${stNorm || 'generic'}`;
const persistUIState = () => { try { localStorage.setItem(uiStateKey, JSON.stringify({ activeKind, presetMode, searchModule, searchJsOnly, })); } catch (_) { } };
const loadUIState = () => { try { return JSON.parse(localStorage.getItem(uiStateKey) || '{}') || {}; } catch { return {}; } };
const persistColumnWidths = () => {
const cg = root.querySelector('#recon-colgroup');
if (!cg) return;
const cols = Array.from(cg.querySelectorAll('col')).map((c) => c.style.width || '');
try { localStorage.setItem(colStateKey, JSON.stringify(cols)); } catch (_) { }
};
const applyColumnWidths = () => {
const cg = root.querySelector('#recon-colgroup');
if (!cg) return;
let widths = null;
try { widths = JSON.parse(localStorage.getItem(colStateKey) || 'null'); } catch { widths = null; }
if (!Array.isArray(widths) || widths.length < 5) return;
const cols = Array.from(cg.querySelectorAll('col'));
cols.forEach((c, i) => { if (widths[i]) c.style.width = widths[i]; });
};
const rowMatch = (r) => {
const k = r.kind || 'other';
if (String(activeKind || '').startsWith('mod:')) {
const moduleKind = String(activeKind).slice(4);
if (window.normalizeModuleKey(r.module) !== moduleKind) return false;
} else if (String(activeKind || '').startsWith('apkcat:')) {
const categorySlug = String(activeKind).slice(7);
if (String(r.apk_category_slug || '') !== categorySlug) return false;
} else if (activeKind === 'vuln') {
if (!VULN_KINDS.has(k)) return false;
if (searchModule !== 'all' && window.normalizeModuleKey(r.module) !== searchModule) return false;
} else if (k !== activeKind) return false;
// Optional module narrow (all standard tabs except per-module rails, already constrained above)
if (searchModule !== 'all' && !String(activeKind || '').startsWith('mod:') && activeKind !== 'vuln') {
if (window.normalizeModuleKey(r.module) !== searchModule) return false;
}
if (activeKind === 'urls' && searchJsOnly && !r.is_js) return false;
if (searchHost && !String(r.host || r.target || '').toLowerCase().includes(searchHost)) return false;
if (searchTitle && !String(r.title || r.finding || '').toLowerCase().includes(searchTitle)) return false;
if (filterSeverity !== 'any') {
const sev = String(r.severity || 'info').toLowerCase();
if (sev !== filterSeverity) return false;
}
const sev = String(r.severity || 'info').toLowerCase();
const targetStr = String(r.target || '').toLowerCase();
const findingStr = String(r.finding || '').toLowerCase();
return true;
};
root.innerHTML = `
<div style="border:1px solid var(--border);border-radius:10px;background:var(--bg-surface);overflow:hidden">
<div style="display:grid;grid-template-columns:240px 1fr;min-height:720px">
<aside style="border-right:1px solid var(--border);background:rgba(2,6,23,.55);display:flex;flex-direction:column;min-width:0">
<div style="padding:10px 12px;border-bottom:1px solid var(--border);font-size:11px;color:var(--text-muted);letter-spacing:.6px;text-transform:uppercase">Findings Views</div>
<div style="padding:8px;border-bottom:1px solid var(--border)">
<input id="recon-rail-search" type="search" placeholder="Search views..." style="width:100%;padding:7px 9px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text-primary);font-size:11px"/>
</div>
<div id="recon-left-rail" style="display:flex;flex-direction:column;gap:6px;padding:8px;overflow-y:auto;overflow-x:hidden;max-height:780px;scrollbar-width:thin"></div>
</aside>
<section style="min-width:0;position:relative">
<div id="recon-apk-meta" style="display:none;padding:10px 12px;border-bottom:1px solid var(--border);background:rgba(34,211,238,.06)"></div>
<div id="recon-filter-bar" style="display:flex;flex-wrap:wrap;align-items:center;gap:10px;padding:10px;border-bottom:1px solid var(--border);background:rgba(2,6,23,.5)">
<input id="recon-filter-host" type="search" placeholder=" Target / URL…" style="flex:1 1 200px;min-width:160px;padding:8px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text-primary);font-size:12px"/>
<select id="recon-filter-severity" title="Severity" style="flex:0 0 auto;min-width:132px;padding:8px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text-primary);font-size:12px">
<option value="any">Any Severity</option>
<option value="critical">Critical</option>
<option value="high">High</option>
<option value="medium">Medium</option>
<option value="low">Low</option>
<option value="info">Info</option>
</select>
<select id="recon-filter-module" title="Module (optional narrow)" style="flex:1 1 140px;min-width:140px;max-width:240px;display:none;padding:8px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text-primary);font-size:12px">
<option value="all">All modules</option>
</select>
<input id="recon-filter-title" type="search" placeholder=" Finding / title…" style="flex:1 1 200px;min-width:160px;padding:8px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text-primary);font-size:12px"/>
<span style="flex:0 0 auto;margin-left:auto;font-size:11px;color:var(--text-muted);white-space:nowrap"><span id="recon-unified-shown">0</span> rows</span>
</div>
<div id="recon-quick-tools" style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:8px 10px;border-bottom:1px solid var(--border);background:rgba(2,6,23,.38)">
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
<button type="button" id="recon-copy-selected-tsv" title="Copy checked rows from the current page" style="padding:6px 10px;background:rgba(34,211,238,.1);border:1px solid rgba(34,211,238,.35);border-radius:6px;color:var(--accent-cyan);font-size:11px;cursor:pointer;white-space:nowrap"> Copy selected</button>
<button type="button" id="recon-report-selected-ai" title="Generate an AI vulnerability report for the checked rows" style="padding:6px 10px;background:rgba(52,211,153,.1);border:1px solid rgba(52,211,153,.4);border-radius:6px;color:#34d399;font-size:11px;cursor:pointer;white-space:nowrap"> Report selected (AI)</button>
<button type="button" id="recon-export-all-json" title="Export all findings in the current view as Markdown" style="padding:6px 10px;background:rgba(167,139,250,.08);border:1px solid rgba(167,139,250,.35);border-radius:6px;color:#c4b5fd;font-size:11px;cursor:pointer;white-space:nowrap"> Export Markdown</button>
</div>
<div style="margin-left:auto;display:flex;align-items:center;gap:6px;flex-wrap:wrap">
<select id="recon-view-mode" style="padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text-primary);font-size:11px">
<option value="smart">Smart columns</option>
<option value="raw">Raw columns</option>
</select>
</div>
</div>
<div id="recon-standard-view">
<div class="result-table-wrap" style="max-height:640px;overflow-x:auto;overflow-y:auto">
<table id="recon-main-table" class="dashboard-table" style="margin:0;table-layout:auto;min-width:100%">
<colgroup id="recon-colgroup"><col style="width:36px"><col style="width:8%"><col style="width:50%"><col style="width:20%"></colgroup>
<thead style="position:sticky;top:0;z-index:2;background:rgba(2,6,23,.97);backdrop-filter:blur(4px)">
<tr id="recon-unified-headrow">
<th style="width:36px;text-align:center;padding-left:10px"><input type="checkbox" id="findings-select-all" title="Select all" style="width:14px;height:14px;accent-color:var(--accent-cyan);cursor:pointer"></th>
<th style="position:relative">TARGET<span class="col-resizer" data-col-index="1" style="position:absolute;top:0;right:-3px;width:6px;height:100%;cursor:col-resize;user-select:none"></span></th>
<th style="text-align:center;position:relative">SEV<span class="col-resizer" data-col-index="2" style="position:absolute;top:0;right:-3px;width:6px;height:100%;cursor:col-resize;user-select:none"></span></th>
<th style="position:relative">VULNERABILITY TYPE<span class="col-resizer" data-col-index="3" style="position:absolute;top:0;right:-3px;width:6px;height:100%;cursor:col-resize;user-select:none"></span></th>
<th style="width:16%">MODULE</th>
</tr>
</thead>
<tbody id="recon-unified-tbody"></tbody>
</table>
</div>
<div id="recon-unified-cap" style="display:none;padding:10px 12px;font-size:12px;color:var(--text-muted);border-top:1px solid var(--border)"></div>
<div id="recon-pagination" style="padding:10px 12px;background:rgba(2,6,23,0.3);border-top:1px solid var(--border);display:flex;justify-content:center;align-items:center;gap:15px;font-size:12px"></div>
</div>
<div id="recon-assets-view" style="display:none">
<div id="recon-assets-content" style="padding:16px;min-height:200px;max-height:680px;overflow:auto">
<div style="text-align:center;padding:40px;color:var(--text-muted)">Loading assets…</div>
</div>
</div>
<div id="recon-urls-view" style="display:none">
<div style="padding:10px 12px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:8px;flex-wrap:wrap;background:rgba(2,6,23,.5)">
<input id="recon-urls-search" type="search" placeholder=" Search URLs…" style="flex:1;min-width:180px;padding:7px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text-primary);font-size:12px"/>
<select id="recon-urls-type" style="padding:7px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text-primary);font-size:12px"><option value="all">All URLs</option><option value="js">JS Only</option><option value="interesting">Interesting Only</option></select>
<span id="recon-urls-count" style="color:var(--text-muted);font-size:12px;white-space:nowrap"></span>
<button id="recon-urls-copy" type="button" style="padding:6px 12px;background:rgba(167,139,250,.12);border:1px solid rgba(167,139,250,.35);border-radius:6px;color:#a78bfa;font-size:11px;cursor:pointer"> Copy</button>
<button id="recon-urls-export" type="button" style="padding:6px 12px;background:rgba(34,211,238,.1);border:1px solid rgba(34,211,238,.3);border-radius:6px;color:var(--accent-cyan);font-size:11px;cursor:pointer"> Export</button>
</div>
<div id="recon-urls-content" style="min-height:200px;max-height:580px;overflow:auto;font-family:var(--font-mono);font-size:12px"><div style="text-align:center;padding:40px;color:var(--text-muted)">Loading URLs…</div></div>
<div id="recon-urls-pagination" style="padding:10px 12px;background:rgba(2,6,23,0.3);border-top:1px solid var(--border);display:flex;justify-content:center;align-items:center;gap:15px;font-size:12px"></div>
</div>
</section>
</div>
</div>`;
const tabsEl = root.querySelector('#recon-left-rail');
const railSearchInput = root.querySelector('#recon-rail-search');
const apkMetaBar = root.querySelector('#recon-apk-meta');
const filterBar = root.querySelector('#recon-filter-bar');
const viewModeSel = root.querySelector('#recon-view-mode');
const standardView = root.querySelector('#recon-standard-view');
const assetsView = root.querySelector('#recon-assets-view');
const assetsContent = root.querySelector('#recon-assets-content');
const urlsView = root.querySelector('#recon-urls-view');
const urlsContent = root.querySelector('#recon-urls-content');
const standardTable = root.querySelector('#recon-standard-view table.dashboard-table');
const renderAPKMetaBar = () => {
if (!apkMetaBar || !isAPKScan || !apkPackageInfo) { if (apkMetaBar) { apkMetaBar.style.display = 'none'; apkMetaBar.innerHTML = ''; } return; }
const riskFromBackend = String(apkPackageInfo.task_hijacking_risk || '').toLowerCase();
let hijackLabel, hijackColor;
if (riskFromBackend === 'possible') { hijackLabel = ' Possible (minSdk ≤ 28)'; hijackColor = '#f97316'; }
else if (riskFromBackend === 'mitigated') { hijackLabel = ' Partially mitigated (minSdk 29–30)'; hijackColor = '#f59e0b'; }
else if (riskFromBackend === 'unlikely') { hijackLabel = ' Unlikely (minSdk ≥ 31)'; hijackColor = '#22c55e'; }
else { hijackLabel = '? Unknown'; hijackColor = '#94a3b8'; }