文件
websafe-kb/08-threat-intel/generated/dashboard/assets/app.js
2026-03-17 00:37:18 -07:00

574 行
25 KiB
JavaScript

const state = {
summary: null,
runs: [],
systems: [],
advisories: {},
profiles: {},
selectedRunId: null,
selectedArtifact: null,
filters: { search: "", system: "", status: "", family: "" },
autoRefresh: true,
refreshMs: 5000,
refreshHandle: null,
};
const $ = (id) => document.getElementById(id);
const statusClass = (status) => `status-pill ${({
"blocked-artifact": "status-blocked-artifact",
"blocked-destructive": "status-blocked-destructive",
"triage-manual": "status-triage-manual",
"verified-real": "status-verified-real",
"verified-synthetic": "status-verified-synthetic",
"suspected": "status-suspected",
"completed": "status-verified-real",
"failed": "status-blocked-artifact",
"skipped": "status-triage-manual"
})[status] || "status-default"}`;
function escapeHtml(value) {
return String(value ?? "")
.replaceAll("&", "&")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;");
}
function timeAgo(value) {
if (!value) return "-";
const diff = Date.now() - new Date(value).getTime();
if (Number.isNaN(diff)) return value;
const seconds = Math.floor(diff / 1000);
if (seconds < 60) return `${seconds}s ago`;
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes}m ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h ago`;
const days = Math.floor(hours / 24);
return `${days}d ago`;
}
async function fetchJson(url) {
const response = await fetch(`${url}?t=${Date.now()}`, { cache: "no-store" });
if (!response.ok) {
throw new Error(`${url} -> ${response.status}`);
}
return response.json();
}
async function loadData(preserveSelection = true) {
$("syncState").innerHTML = `<span class="dot"></span><strong>Refreshing</strong><span>${new Date().toLocaleTimeString()}</span>`;
const previousRun = state.selectedRunId;
try {
const [summary, runs, systems, advisories, profiles] = await Promise.all([
fetchJson("./summary.json"),
fetchJson("./runs.json"),
fetchJson("./systems.json"),
fetchJson("./advisories.json"),
fetchJson("./profiles.json"),
]);
state.summary = summary;
state.runs = runs;
state.systems = systems;
state.advisories = advisories;
state.profiles = profiles;
hydrateFilterOptions();
const hashRun = location.hash.startsWith("#run=") ? location.hash.replace("#run=", "") : null;
const selectedCandidate = preserveSelection ? (hashRun || previousRun) : hashRun;
if (selectedCandidate && runs.some((item) => item.run_id === selectedCandidate)) {
state.selectedRunId = selectedCandidate;
} else {
state.selectedRunId = runs[0]?.run_id || null;
}
renderDashboard();
$("syncState").innerHTML = `<span class="dot"></span><strong>Live</strong><span>${summary.generated_at || new Date().toISOString()}</span>`;
} catch (error) {
$("syncState").innerHTML = `<span class="dot"></span><strong>Load Failed</strong><span>${escapeHtml(error.message)}</span>`;
$("runList").innerHTML = `<div class="empty-state">Dashboard load failed: ${escapeHtml(error.message)}</div>`;
$("detailRoot").innerHTML = `<div class="glass-panel empty-state">Unable to load dashboard data. Check generated JSON and local static server state.</div>`;
}
}
function filteredRuns() {
return state.runs.filter((item) => {
if (state.filters.system && item.system_id !== state.filters.system) return false;
if (state.filters.status && item.verification_status !== state.filters.status) return false;
if (state.filters.family && item.repro_profile_id !== state.filters.family) return false;
if (!state.filters.search) return true;
const advisoryTitle = item.advisory_meta?.title || "";
const haystack = [item.run_id, item.advisory_id, item.system_id, item.repro_profile_id, advisoryTitle]
.join(" ")
.toLowerCase();
return haystack.includes(state.filters.search);
});
}
function renderMetrics() {
const metrics = [
{ label: "Advisories", value: state.summary?.advisory_count ?? 0 },
{ label: "Run Bundles", value: state.summary?.run_count ?? 0 },
...Object.entries(state.summary?.statuses || {}).map(([label, value]) => ({ label, value })),
];
$("metrics").innerHTML = metrics
.map((item) => `<article class="meta-card"><strong>${escapeHtml(item.label)}</strong><span>${escapeHtml(item.value)}</span></article>`)
.join("");
}
function renderSystemCoverage() {
$("systemCoverage").innerHTML = state.systems
.map((system) => {
const total = Math.max(system.total || 0, 1);
const verified = (system.verified_real || 0) + (system.verified_synthetic || 0);
const fill = Math.round((verified / total) * 100);
return `
<div class="system-card">
<div class="run-card-top">
<strong>${escapeHtml(system.display_name || system.system_id)}</strong>
<span class="tag">${escapeHtml(system.browser_present || 0)}/${escapeHtml(system.browser_required || 0)} browser</span>
</div>
<div class="mini-muted">${escapeHtml(system.system_id)} · latest ${escapeHtml(system.latest_update || "-")}</div>
<div class="tag-row" style="margin-top:10px;">
<span class="tag">real ${escapeHtml(system.verified_real || 0)}</span>
<span class="tag">synthetic ${escapeHtml(system.verified_synthetic || 0)}</span>
<span class="tag">blocked ${escapeHtml(system.blocked || 0)}</span>
<span class="tag">manual ${escapeHtml(system.manual || 0)}</span>
</div>
<div class="meter"><span style="--fill:${fill}%"></span></div>
</div>
`;
})
.join("");
}
function renderFailures() {
const failures = state.summary?.recent_failures || [];
$("failureFeed").innerHTML = failures.length
? failures
.map((item) => `
<div class="failure-item">
<div class="run-card-top">
<strong>${escapeHtml(item.run_id)}</strong>
<span class="${statusClass(item.status)}">${escapeHtml(item.status)}</span>
</div>
<div class="mini-muted" style="margin-top:8px;">${escapeHtml(item.title || item.advisory_id)}</div>
<div class="mini-muted" style="margin-top:8px;">${escapeHtml(item.blocked_reason || "-")}</div>
</div>
`)
.join("")
: `<div class="empty-state">No recent blockers.</div>`;
}
function renderRunList() {
const filtered = filteredRuns();
$("runCount").textContent = `${filtered.length} shown`;
$("runList").innerHTML = filtered.length
? filtered
.map((item) => {
const active = item.run_id === state.selectedRunId ? "is-active" : "";
const title = item.advisory_meta?.title || item.advisory_id;
const reasoning = item.reasoning_lines?.[0] || item.blocked_reason || "";
const browserLabel = item.browser_evidence?.present ? "ready" : (item.browser_evidence?.required ? "required" : "n/a");
return `
<button class="run-card ${active}" data-run-id="${escapeHtml(item.run_id)}">
<div class="run-card-top">
<code>${escapeHtml(item.run_id)}</code>
<span class="${statusClass(item.verification_status)}">${escapeHtml(item.verification_status)}</span>
</div>
<h4>${escapeHtml(title)}</h4>
<div class="mini-muted">${escapeHtml(item.system_id)} · ${escapeHtml(item.repro_profile_id)} · ${escapeHtml(timeAgo(item.finished_at))}</div>
<div class="tag-row" style="margin-top:10px;">
<span class="tag">timeline ${escapeHtml(item.timeline?.length || 0)}</span>
<span class="tag">artifacts ${escapeHtml((item.artifact_groups || []).reduce((sum, group) => sum + group.count, 0))}</span>
<span class="tag">browser ${escapeHtml(browserLabel)}</span>
</div>
<div class="mini-muted" style="margin-top:10px;">${escapeHtml(reasoning)}</div>
</button>
`;
})
.join("")
: `<div class="empty-state">No runs match the current filters.</div>`;
document.querySelectorAll("[data-run-id]").forEach((button) => {
button.addEventListener("click", () => {
state.selectedRunId = button.dataset.runId;
location.hash = `run=${state.selectedRunId}`;
renderRunList();
renderDetail();
});
});
}
function renderDashboard() {
renderMetrics();
renderSystemCoverage();
renderFailures();
renderRunList();
renderDetail();
}
function setFilterListeners() {
[["searchInput", "search"], ["systemFilter", "system"], ["statusFilter", "status"], ["familyFilter", "family"]].forEach(([id, key]) => {
$(id).addEventListener("input", (event) => {
state.filters[key] = String(event.target.value || "").trim().toLowerCase();
if (key !== "search") {
state.filters[key] = String(event.target.value || "");
}
renderRunList();
});
});
}
function hydrateFilterOptions() {
const distinct = (items) => [...new Set(items.filter(Boolean))].sort();
const patchOptions = (id, values) => {
const control = $(id);
const current = control.value;
control.innerHTML = control.dataset.base;
control.innerHTML += distinct(values).map((value) => `<option value="${escapeHtml(value)}">${escapeHtml(value)}</option>`).join("");
control.value = current;
};
patchOptions("systemFilter", state.runs.map((item) => item.system_id));
patchOptions("statusFilter", state.runs.map((item) => item.verification_status));
patchOptions("familyFilter", state.runs.map((item) => item.repro_profile_id));
}
function defaultArtifact(run) {
const preference = ["attack", "requests", "container", "browser", "baseline", "compose", "reports"];
for (const key of preference) {
const group = (run.artifact_groups || []).find((item) => item.key === key && item.items?.length);
if (!group) continue;
const preferredText = group.items.find((item) => item.kind === "text");
return preferredText || group.items[0];
}
return null;
}
function totalProgress(progress) {
const values = Object.values(progress || {}).map((value) => Number(value || 0));
return values.reduce((sum, value) => sum + value, 0);
}
function renderProgressStrip(progress) {
const total = totalProgress(progress);
if (!total) {
return `
<div class="progress-strip">
<div class="progress-bar"><div class="progress-segment progress-other" style="width:100%"></div></div>
<div class="mini-muted">No timeline progress recorded.</div>
</div>
`;
}
const order = [
["completed", "Completed", "progress-completed"],
["blocked", "Blocked", "progress-blocked"],
["failed", "Failed", "progress-failed"],
["skipped", "Skipped", "progress-skipped"],
["planned", "Planned", "progress-planned"],
["other", "Other", "progress-other"],
];
const segments = order
.filter(([key]) => Number(progress?.[key] || 0) > 0)
.map(([key, _label, klass]) => {
const count = Number(progress?.[key] || 0);
const pct = Math.max((count / total) * 100, 4);
return `<div class="progress-segment ${klass}" style="width:${pct}%"></div>`;
})
.join("");
const legend = order
.filter(([key]) => Number(progress?.[key] || 0) > 0)
.map(([key, label, klass]) => `
<span class="tag">
<span class="swatch ${klass}"></span>
${escapeHtml(label)} ${escapeHtml(progress?.[key] || 0)}
</span>
`)
.join("");
return `
<div class="progress-strip">
<div class="progress-bar">${segments}</div>
<div class="progress-legend">${legend}</div>
</div>
`;
}
function renderStageCards(run) {
const timeline = run.timeline || [];
if (!timeline.length) {
return `<div class="empty-state">No stage records available.</div>`;
}
return `
<div class="stage-grid">
${timeline.map((item) => `
<article class="stage-card">
<strong>${escapeHtml(item.step || "-")}</strong>
<div class="${statusClass(item.status || "default")}">${escapeHtml(item.status || "unknown")}</div>
<div class="mini-muted" style="margin-top:10px;">${escapeHtml(item.detail || "-")}</div>
<div class="mini-muted" style="margin-top:8px;">${escapeHtml(item.at || "-")}</div>
</article>
`).join("")}
</div>
`;
}
async function openArtifact(href, label, kind) {
state.selectedArtifact = { href, label, kind };
document.querySelectorAll(".artifact-button").forEach((button) => {
button.classList.toggle("is-active", button.dataset.href === href);
});
$("artifactLabel").textContent = label;
$("artifactOpen").href = href;
$("artifactMeta").textContent = href;
try {
if (kind === "image") {
$("artifactViewer").innerHTML = `<img src="${escapeHtml(href)}?t=${Date.now()}" alt="${escapeHtml(label)}">`;
return;
}
if (href.endsWith(".html")) {
$("artifactViewer").innerHTML = `<iframe src="${escapeHtml(href)}?t=${Date.now()}" style="width:100%;height:560px;border:0;background:white;"></iframe>`;
return;
}
const response = await fetch(`${href}?t=${Date.now()}`, { cache: "no-store" });
if (!response.ok) throw new Error(`${href} -> ${response.status}`);
const text = await response.text();
let formatted = text;
if (href.endsWith(".json")) {
try {
formatted = JSON.stringify(JSON.parse(text), null, 2);
} catch (_error) {
}
}
$("artifactViewer").innerHTML = `<pre>${escapeHtml(formatted)}</pre>`;
} catch (error) {
$("artifactViewer").innerHTML = `<pre>Artifact load failed: ${escapeHtml(error.message)}</pre>`;
}
}
function renderDetail() {
const run = state.runs.find((item) => item.run_id === state.selectedRunId);
if (!run) {
$("detailRoot").innerHTML = `<div class="glass-panel empty-state">Select a run to inspect full timeline, logs, sources, and reasoning.</div>`;
return;
}
const advisory = run.advisory_meta || {};
const profile = run.profile_meta || {};
const screenshotItems = (run.artifact_groups || [])
.find((group) => group.key === "browser")
?.items.filter((item) => item.kind === "image") || [];
$("detailRoot").innerHTML = `
<section class="glass-panel detail-hero">
<div class="eyebrow">Local Verification Workspace</div>
<div class="flex-row" style="margin-top:14px;">
<span class="${statusClass(run.verification_status)}">${escapeHtml(run.verification_status)}</span>
<div class="tag-row">
<span class="tag">${escapeHtml(run.system_id)}</span>
<span class="tag">${escapeHtml(run.repro_profile_id)}</span>
<span class="tag">${escapeHtml(run.artifact_mode)}</span>
<span class="tag">${escapeHtml(run.verification_mode)}</span>
<span class="tag">${escapeHtml(run.target_env || "local-docker")}</span>
</div>
</div>
<h2 class="detail-headline">${escapeHtml(advisory.title || run.advisory_id)}</h2>
<p class="mini-muted">${escapeHtml(advisory.summary || "No summary available.")}</p>
<div class="link-row" style="margin-top:18px;">
<a class="chip" href="${escapeHtml(run.dashboard_refs.report_html)}" target="_blank" rel="noreferrer">Open HTML report</a>
<a class="ghost-chip" href="${escapeHtml(run.dashboard_refs.report_md)}" target="_blank" rel="noreferrer">Open Markdown</a>
<a class="ghost-chip" href="${escapeHtml(run.dashboard_refs.bundle)}" target="_blank" rel="noreferrer">Open run JSON</a>
<a class="ghost-chip" href="./docs/frontend-dashboard-design.html" target="_blank" rel="noreferrer">Open UI spec</a>
</div>
<div class="stat-grid">
<article class="stat-card"><strong>Timeline Steps</strong><span>${escapeHtml(run.timeline?.length || 0)}</span></article>
<article class="stat-card"><strong>Artifacts</strong><span>${escapeHtml((run.artifact_groups || []).reduce((sum, group) => sum + group.count, 0))}</span></article>
<article class="stat-card"><strong>Browser</strong><span>${run.browser_evidence?.present ? "Ready" : (run.browser_evidence?.required ? "Required" : "Optional")}</span></article>
<article class="stat-card"><strong>Finished</strong><span>${escapeHtml(timeAgo(run.finished_at))}</span></article>
</div>
</section>
<div class="detail-grid">
<div class="stack">
<details class="glass-panel accordion" open>
<summary><span>Progress Timeline</span><span class="tag">${escapeHtml(run.timeline?.length || 0)} steps</span></summary>
<div class="accordion-content">
${renderProgressStrip(run.progress)}
${renderStageCards(run)}
<div class="timeline-list">
${(run.timeline || []).map((item) => `
<article class="timeline-item">
<div class="mini-muted">${escapeHtml(item.at || "-")}</div>
<div class="timeline-step">${escapeHtml(item.step || "-")}</div>
<div>
<div class="${statusClass(item.status || "default")}">${escapeHtml(item.status || "unknown")}</div>
<div class="mini-muted" style="margin-top:8px;">${escapeHtml(item.detail || "-")}</div>
</div>
</article>
`).join("") || `<div class="empty-state">No timeline items available.</div>`}
</div>
</div>
</details>
<details class="glass-panel accordion" open>
<summary><span>Attack Plan & Reasoning</span><span class="tag">${escapeHtml(profile.vuln_family || "unknown")}</span></summary>
<div class="accordion-content">
${run.blocked_reason ? `<div class="failure-callout"><strong>Failure reason</strong><div class="mini-muted" style="margin-top:8px;">${escapeHtml(run.blocked_reason)}</div></div>` : ""}
<div class="tag-row" style="margin:16px 0;">
<span class="tag">destructive risk ${escapeHtml(profile.destructive_risk || "-")}</span>
<span class="tag">cleanup ${escapeHtml(profile.cleanup_policy || "-")}</span>
<span class="tag">targets ${(profile.allowed_target_types || []).join(", ") || "-"}</span>
</div>
<div class="stack" style="gap:12px;">
${(run.reasoning_lines || []).map((line) => `<div class="system-card">${escapeHtml(line)}</div>`).join("")}
</div>
<div class="tag-row" style="margin-top:16px;">
${(profile.success_criteria || []).map((line) => `<span class="tag">${escapeHtml(line)}</span>`).join("")}
</div>
</div>
</details>
<details class="glass-panel accordion" open>
<summary><span>Evidence Explorer</span><span class="tag">${escapeHtml((run.artifact_groups || []).length)} groups</span></summary>
<div class="accordion-content">
${(run.artifact_groups || []).map((group) => `
<section class="artifact-group">
<h4>${escapeHtml(group.label)} · ${escapeHtml(group.count)}</h4>
<div class="artifact-row">
${group.items.map((item) => `
<button class="artifact-button" data-href="${escapeHtml(item.href)}" data-kind="${escapeHtml(item.kind)}" data-label="${escapeHtml(item.label)}">
<span>${escapeHtml(item.label)}</span>
<span class="mini-muted">${escapeHtml(item.kind)}</span>
</button>
`).join("")}
</div>
</section>
`).join("") || `<div class="empty-state">No artifacts linked for this run.</div>`}
${screenshotItems.length ? `
<div class="gallery" style="margin-top:12px;">
${screenshotItems.map((item) => `
<button class="gallery-item artifact-button" data-href="${escapeHtml(item.href)}" data-kind="${escapeHtml(item.kind)}" data-label="${escapeHtml(item.label)}">
<figure style="margin:0;">
<img src="${escapeHtml(item.href)}" alt="${escapeHtml(item.label)}">
<figcaption>${escapeHtml(item.label)}</figcaption>
</figure>
</button>
`).join("")}
</div>
` : ""}
</div>
</details>
<details class="glass-panel accordion" open>
<summary><span>Live Log Viewer</span><span class="tag">${state.selectedArtifact ? "active" : "idle"}</span></summary>
<div class="accordion-content">
<div class="log-viewer">
<div class="viewer-toolbar">
<div>
<strong id="artifactLabel">${escapeHtml(state.selectedArtifact?.label || "Select an artifact")}</strong>
<div class="mini-muted" id="artifactMeta">${escapeHtml(state.selectedArtifact?.href || "Artifacts and logs can be previewed here.")}</div>
</div>
<div class="tag-row">
<a id="artifactOpen" class="chip" href="${escapeHtml(state.selectedArtifact?.href || run.dashboard_refs.report_html)}" target="_blank" rel="noreferrer">Open artifact</a>
<button id="refreshArtifact" class="ghost-chip" type="button">Refresh preview</button>
</div>
</div>
<div class="viewer-frame" id="artifactViewer"><pre>Select a report, log, JSON, screenshot, or timeline file to preview it here.</pre></div>
</div>
</div>
</details>
</div>
<div class="stack">
<details class="glass-panel accordion" open>
<summary><span>Sources & Fix Topics</span><span class="tag">${escapeHtml((advisory.secondary_source_urls || []).length + (advisory.official_source_url ? 1 : 0))} links</span></summary>
<div class="accordion-content">
<div class="tag-row">
${(advisory.aliases || []).map((alias) => `<span class="tag">${escapeHtml(alias)}</span>`).join("")}
</div>
<div class="stack" style="gap:10px; margin-top:14px;">
${advisory.official_source_url ? `<a href="${escapeHtml(advisory.official_source_url)}" target="_blank" rel="noreferrer">${escapeHtml(advisory.official_source_url)}</a>` : `<div class="mini-muted">No official source linked.</div>`}
${(advisory.secondary_source_urls || []).map((ref) => `<a href="${escapeHtml(ref)}" target="_blank" rel="noreferrer">${escapeHtml(ref)}</a>`).join("")}
</div>
<div class="tag-row" style="margin-top:16px;">
${(advisory.secure_code_topics || []).map((topic) => `<a class="tag" href="./docs/secure-code-index.html" target="_blank" rel="noreferrer">${escapeHtml(topic)}</a>`).join("")}
</div>
</div>
</details>
<details class="glass-panel accordion">
<summary><span>Run JSON</span><span class="tag">raw</span></summary>
<div class="accordion-content"><pre class="json-block">${escapeHtml(JSON.stringify(run, null, 2))}</pre></div>
</details>
<details class="glass-panel accordion">
<summary><span>Advisory JSON</span><span class="tag">raw</span></summary>
<div class="accordion-content"><pre class="json-block">${escapeHtml(JSON.stringify(advisory, null, 2))}</pre></div>
</details>
<details class="glass-panel accordion">
<summary><span>Profile JSON</span><span class="tag">raw</span></summary>
<div class="accordion-content"><pre class="json-block">${escapeHtml(JSON.stringify(profile, null, 2))}</pre></div>
</details>
</div>
</div>
`;
document.querySelectorAll(".artifact-button").forEach((button) => {
button.addEventListener("click", () => openArtifact(button.dataset.href, button.dataset.label, button.dataset.kind));
});
$("refreshArtifact")?.addEventListener("click", () => {
if (state.selectedArtifact) {
openArtifact(state.selectedArtifact.href, state.selectedArtifact.label, state.selectedArtifact.kind);
}
});
if (!state.selectedArtifact || !(run.artifact_groups || []).some((group) => group.items.some((item) => item.href === state.selectedArtifact.href))) {
const artifact = defaultArtifact(run);
if (artifact) {
openArtifact(artifact.href, artifact.label, artifact.kind);
}
} else {
openArtifact(state.selectedArtifact.href, state.selectedArtifact.label, state.selectedArtifact.kind);
}
}
function attachGlobalActions() {
$("searchInput").addEventListener("input", (event) => {
state.filters.search = String(event.target.value || "").trim().toLowerCase();
renderRunList();
});
[["systemFilter", "system"], ["statusFilter", "status"], ["familyFilter", "family"]].forEach(([id, key]) => {
$(id).addEventListener("input", (event) => {
state.filters[key] = String(event.target.value || "");
renderRunList();
});
});
$("refreshDashboard").addEventListener("click", () => loadData(false));
$("autoRefresh").addEventListener("change", (event) => {
state.autoRefresh = Boolean(event.target.checked);
startRefreshLoop();
});
}
function startRefreshLoop() {
if (state.refreshHandle) {
clearInterval(state.refreshHandle);
state.refreshHandle = null;
}
if (!state.autoRefresh) return;
state.refreshHandle = setInterval(() => loadData(true), state.refreshMs);
}
async function init() {
["systemFilter", "statusFilter", "familyFilter"].forEach((id) => {
$(id).dataset.base = $(id).innerHTML;
});
attachGlobalActions();
await loadData(false);
startRefreshLoop();
window.addEventListener("hashchange", () => loadData(false));
}
document.addEventListener("DOMContentLoaded", init);