Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:test_tube: Verify isolated map webview compositing https://github.com/siyuan-note/siyuan/issues/20129

Daniel4c4618952658
diff --git a/app/tests/fixtures/map-webview-boundary/README.md b/app/tests/fixtures/map-webview-boundary/README.md
new file mode 100644
index 0000000000..ab7ef27222
--- /dev/null
+++ b/app/tests/fixtures/map-webview-boundary/README.md
@@ -0,0 +1,30 @@
+# 独立地图 webview 原型
+
+此入口只运行合成数据,不读取笔记,也不接入生产窗口。主窗口保留本地实际配置:`nodeIntegration=true`、`contextIsolation=false`、`webSecurity=false`。地图 guest 使用独立内存会话、固定预载脚本和既有资源路由,强制启用 sandbox、contextIsolation 和 webSecurity,关闭全部 Node 能力。
+
+在 `app/` 中运行,确保没有设置 `ELECTRON_RUN_AS_NODE`:
+
+```sh
+node node_modules/electron/cli.js tests/fixtures/map-webview-boundary/harness.cjs
+```
+
+默认是真实 OpenFreeMap 模式,直接读取开发者已有的 `stage/build/map/` 产物,使用固定合成坐标。缺产物会明确报错,不自动编译或替换成假图。此模式需要访问 OpenFreeMap。先等终端输出边界检查通过与窗口就绪,再确认真实瓦片出图。
+
+不访问地图服务的合成模式,以及自动安全与覆盖断言:
+
+```sh
+node node_modules/electron/cli.js tests/fixtures/map-webview-boundary/harness.cjs --synthetic
+node node_modules/electron/cli.js tests/fixtures/map-webview-boundary/harness.cjs --synthetic --verify
+```
+
+自动验证覆盖 guest Node/IPC 与 owner DOM 不可访问、独立会话不受默认会话删除 CSP 影响、内核 API/非白名单/worker 请求拒绝、导航及伪造 guest 拒绝、普通 DOM 菜单合成像素及真实输入、Esc、滚动、地图实例/视野/visibility 稳定。合成适配器验证不等于真实 OFM/WebGL 出图验证。
+
+手动打开普通菜单,输入中文并使用输入法候选,按 Esc,反复开关菜单,滚动地图所在容器。地图应持续可见,不重建、不重置视野;菜单应覆盖地图并正确接受输入。输入法与平台合成仍需在目标桌面实际确认。
+
+```sh
+node --test tests/mapWebviewStartup.test.js tests/mapWebviewBoundary.test.js
+```
+
+没有 DISPLAY/WAYLAND_DISPLAY 的 Linux 环境会明确跳过真实 Electron 验证,单元测试通过不能替代运行验证。禁止使用 `--no-sandbox`、`--disable-web-security` 或其他安全降级参数。开发环境实装 Electron 44.5.1,package.json 声明 44.7.0;两个版本的真实桌面验证结果需要分别记录。
+
+本原型没有生产接线;远程内核保持现有宿主路径。生产迁移与旧代码清理需后续独立检查。
diff --git a/app/tests/fixtures/map-webview-boundary/harness.cjs b/app/tests/fixtures/map-webview-boundary/harness.cjs
new file mode 100644
index 0000000000..d4f2e99336
--- /dev/null
+++ b/app/tests/fixtures/map-webview-boundary/harness.cjs
@@ -0,0 +1,62 @@
+// Electron 默认应用通过动态导入执行此入口,不使用 require.main 判断。
+// 可复用测试只导入 harnessSupport.cjs,该模块导入时不会创建窗口。
+const {app, BrowserWindow} = require("electron");
+const {createHarness, createTemporaryProfile, verifyHarness} = require("./harnessSupport.cjs");
+
+if (!app || !BrowserWindow) {
+ console.error("Map webview prototype requires Electron GUI mode; check ELECTRON_RUN_AS_NODE.");
+ process.exitCode = 1;
+} else {
+ let temporary;
+ const fail = error => {
+ console.error("Map webview prototype startup failed.");
+ const codes = ["attachPreferenceMismatch", "hostAttachFailed", "hostDocumentLoadFailed", "hostDocumentMismatch",
+ "hostRendererGone", "hostDestroyed", "hostBootstrapTimeout", "hostSDKTimeout", "documentCSPBlocked",
+ "isolationAssertionFailed", "isolationCheckTimeout", "fixtureSetupFailed", "ownerClosed", "sdkUnavailable", "hostUnavailable",
+ "sdkScriptLoadFailed", "sdkGlobalMissing", "mapCreationFailed", "mapReadyTimeout", "mapUnavailable"];
+ if (codes.includes(error?.code)) {
+ const prefKeys = ["sandbox", "contextIsolation", "webSecurity", "nodeIntegration", "nodeIntegrationInSubFrames",
+ "nodeIntegrationInWorker", "webviewTag", "allowRunningInsecureContent", "experimentalFeatures", "disablePopups", "safeDialogs", "disableDialogs"];
+ console.error("Boundary stage: " + error.code +
+ (prefKeys.includes(error.preference) ? "; preference: " + error.preference : "") +
+ (Number.isInteger(error.netError) && error.netError < 0 && error.netError > -1000 ? "; net error: " + error.netError : ""));
+ }
+ if (error?.code === "MAP_FIXTURE_ASSETS_MISSING") {
+ console.error("Real mode requires existing app/stage/build/map assets. Run your normal development build first; this fixture does not build or substitute them.");
+ }
+ try {
+ for (const win of BrowserWindow.getAllWindows()) if (!win.isDestroyed()) win.destroy();
+ } finally {
+ temporary?.cleanup();
+ app.exit(1);
+ }
+ };
+ try {
+ console.info("Map webview prototype starting...");
+ const flags = new Set(process.argv.slice(2));
+ if ([...flags].some(flag => !["--real", "--synthetic", "--verify"].includes(flag)) ||
+ (flags.has("--real") && flags.has("--synthetic")) || (flags.has("--verify") && !flags.has("--synthetic"))) {
+ throw new Error("Invalid fixture mode");
+ }
+ temporary = createTemporaryProfile();
+ app.once("will-quit", temporary.cleanup);
+ app.once("quit", temporary.cleanup);
+ void createHarness({profile: temporary.profile, mode: flags.has("--synthetic") ? "synthetic" : "real",
+ automate: flags.has("--verify")}).then(async harness => {
+ console.info("Map webview prototype window ready.");
+ if (flags.has("--verify")) {
+ try { await verifyHarness(harness); }
+ catch (failure) {
+ const error = new Error("Fixture verification failed");
+ error.code = failure?.code === "isolationCheckTimeout" ? "isolationCheckTimeout" : "isolationAssertionFailed";
+ throw error;
+ }
+ console.info("Map webview prototype verification passed.");
+ await harness.destroy();
+ app.exit(0);
+ }
+ }).catch(fail);
+ } catch (error) {
+ fail(error);
+ }
+}
diff --git a/app/tests/fixtures/map-webview-boundary/harnessSupport.cjs b/app/tests/fixtures/map-webview-boundary/harnessSupport.cjs
new file mode 100644
index 0000000000..29a7b941cc
--- /dev/null
+++ b/app/tests/fixtures/map-webview-boundary/harnessSupport.cjs
@@ -0,0 +1,402 @@
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const http = require("node:http");
+const os = require("node:os");
+const path = require("node:path");
+const {randomBytes} = require("node:crypto");
+const {createMapSessionRouter, MAP_HOST_BOOTSTRAP_TIMEOUT, MAP_HOST_READY_TIMEOUT} = require("../../../electron/mapHostManager");
+const {hasUnsafeMapSwitches, mapHostFiles, parseMapReply} = require("../../../electron/mapHostPolicy");
+
+const appDir = path.resolve(__dirname, "../../..");
+const preload = path.join(appDir, "electron/mapHostPreload.js");
+const ownerPreferences = Object.freeze({nodeIntegration: true, nodeIntegrationInSubFrames: false,
+ nodeIntegrationInWorker: false, webviewTag: true, webSecurity: false, contextIsolation: false,
+ autoplayPolicy: "user-gesture-required"});
+const guestPreferences = Object.freeze({sandbox: true, contextIsolation: true, webSecurity: true,
+ nodeIntegration: false, nodeIntegrationInSubFrames: false, nodeIntegrationInWorker: false,
+ webviewTag: false, allowRunningInsecureContent: false, plugins: false, experimentalFeatures: false,
+ navigateOnDragDrop: false, disablePopups: true, safeDialogs: true, disableDialogs: true,
+ spellcheck: false, backgroundThrottling: false, autoplayPolicy: "user-gesture-required"});
+// Electron 44 的 getLastWebPreferences 只回传此固定子集,不包含 preload 等构造参数。
+const reportedPreferenceKeys = Object.freeze(["sandbox", "contextIsolation", "webSecurity", "nodeIntegration",
+ "nodeIntegrationInSubFrames", "nodeIntegrationInWorker", "webviewTag", "allowRunningInsecureContent",
+ "experimentalFeatures", "disablePopups", "safeDialogs", "disableDialogs"]);
+const getGuestPreferenceMismatch = actual => reportedPreferenceKeys.find(name => actual?.[name] !== guestPreferences[name]);
+
+// 仅供独立原型使用;渲染器不能指定偏好或预载脚本。
+const hardenAttachment = (event, preferences, params, expected) => {
+ const unsafe = ["preload", "webpreferences", "nodeintegration", "nodeintegrationinsubframes",
+ "disablewebsecurity", "allowpopups", "plugins", "blinkfeatures", "disableblinkfeatures",
+ "useragent", "httpreferrer"].some(name => !!params[name]);
+ if (expected.used || event.sender !== expected.owner || params.src !== expected.src ||
+ params.partition !== expected.partition || unsafe) {
+ event.preventDefault();
+ return false;
+ }
+ expected.used = true;
+ for (const name of Object.keys(preferences)) delete preferences[name];
+ Object.assign(preferences, guestPreferences, {preload, session: expected.session, partition: expected.partition});
+ return true;
+};
+
+const checkRealAssets = (directory = appDir) => {
+ for (const [relative] of Object.values(mapHostFiles)) {
+ try {
+ if (!fs.statSync(path.join(directory, relative)).isFile()) throw new Error("Missing asset");
+ } catch (_error) {
+ const error = new Error("Real map assets are missing");
+ error.code = "MAP_FIXTURE_ASSETS_MISSING";
+ throw error;
+ }
+ }
+};
+
+const createTemporaryProfile = () => {
+ const profile = fs.mkdtempSync(path.join(os.tmpdir(), "siyuan-map-webview-"));
+ return {profile, cleanup() {
+ if (path.dirname(path.resolve(profile)) !== path.resolve(os.tmpdir()) ||
+ !path.basename(profile).startsWith("siyuan-map-webview-")) return;
+ try { fs.rmSync(profile, {recursive: true, force: true, maxRetries: 3, retryDelay: 100}); }
+ catch (_error) { /* Electron 退出时可能暂时保留配置目录的文件锁。 */ }
+ }};
+};
+
+// 合成模式复用真实协议、准备阶段和运行时,仅替换地图适配器。
+const createSyntheticFiles = () => {
+ const ts = require("typescript");
+ const directory = path.join(appDir, "src/protyle/render/av/map");
+ const modules = Object.fromEntries(["protocol", "loadingBudget", "bootstrap", "hostRuntime"].map(name =>
+ ["./" + name, ts.transpileModule(fs.readFileSync(path.join(directory, name + ".ts"), "utf8"), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},
+ }).outputText]));
+ modules["./providersLoader"] = `
+ window.mapFixture = {fits: 0, revisions: [], destroyed: 0, visible: [], clicks: 0, locked: false};
+ exports.prepareAVMapAssets = async () => ({lock() { window.mapFixture.locked = true; }, destroy() {}});
+ exports.loadAVMapAdapter = async (_init, container, callbacks) => {
+ window.mapFixture.callbacks = callbacks;
+ container.style.background = "rgb(25, 119, 145)";
+ container.textContent = "Synthetic map adapter. No provider network or WebGL.";
+ container.addEventListener("click", () => window.mapFixture.clicks++);
+ return {setPoints(points, revision) { window.mapFixture.revisions.push(revision); },
+ fit() { window.mapFixture.fits++; }, resize() {}, setTheme() {},
+ setVisible(value) { window.mapFixture.visible.push(value); },
+ destroy() { window.mapFixture.destroyed++; }};
+ };`;
+ const runtime = `(() => {
+ const modules = {${Object.entries(modules).map(([name, source]) =>
+ `${JSON.stringify(name)}: (require, exports) => {${source}\n}`).join(",")}};
+ const cache = {};
+ const load = name => {
+ if (!modules[name]) throw new Error("Unknown fixture module");
+ if (!cache[name]) { cache[name] = {}; modules[name](load, cache[name]); }
+ return cache[name];
+ };
+ load("./hostRuntime").connectAVMapRuntime(window);
+ })();`;
+ return new Map([["stage/map/index.html", fs.readFileSync(path.join(appDir, "stage/map/index.html"))],
+ ["stage/map/host.css", fs.readFileSync(path.join(appDir, "stage/map/host.css"))],
+ ["stage/build/map/host.js", Buffer.from(runtime)]]);
+};
+
+const waitFor = async (predicate, label, timeout = 5000) => {
+ const deadline = Date.now() + timeout;
+ while (!await predicate()) {
+ assert.ok(Date.now() < deadline, label);
+ await new Promise(resolve => setTimeout(resolve, 25));
+ }
+};
+
+const createHarness = async ({profile, mode = "real", automate = false} = {}) => {
+ if (typeof profile !== "string" || !path.isAbsolute(profile) || !["real", "synthetic"].includes(mode)) {
+ throw new Error("An isolated profile and fixed fixture mode are required");
+ }
+ const {app, BrowserWindow, MessageChannelMain, session} = require("electron");
+ if (hasUnsafeMapSwitches(app.commandLine)) throw new Error("Unsafe process switches are prohibited");
+ if (mode === "real") checkRealAssets();
+ app.setPath("userData", profile);
+ await app.whenReady();
+ const syntheticFiles = mode === "synthetic" ? createSyntheticFiles() : undefined;
+ const instanceID = randomBytes(24).toString("hex"), nonce = randomBytes(24).toString("hex");
+ const partition = "map-webview-fixture-" + instanceID;
+ const ses = session.fromPartition(partition, {cache: false});
+ let win, owner, guest, router, port, expected, timer, ready = false, closed = false, loaded = false, isolating = false;
+ let resolveReady, rejectReady;
+ const readiness = new Promise((resolve, reject) => { resolveReady = resolve; rejectReady = reject; });
+ // 事件可能在 createHarness 等待就绪前失败。
+ void readiness.catch(() => {});
+ const evidence = {privateRequests: 0, guestNetworkRequests: 0, defaultHeaderCalls: 0,
+ defaultGuestHeaderCalls: 0, rejectedAttachments: 0, attached: 0, replies: [], diagnostics: []};
+ const server = http.createServer((request, response) => {
+ const files = {"/stage/build/app/": ["owner.html", "text/html"],
+ "/fixture-owner.js": ["owner.js", "text/javascript"], "/fixture-owner.css": ["owner.css", "text/css"]};
+ const resource = files[request.url];
+ if (!resource) {
+ if (request.url.startsWith("/api/")) evidence.privateRequests++;
+ else evidence.guestNetworkRequests++;
+ response.writeHead(403).end();
+ return;
+ }
+ // 复现真实默认会话删除 CSP 的行为,不改生产入口。
+ response.setHeader("Content-Security-Policy", "default-src 'none'");
+ response.setHeader("Content-Type", resource[1]);
+ response.end(fs.readFileSync(path.join(__dirname, resource[0])));
+ });
+ const fail = (code, detail = {}) => {
+ if (closed) return;
+ if (owner && !owner.isDestroyed()) owner.send("map-webview-fixture-state", {type: "error", code});
+ const error = new Error("Map fixture failure");
+ error.code = code;
+ error.netError = detail.netError;
+ error.preference = detail.preference;
+ rejectReady(error);
+ if (ready) void destroy();
+ };
+ const send = value => { if (port && !closed) port.postMessage({version: 1, instanceID, ...value}); };
+ const onCreated = (_event, contents) => {
+ if (contents.getType() !== "webview") return;
+ if (closed || guest || !expected?.used || contents.hostWebContents !== owner || contents.session !== ses) {
+ contents.close({waitForBeforeUnload: false});
+ return;
+ }
+ guest = contents;
+ // 此事件早于首次 loadURL;did-attach-webview 仅用于复核,不能承担首次防护。
+ contents.setWindowOpenHandler(() => ({action: "deny"}));
+ for (const name of ["will-navigate", "will-frame-navigate", "will-redirect", "will-attach-webview"]) {
+ contents.on(name, event => event.preventDefault());
+ }
+ contents.on("will-prevent-unload", event => event.preventDefault());
+ contents.on("select-client-certificate", (event, _url, _certificates, callback) => { event.preventDefault(); callback(); });
+ contents.on("login", (event, _details, _auth, callback) => { event.preventDefault(); callback(); });
+ contents.on("certificate-error", (_event, _url, _error, _certificate, callback) => callback(false));
+ contents.on("console-message", (event, _level, legacyMessage) => {
+ const message = event?.message ?? legacyMessage;
+ if (!ready && typeof message === "string" && message.includes("frame-ancestors")) fail("documentCSPBlocked");
+ });
+ contents.on("did-navigate", (_event, url) => { if (url !== expected.src) fail("hostDocumentMismatch"); });
+ contents.on("did-navigate-in-page", () => fail("hostDocumentMismatch"));
+ contents.on("render-process-gone", () => fail("hostRendererGone"));
+ contents.on("destroyed", () => { if (!closed) fail("hostDestroyed"); });
+ contents.on("did-fail-load", (_event, code, _description, _url, isMainFrame) => {
+ if (isMainFrame && code !== -3) fail("hostDocumentLoadFailed", {netError: code});
+ });
+ contents.on("did-finish-load", () => {
+ if (loaded || contents.getURL() !== expected.src) { fail("hostDocumentMismatch"); return; }
+ loaded = true;
+ const channel = new MessageChannelMain();
+ port = channel.port1;
+ port.on("message", event => {
+ const reply = parseMapReply(event.data, instanceID);
+ if (!reply || closed) return;
+ if (reply.type === "bootstrapReady" && !ready) {
+ clearTimeout(timer);
+ timer = setTimeout(() => fail("hostSDKTimeout"), MAP_HOST_READY_TIMEOUT);
+ send({type: "init", provider: "openfreemap", theme: "light"});
+ } else if (reply.type === "ready" && !ready) {
+ ready = true;
+ clearTimeout(timer);
+ send({type: "setPoints", revision: 1, points: [{id: "synthetic-row-1", longitude: 121.4737, latitude: 31.2304},
+ {id: "synthetic-row-2", longitude: 121.5037, latitude: 31.2404}]});
+ send({type: "visibility", visible: true});
+ owner.send("map-webview-fixture-state", {type: "ready", mode});
+ resolveReady();
+ } else if (reply.type === "error") fail(reply.code);
+ else if (reply.type === "markerClick" && ready && reply.revision === 1 &&
+ ["synthetic-row-1", "synthetic-row-2"].includes(reply.id)) {
+ evidence.replies.push(reply);
+ owner.send("map-webview-fixture-state", reply);
+ }
+ });
+ port.start();
+ contents.postMessage("siyuan-map-port", {version: 1, instanceID, nonce, provider: "openfreemap"}, [channel.port2]);
+ });
+ };
+ const destroy = async () => {
+ if (closed) return;
+ send({type: "destroy"});
+ closed = true;
+ if (!ready) {
+ const error = new Error("Map fixture closed before ready");
+ error.code = "ownerClosed";
+ rejectReady(error);
+ }
+ clearTimeout(timer);
+ app.removeListener("web-contents-created", onCreated);
+ port?.close();
+ router?.destroy();
+ if (guest && !guest.isDestroyed()) guest.close({waitForBeforeUnload: false});
+ if (win && !win.isDestroyed()) win.destroy();
+ session.defaultSession.webRequest.onHeadersReceived(null);
+ server.closeAllConnections?.();
+ if (server.listening) await new Promise(resolve => server.close(resolve));
+ };
+ try {
+ await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
+ const origin = `http://127.0.0.1:${server.address().port}`;
+ const src = origin + "/stage/map/index.html?provider=openfreemap#" + instanceID + ":" + nonce;
+ router = createMapSessionRouter({ses, origin, appDir,
+ readFile: syntheticFiles ? async filename => {
+ const relative = path.relative(appDir, filename).split(path.sep).join("/");
+ if (!syntheticFiles.has(relative)) throw new Error("Unknown synthetic fixture asset");
+ return syntheticFiles.get(relative);
+ } : undefined,
+ report: code => evidence.diagnostics.push(code)});
+ session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
+ evidence.defaultHeaderCalls++;
+ if (details.url.includes("/stage/map/") || details.url.includes("/stage/build/map/")) evidence.defaultGuestHeaderCalls++;
+ callback({responseHeaders: Object.fromEntries(Object.entries(details.responseHeaders || {})
+ .filter(([name]) => !["content-security-policy", "x-frame-options", "access-control-allow-origin"].includes(name.toLowerCase())))});
+ });
+ app.on("web-contents-created", onCreated);
+ win = new BrowserWindow({width: 820, height: 620, useContentSize: true, show: true,
+ webPreferences: {...ownerPreferences}});
+ owner = win.webContents;
+ expected = {owner, src, partition, session: ses, used: false};
+ owner.on("will-attach-webview", (event, preferences, params) => {
+ if (!hardenAttachment(event, preferences, params, expected)) evidence.rejectedAttachments++;
+ });
+ owner.on("did-attach-webview", (_event, attached) => {
+ const actual = attached.getLastWebPreferences();
+ const mismatch = getGuestPreferenceMismatch(actual);
+ if (attached !== guest || attached.hostWebContents !== owner || attached.session !== ses || mismatch) {
+ fail(mismatch ? "attachPreferenceMismatch" : "hostAttachFailed", {preference: mismatch});
+ attached.close({waitForBeforeUnload: false});
+ return;
+ }
+ evidence.attached++;
+ });
+ win.on("closed", () => { void destroy().then(() => { if (!automate) app.quit(); }); });
+ await win.loadURL(origin + "/stage/build/app/");
+ timer = setTimeout(() => fail("hostBootstrapTimeout"), MAP_HOST_BOOTSTRAP_TIMEOUT);
+ owner.send("map-webview-fixture-start", {src, partition, mode});
+ await readiness;
+ const harness = {win, owner, get guest() { return guest; }, session: ses, origin, src, partition, instanceID,
+ mode, evidence, send, destroy};
+ isolating = true;
+ await verifyIsolation(harness);
+ console.info("Map webview boundary checks passed: isolated session, opaque origin, no Node/IPC or owner DOM access, private network denied.");
+ return harness;
+ } catch (error) {
+ await destroy();
+ if (isolating && error.code !== "isolationCheckTimeout") error.code = "isolationAssertionFailed";
+ else if (!error.code) error.code = "fixtureSetupFailed";
+ throw error;
+ }
+};
+
+const verifyIsolationChecks = async harness => {
+ const {owner, guest, evidence, origin} = harness;
+ const inspect = source => guest.executeJavaScript(source);
+ const ownerPrefs = owner.getLastWebPreferences();
+ for (const [name, value] of Object.entries(ownerPreferences)) {
+ if (reportedPreferenceKeys.includes(name)) assert.equal(ownerPrefs[name], value, name);
+ }
+ assert.equal(getGuestPreferenceMismatch(guest.getLastWebPreferences()), undefined);
+ assert.notEqual(guest.session, owner.session);
+ assert.notEqual(guest.getOSProcessId(), owner.getOSProcessId());
+ assert.equal(guest.session.isPersistent(), false);
+ assert.deepEqual(await inspect(`(() => {
+ const ownerVisible = target => { try { return !!target?.document?.getElementById("owner-private-sentinel"); } catch (_) { return false; } };
+ let evalBlocked = false; try { (0, eval)("1"); } catch (_) { evalBlocked = true; }
+ return {origin: window.origin, require: typeof require, process: typeof process, ipc: typeof ipcRenderer,
+ bridge: Object.keys(window.siyuanMapDesktop), parentOwner: ownerVisible(parent), topOwner: ownerVisible(top),
+ openerOwner: ownerVisible(opener), evalBlocked};
+ })()`), {origin: "null", require: "undefined", process: "undefined", ipc: "undefined", bridge: ["version"],
+ parentOwner: false, topOwner: false, openerOwner: false, evalBlocked: true});
+ assert.ok(evidence.defaultHeaderCalls > 0, "the unsafe owner header-removal fixture is active");
+ assert.equal(evidence.defaultGuestHeaderCalls, 0, "guest resources bypass the owner's default session entirely");
+ assert.equal(evidence.guestNetworkRequests, 0, "fixed local guest resources never reach the kernel server");
+ for (const target of [origin + "/api/fixture-private", "https://example.invalid/private", "file:///fixture-private"]) {
+ assert.equal(await inspect(`fetch(${JSON.stringify(target)}).then(() => false, () => true)`), true);
+ }
+ assert.equal(evidence.privateRequests, 0, "private API probes never reach the kernel server");
+};
+
+const verifyIsolation = async harness => {
+ let timer;
+ const deadline = new Promise((_resolve, reject) => {
+ timer = setTimeout(() => {
+ const error = new Error("Map isolation check deadline exceeded");
+ error.code = "isolationCheckTimeout";
+ reject(error);
+ }, 5000);
+ });
+ try { await Promise.race([verifyIsolationChecks(harness), deadline]); }
+ finally { clearTimeout(timer); }
+};
+
+const verifyHarness = async harness => {
+ assert.equal(harness.mode, "synthetic", "automated adapter checks require explicit synthetic mode");
+ const {owner, guest, win, evidence, origin, src} = harness;
+ const evaluate = source => owner.executeJavaScript(source);
+ const inspect = source => guest.executeJavaScript(source);
+ await verifyIsolation(harness);
+ await waitFor(() => inspect("window.mapFixture?.fits === 1 && window.mapFixture.visible.length === 1"), "runtime receives points and visibility");
+ assert.equal(await inspect("window.mapFixture.locked"), true);
+ const privateURL = origin + "/api/fixture-private";
+ assert.deepEqual(await inspect(`new Promise(resolve => {
+ const code = "fetch(" + ${JSON.stringify(JSON.stringify(privateURL))} + ").then(() => postMessage({denied:false}), () => postMessage({denied:true,node:typeof require,process:typeof process}))";
+ const url = URL.createObjectURL(new Blob([code], {type:"text/javascript"}));
+ const worker = new Worker(url);
+ const done = result => { worker.terminate(); URL.revokeObjectURL(url); resolve(result); };
+ worker.onmessage = event => done(event.data);
+ worker.onerror = () => done({workerFailed:true});
+ })`), {denied: true, node: "undefined", process: "undefined"});
+ await inspect(`window.open(${JSON.stringify(privateURL)}); window.location.href = ${JSON.stringify(privateURL)}`);
+ await new Promise(resolve => setTimeout(resolve, 100));
+ assert.equal(guest.getURL(), src);
+ assert.equal(evidence.privateRequests, 0);
+ const identity = guest.id;
+ const before = await inspect("JSON.stringify({fits:mapFixture.fits,revisions:mapFixture.revisions,visible:mapFixture.visible})");
+ const pixel = async () => {
+ const shot = await win.webContents.capturePage({x: 600, y: 285, width: 1, height: 1});
+ const bitmap = shot.toBitmap();
+ return [bitmap[2], bitmap[1], bitmap[0]];
+ };
+ await waitFor(async () => (await pixel()).join() === "25,119,145", "the guest surface is composited into the owner page");
+ await evaluate("window.setFixtureMenu(true)");
+ await waitFor(async () => (await pixel()).join() === "214,49,49", "ordinary DOM menu paints over the guest");
+ owner.sendInputEvent({type: "mouseDown", x: 435, y: 200, button: "left", clickCount: 1});
+ owner.sendInputEvent({type: "mouseUp", x: 435, y: 200, button: "left", clickCount: 1});
+ await waitFor(() => evaluate("window.ownerFixture.menuActions === 1"), "the overlaid menu receives real input");
+ assert.equal(await inspect("window.mapFixture.clicks"), 0);
+ await evaluate("document.getElementById('menu-input').focus()");
+ owner.sendInputEvent({type: "keyDown", keyCode: "Escape"});
+ owner.sendInputEvent({type: "keyUp", keyCode: "Escape"});
+ await waitFor(() => evaluate("document.getElementById('menu').hidden"), "Escape dismisses the ordinary DOM menu");
+ await waitFor(async () => (await pixel()).join() === "25,119,145", "dismissal uncovers the still-rendered map");
+ assert.equal(guest.id, identity);
+ assert.equal(await inspect("JSON.stringify({fits:mapFixture.fits,revisions:mapFixture.revisions,visible:mapFixture.visible})"), before,
+ "opening/closing an ordinary menu neither hides, rebuilds nor refits the map");
+ await evaluate("document.getElementById('scroll-area').scrollTop = 80");
+ assert.equal(await evaluate("document.getElementById('scroll-area').scrollTop"), 80);
+ assert.equal(guest.id, identity);
+ // 拒绝第二个伪造 guest,不影响已准入的 guest 和独立会话。
+ await evaluate(`(() => {
+ const bad = document.createElement("webview");
+ bad.setAttribute("src", ${JSON.stringify(privateURL)});
+ bad.setAttribute("partition", "persist:untrusted-fixture");
+ bad.setAttribute("nodeintegration", "");
+ bad.setAttribute("disablewebsecurity", "");
+ document.body.appendChild(bad);
+ })()`);
+ await waitFor(() => evidence.rejectedAttachments > 0, "a forged second guest is rejected before creation");
+ assert.equal(evidence.attached, 1);
+ assert.equal(evidence.privateRequests, 0);
+ assert.equal(guest.id, identity);
+ await inspect("window.mapFixture.callbacks.onMarkerClick('foreign-row', 1); window.mapFixture.callbacks.onMarkerClick('synthetic-row-1', 0)");
+ await new Promise(resolve => setTimeout(resolve, 50));
+ assert.equal(evidence.replies.length, 0);
+ await inspect("window.mapFixture.callbacks.onMarkerClick('synthetic-row-1', 1)");
+ await waitFor(() => evidence.replies.length === 1, "the existing finite protocol accepts only current member actions");
+ await evaluate(`window.fixtureGuest.setAttribute("src", ${JSON.stringify(privateURL)})`);
+ await new Promise(resolve => setTimeout(resolve, 100));
+ assert.ok(guest.isDestroyed() || guest.getURL() === src, "dynamic src changes cannot load another document");
+ assert.equal(evidence.privateRequests, 0);
+ if (!guest.isDestroyed()) {
+ await evaluate("window.fixtureGuest.remove()");
+ await waitFor(() => guest.isDestroyed(), "removing the DOM guest destroys its renderer");
+ }
+};
+
+module.exports = {createHarness, createTemporaryProfile, verifyHarness, hardenAttachment, checkRealAssets,
+ createSyntheticFiles, ownerPreferences, guestPreferences, getGuestPreferenceMismatch, reportedPreferenceKeys, verifyIsolation};
diff --git a/app/tests/fixtures/map-webview-boundary/owner.css b/app/tests/fixtures/map-webview-boundary/owner.css
new file mode 100644
index 0000000000..6ed58db757
--- /dev/null
+++ b/app/tests/fixtures/map-webview-boundary/owner.css
@@ -0,0 +1,11 @@
+body { margin: 0; padding: 20px; font: 15px system-ui, sans-serif; color: #202124; background: #fff; }
+header { display: flex; align-items: center; gap: 16px; }
+button, input { font: inherit; padding: 8px; }
+#scroll-area { position: absolute; left: 20px; top: 110px; width: 740px; height: 410px; overflow: auto; border: 1px solid #444; }
+#map-slot { width: 720px; height: 360px; }
+webview { display: flex; width: 100%; height: 100%; }
+.spacer { height: 300px; padding: 16px; }
+#menu { position: fixed; z-index: 10; left: 360px; top: 90px; width: 260px; height: 230px; box-sizing: border-box; padding: 16px; background: rgb(214, 49, 49); color: white; border-radius: 8px; }
+#menu[hidden] { display: none; }
+#menu label { display: block; }
+#menu input { box-sizing: border-box; width: 100%; margin: 8px 0; }
diff --git a/app/tests/fixtures/map-webview-boundary/owner.html b/app/tests/fixtures/map-webview-boundary/owner.html
new file mode 100644
index 0000000000..ab72b6f515
--- /dev/null
+++ b/app/tests/fixtures/map-webview-boundary/owner.html
@@ -0,0 +1,23 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <title>Map webview boundary prototype</title>
+ <link rel="stylesheet" href="/fixture-owner.css">
+ <script defer src="/fixture-owner.js"></script>
+</head>
+<body>
+ <header>
+ <button id="toggle-menu" type="button">Open ordinary DOM menu</button>
+ <span id="status">Preparing isolated map...</span>
+ </header>
+ <p>Local prototype with synthetic points. Open the menu, enter Chinese text, press Escape, and scroll.</p>
+ <div id="scroll-area"><div id="map-slot"></div><div class="spacer">Scroll inside this region.</div></div>
+ <div id="owner-private-sentinel" hidden>Owner-only fixture data</div>
+ <div id="menu" class="b3-menu" hidden>
+ <label>中文输入 <input id="menu-input" placeholder="输入中文,测试组合输入"></label>
+ <button id="menu-action" type="button">Menu action</button>
+ <p>Escape or click outside to close.</p>
+ </div>
+</body>
+</html>
diff --git a/app/tests/fixtures/map-webview-boundary/owner.js b/app/tests/fixtures/map-webview-boundary/owner.js
new file mode 100644
index 0000000000..bbded5ce3e
--- /dev/null
+++ b/app/tests/fixtures/map-webview-boundary/owner.js
@@ -0,0 +1,32 @@
+const {ipcRenderer} = require("electron");
+const menu = document.getElementById("menu");
+const status = document.getElementById("status");
+window.ownerFixture = {ready: 0, menuActions: 0, errors: [], replies: [], changes: 0};
+window.setFixtureMenu = open => { menu.hidden = !open; };
+document.getElementById("toggle-menu").addEventListener("click", () => window.setFixtureMenu(menu.hidden));
+document.getElementById("menu-action").addEventListener("click", () => { window.ownerFixture.menuActions++; });
+document.getElementById("menu-input").addEventListener("input", () => { window.ownerFixture.changes++; });
+document.addEventListener("keydown", event => {
+ if (event.key === "Escape" && !event.isComposing) window.setFixtureMenu(false);
+});
+document.addEventListener("pointerdown", event => {
+ if (!menu.contains(event.target) && event.target.id !== "toggle-menu") window.setFixtureMenu(false);
+});
+ipcRenderer.once("map-webview-fixture-start", (_event, settings) => {
+ const guest = document.createElement("webview");
+ guest.id = "map-guest";
+ guest.setAttribute("partition", settings.partition);
+ guest.setAttribute("src", settings.src);
+ document.getElementById("map-slot").appendChild(guest);
+ window.fixtureGuest = guest;
+ status.textContent = settings.mode === "real" ? "Loading real OpenFreeMap..." : "Loading synthetic boundary adapter...";
+});
+ipcRenderer.on("map-webview-fixture-state", (_event, value) => {
+ if (value.type === "ready") {
+ window.ownerFixture.ready++;
+ status.textContent = value.mode === "real" ? "Real OpenFreeMap ready" : "Synthetic boundary adapter ready";
+ } else if (value.type === "error") {
+ window.ownerFixture.errors.push(value.code);
+ status.textContent = "Map failed: " + value.code;
+ } else window.ownerFixture.replies.push(value);
+});
diff --git a/app/tests/mapWebviewBoundary.test.js b/app/tests/mapWebviewBoundary.test.js
new file mode 100644
index 0000000000..97acb4ab0c
--- /dev/null
+++ b/app/tests/mapWebviewBoundary.test.js
@@ -0,0 +1,150 @@
+const assert = require("node:assert/strict");
+const {test} = require("node:test");
+const {execFile} = require("node:child_process");
+const {promisify} = require("node:util");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const {hardenAttachment, ownerPreferences, guestPreferences, createSyntheticFiles, checkRealAssets, getGuestPreferenceMismatch,
+ reportedPreferenceKeys, verifyIsolation} =
+ require("./fixtures/map-webview-boundary/harnessSupport.cjs");
+const {createMapSessionRouter} = require("../electron/mapHostManager");
+const {createMapContentSecurityPolicy} = require("../electron/mapHostPolicy");
+
+const attachCase = () => {
+ const owner = {}, session = {};
+ const expected = {owner, session, partition: "map-webview-fixture-example", src: "http://127.0.0.1:1234/stage/map/index.html?provider=openfreemap#fixed", used: false};
+ const event = {sender: owner, denied: false, preventDefault() { this.denied = true; }};
+ return {event, expected, params: {src: expected.src, partition: expected.partition}};
+};
+
+test("webview attachment fixes all guest privileges, preload and independent session before creation", () => {
+ const {event, expected, params} = attachCase();
+ const preferences = {nodeIntegration: true, sandbox: false, contextIsolation: false, webSecurity: false,
+ preload: "/untrusted/preload.js", partition: "persist:default", session: {}, additionalArguments: ["--unsafe"]};
+ assert.equal(hardenAttachment(event, preferences, params, expected), true);
+ assert.equal(event.denied, false);
+ assert.equal(expected.used, true);
+ for (const [name, value] of Object.entries(guestPreferences)) assert.equal(preferences[name], value, name);
+ assert.equal(preferences.session, expected.session);
+ assert.equal(preferences.partition, expected.partition);
+ assert.equal(preferences.preload, path.resolve(__dirname, "../electron/mapHostPreload.js"));
+ assert.equal(Object.hasOwn(preferences, "additionalArguments"), false);
+ assert.equal(hardenAttachment(event, {}, params, expected), false, "one admitted guest per fixture owner");
+});
+
+test("webview attachment rejects forged owner, source, session and renderer privilege attributes", () => {
+ const mutations = [
+ item => { item.event.sender = {}; },
+ item => { item.params.src = "http://127.0.0.1:1234/api/private"; },
+ item => { item.params.partition = "persist:shared"; },
+ ...["preload", "webpreferences", "nodeintegration", "nodeintegrationinsubframes", "disablewebsecurity",
+ "allowpopups", "plugins", "blinkfeatures", "disableblinkfeatures", "useragent", "httpreferrer"]
+ .map(name => item => { item.params[name] = "requested"; }),
+ ];
+ for (const mutate of mutations) {
+ const item = attachCase();
+ mutate(item);
+ const preferences = {sandbox: false};
+ assert.equal(hardenAttachment(item.event, preferences, item.params, item.expected), false);
+ assert.equal(item.event.denied, true);
+ assert.equal(item.expected.used, false);
+ assert.deepEqual(preferences, {sandbox: false});
+ }
+});
+
+test("guest preference readback checks the Electron 44 subset and rejects every missing or changed boundary value", () => {
+ const actual = Object.fromEntries(reportedPreferenceKeys.map(name => [name, guestPreferences[name]]));
+ assert.equal(getGuestPreferenceMismatch(actual), undefined);
+ assert.equal(Object.hasOwn(actual, "preload"), false);
+ for (const name of reportedPreferenceKeys) {
+ assert.equal(getGuestPreferenceMismatch({...actual, [name]: !actual[name]}), name);
+ const missing = {...actual};
+ delete missing[name];
+ assert.equal(getGuestPreferenceMismatch(missing), name);
+ }
+});
+
+test("common isolation checks have a fixed deadline and clear their timer on success, failure and timeout", async t => {
+ let fire, delay;
+ const timer = {}, cleared = [];
+ t.mock.method(global, "setTimeout", (callback, milliseconds) => { fire = callback; delay = milliseconds; return timer; });
+ t.mock.method(global, "clearTimeout", value => { cleared.push(value); });
+ const result = {origin: "null", require: "undefined", process: "undefined", ipc: "undefined", bridge: ["version"],
+ parentOwner: false, topOwner: false, openerOwner: false, evalBlocked: true};
+ const harness = inspect => ({origin: "http://127.0.0.1:1234",
+ owner: {getLastWebPreferences: () => ownerPreferences, session: {}, getOSProcessId: () => 1},
+ guest: {getLastWebPreferences: () => guestPreferences, session: {isPersistent: () => false},
+ getOSProcessId: () => 2, executeJavaScript: inspect},
+ evidence: {defaultHeaderCalls: 1, defaultGuestHeaderCalls: 0, guestNetworkRequests: 0, privateRequests: 0}});
+ await verifyIsolation(harness(source => Promise.resolve(source.startsWith("fetch(") ? true : result)));
+ assert.equal(delay, 5000);
+ assert.deepEqual(cleared, [timer]);
+ await assert.rejects(verifyIsolation(harness(() => Promise.reject(new Error("fixture probe failed")))));
+ assert.deepEqual(cleared, [timer, timer]);
+ const pending = verifyIsolation(harness(() => new Promise(() => {})));
+ const rejected = assert.rejects(pending, {code: "isolationCheckTimeout"});
+ assert.equal(delay, 5000);
+ fire();
+ await rejected;
+ assert.deepEqual(cleared, [timer, timer, timer]);
+});
+
+test("independent guest router retains exact CSP and denies private resources without using the owner session", async () => {
+ const hooks = {}, protocols = {}, permissions = {};
+ const ses = {webRequest: {}, protocol: {handle(name, fn) { protocols[name] = fn; }}, on() {},
+ allowNTLMCredentialsForDomains() {}, closeAllConnections() {}, clearStorageData() {}, clearAuthCache() {}, clearCache() {}, clearHostResolverCache() {}};
+ for (const name of ["onBeforeRequest", "onBeforeSendHeaders", "onHeadersReceived"]) ses.webRequest[name] = fn => { hooks[name] = fn; };
+ for (const name of ["setPermissionRequestHandler", "setPermissionCheckHandler", "setDevicePermissionHandler", "setDisplayMediaRequestHandler", "setCertificateVerifyProc"]) {
+ ses[name] = fn => { permissions[name] = fn; };
+ }
+ const origin = "http://127.0.0.1:1234";
+ let reads = 0;
+ const router = createMapSessionRouter({ses, origin, appDir: path.resolve(__dirname, ".."), readFile: async () => {
+ reads++;
+ return Buffer.from("<!doctype html><div id=map></div>");
+ }});
+ try {
+ const document = await protocols.http(new Request(origin + "/stage/map/index.html?provider=openfreemap"));
+ assert.equal(document.headers.get("Content-Security-Policy"), createMapContentSecurityPolicy(origin));
+ assert.match(document.headers.get("Content-Security-Policy"), /sandbox allow-scripts/);
+ assert.match(document.headers.get("Content-Security-Policy"), /frame-ancestors 'none'/);
+ let filtered;
+ hooks.onHeadersReceived({responseHeaders: {"Content-Security-Policy": ["fixed-policy"], "Set-Cookie": ["private=value"]}}, value => { filtered = value; });
+ assert.deepEqual(filtered.responseHeaders, {"Content-Security-Policy": ["fixed-policy"]});
+ for (const url of [origin + "/api/private", "https://example.invalid/private", "file:///private"]) {
+ const handler = url.startsWith("file:") ? protocols.file : protocols.http;
+ assert.equal((await handler(new Request(url))).status, 403);
+ }
+ assert.equal(reads, 1);
+ assert.equal(permissions.setPermissionCheckHandler(), false);
+ assert.equal(permissions.setDevicePermissionHandler(), false);
+ let allowed;
+ permissions.setPermissionRequestHandler({}, "clipboard-read", value => { allowed = value; });
+ assert.equal(allowed, false);
+ } finally { router.destroy(); }
+});
+
+test("synthetic mode bundles the existing runtime while real mode fails explicitly when production assets are absent", () => {
+ const files = createSyntheticFiles();
+ assert.equal(files.size, 3);
+ const runtime = files.get("stage/build/map/host.js").toString();
+ assert.match(runtime, /connectAVMapRuntime/);
+ assert.match(runtime, /parseAVMapCommand/);
+ assert.match(runtime, /getAVMapLockedPolicy/);
+ assert.doesNotThrow(() => new Function(runtime));
+ const empty = fs.mkdtempSync(path.join(os.tmpdir(), "siyuan-map-missing-assets-"));
+ try { assert.throws(() => checkRealAssets(empty), {code: "MAP_FIXTURE_ASSETS_MISSING"}); }
+ finally { fs.rmSync(empty, {recursive: true, force: true}); }
+});
+
+test("real Electron webview retains isolation and ordinary DOM menus cover its live surface without hide or refit", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY
+ ? "Real Electron verification requires DISPLAY or WAYLAND_DISPLAY; no unsafe startup fallback is allowed" : false,
+}, async () => {
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ const result = await promisify(execFile)(require("electron"), [path.join(__dirname, "fixtures/map-webview-boundary/harness.cjs"),
+ "--synthetic", "--verify"], {env, windowsHide: true, timeout: 90000});
+ assert.match(result.stdout, /Map webview prototype verification passed\./);
+});
diff --git a/app/tests/mapWebviewStartup.test.js b/app/tests/mapWebviewStartup.test.js
new file mode 100644
index 0000000000..78d737ddf2
--- /dev/null
+++ b/app/tests/mapWebviewStartup.test.js
@@ -0,0 +1,193 @@
+const assert = require("node:assert/strict");
+const {test} = require("node:test");
+const {spawnSync} = require("node:child_process");
+const path = require("node:path");
+const {pathToFileURL} = require("node:url");
+
+const entryPath = path.join(__dirname, "fixtures/map-webview-boundary/harness.cjs");
+const entry = pathToFileURL(entryPath).href;
+const support = pathToFileURL(path.join(__dirname, "fixtures/map-webview-boundary/harnessSupport.cjs")).href;
+
+// 在独立进程中复现 Electron 的动态导入,只替换 Electron 和可复用的测试辅助模块。
+const runEntry = (scenario = "success", args = []) => spawnSync(process.execPath, ["--input-type=module", "--eval", `
+ import {createRequire} from "node:module";
+ const require = createRequire(import.meta.url);
+ const Module = require("node:module");
+ const load = Module._load;
+ const calls = [];
+ const options = [];
+ const scenario = ${JSON.stringify(scenario)};
+ const args = ${JSON.stringify(args)};
+ process.argv = [process.execPath, ${JSON.stringify(entryPath)}, ...args];
+ const electron = {app: {
+ once(name) { calls.push(name); },
+ exit(code) { calls.push("exit:" + code); process.exitCode = code; },
+ commandLine: {hasSwitch(name) {
+ return args.some(arg => arg === "--" + name || arg.startsWith("--" + name + "="));
+ }}
+ }, BrowserWindow: {getAllWindows() { return [{isDestroyed: () => false,
+ destroy() { calls.push("destroy"); }}, {isDestroyed: () => true,
+ destroy() { throw new Error("destroyed window must be skipped"); }}]; }}};
+ const helper = {
+ createTemporaryProfile() {
+ calls.push("profile");
+ if (scenario === "profile-failure") throw new Error("private fixture error");
+ return {profile: "isolated-fixture-profile", cleanup() { calls.push("cleanup"); }};
+ },
+ createHarness(value) {
+ options.push(value);
+ calls.push("create");
+ if (scenario === "sync-failure") throw new Error("private fixture error");
+ if (scenario === "isolation-timeout") {
+ return Promise.reject(Object.assign(new Error("private fixture error"), {code: "isolationCheckTimeout"}));
+ }
+ return scenario === "async-failure" ? Promise.reject(new Error("private fixture error")) :
+ Promise.resolve({destroy() { calls.push("destroy-harness"); }});
+ },
+ verifyHarness(harness) {
+ if (!harness || typeof harness.destroy !== "function") throw new Error("missing harness");
+ calls.push("verify");
+ return scenario === "verification-failure" ? Promise.reject(new Error("private fixture error")) :
+ Promise.resolve();
+ }
+ };
+ Module._load = function(name, parent, isMain) {
+ if (name === "electron") return scenario === "node-mode" ? "electron-binary" : electron;
+ if (name === "./harnessSupport.cjs") return helper;
+ return load.call(this, name, parent, isMain);
+ };
+ await import(${JSON.stringify(entry)});
+ await import(${JSON.stringify(entry)});
+ await new Promise(resolve => setImmediate(resolve));
+ console.log("fixture-state:" + JSON.stringify({calls, options}));
+`], {cwd: path.join(__dirname, ".."), encoding: "utf8", timeout: 10000});
+
+const readState = result => {
+ assert.equal(result.error, undefined);
+ const state = result.stdout.match(/^fixture-state:(.+)$/m);
+ assert.ok(state, result.stderr || result.stdout);
+ return JSON.parse(state[1]);
+};
+
+test("manual webview dynamic-import entry starts exactly once and reports readiness", () => {
+ const result = runEntry();
+ const state = readState(result);
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stdout.split("Map webview prototype starting...").length - 1, 1);
+ assert.equal(result.stdout.split("Map webview prototype window ready.").length - 1, 1);
+ assert.deepEqual(state.calls, ["profile", "will-quit", "quit", "create"]);
+ assert.deepEqual(state.options, [{profile: "isolated-fixture-profile", mode: "real", automate: false}]);
+ assert.equal(result.stderr, "");
+});
+
+test("manual webview mode flags select real or synthetic harness and synthetic verification", () => {
+ const cases = [
+ {args: ["--real"], mode: "real", automate: false},
+ {args: ["--synthetic"], mode: "synthetic", automate: false},
+ {args: ["--synthetic", "--verify"], mode: "synthetic", automate: true},
+ {args: ["--verify", "--synthetic"], mode: "synthetic", automate: true},
+ ];
+ for (const {args, mode, automate} of cases) {
+ const result = runEntry("success", args);
+ const state = readState(result);
+ assert.equal(result.status, 0, `${args.join(" ")}: ${result.stderr}`);
+ assert.deepEqual(state.options, [{profile: "isolated-fixture-profile", mode, automate}]);
+ if (automate) {
+ assert.match(result.stdout, /Map webview prototype verification passed\./);
+ assert.equal(state.calls.filter(call => call === "verify").length, 1);
+ assert.ok(state.calls.includes("destroy-harness"));
+ assert.ok(state.calls.includes("exit:0"));
+ } else {
+ assert.ok(!state.calls.includes("verify"));
+ }
+ assert.equal(result.stderr, "");
+ }
+});
+
+test("manual webview entry rejects conflicting, unsupported and unsafe switches before creating the harness", () => {
+ const cases = [
+ ["--real", "--synthetic"],
+ ["--synthetic", "--real"],
+ ["--verify"],
+ ["--real", "--verify"],
+ ["--unknown-option"],
+ ["--synthetic", "--no-sandbox"],
+ ["--synthetic", "--disable-web-security"],
+ ];
+ for (const args of cases) {
+ const result = runEntry("success", args);
+ const state = readState(result);
+ assert.equal(result.status, 1, args.join(" "));
+ assert.match(result.stderr, /Map webview prototype startup failed\./);
+ assert.deepEqual(state.options, []);
+ assert.doesNotMatch(result.stdout, /window ready|verification passed/);
+ }
+});
+
+test("manual webview startup cleans up synchronous, asynchronous and profile failures", () => {
+ for (const scenario of ["sync-failure", "async-failure", "profile-failure"]) {
+ const result = runEntry(scenario);
+ const state = readState(result);
+ assert.equal(result.status, 1, scenario);
+ assert.match(result.stderr, /Map webview prototype startup failed\./, scenario);
+ assert.doesNotMatch(result.stdout + result.stderr, /private fixture error|window ready/, scenario);
+ assert.equal(state.calls.filter(call => call === "destroy").length, 1, scenario);
+ assert.equal(state.calls.filter(call => call === "exit:1").length, 1, scenario);
+ assert.equal(state.calls.filter(call => call === "cleanup").length, scenario === "profile-failure" ? 0 : 1,
+ scenario);
+ }
+});
+
+test("synthetic verification failures clean up without reporting success or exception details", () => {
+ const result = runEntry("verification-failure", ["--synthetic", "--verify"]);
+ const state = readState(result);
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /Map webview prototype startup failed\./);
+ assert.doesNotMatch(result.stdout + result.stderr, /private fixture error|verification passed/);
+ assert.ok(state.calls.includes("verify"));
+ assert.ok(state.calls.includes("destroy"));
+ assert.ok(state.calls.includes("cleanup"));
+ assert.ok(state.calls.includes("exit:1"));
+});
+
+test("isolation timeout reports a fixed boundary stage and cleans up without exposing private details", () => {
+ const result = runEntry("isolation-timeout");
+ const state = readState(result);
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /Map webview prototype startup failed\./);
+ assert.match(result.stderr, /Boundary stage: isolationCheckTimeout/);
+ assert.doesNotMatch(result.stdout + result.stderr, /private fixture error|window ready/);
+ assert.equal(state.calls.filter(call => call === "destroy").length, 1);
+ assert.equal(state.calls.filter(call => call === "cleanup").length, 1);
+ assert.equal(state.calls.filter(call => call === "exit:1").length, 1);
+});
+
+test("Node-mode webview invocation explains ELECTRON_RUN_AS_NODE without creating resources", () => {
+ const result = runEntry("node-mode");
+ const state = readState(result);
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /Map webview prototype requires Electron GUI mode; check ELECTRON_RUN_AS_NODE\./);
+ assert.deepEqual(state, {calls: [], options: []});
+ assert.doesNotMatch(result.stdout, /prototype starting|window ready/);
+});
+
+test("importing webview harness support does not start Electron or create a profile", () => {
+ const result = spawnSync(process.execPath, ["--input-type=module", "--eval", `
+ import {createRequire} from "node:module";
+ const require = createRequire(import.meta.url);
+ const Module = require("node:module");
+ const load = Module._load;
+ Module._load = function(name, parent, isMain) {
+ if (name === "electron") throw new Error("support must not initialize Electron");
+ return load.call(this, name, parent, isMain);
+ };
+ require("node:fs").mkdtempSync = () => { throw new Error("support must not create a profile"); };
+ const imported = await import(${JSON.stringify(support)});
+ if (typeof imported.default.createHarness !== "function") throw new Error("missing reusable harness");
+ if (typeof imported.default.createTemporaryProfile !== "function") throw new Error("missing profile helper");
+ `], {cwd: path.join(__dirname, ".."), encoding: "utf8", timeout: 10000});
+ assert.equal(result.error, undefined);
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stdout, "");
+ assert.equal(result.stderr, "");
+});