import type { Check, Snapshot } 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 checkRow(check: Check): string { return `
  • ${check.pass ? "PASS" : "FAIL"} ${escape(check.label)} ${escape(check.detail)}
  • `; } export function mountApp(root: HTMLElement): void { root.innerHTML = `

    沙箱与权限实验室

    sandbox · contextIsolation · 权限请求 · 下载拦截 · 迁移
    sandbox: true —

    沙箱能力边界

    —
        尚未尝试

        权限请求

        0 条

          下载拦截

          will-download → preventDefault
          尚未触发

          沙箱保留了什么

          移除 Node,不关闭网页
          能力sandbox说明
          require / process / Buffer移除不能直接读文件、起进程
          DOM / CSS / 事件保留页面仍可渲染与交互
          fetch / WebSocket受 CSP不是自动关闭,要白名单
          preload 白名单保留通过 contextBridge 暴露
          权限请求需处理默认拒绝,显式放行

          nodeIntegration 迁移

          旧写法 → 新写法

          旧:页面直接读文件

          const fs = require("fs");
          fs.readFileSync(path);

          新:preload + IPC

          window.api.fs.read(path)
            .then(handleFile);

          迁移不是把 require 换个名字,而是把能力移到主进程, 渲染进程只发送意图,主进程做路径、大小与权限校验。

          活动

          探针 / 权限 / 下载
            `; const score = root.querySelector('[data-testid="score"]'); const checkCount = root.querySelector( '[data-testid="check-count"]', ); const checksEl = root.querySelector('[data-testid="checks"]'); const probeEl = root.querySelector('[data-testid="probe"]'); const requireOutput = root.querySelector( '[data-testid="require-output"]', ); const toggle = root.querySelector( '[data-testid="notifications-toggle"]', ); const permissionCount = root.querySelector( '[data-testid="permission-count"]', ); const permissionsEl = root.querySelector( '[data-testid="permissions"]', ); const notificationResult = root.querySelector( '[data-testid="notification-result"]', ); const downloadResult = root.querySelector( '[data-testid="download-result"]', ); const eventsEl = root.querySelector('[data-testid="events"]'); let state: Snapshot | null = null; function renderChecks(): void { if (!state) return; if (checksEl) 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 ${state.score === 100 ? "ok-pill" : "bad-pill"}`; } if (probeEl) { const probe = state.probe; probeEl.innerHTML = `
          • require${escape(probe.requireType)}
          • process${escape(probe.processType)}
          • Buffer${escape(probe.bufferType)}
          • window.api${escape(probe.apiKeys.join(", ") || "—")}
          • CSP${probe.csp ? "present" : "missing"}
          • `; } } function renderPermissions(): void { if (!state) return; if (toggle) toggle.checked = state.permissions.notificationsAllowed; if (permissionCount) { permissionCount.textContent = `${state.permissions.entries.length} 条`; } if (permissionsEl) { permissionsEl.innerHTML = state.permissions.entries.length === 0 ? `
          • 尚未请求
          • ` : state.permissions.entries .map( (entry) => `
          • ${entry.allowed ? "允许" : "拒绝"} ${escape(entry.permission)} ${entry.source} · ${time(entry.at)}
          • `, ) .join(""); } if (downloadResult) { const download = state.download; downloadResult.innerHTML = download ? `${download.blocked ? "已拦截" : "未拦截"} ${escape(download.filename)} ${download.bytes} B · ${time(download.at)}` : "尚未触发"; } } function renderEvents(): void { if (!eventsEl || !state) return; eventsEl.innerHTML = state.events.length === 0 ? `
          • 暂无活动
          • ` : state.events .slice(0, 8) .map( (row) => `
          • ${time(row.at)} ${escape(row.kind)} ${escape(row.detail)}
          • `, ) .join(""); } function render(next: Snapshot): void { state = next; renderChecks(); renderPermissions(); 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.sandbox.snapshot().then(render); const unsubscribe = window.api.sandbox.onEvent(() => { void window.api.sandbox.snapshot().then(render); }); root .querySelector('[data-testid="refresh"]') ?.addEventListener("click", async () => { render(await window.api.sandbox.refresh()); }); root .querySelector('[data-testid="require-probe"]') ?.addEventListener("click", showRequire); toggle?.addEventListener("change", async () => { render(await window.api.sandbox.setNotifications(toggle.checked)); }); root .querySelector('[data-testid="request-notification"]') ?.addEventListener("click", async () => { try { const result = await Notification.requestPermission(); if (notificationResult) { notificationResult.textContent = `Notification.requestPermission() → ${result}`; } } catch (error) { if (notificationResult) { notificationResult.textContent = String(error); } } render(await window.api.sandbox.refresh()); }); for (const [id, permission] of [ ["simulate-media", "media"], ["simulate-clipboard", "clipboard-read"], ["simulate-geo", "geolocation"], ] as const) { root .querySelector(`[data-testid="${id}"]`) ?.addEventListener("click", async () => { render(await window.api.sandbox.simulate(permission)); }); } root .querySelector('[data-testid="download"]') ?.addEventListener("click", async () => { render(await window.api.sandbox.download()); }); const sleep = (value: number): Promise => new Promise((resolve) => setTimeout(resolve, value)); window.__prepareShots = async (stage) => { document.body.dataset.shot = stage; if (stage === "sandbox") { render(await window.api.sandbox.probe()); return; } if (stage === "permissions") { await window.api.sandbox.setNotifications(true); try { const result = await Notification.requestPermission(); if (notificationResult) { notificationResult.textContent = `Notification.requestPermission() → ${result}`; } } catch { // 忽略无通知支持的平台。 } await window.api.sandbox.simulate("notifications"); await window.api.sandbox.simulate("media"); render(await window.api.sandbox.simulate("clipboard-read")); document .querySelector(".permissions-card") ?.scrollIntoView({ block: "start" }); return; } render(await window.api.sandbox.download()); showRequire(); document .querySelector(".download-card") ?.scrollIntoView({ block: "start" }); await sleep(100); }; window.__smoke = async () => { const api = window.api.sandbox; const first = await api.probe(); let notificationResult = "unsupported"; try { notificationResult = await Notification.requestPermission(); } catch { notificationResult = "error"; } await api.simulate("notifications"); await api.simulate("media"); await api.setNotifications(false); await api.simulate("notifications"); await api.setNotifications(true); const downloaded = await api.download(); const requireError = probeRequire(); const final = await api.refresh(); unsubscribe(); const allowedEntries = final.permissions.entries.filter( (entry) => entry.allowed, ).length; const deniedEntries = final.permissions.entries.filter( (entry) => !entry.allowed, ).length; return { score: first.score, checks: first.checks.length, passed: first.checks.filter((check) => check.pass).length, requireType: first.probe.requireType, processType: first.probe.processType, bufferType: first.probe.bufferType, apiKeys: first.probe.apiKeys.length, csp: first.probe.csp, notificationResult, permissionEntries: final.permissions.entries.length, allowedEntries, deniedEntries, downloadFilename: downloaded.download?.filename ?? "", downloadBlocked: downloaded.download?.blocked ?? false, requireError, events: final.events.length, }; }; }