示例工程 44-threat-model
44-threat-model/app/src/App.ts
import type { Check, Snapshot, Verdict } from "../shared/ipc";
function escape(text: string): string {
return text.replace(/[&<>"]/g, (char) => {
if (char === "&") return "&";
if (char === "<") return "<";
if (char === ">") return ">";
return """;
});
}
function time(at: number): string {
return new Date(at).toLocaleTimeString("zh-CN", { hour12: false });
}
function verdictRows(items: Verdict[]): string {
return items
.map(
(item) => `
<li class="attack-row" data-testid="attack-row">
<span class="attack-label">${escape(item.label)}</span>
<span class="tag ${item.allowed ? "ok" : "bad"}">${item.allowed ? "允许" : "拒绝"}</span>
<code>${escape(item.reason)}</code>
</li>`,
)
.join("");
}
export function mountApp(root: HTMLElement): void {
root.innerHTML = `
<div class="app">
<header class="header">
<div class="brand">
<span class="logo">🛡</span>
<div>
<h1>威胁模型实验室</h1>
<span class="muted small">信任边界 · 五类攻击 · 默认防线 · 残余风险</span>
</div>
</div>
<div class="header-side">
<span class="pill score-pill" data-testid="score">—</span>
<span class="pill" data-testid="versions">—</span>
<button class="btn" data-testid="probe">重新检查</button>
</div>
</header>
<main class="layout">
<div class="column">
<section class="card pad map-card">
<div class="card-head">
<h2>信任边界</h2>
<span class="muted small">数据流与防线</span>
</div>
<svg viewBox="0 0 360 210" class="trust-map" role="img" aria-label="信任边界图">
<rect x="8" y="10" width="150" height="70" rx="8" fill="#eff6ff" stroke="#2563eb" />
<text x="20" y="32" class="map-title">渲染进程</text>
<text x="20" y="50" class="map-sub">sandbox · 无 Node</text>
<text x="20" y="66" class="map-sub">DOM / 网络 / CSP</text>
<rect x="172" y="10" width="100" height="70" rx="8" fill="#f0fdf4" stroke="#16a34a" />
<text x="184" y="32" class="map-title">preload</text>
<text x="184" y="50" class="map-sub">contextBridge</text>
<text x="184" y="66" class="map-sub">白名单方法</text>
<rect x="286" y="10" width="66" height="70" rx="8" fill="#fff7ed" stroke="#f97316" />
<text x="294" y="32" class="map-title">主进程</text>
<text x="294" y="50" class="map-sub">Node</text>
<text x="294" y="66" class="map-sub">系统 API</text>
<rect x="8" y="128" width="100" height="60" rx="8" fill="#f8fafc" stroke="#94a3b8" />
<text x="20" y="150" class="map-title">用户文件</text>
<text x="20" y="168" class="map-sub">workspace</text>
<rect x="128" y="128" width="100" height="60" rx="8" fill="#f8fafc" stroke="#94a3b8" />
<text x="140" y="150" class="map-title">网络</text>
<text x="140" y="168" class="map-sub">allowlist</text>
<rect x="248" y="128" width="104" height="60" rx="8" fill="#f8fafc" stroke="#94a3b8" />
<text x="260" y="150" class="map-title">Keychain</text>
<text x="260" y="168" class="map-sub">safeStorage</text>
<line x1="158" y1="45" x2="172" y2="45" stroke="#2563eb" stroke-width="2" marker-end="url(#arrow)" />
<line x1="272" y1="45" x2="286" y2="45" stroke="#16a34a" stroke-width="2" marker-end="url(#arrow)" />
<line x1="58" y1="80" x2="58" y2="128" stroke="#94a3b8" stroke-width="1.5" stroke-dasharray="4 3" />
<line x1="300" y1="80" x2="300" y2="128" stroke="#f97316" stroke-width="1.5" stroke-dasharray="4 3" />
<rect x="4" y="4" width="274" height="84" rx="10" fill="none" stroke="#2563eb" stroke-width="1" stroke-dasharray="6 4" />
<text x="10" y="100" class="map-note">不可信边界</text>
<text x="286" y="100" class="map-note">高权限边界</text>
<defs>
<marker id="arrow" markerWidth="6" markerHeight="6" refX="5" refY="3" orient="auto">
<path d="M0,0 L6,3 L0,6 z" fill="#64748b" />
</marker>
</defs>
</svg>
</section>
<section class="card pad">
<div class="card-head">
<h2>五类攻击</h2>
<span class="muted small" data-testid="blocked-count">—</span>
</div>
<ul class="scenarios" data-testid="scenarios"></ul>
</section>
<section class="card pad">
<div class="card-head">
<h2>活动</h2>
<span class="muted small">导航 / 权限 / 探针</span>
</div>
<ul class="activity" data-testid="events"></ul>
</section>
</div>
<div class="column">
<section class="card pad checklist-card">
<div class="card-head">
<h2>默认防线</h2>
<span class="muted small" data-testid="check-count">—</span>
</div>
<ul class="checks" data-testid="checks"></ul>
</section>
<section class="card pad runtime-card">
<div class="card-head">
<h2>运行时探针</h2>
<span class="muted small" data-testid="csp-state">—</span>
</div>
<div class="actions wrap">
<button class="btn primary" data-testid="require-probe">尝试 require("node:fs")</button>
</div>
<div class="probe-output" data-testid="require-output">尚未尝试</div>
<div class="muted small csp" data-testid="csp"></div>
</section>
<section class="card pad attacks-card">
<div class="card-head">
<h2>攻击模拟</h2>
<span class="muted small">只看判定,不真的导航</span>
</div>
<div class="attack-groups">
<div><h3>导航</h3><ul data-testid="nav-attacks"></ul></div>
<div><h3>路径</h3><ul data-testid="path-attacks"></ul></div>
<div><h3>更新</h3><ul data-testid="update-attacks"></ul></div>
<div><h3>插件</h3><ul data-testid="plugin-attacks"></ul></div>
</div>
</section>
</div>
</main>
</div>
`;
const score = root.querySelector<HTMLElement>('[data-testid="score"]');
const versions = root.querySelector<HTMLElement>('[data-testid="versions"]');
const blockedCount = root.querySelector<HTMLElement>(
'[data-testid="blocked-count"]',
);
const scenariosEl = root.querySelector<HTMLElement>(
'[data-testid="scenarios"]',
);
const checkCount = root.querySelector<HTMLElement>(
'[data-testid="check-count"]',
);
const checksEl = root.querySelector<HTMLElement>('[data-testid="checks"]');
const navAttacks = root.querySelector<HTMLElement>(
'[data-testid="nav-attacks"]',
);
const pathAttacks = root.querySelector<HTMLElement>(
'[data-testid="path-attacks"]',
);
const updateAttacks = root.querySelector<HTMLElement>(
'[data-testid="update-attacks"]',
);
const pluginAttacks = root.querySelector<HTMLElement>(
'[data-testid="plugin-attacks"]',
);
const eventsEl = root.querySelector<HTMLElement>('[data-testid="events"]');
const cspState = root.querySelector<HTMLElement>('[data-testid="csp-state"]');
const cspEl = root.querySelector<HTMLElement>('[data-testid="csp"]');
const requireOutput = root.querySelector<HTMLElement>(
'[data-testid="require-output"]',
);
const status = root.querySelector<HTMLElement>('[data-testid="score"]');
let state: Snapshot | null = null;
function checkRow(check: Check): string {
return `<li class="check-row" data-testid="check-row">
<span class="tag ${check.pass ? "ok" : "bad"}">${check.pass ? "PASS" : "FAIL"}</span>
<span class="check-label">${escape(check.label)}</span>
<code>${escape(check.detail)}</code>
</li>`;
}
function renderChecks(): void {
if (!state || !checksEl) return;
checksEl.innerHTML = state.checks.map(checkRow).join("");
if (checkCount) {
const passed = state.checks.filter((check) => check.pass).length;
checkCount.textContent = `${passed}/${state.checks.length} 通过`;
}
if (score) {
score.textContent = `${state.score} / 100`;
score.className = `pill score-pill ${state.score === 100 ? "ok-pill" : "bad-pill"}`;
}
}
function renderScenarios(): void {
if (!state || !scenariosEl) return;
const blocked = state.scenarios.filter(
(scenario) => scenario.status === "blocked",
).length;
if (blockedCount) blockedCount.textContent = `${blocked} 类已挡住`;
scenariosEl.innerHTML = state.scenarios
.map(
(scenario) => `
<li class="scenario" data-testid="scenario-row">
<div class="scenario-head">
<strong>${escape(scenario.title)}</strong>
<span class="tag ${scenario.status === "blocked" ? "ok" : "warn"}">${
scenario.status === "blocked" ? "默认挡住" : "残余风险"
}</span>
</div>
<div class="muted small">${escape(scenario.controls.join(" · "))}</div>
</li>`,
)
.join("");
}
function renderAttacks(): void {
if (!state) return;
if (navAttacks)
navAttacks.innerHTML = verdictRows(state.attacks.navigation);
if (pathAttacks) pathAttacks.innerHTML = verdictRows(state.attacks.path);
if (updateAttacks)
updateAttacks.innerHTML = verdictRows(state.attacks.update);
if (pluginAttacks)
pluginAttacks.innerHTML = verdictRows(state.attacks.plugin);
}
function renderRuntime(): void {
if (!state) return;
if (cspState) {
cspState.textContent = state.runtime.csp ? "CSP 已启用" : "CSP 缺失";
cspState.className = `muted small ${state.runtime.csp ? "ok" : "bad"}`;
}
if (cspEl) cspEl.textContent = state.runtime.csp;
}
function renderEvents(): void {
if (!eventsEl || !state) return;
eventsEl.innerHTML =
state.events.length === 0
? `<li class="muted small">暂无活动</li>`
: state.events
.slice(0, 7)
.map(
(row) => `
<li class="event-row" data-testid="event-row">
<span class="muted">${time(row.at)}</span>
<span class="kind">${escape(row.kind)}</span>
<span>${escape(row.detail)}</span>
</li>`,
)
.join("");
}
function render(next: Snapshot): void {
state = next;
if (versions) {
versions.textContent = `Electron ${next.electronVersion} · Node ${next.nodeVersion}`;
}
renderChecks();
renderScenarios();
renderAttacks();
renderRuntime();
renderEvents();
}
const probeRequire = (): string => {
try {
(window as unknown as { require: (name: string) => unknown }).require(
"node:fs",
);
return "UNEXPECTED: require is available";
} catch (error) {
return error instanceof Error ? error.message : String(error);
}
};
const showRequire = (): void => {
const message = probeRequire();
if (requireOutput) {
requireOutput.textContent = message;
requireOutput.className = `probe-output ${message.includes("not a function") ? "ok" : "bad"}`;
}
};
void window.api.threat.snapshot().then(render);
const unsubscribe = window.api.threat.onEvent(() => {
void window.api.threat.snapshot().then(render);
});
root
.querySelector<HTMLButtonElement>('[data-testid="probe"]')
?.addEventListener("click", async () => {
render(await window.api.threat.probe());
if (status) status.textContent = "已重新检查";
});
root
.querySelector<HTMLButtonElement>('[data-testid="require-probe"]')
?.addEventListener("click", showRequire);
const sleep = (value: number): Promise<void> =>
new Promise((resolve) => setTimeout(resolve, value));
window.__prepareShots = async (stage) => {
document.body.dataset.shot = stage;
render(await window.api.threat.probe());
if (stage === "attacks") {
document
.querySelector(".attacks-card")
?.scrollIntoView({ block: "start" });
} else if (stage === "checklist") {
showRequire();
document
.querySelector(".checklist-card")
?.scrollIntoView({ block: "start" });
}
await sleep(100);
};
window.__smoke = async () => {
const api = window.api.threat;
const first = await api.probe();
const refreshed = await api.refresh();
const requireError = probeRequire();
unsubscribe();
const passed = first.checks.filter((check) => check.pass).length;
const blocked = first.scenarios.filter(
(scenario) => scenario.status === "blocked",
).length;
return {
score: first.score,
checks: first.checks.length,
passed,
scenarios: first.scenarios.length,
blocked,
residual: first.scenarios.length - blocked,
navAllowed: first.attacks.navigation.filter((item) => item.allowed)
.length,
navBlocked: first.attacks.navigation.filter((item) => !item.allowed)
.length,
pathAllowed: first.attacks.path.filter((item) => item.allowed).length,
pathBlocked: first.attacks.path.filter((item) => !item.allowed).length,
updateAllowed: first.attacks.update.filter((item) => item.allowed).length,
updateBlocked: first.attacks.update.filter((item) => !item.allowed)
.length,
pluginAllowed: first.attacks.plugin.filter((item) => item.allowed).length,
pluginBlocked: first.attacks.plugin.filter((item) => !item.allowed)
.length,
requireType: first.runtime.requireType,
processType: first.runtime.processType,
requireError,
csp: first.runtime.csp,
events: refreshed.events.length,
};
};
}