-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
4908 lines (4536 loc) · 197 KB
/
Copy pathscript.js
File metadata and controls
4908 lines (4536 loc) · 197 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 state = {
config: null,
modules: [],
jobs: [],
assessments: [],
activeAssessmentId: null,
activeAssessment: null,
activeApprovals: [],
activeRecommendations: null,
activeFindings: [],
activeFindingSummary: null,
activeAssessmentDetail: null,
activeCorrelation: null,
activeWorkspace: null,
activeDiff: null,
activeDrift: null,
approvalsDashboard: null,
chainPresets: [],
toolsStatus: null,
toolingCatalog: [],
toolSearchQuery: "",
toolStatusFilter: "all",
toolSortMode: "usage",
selectedToolLabel: "",
highlightedModuleId: "",
engagements: [],
referenceFindings: [],
assets: [],
targetAsset: null,
importResult: null,
destructiveActions: [],
destructiveResult: null,
workspacePreviewPath: "",
activeJobId: null,
activeJob: null,
pollTimer: null,
tooling: null,
selectedPhase: "all",
catalogSurface: "modules",
viewMode: "playbook",
operationsTab: "workspace",
healthTab: "strategy",
advancedTab: "findings",
moduleExecutionProfile: "fast",
moduleSearchQuery: "",
insightTab: "console",
consoleHeightLocked: false,
operationsVisible: false,
moduleRenderFrame: 0,
expandedModuleCommandIds: [],
moduleDryRunCache: {},
targetAssetTimer: 0,
targetAssetRequestSeq: 0,
lastTargetAssetKey: "",
moduleSearchTimer: 0,
toolSearchTimer: 0,
operatorWorkspaceLoaded: false,
toolCatalogLoaded: false,
toolCatalogLoading: false,
toolCatalogLoadPromise: null,
apiBaseUrl: "",
apiBasePromise: null,
chainRunPending: false,
chainRunStage: "idle",
chainRunUiTimer: 0,
referencePanelLoaded: false,
activeInteractiveSession: null,
interactivePollTimer: 0,
interactiveTabState: null
};
const $ = (selector) => document.querySelector(selector);
const LAST_TARGET_STORAGE_KEY = "lab-console-last-target";
const CONSOLE_MIN_HEIGHT = 260;
const MODULES_CACHE_KEY = "lab-console-modules-cache-v1";
const MODULES_CACHE_TTL_MS = 60 * 1000;
const BACKEND_DEFAULT_PORT = "4080";
const INTERACTIVE_COMMAND_HINTS = {
metasploit: [
"help",
"search",
"use",
"show",
"show options",
"show payloads",
"show exploits",
"show auxiliary",
"info",
"check",
"run",
"exploit",
"set",
"setg",
"unset",
"unsetg",
"back",
"sessions",
"jobs",
"route",
"workspace",
"notes",
"creds",
"services",
"hosts",
"version",
"banner",
"exit",
"quit"
],
ssh: ["help", "exit", "quit", "pwd", "ls", "cd", "cat", "whoami", "id", "uname -a"],
smbclient: ["help", "ls", "dir", "cd", "pwd", "get", "put", "mget", "mkdir", "rmdir", "exit", "quit"],
rpcclient: ["help", "enumdomusers", "enumdomgroups", "queryuser", "querygroup", "lsaquery", "srvinfo", "exit", "quit"],
mysql: ["help", "show databases;", "use ", "show tables;", "select ", "status;", "exit"],
psql: ["\\?", "\\l", "\\c ", "\\dt", "\\d ", "select ", "\\q"],
ftp: ["help", "ls", "pwd", "cd ", "get ", "put ", "passive", "binary", "ascii", "bye", "quit"],
telnet: ["help", "open ", "close", "quit", "status", "send "]
};
function isAbsoluteUrl(value) {
return /^https?:\/\//i.test(String(value || ""));
}
function normalizeRequestPath(path) {
const value = String(path || "").trim();
if (!value) return "/";
if (isAbsoluteUrl(value)) return value;
return value.startsWith("/") ? value : `/${value}`;
}
function candidateApiBases() {
const candidates = [];
const append = (value) => {
const normalized = String(value || "").trim().replace(/\/+$/, "");
if (!normalized || candidates.includes(normalized)) return;
candidates.push(normalized);
};
append(window.localStorage.getItem("lab-console-api-base"));
append(window.__LAB_CONSOLE_API_BASE__);
append(window.location.origin);
if (window.location.port !== BACKEND_DEFAULT_PORT) {
append(`${window.location.protocol}//${window.location.hostname}:${BACKEND_DEFAULT_PORT}`);
}
if (window.location.hostname === "localhost") {
append(`${window.location.protocol}//127.0.0.1:${BACKEND_DEFAULT_PORT}`);
}
return candidates;
}
function buildRequestUrl(path, base = "") {
const normalizedPath = normalizeRequestPath(path);
if (isAbsoluteUrl(normalizedPath)) return normalizedPath;
if (!base) return normalizedPath;
return `${String(base).replace(/\/+$/, "")}${normalizedPath}`;
}
function apiUrl(path) {
const normalizedPath = normalizeRequestPath(path);
if (!normalizedPath.startsWith("/api/")) {
return buildRequestUrl(normalizedPath);
}
const base = state.apiBaseUrl
|| candidateApiBases().find((entry) => entry.endsWith(`:${BACKEND_DEFAULT_PORT}`))
|| window.location.origin;
return buildRequestUrl(normalizedPath, base);
}
async function probeApiBase(base) {
try {
const response = await fetch(buildRequestUrl("/api/health", base), {
method: "GET",
cache: "no-store"
});
return response.ok;
} catch (error) {
return false;
}
}
async function resolveApiBase(force = false) {
if (!force && state.apiBaseUrl) return state.apiBaseUrl;
if (!force && state.apiBasePromise) return state.apiBasePromise;
state.apiBasePromise = (async () => {
for (const base of candidateApiBases()) {
if (await probeApiBase(base)) {
state.apiBaseUrl = base;
window.localStorage.setItem("lab-console-api-base", base);
return base;
}
}
throw new Error("Backend API tidak terdeteksi. Pastikan server backend berjalan di port 4080.");
})();
try {
return await state.apiBasePromise;
} finally {
state.apiBasePromise = null;
}
}
function debounce(fn, delay = 160) {
let timer = 0;
return (...args) => {
window.clearTimeout(timer);
timer = window.setTimeout(() => fn(...args), delay);
};
}
function scheduleModulesRender() {
if (state.moduleRenderFrame) return;
state.moduleRenderFrame = window.requestAnimationFrame(() => {
state.moduleRenderFrame = 0;
renderModules();
});
}
function scheduleDeferredTask(task) {
const runner = () => Promise.resolve().then(task).catch((error) => console.warn(error));
if (typeof window.requestIdleCallback === "function") {
window.requestIdleCallback(() => runner(), { timeout: 1200 });
return;
}
window.setTimeout(runner, 120);
}
function readModulesCache() {
try {
const raw = localStorage.getItem(MODULES_CACHE_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw);
const savedAt = Number(parsed?.savedAt || 0);
const modules = Array.isArray(parsed?.modules) ? parsed.modules : null;
if (!modules?.length || !savedAt) return null;
if (Date.now() - savedAt > MODULES_CACHE_TTL_MS) return null;
return modules;
} catch (error) {
localStorage.removeItem(MODULES_CACHE_KEY);
return null;
}
}
function writeModulesCache(modules) {
try {
localStorage.setItem(MODULES_CACHE_KEY, JSON.stringify({
savedAt: Date.now(),
modules: Array.isArray(modules) ? modules : []
}));
} catch (error) {
// Abaikan jika storage penuh atau tidak tersedia.
}
}
function clampConsoleHeight(value) {
const numericValue = Number(value);
if (!Number.isFinite(numericValue)) return CONSOLE_MIN_HEIGHT;
return Math.max(CONSOLE_MIN_HEIGHT, Math.round(numericValue));
}
function insightScrollPanels() {
return ["#consoleOutput", "#evidenceList"]
.map((selector) => $(selector))
.filter(Boolean);
}
function activeInsightScrollPanel() {
if (state.insightTab === "evidence") return $("#evidenceList");
return $("#consoleOutput");
}
function applyInsightPanelHeight(value) {
const height = clampConsoleHeight(value);
insightScrollPanels().forEach((panel) => {
panel.style.height = `${height}px`;
});
}
function persistConsoleHeight() {
const activePanel = activeInsightScrollPanel();
if (!activePanel) return;
state.consoleHeightLocked = true;
applyInsightPanelHeight(activePanel.getBoundingClientRect().height);
}
function syncConsoleHeightToModulePane({ force = false } = {}) {
const activePanel = activeInsightScrollPanel();
const modulePane = document.querySelector(".module-pane");
const insightCard = document.querySelector(".insight-card");
if (!activePanel || !modulePane || !insightCard) return;
if (state.consoleHeightLocked && !force) {
return;
}
const activePanelRect = activePanel.getBoundingClientRect();
const modulePaneRect = modulePane.getBoundingClientRect();
const insightCardRect = insightCard.getBoundingClientRect();
const desiredHeight = activePanelRect.height + (modulePaneRect.bottom - insightCardRect.bottom);
applyInsightPanelHeight(desiredHeight);
}
function queueConsoleHeightSync(options = {}) {
window.requestAnimationFrame(() => syncConsoleHeightToModulePane(options));
}
function bindConsoleResizeHandle() {
let resizeIntent = false;
const armResize = (event) => {
const target = event.currentTarget;
if (!target) return;
const rect = target.getBoundingClientRect();
resizeIntent = rect.bottom - event.clientY <= 28;
};
const commitResize = () => {
if (!resizeIntent) return;
resizeIntent = false;
persistConsoleHeight();
};
insightScrollPanels().forEach((panel) => {
panel.addEventListener("pointerdown", armResize);
});
window.addEventListener("pointerup", commitResize);
window.addEventListener("mouseup", commitResize);
window.addEventListener("resize", () => {
if (!state.consoleHeightLocked) {
queueConsoleHeightSync();
}
});
}
function showToast(message) {
const toast = $("#toast");
if (!toast) return;
toast.textContent = message;
toast.classList.add("show");
window.clearTimeout(showToast.timer);
showToast.timer = window.setTimeout(() => toast.classList.remove("show"), 2200);
}
function setRunChainUiState(stage = "idle", message = "") {
state.chainRunStage = stage || "idle";
state.chainRunPending = !["idle", "success", "error"].includes(state.chainRunStage);
const button = $("#runChainBtn");
const note = $("#runChainStatusNote");
const stepTarget = $("#workflowStepTarget");
const stepAssessment = $("#workflowStepAssessment");
const stepReview = $("#workflowStepReview");
const applyStepState = (element, mode) => {
if (!element) return;
element.classList.toggle("is-active", mode === "active");
element.classList.toggle("is-done", mode === "done");
};
let buttonLabel = "Run Full Simulation Chain";
let noteLabel = message || "Siap menjalankan full chain untuk target aktif.";
let stepTargetMode = "";
let stepAssessmentMode = "";
let stepReviewMode = "";
if (stage === "preflight") {
buttonLabel = "Running...";
noteLabel = message || "Memvalidasi target dan menyiapkan payload eksekusi.";
stepTargetMode = "active";
} else if (stage === "assessment") {
buttonLabel = "Running...";
noteLabel = message || "Membuat atau menyelaraskan assessment aktif.";
stepTargetMode = "done";
stepAssessmentMode = "active";
} else if (stage === "approval") {
buttonLabel = "Running...";
noteLabel = message || "Menyimpan approval chain yang dibutuhkan sebelum eksekusi.";
stepTargetMode = "done";
stepAssessmentMode = "active";
} else if (stage === "submitting") {
buttonLabel = "Running...";
noteLabel = message || "Mengirim full simulation chain ke backend worker.";
stepTargetMode = "done";
stepAssessmentMode = "done";
stepReviewMode = "active";
} else if (stage === "success") {
buttonLabel = "Run Full Simulation Chain";
noteLabel = message || "Job full chain berhasil dibuat. Pantau live console dan evidence.";
stepTargetMode = "done";
stepAssessmentMode = "done";
stepReviewMode = "active";
} else if (stage === "error") {
buttonLabel = "Run Full Simulation Chain";
noteLabel = message || "Eksekusi chain berhenti. Periksa toast atau recent jobs untuk detail.";
stepTargetMode = "";
stepAssessmentMode = "";
stepReviewMode = "";
}
if (button) {
button.disabled = state.chainRunPending;
button.textContent = buttonLabel;
button.setAttribute("aria-busy", String(state.chainRunPending));
}
if (note) {
note.textContent = noteLabel;
}
applyStepState(stepTarget, stepTargetMode);
applyStepState(stepAssessment, stepAssessmentMode);
applyStepState(stepReview, stepReviewMode);
}
function renderInsightTabs() {
const tabs = Array.from(document.querySelectorAll("[data-insight-tab]"));
const tabIds = tabs.map((button) => button.dataset.insightTab);
if (!tabIds.includes(state.insightTab)) {
state.insightTab = tabIds.includes("console") ? "console" : (tabIds[0] || "console");
}
tabs.forEach((button) => {
button.classList.toggle("is-active", button.dataset.insightTab === state.insightTab);
});
document.querySelectorAll("[data-insight-panel]").forEach((panel) => {
panel.classList.toggle("hidden", panel.dataset.insightPanel !== state.insightTab);
});
queueConsoleHeightSync();
}
function requestRangePassword() {
const modal = $("#rangePasswordModal");
const input = $("#rangePasswordInput");
const confirmBtn = $("#confirmRangePasswordBtn");
const cancelBtn = $("#cancelRangePasswordBtn");
if (!modal || !input || !confirmBtn || !cancelBtn) {
return Promise.resolve(window.prompt("Masukkan password simpan ranges") || "");
}
return new Promise((resolve) => {
const cleanup = () => {
modal.classList.add("hidden");
modal.setAttribute("aria-hidden", "true");
input.value = "";
confirmBtn.removeEventListener("click", onConfirm);
cancelBtn.removeEventListener("click", onCancel);
modal.removeEventListener("click", onBackdrop);
input.removeEventListener("keydown", onKeydown);
document.removeEventListener("keydown", onEscape);
};
const onConfirm = () => {
const value = input.value;
cleanup();
resolve(value);
};
const onCancel = () => {
cleanup();
resolve("");
};
const onBackdrop = (event) => {
if (event.target === modal) {
onCancel();
}
};
const onKeydown = (event) => {
if (event.key === "Enter") {
event.preventDefault();
onConfirm();
}
};
const onEscape = (event) => {
if (event.key === "Escape") {
onCancel();
}
};
modal.classList.remove("hidden");
modal.setAttribute("aria-hidden", "false");
confirmBtn.addEventListener("click", onConfirm);
cancelBtn.addEventListener("click", onCancel);
modal.addEventListener("click", onBackdrop);
input.addEventListener("keydown", onKeydown);
document.addEventListener("keydown", onEscape);
window.setTimeout(() => input.focus(), 0);
});
}
async function api(path, options = {}) {
const normalizedPath = normalizeRequestPath(path);
const requestUrl = normalizedPath.startsWith("/api/")
? buildRequestUrl(normalizedPath, await resolveApiBase())
: buildRequestUrl(normalizedPath);
const response = await fetch(requestUrl, {
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
...(options.headers || {})
},
...options
});
if (response.status === 401) {
let loginUrl = `/login?next=${encodeURIComponent(window.location.pathname + window.location.search)}`;
try {
const data = await response.json();
if (data?.login_url) {
loginUrl = data.login_url;
}
} catch (error) {
// Abaikan dan gunakan fallback login URL.
}
window.location.href = loginUrl;
throw new Error("Sesi login berakhir. Silakan masuk kembali.");
}
if (response.redirected && response.url.includes("/login")) {
window.location.href = response.url;
throw new Error("Sesi login berakhir. Silakan masuk kembali.");
}
if (!response.ok) {
let message = `HTTP ${response.status}`;
try {
const data = await response.json();
message = data.detail || message;
} catch (error) {
// Keep fallback.
}
throw new Error(message);
}
const contentType = response.headers.get("content-type") || "";
if (!contentType.includes("application/json")) {
throw new Error("Respon backend tidak valid. Muat ulang halaman dan login kembali bila diperlukan.");
}
return response.json();
}
async function apiOptional(path, fallback = null, options = {}) {
try {
return await api(path, options);
} catch (error) {
return fallback;
}
}
function groupModulesByPhase(modules) {
return modules.reduce((accumulator, module) => {
const key = module.phase_id;
if (!accumulator[key]) {
accumulator[key] = {
label: module.phase_label,
order: module.phase_order,
modules: []
};
}
accumulator[key].modules.push(module);
return accumulator;
}, {});
}
function moduleUiPriority(module) {
const priority = {
"sensitive-file-discovery": -20,
"read-sensitive-file": -20,
"baseline-nikto-review": -10,
"recon-service-scan": -10
};
return priority[module?.id] ?? 0;
}
function severityBadgeMarkup(key, value) {
return `<span class="severity-pill severity-${key}">${key} ${value}</span>`;
}
function chipMarkup(items = [], className = "") {
return items.map((item) => `<span class="${className}">${item}</span>`).join("");
}
function escapeHtml(value) {
return String(value ?? "")
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
function currentTargetValue() {
return $("#targetInput")?.value?.trim() || "TARGET";
}
function selectedRiskMode() {
return riskModeForProfile(selectedModuleProfile());
}
function currentOperatorName() {
return $("#operatorNameInput")?.value?.trim() || "operator";
}
function currentTicketRef() {
return $("#ticketRefInput")?.value?.trim() || "";
}
function activeAssessmentRiskMode() {
return state.activeAssessment?.risk_mode || selectedRiskMode();
}
function riskModeForProfile(profile) {
if (profile === "deep") return "intrusive";
if (profile === "balanced") return "deep";
return "safe";
}
function profileForRiskMode(riskMode) {
if (riskMode === "intrusive") return "deep";
if (riskMode === "deep") return "balanced";
return "fast";
}
function currentTargetKind() {
return $("#targetKindSelect")?.value === "url" ? "url" : "ip";
}
const INTERACTIVE_TOOL_LABELS = new Set(["metasploit", "ssh", "smbclient", "rpcclient"]);
function isInteractiveToolLabel(label = "") {
return INTERACTIVE_TOOL_LABELS.has(String(label || "").trim().toLowerCase());
}
function selectedChainPreset() {
return selectedRiskMode() === "intrusive" ? "intrusive-validation" : "full-chain-default";
}
function severityClass(label) {
const value = String(label || "info").toLowerCase();
if (value === "kritis") return "critical";
if (value === "tinggi") return "high";
if (value === "sedang") return "medium";
if (value === "rendah") return "low";
return "info";
}
function remediationPromptDefaults(findingId) {
const finding = (state.activeFindings || []).find((item) => item.id === findingId) || {};
const metadata = finding.metadata || {};
return {
owner: metadata.owner || "",
due_date: metadata.due_date || "",
sla: metadata.sla || ""
};
}
function renderApprovalsDashboard() {
const container = $("#approvalsDashboardList");
const label = $("#approvalsDashboardLabel");
if (!container) return;
if (label) label.textContent = "0 active / 0 expired";
container.innerHTML = '<p class="empty-jobs">Approval flow nonaktif untuk workflow harian.</p>';
}
function renderAssessmentSummary() {
const container = $("#assessmentSummary");
if (!container) return;
const assessment = state.activeAssessment;
if (!assessment) {
container.textContent = "Belum ada assessment aktif.";
return;
}
const recommendations = state.activeRecommendations?.recommended_modules || [];
const detail = state.activeAssessmentDetail || {};
const severitySummary = state.activeFindingSummary?.severity_summary || {};
const diffSummary = detail.diff_summary || {};
const remediationSummary = detail.remediation_summary || {};
const driftSummary = detail.drift_summary || {};
const severityMarkup = Object.entries(severitySummary)
.filter(([, count]) => Number(count || 0) > 0)
.map(([label, count]) => `<span class="severity-pill severity-${severityClass(label)}">${label}: ${count}</span>`)
.join(" ") || '<span class="severity-pill severity-info">Belum ada finding</span>';
const recommendationMarkup = recommendations.length
? `<ul>${recommendations.map((item) => `<li><strong>${item.phase_label}</strong> - ${item.title} <em>(${item.risk_class})</em></li>`).join("")}</ul>`
: "<div>Tidak ada rekomendasi tambahan. Coverage assessment sudah penuh atau belum ada data.</div>";
container.innerHTML = `
<div><strong>ID:</strong> ${assessment.id}</div>
<div><strong>Target:</strong> ${assessment.target}</div>
<div><strong>Target Kind:</strong> ${assessment.target_kind || "ip"}</div>
<div><strong>Mode:</strong> ${assessment.risk_mode}</div>
<div><strong>Operator:</strong> ${assessment.operator_name}</div>
<div><strong>Ticket:</strong> ${assessment.ticket_ref || "-"}</div>
<div><strong>Workspace:</strong> ${detail.workspace || assessment.metadata?.workspace || "-"}</div>
<div><strong>Jobs terkait:</strong> ${detail.job_count || 0}</div>
<div><strong>Coverage:</strong> ${state.activeRecommendations?.completed_modules || 0}/${state.activeRecommendations?.total_chain_modules || 0}</div>
<div><strong>Normalized findings:</strong> ${detail.finding_count || 0}</div>
<div><strong>Severity summary:</strong> ${severityMarkup}</div>
<div><strong>Diff vs assessment sebelumnya:</strong> new ${diffSummary.new || 0}, recurring ${diffSummary.recurring || 0}, resolved ${diffSummary.resolved || 0}</div>
<div><strong>Drift exposure:</strong> port baru ${driftSummary.open_ports?.new || 0}, path baru ${driftSummary.paths?.new || 0}, subdomain/DNS baru ${(driftSummary.subdomains?.new || 0) + (driftSummary.dns_records?.new || 0)}</div>
<div><strong>Remediation tracking:</strong> owner ${remediationSummary.assigned || 0}, due date ${remediationSummary.with_due_date || 0}, overdue ${remediationSummary.overdue_open || 0}</div>
<div><strong>Next recommended modules:</strong>${recommendationMarkup}</div>
`;
}
function renderAssessmentFindings() {
const container = $("#assessmentFindings");
const label = $("#assessmentFindingsLabel");
if (!container) return;
const findings = Array.isArray(state.activeFindings) ? state.activeFindings : [];
const diff = state.activeDiff || { new: [], recurring: [], resolved: [] };
const newIds = new Set((diff.new || []).map((item) => item.id));
const recurringIds = new Set((diff.recurring || []).map((item) => item.id));
if (label) label.textContent = `${findings.length} findings`;
if (!findings.length) {
container.innerHTML = '<p class="empty-jobs">Belum ada normalized finding pada assessment aktif.</p>';
return;
}
container.innerHTML = findings.map((finding) => {
const diffLabel = newIds.has(finding.id) ? 'new' : recurringIds.has(finding.id) ? 'recurring' : 'current';
return `
<article class="evidence-item severity-border-${severityClass(finding.severity)}">
<div class="evidence-head finding-head-wrap">
<strong>${finding.title}</strong>
<div class="finding-pill-row">
<span class="severity-pill severity-${severityClass(finding.severity)}">${finding.severity}</span>
<span class="severity-pill severity-info">${finding.status || 'open'}</span>
<span class="severity-pill severity-low">${diffLabel}</span>
<span class="severity-pill severity-medium">${(finding.metadata || {}).rule_id || 'generic'}</span>
</div>
</div>
<p class="evidence-detail">${Array.isArray(finding.description) && finding.description.length ? finding.description[0] : 'Temuan telah dinormalisasi dari evidence assessment.'}</p>
${(Array.isArray(finding.evidence_lines) ? finding.evidence_lines : []).slice(0, 3).map((line) => `<p class="evidence-detail evidence-detail-code">- ${line}</p>`).join('')}
<div class="finding-actions-row">
<button class="ghost-button compact" type="button" data-finding-action="open" data-finding-id="${finding.id}">Open</button>
<button class="ghost-button compact" type="button" data-finding-action="accepted-risk" data-finding-id="${finding.id}">Accepted Risk</button>
<button class="ghost-button compact" type="button" data-finding-action="mitigated" data-finding-id="${finding.id}">Mitigated</button>
<button class="ghost-button compact" type="button" data-finding-action="false-positive" data-finding-id="${finding.id}">False Positive</button>
</div>
<small>${finding.phase_label || '-'} - ${finding.module_title || '-'} - owner: ${(finding.metadata || {}).owner || '-'} - due: ${(finding.metadata || {}).due_date || '-'} - sla: ${(finding.metadata || {}).sla || '-'} - note: ${(finding.metadata || {}).status_note || '-'}</small>
</article>`;
}).join('');
}
function renderApprovalQueue() {
const card = $("#approvalQueueCard");
const container = $("#approvalQueueList");
const label = $("#approvalQueueLabel");
if (!container) return;
if (label) label.textContent = "0 pending";
if (card) card.classList.add("hidden");
container.innerHTML = '<p class="empty-jobs">Approval queue dinonaktifkan.</p>';
}
function formatDateLabel(value) {
if (!value) return "-";
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
return date.toLocaleString("id-ID", {
year: "numeric",
month: "short",
day: "2-digit",
hour: "2-digit",
minute: "2-digit"
});
}
function renderChainPresetSelect() {
const select = $("#chainPresetSelect");
if (!select) return;
const presets = Array.isArray(state.chainPresets) ? state.chainPresets : [];
if (!presets.length) {
select.innerHTML = '<option value="full-chain-default">full-chain-default</option>';
return;
}
const activeValue = selectedChainPreset();
select.innerHTML = presets.map((preset) => `
<option value="${preset.id}" ${preset.id === activeValue ? "selected" : ""}>${preset.label}</option>
`).join("");
}
function renderChainPresetList() {
const container = $("#chainPresetList");
if (!container) return;
const presets = Array.isArray(state.chainPresets) ? state.chainPresets : [];
if (!presets.length) {
container.innerHTML = '<p class="empty-jobs">Belum ada chain preset.</p>';
return;
}
const activePreset = selectedChainPreset();
container.innerHTML = presets.map((preset) => `
<article class="preset-item${preset.id === activePreset ? " is-active" : ""}">
<div class="preset-item-head">
<strong>${preset.label}</strong>
<span class="severity-pill severity-info">${preset.recommended_risk_mode || "safe"}</span>
</div>
<p>${preset.description}</p>
<div class="preset-item-meta">
<span class="module-chip module-chip-muted">${preset.id}</span>
<span class="module-chip module-chip-soft">${(preset.priority_module_ids || []).length} priority modules</span>
</div>
</article>
`).join("");
}
function toolCategoryForLabel(label) {
const tool = String(label || "").toLowerCase();
if (["nmap", "masscan", "rustscan", "naabu", "ncat", "socat"].some((item) => tool.includes(item))) return "Discovery";
if (["subfinder", "dnsx", "dnsrecon", "fierce", "chaos", "amass", "dig", "shuffledns"].some((item) => tool.includes(item))) return "DNS & Surface";
if (["httpx", "whatweb", "wappalyzer", "nikto", "nuclei", "ffuf", "gobuster", "katana", "urlscan", "curl"].some((item) => tool.includes(item))) return "Web Assessment";
if (["sqlmap", "dalfox", "xsstrike", "commix", "jwt", "wpscan"].some((item) => tool.includes(item))) return "Validation";
if (["hydra", "medusa", "crowbar", "kerbrute", "john", "hashcat", "ncrack", "patator"].some((item) => tool.includes(item))) return "Credential";
if (["metasploit", "searchsploit", "beef", "bettercap", "responder", "mitm6", "bloodhound", "impacket", "enum4linux", "mimikatz", "proxychains", "chisel", "ssh", "smbclient", "ldapsearch", "rpcclient"].some((item) => tool.includes(item))) return "Post Exploitation";
if (["openssl", "sslyze", "tcpdump", "wireshark", "zeek", "suricata", "sigma", "sysmon", "yara", "strings", "file", "sha256sum"].some((item) => tool.includes(item))) return "Detection & Forensics";
if (["jq", "pandoc", "graphviz", "markdown", "mailparser", "swaks", "otp-review", "killchain", "ngrok"].some((item) => tool.includes(item))) return "Utility";
return "Other";
}
function toolPurposeCopy(category) {
const mapping = {
"Discovery": "Dipakai untuk memastikan host hidup, membuka port map, dan membangun baseline exposure sebelum validasi lebih dalam.",
"DNS & Surface": "Dipakai saat kita perlu memperluas scope permukaan, host, subdomain, atau jejak layanan yang terhubung ke target.",
"Web Assessment": "Dipakai untuk fingerprinting, crawling, content discovery, dan observasi misconfiguration web secara cepat.",
"Validation": "Dipakai ketika perlu menguji hipotesis temuan spesifik seperti injection, auth issue, atau komponen rentan.",
"Credential": "Dipakai untuk mengukur risiko paparan kredensial atau validasi account attack path secara terkontrol.",
"Post Exploitation": "Dipakai pada fase lanjutan untuk eksploitasi, pivot, lateral movement, atau emulasi attacker pasca-akses.",
"Detection & Forensics": "Dipakai untuk melihat jejak, paket, indikator pertahanan, dan artefak yang berguna untuk hunting atau evidence.",
"Utility": "Dipakai sebagai alat bantu pengolahan data, dokumentasi, parsing, dan workflow pendukung operator.",
"Other": "Dipakai sebagai tool pendukung yang belum masuk kelompok dominan tertentu."
};
return mapping[category] || mapping.Other;
}
function toolUsageModules(label) {
return (state.modules || [])
.filter((module) => Array.isArray(module.tooling) && module.tooling.includes(label))
.map((module) => ({
id: module.id,
title: module.title,
phaseId: module.phase_id,
phase: module.phase_label,
risk: module.risk
}));
}
function selectedToolSortMode() {
return $("#toolSortSelect")?.value || state.toolSortMode || "usage";
}
function filteredToolCatalogEntries() {
const toolMap = state.toolsStatus?.tools || {};
const rows = Array.isArray(state.toolingCatalog) && state.toolingCatalog.length
? state.toolingCatalog.map((entry) => [entry.label, entry.status || toolMap[entry.label] || {}])
: Object.entries(toolMap);
const matchesFilter = (status) => {
if (state.toolStatusFilter === "installed") return status?.installed === true;
if (state.toolStatusFilter === "missing") return status?.installed === false;
if (state.toolStatusFilter === "conceptual") return status?.kind === "conceptual";
return true;
};
const matchesSearch = (label, status, category) => {
const needle = String(state.toolSearchQuery || "").trim().toLowerCase();
if (!needle) return true;
const haystack = [label, category, status?.command, status?.kind].filter(Boolean).join(" ").toLowerCase();
return haystack.includes(needle);
};
return rows
.map(([label, status]) => ({ label, status, category: toolCategoryForLabel(label) }))
.filter((entry) => matchesFilter(entry.status) && matchesSearch(entry.label, entry.status, entry.category))
.sort((a, b) => {
const aUsage = toolUsageModules(a.label).length;
const bUsage = toolUsageModules(b.label).length;
const installedRank = (entry, mode) => {
if (mode === "missing") return entry.status?.installed === false ? 0 : entry.status?.kind === "conceptual" ? 2 : 1;
return entry.status?.installed === true ? 0 : entry.status?.kind === "conceptual" ? 2 : 1;
};
const sortMode = selectedToolSortMode();
if (sortMode === "usage") return bUsage - aUsage || a.category.localeCompare(b.category) || a.label.localeCompare(b.label);
if (sortMode === "installed" || sortMode === "missing") {
return installedRank(a, sortMode) - installedRank(b, sortMode) || bUsage - aUsage || a.label.localeCompare(b.label);
}
return a.label.localeCompare(b.label);
});
}
function toolReferenceContext(status) {
const target = currentTargetValue();
const domainTarget = currentTargetKind() === "ip" || currentTargetKind() === "cidr" ? target : target;
const httpTarget = currentTargetKind() === "url"
? target
: `http://${currentTargetKind() === "ip" || currentTargetKind() === "cidr" ? target : domainTarget}`;
return {
target,
domainTarget,
httpTarget,
command: status?.command || "tool",
riskMode: selectedRiskMode()
};
}
function fallbackToolReference(label, status, category) {
const context = toolReferenceContext(status);
const primaryCommand = status?.command || label;
const usageModules = toolUsageModules(label);
const usageCopy = usageModules.length
? `${usageModules.length} modul memakai ${label}. Fokusnya ada pada fase ${[...new Set(usageModules.map((item) => item.phase))].join(", ")}.`
: `${label} belum dipetakan langsung ke modul katalog, jadi paling pas dipakai sebagai alat bantu eksplorasi atau verifikasi manual.`;
const categoryPlaybooks = {
"Discovery": [
{ title: "Quick Discovery", tone: "baseline", description: "Mulai dengan enumerasi ringan untuk memastikan host dan port utama.", command: `${primaryCommand} ${context.target}` },
{ title: "Safer Validation", tone: "safe", description: "Lihat opsi aman sebelum menambah agresivitas scan.", command: `${primaryCommand} --help` }
],
"DNS & Surface": [
{ title: "Quick Enumeration", tone: "baseline", description: "Mulai dari domain aktif lalu perluas permukaan secara bertahap.", command: `${primaryCommand} -d ${context.domainTarget}` },
{ title: "Review Options", tone: "safe", description: "Cek syntax dan mode yang tersedia sebelum menjalankan wordlist besar.", command: `${primaryCommand} --help` }
],
"Web Assessment": [
{ title: "Quick Baseline", tone: "baseline", description: "Lakukan fingerprinting web ringan pada target aktif.", command: `${primaryCommand} ${context.httpTarget}` },
{ title: "Review Options", tone: "safe", description: "Pastikan flag yang dipakai sesuai scope dan risk mode.", command: `${primaryCommand} --help` }
],
"Validation": [
{ title: "Targeted Check", tone: "baseline", description: "Gunakan hanya setelah ada hipotesis temuan yang cukup kuat.", command: `${primaryCommand} --help` },
{ title: "Operator Guardrail", tone: "safe", description: "Cek lagi approval dan risk mode sebelum validasi agresif.", command: `echo "Risk mode: ${context.riskMode}"` }
],
"Credential": [
{ title: "Dry Review", tone: "baseline", description: "Mulai dari mode bantuan atau audit lokal sebelum brute-force terkontrol.", command: `${primaryCommand} --help` },
{ title: "Operator Guardrail", tone: "safe", description: "Pastikan lockout policy target dipahami sebelum validasi kredensial.", command: `echo "Review lockout policy sebelum memakai ${label}"` }
],
"Post Exploitation": [
{ title: "Operator Prep", tone: "baseline", description: "Tool fase lanjutan perlu konteks akses, scope, dan approval yang jelas.", command: `${primaryCommand} --help` },
{ title: "Guardrail", tone: "safe", description: "Gunakan hanya saat assessment memang mengizinkan validasi lanjut.", command: `echo "Pastikan approval tersedia untuk ${label}"` }
],
"Detection & Forensics": [
{ title: "Quick Collection", tone: "baseline", description: "Ambil baseline artefak atau traffic lebih dulu sebelum analisis mendalam.", command: `${primaryCommand} --help` },
{ title: "Operator Note", tone: "safe", description: "Verifikasi format output agar mudah diimpor ke evidence parser.", command: `echo "Simpan output ${label} ke workspace assessment"` }
],
"Utility": [
{ title: "Quick Use", tone: "baseline", description: "Tool utilitas biasanya dipakai sebagai pendukung parsing, relay, atau dokumentasi.", command: `${primaryCommand} --help` },
{ title: "Workflow Hint", tone: "safe", description: "Cek contoh command dan integrasikan ke module output bila perlu.", command: `${primaryCommand} --version` }
],
"Other": [
{ title: "Primary Command", tone: "baseline", description: "Mulai dari alias utama yang terdeteksi di backend.", command: primaryCommand },
{ title: "Review Options", tone: "safe", description: "Buka bantuan tool untuk melihat mode yang tersedia.", command: `${primaryCommand} --help` }
]
};
return {
commands: categoryPlaybooks[category] || categoryPlaybooks.Other,
usage: usageCopy,
notes: [
"Sesuaikan wordlist, rate, dan concurrency dengan scope lab.",
"Simpan output mentah ke workspace assessment agar evidence tetap dapat ditelusuri.",
status?.installed === false ? "Status backend menunjukkan tool ini belum tersedia di environment." : "Status backend menunjukkan binary terdeteksi atau tool bersifat wrapper."
]
};
}
function toolReferenceData(label, status) {
const tool = String(label || "").toLowerCase();
const category = toolCategoryForLabel(label);
const context = toolReferenceContext(status);
const explicit = {
nmap: {
commands: [
{ title: "Quick Port Baseline", tone: "baseline", description: "Cocok untuk melihat port penting lebih dulu tanpa sweep penuh.", command: `nmap -Pn -sV -T4 ${context.target}` },
{ title: "Safe Web Triage", tone: "safe", description: "Kalau scope hati-hati, fokuskan ke port web dan simpan output normal.", command: `nmap -Pn -p 80,443,8080,8443 --open -sV ${context.target} -oN nmap-web.txt` },
{ title: "Deep Service Review", tone: "advanced", description: "Pakai hanya saat butuh service fingerprint lebih lengkap.", command: `nmap -Pn -sC -sV -O ${context.target} -oA nmap-deep` }
],
notes: ["Mulai dari `-Pn` bila ICMP diblokir.", "Gunakan `-oA` saat hasil akan dipakai modul lain atau dibandingkan antar assessment.", "Jaga `-T4` hanya untuk subnet yang memang diizinkan."]
},
masscan: {
commands: [
{ title: "Fast Port Sweep", tone: "baseline", description: "Untuk baseline port exposure dengan rate terkontrol.", command: `masscan ${context.target} -p1-1000 --rate 1000` },
{ title: "Conservative Rate", tone: "safe", description: "Turunkan laju ketika target sensitif atau jaringan terbatas.", command: `masscan ${context.target} -p80,443,445,3389 --rate 300` }
],
notes: ["Masscan cepat tetapi mudah bising.", "Selalu turunkan `--rate` pada scope internal yang sensitif.", "Validasi hasil penting dengan `nmap`."]
},
rustscan: {
commands: [
{ title: "Fast Port Discovery", tone: "baseline", description: "Bagus untuk buka peta port cepat lalu chaining ke nmap.", command: `rustscan -a ${context.target} --ulimit 5000` },
{ title: "Focused Range", tone: "safe", description: "Batasi port bila target tidak butuh sweep penuh.", command: `rustscan -a ${context.target} -r 1-1000` }
],
notes: ["Rustscan cocok sebagai pre-scan.", "Bila ada hasil menarik, lanjutkan ke `nmap -sV`."]
},
subfinder: {
commands: [
{ title: "Passive Subdomain Enum", tone: "baseline", description: "Mulai dari enumerasi pasif untuk memperluas permukaan domain.", command: `subfinder -d ${context.domainTarget} -silent` },
{ title: "Save Resolved Hosts", tone: "safe", description: "Simpan hasil yang akan dipakai httpx atau dnsx.", command: `subfinder -d ${context.domainTarget} -all -o subfinder.txt` }
],
notes: ["Cocok dikombinasikan dengan `httpx` atau `dnsx`.", "Gunakan mode pasif lebih dulu untuk mengurangi noise."]
},
amass: {
commands: [
{ title: "Passive Mapping", tone: "baseline", description: "Bangun baseline permukaan subdomain dan ASN secara bertahap.", command: `amass enum -passive -d ${context.domainTarget}` },
{ title: "Deeper Enum", tone: "advanced", description: "Lebih lengkap, tetapi lebih berat dan perlu review sumber data.", command: `amass enum -src -ip -d ${context.domainTarget} -o amass.txt` }
],
notes: ["Bagus untuk ekspansi asset.", "Hindari mode terlalu agresif bila belum ada kebutuhan."]
},
dnsx: {
commands: [
{ title: "Resolve Candidate Hosts", tone: "baseline", description: "Validasi host hasil enumerasi agar cepat terlihat yang hidup.", command: `dnsx -l subfinder.txt -resp -a -aaaa -cname` },
{ title: "Direct Probe", tone: "safe", description: "Pakai untuk domain tunggal saat perlu cek record dasar.", command: `echo ${context.domainTarget} | dnsx -silent -resp` }
],