Skip to content

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

:bug: Diagnose isolated map SDK failures without exposing credentials https://github.com/siyuan-note/siyuan/issues/20129

Daniel7d8e2a4ca8d5
diff --git a/app/electron/mapHostDiagnostics.js b/app/electron/mapHostDiagnostics.js
new file mode 100644
index 0000000000..cd526bc0b6
--- /dev/null
+++ b/app/electron/mapHostDiagnostics.js
@@ -0,0 +1,29 @@
+// 仅返回固定分类,不转发 SDK 日志、请求地址、脚本片段或凭据。
+const mapDiagnosticCodes = Object.freeze([
+ "hostSetupFailed", "assetUnavailable", "documentLoadFailed", "bootstrapTimeout", "sdkTimeout",
+ "providerRequestDenied", "providerInsecureRequest", "providerHTTPFailure", "providerNetworkFailure",
+ "cspScript", "cspWorker", "cspConnect", "cspImage", "cspStyle", "cspEval", "cspWasm",
+ "storageUnavailable", "webglUnavailable", "amapInvalidKey", "amapInvalidSecurityCode",
+ "amapDomainMismatch", "amapPlatformMismatch",
+]);
+
+const classifyMapConsoleMessage = message => {
+ if (typeof message !== "string") return [];
+ const ret = [];
+ if (/content security policy|violates.*directive/i.test(message)) {
+ for (const [token, code] of [["script-src", "cspScript"], ["worker-src", "cspWorker"],
+ ["connect-src", "cspConnect"], ["img-src", "cspImage"], ["style-src", "cspStyle"],
+ ["unsafe-eval", "cspEval"], ["wasm-unsafe-eval", "cspWasm"]]) {
+ if (message.includes(token)) ret.push(code);
+ }
+ }
+ if (/localStorage|sessionStorage/.test(message) && /denied|SecurityError|insecure/i.test(message)) ret.push("storageUnavailable");
+ if (/webgl/i.test(message) && /fail|error|unsupported/i.test(message)) ret.push("webglUnavailable");
+ for (const [token, code] of [["INVALID_USER_KEY", "amapInvalidKey"], ["INVALID_USER_SCODE", "amapInvalidSecurityCode"],
+ ["INVALID_USER_DOMAIN", "amapDomainMismatch"], ["USERKEY_PLAT_NOMATCH", "amapPlatformMismatch"]]) {
+ if (message.includes(token)) ret.push(code);
+ }
+ return ret;
+};
+
+module.exports = {mapDiagnosticCodes, classifyMapConsoleMessage};
diff --git a/app/electron/mapHostDiagnostics.test.js b/app/electron/mapHostDiagnostics.test.js
new file mode 100644
index 0000000000..494b4790a4
--- /dev/null
+++ b/app/electron/mapHostDiagnostics.test.js
@@ -0,0 +1,20 @@
+const assert = require("node:assert/strict");
+const {test} = require("node:test");
+const {mapDiagnosticCodes, classifyMapConsoleMessage} = require("./mapHostDiagnostics");
+
+test("provider console diagnostics return fixed categories without SDK text, URL or credentials", () => {
+ const cases = [
+ ["Refused blob:https://secret.invalid/key to worker because it violates Content Security Policy worker-src 'none'", ["cspWorker"]],
+ ["Refused eval because Content Security Policy script-src does not allow unsafe-eval; key=private", ["cspScript", "cspEval"]],
+ ["SecurityError: Access to localStorage is denied for https://secret.invalid", ["storageUnavailable"]],
+ ["WebGL initialization failed", ["webglUnavailable"]],
+ ["INVALID_USER_SCODE credential=private", ["amapInvalidSecurityCode"]],
+ ["arbitrary provider text with key=private", []],
+ [undefined, []],
+ ];
+ for (const [message, expected] of cases) {
+ const result = classifyMapConsoleMessage(message);
+ assert.deepEqual(result, expected);
+ assert.ok(result.every(code => mapDiagnosticCodes.includes(code)));
+ }
+});
diff --git a/app/electron/mapHostManager.js b/app/electron/mapHostManager.js
index 33789ec4da..1e925174cf 100644
--- a/app/electron/mapHostManager.js
+++ b/app/electron/mapHostManager.js
@@ -5,6 +5,7 @@
const path = require("node:path");
const fs = require("node:fs/promises");
const {randomBytes} = require("node:crypto");
+const {mapDiagnosticCodes, classifyMapConsoleMessage} = require("./mapHostDiagnostics");
const {
hasUnsafeMapSwitches, normalizeMapOrigin, parseMapCreate, parseMapCommand, parseMapReply, parseMapGeometry,
isAllowedMapProviderURL, getMapRequestPolicy, createMapContentSecurityPolicy,
@@ -16,7 +17,7 @@ const withoutCredentials = (headers) => Object.fromEntries(Object.entries(header
.filter(([name]) => !["cookie", "authorization", "proxy-authorization"].includes(name.toLowerCase())));
// 此会话从不向任何内核发送网络请求,包括未设置密码的本机内核。
-const createMapSessionRouter = ({ses, origin, provider, appDir, readFile = fs.readFile, trackFetch = () => {}}) => {
+const createMapSessionRouter = ({ses, origin, provider, appDir, readFile = fs.readFile, trackFetch = () => {}, report = () => {}}) => {
let destroyed = false;
let documentRequested = false;
const requests = new Set();
@@ -39,6 +40,10 @@ const createMapSessionRouter = ({ses, origin, provider, appDir, readFile = fs.re
// 仅允许无网络权限的图片数据,以及本地预载后创建的 CSP worker。
allowed = ["image", "other"].includes(details.resourceType);
}
+ if (!allowed && !destroyed) {
+ report(details.url.startsWith("http:") && !details.url.startsWith(origin + "/") ?
+ "providerInsecureRequest" : "providerRequestDenied");
+ }
callback({cancel: !allowed});
});
ses.webRequest.onBeforeSendHeaders((details, callback) => {
@@ -63,6 +68,7 @@ const createMapSessionRouter = ({ses, origin, provider, appDir, readFile = fs.re
if (policy.document) headers["Content-Security-Policy"] = createMapContentSecurityPolicy(origin, provider);
return new Response(request.method === "HEAD" ? null : data, {headers});
} catch (_error) {
+ report("assetUnavailable");
return new Response("Not Found", {status: 404});
}
}
@@ -87,7 +93,11 @@ const createMapSessionRouter = ({ses, origin, provider, appDir, readFile = fs.re
try {
let url = request.url;
for (let redirects = 0; redirects <= 5; redirects++) {
- if (destroyed || abort.signal.aborted || !isAllowedMapProviderURL(url, provider)) break;
+ if (destroyed || abort.signal.aborted) break;
+ if (!isAllowedMapProviderURL(url, provider)) {
+ report(url.startsWith("http:") ? "providerInsecureRequest" : "providerRequestDenied");
+ break;
+ }
if (activeURL) trackFetch(activeURL, -1);
activeURL = url;
trackFetch(activeURL, 1);
@@ -99,6 +109,7 @@ const createMapSessionRouter = ({ses, origin, provider, appDir, readFile = fs.re
}
const response = await ses.fetch(url, {method: request.method, headers, credentials: "omit",
cache: "no-store", redirect: "manual", bypassCustomProtocolHandlers: true, signal: abort.signal});
+ if (response.status >= 400) report("providerHTTPFailure");
if ([301, 302, 303, 307, 308].includes(response.status)) {
const location = response.headers.get("location");
await response.body?.cancel();
@@ -127,7 +138,10 @@ const createMapSessionRouter = ({ses, origin, provider, appDir, readFile = fs.re
const {done, value} = await reader.read();
if (destroyed || abort.signal.aborted) throw new Error("Map request closed");
if (done) { controller.close(); finish(); } else controller.enqueue(value);
- } catch (error) { controller.error(error); finish(); }
+ } catch (error) {
+ if (!destroyed && !abort.signal.aborted) report("providerNetworkFailure");
+ controller.error(error); finish();
+ }
},
async cancel() { abort.abort(); await reader.cancel().catch(() => {}); finish(); },
});
@@ -135,6 +149,7 @@ const createMapSessionRouter = ({ses, origin, provider, appDir, readFile = fs.re
}
} catch (_error) {
// 服务商地址可能包含密钥,不记录请求地址或异常文本。
+ if (!destroyed && !abort.signal.aborted) report("providerNetworkFailure");
}
finish();
return deniedResponse();
@@ -269,23 +284,28 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContents
return {version: 1, instanceID: init.instanceID, error: "hostUnavailable"};
}
const ses = session.fromPartition("siyuan-map-" + randomID(), {cache: false});
- const router = createMapSessionRouter({ses, origin: owner.origin, provider: init.provider, appDir, readFile, trackFetch});
- let view;
+ let host, router, view;
+ const report = code => {
+ if (!host || host.destroyed || !mapDiagnosticCodes.includes(code) || host.diagnostics.has(code)) return;
+ host.diagnostics.add(code);
+ sendOwner(host, {version: 1, instanceID: init.instanceID, type: "diagnostic", code});
+ };
try {
+ router = createMapSessionRouter({ses, origin: owner.origin, provider: init.provider, appDir, readFile, trackFetch, report});
view = new WebContentsView({webPreferences: {session: ses, sandbox: true, contextIsolation: true,
webSecurity: true, nodeIntegration: false, nodeIntegrationInSubFrames: false,
nodeIntegrationInWorker: false, webviewTag: false, allowRunningInsecureContent: false,
navigateOnDragDrop: false, safeDialogs: true, disableDialogs: true, devTools: false,
spellcheck: false, backgroundThrottling: false, preload: path.join(__dirname, "mapHostPreload.js")}});
} catch (_error) {
- router.destroy();
- return {version: 1, instanceID: init.instanceID, error: "hostUnavailable"};
+ router?.destroy();
+ return {version: 1, instanceID: init.instanceID, error: "hostUnavailable", diagnostic: "hostSetupFailed"};
}
const contents = view.webContents;
// 全局 web-contents-created 会安装外部打开链接处理器,必须在加载前替换为拒绝。
contents.setWindowOpenHandler(() => ({action: "deny"}));
mapContents.add(contents.id);
- const host = {key, init, owner: event.sender, frame: event.senderFrame, win: owner.win, origin: owner.origin,
+ host = {key, init, owner: event.sender, frame: event.senderFrame, win: owner.win, origin: owner.origin, diagnostics: new Set(),
view, router, listeners: [], ids: new Set(), revision: -1, loaded: false, ready: false, bootstrapped: false, destroyed: false};
hosts.set(key, host);
const denyNavigation = event => event.preventDefault();
@@ -295,6 +315,10 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContents
listen(host, contents, "select-client-certificate", (event, _url, _certificates, callback) => { event.preventDefault(); callback(); });
listen(host, contents, "login", (event, _details, _auth, callback) => { event.preventDefault(); callback(); });
listen(host, contents, "certificate-error", (_event, _url, _error, _certificate, callback) => callback(false));
+ listen(host, contents, "console-message", (event, _level, legacyMessage) => {
+ for (const code of classifyMapConsoleMessage(event?.message ?? legacyMessage)) report(code);
+ });
+ listen(host, contents, "did-fail-load", () => report("documentLoadFailed"));
listen(host, contents, "render-process-gone", () => fail(host, "hostUnavailable"));
listen(host, contents, "destroyed", () => destroy(host));
listen(host, event.sender, "destroyed", () => destroy(host));
@@ -345,14 +369,17 @@ const createMapHostManager = ({app, ipcMain, session, BrowserWindow, WebContents
port1.start();
contents.postMessage("siyuan-map-port", {version: 1, instanceID: init.instanceID, nonce, provider: init.provider}, [port2]);
});
- host.timer = setTimeout(() => fail(host, "hostUnavailable"), 30000);
+ host.timer = setTimeout(() => {
+ report(host.bootstrapped ? "sdkTimeout" : "bootstrapTimeout");
+ fail(host, "hostUnavailable");
+ }, 30000);
host.timer.unref?.();
try {
view.setVisible(false);
// DOM 暂时不可见时也能完成初始化;此占位视图始终隐藏,不会覆盖编辑器。
view.setBounds({x: 0, y: 0, width: 1, height: 1});
owner.win.contentView.addChildView(view);
- void contents.loadURL(entryURL).catch(() => fail(host, "hostUnavailable"));
+ void contents.loadURL(entryURL).catch(() => { report("documentLoadFailed"); fail(host, "hostUnavailable"); });
} catch (_error) { fail(host, "hostUnavailable"); }
return {version: 1, instanceID: init.instanceID};
});
diff --git a/app/electron/mapHostManager.test.js b/app/electron/mapHostManager.test.js
index 2a232e5717..fb7cce32a3 100644
--- a/app/electron/mapHostManager.test.js
+++ b/app/electron/mapHostManager.test.js
@@ -313,6 +313,44 @@ test("an initially hidden or zero-size DOM can finish bootstrap without exposing
assert.equal(s.views[0].webContents.destroyed, true);
});
+test("known host diagnostics are bounded fixed codes and stop on disposal", () => {
+ const s = setup(); s.create();
+ const contents = s.views[0].webContents;
+ const message = "Content Security Policy worker-src 'none'; https://secret.invalid/?key=private";
+ contents.emit("console-message", {message});
+ contents.emit("console-message", {message});
+ contents.emit("console-message", {message: "unclassified private detail"});
+ assert.deepEqual(s.owner.sent.map(entry => entry[1]), [{...envelope, type: "diagnostic", code: "cspWorker"}]);
+ s.manager.destroyAll();
+ contents.emit("console-message", {message: "INVALID_USER_KEY"});
+ assert.equal(s.owner.sent.length, 1);
+});
+
+test("provider routing reports fixed transport failures without logging requests", async () => {
+ const diagnostics = [];
+ const {ses, router} = setupRouter({report: code => diagnostics.push(code)});
+ ses.before({url: "http://webapi.amap.com/maps?key=private"});
+ assert.deepEqual(diagnostics, ["providerInsecureRequest"]);
+ ses.fetch = async () => new Response("private body", {status: 403});
+ assert.equal((await ses.protocols.https(new Request("https://tiles.openfreemap.org/style?key=private"))).status, 403);
+ assert.equal(diagnostics.at(-1), "providerHTTPFailure");
+ ses.fetch = async () => { throw new Error("https://secret.invalid/?key=private"); };
+ await ses.protocols.https(new Request("https://tiles.openfreemap.org/style?key=private"));
+ assert.equal(diagnostics.at(-1), "providerNetworkFailure");
+ ses.fetch = async () => new Response(null, {status: 302, headers: {Location: "http://tiles.openfreemap.org/?key=private"}});
+ await ses.protocols.https(new Request("https://tiles.openfreemap.org/style"));
+ assert.equal(diagnostics.at(-1), "providerInsecureRequest");
+ ses.fetch = async () => new Response(new ReadableStream({pull(controller) { controller.error(new Error("private body failure")); }}));
+ const broken = await ses.protocols.https(new Request("https://tiles.openfreemap.org/style"));
+ await assert.rejects(broken.text());
+ assert.equal(diagnostics.at(-1), "providerNetworkFailure");
+ const count = diagnostics.length;
+ router.destroy();
+ ses.before({url: "http://webapi.amap.com/maps?key=private"});
+ assert.equal(diagnostics.length, count);
+ assert.equal(JSON.stringify(diagnostics).includes("private"), false);
+});
+
test("destroy and owner navigation close real contents, ports, requests and session; stale events cannot resurrect", () => {
const s = setup(); s.create(); s.load(); s.reply({type: "bootstrapReady"});
s.owner.emit("did-start-navigation", {isMainFrame: true, isSameDocument: false});
diff --git a/app/src/protyle/render/av/map/desktopTransport.test.ts b/app/src/protyle/render/av/map/desktopTransport.test.ts
index 384f51325e..3d51bd3450 100644
--- a/app/src/protyle/render/av/map/desktopTransport.test.ts
+++ b/app/src/protyle/render/av/map/desktopTransport.test.ts
@@ -28,7 +28,7 @@ const load = (ipc: unknown, browser = false, warnings: unknown[][] = []) => {
return result;
};
-const fixture = () => {
+const fixture = (warnings: unknown[][] = []) => {
const calls: Array<[string, any]> = [];
const listeners = new Map<string, (...args: any[]) => void>();
const domListeners = new Map<string, () => void>();
@@ -62,7 +62,7 @@ const fixture = () => {
getClientRects: () => [rect], getBoundingClientRect: () => rect, contains: (target: unknown) => target === container};
const errors: string[] = [], clicks: unknown[] = [];
let ready = 0;
- const api = load(ipc);
+ const api = load(ipc, false, warnings);
const host = api.createDesktopAVMapHost(container, {provider: "openfreemap", theme: "light",
credentials: {apiKey: "do-not-send", extra: "private"}, onError: (value: string) => errors.push(value),
onMarkerClick: (...args: unknown[]) => clicks.push(args), onReady: () => ready++});
@@ -83,6 +83,20 @@ const fixture = () => {
};
describe("desktop map transport", () => {
+ it("logs only allowlisted diagnostics for the current instance and ignores provider text", () => {
+ const warnings: unknown[][] = [];
+ const f = fixture(warnings);
+ f.reply({type: "diagnostic", code: "cspWorker", detail: "https://secret.invalid/?key=private"});
+ f.reply({type: "diagnostic", code: "https://secret.invalid/?key=private"});
+ f.reply({type: "diagnostic", code: "cspScript", instanceID: "wrong"});
+ assert.deepEqual(warnings, [["Database map diagnostic:", "cspWorker"]]);
+ assert.deepEqual(f.errors, []);
+ f.host.destroy();
+ f.reply({type: "diagnostic", code: "cspScript"});
+ assert.equal(warnings.length, 1);
+ const {mapDiagnosticCodes} = require("../../../../../electron/mapHostDiagnostics");
+ for (const code of mapDiagnosticCodes) assert.ok(source.includes(`"${code}"`));
+ });
it("logs only approved capability reason codes and never exception or response details", async () => {
for (const reason of ["ownerUnavailable", "notMainFrame", "notInitialized", "unregisteredOwner", "invalidKernelOrigin",
"originMismatch", "unsupportedDocument", "invalidDocument", "unsafeProcessSwitches"]) {
diff --git a/app/src/protyle/render/av/map/desktopTransport.ts b/app/src/protyle/render/av/map/desktopTransport.ts
index 5317850a63..863b7bf111 100644
--- a/app/src/protyle/render/av/map/desktopTransport.ts
+++ b/app/src/protyle/render/av/map/desktopTransport.ts
@@ -50,6 +50,19 @@ const capabilityFailureReasons = new Set([
"originMismatch", "unsupportedDocument", "invalidDocument", "unsafeProcessSwitches",
]);
+const mapDiagnosticCodes = new Set([
+ "hostSetupFailed", "assetUnavailable", "documentLoadFailed", "bootstrapTimeout", "sdkTimeout",
+ "providerRequestDenied", "providerInsecureRequest", "providerHTTPFailure", "providerNetworkFailure",
+ "cspScript", "cspWorker", "cspConnect", "cspImage", "cspStyle", "cspEval", "cspWasm",
+ "storageUnavailable", "webglUnavailable", "amapInvalidKey", "amapInvalidSecurityCode",
+ "amapDomainMismatch", "amapPlatformMismatch",
+]);
+const logMapDiagnostic = (code: unknown) => {
+ if (typeof code === "string" && mapDiagnosticCodes.has(code)) {
+ console.warn("Database map diagnostic:", code);
+ }
+};
+
export const isDesktopAVMapHostSupported = async (): Promise<boolean> => {
const ipc = getIPC();
if (!ipc) {
@@ -197,6 +210,7 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
};
const fail = (code: AVMapErrorCode) => {
if (!destroyed) {
+ console.warn("Database map failed:", code);
destroy();
options.onError(code);
}
@@ -210,6 +224,11 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
if (destroyed) {
return;
}
+ const diagnostic = value as {version?: unknown; instanceID?: unknown; type?: unknown; code?: unknown};
+ if (diagnostic?.version === AV_MAP_PROTOCOL_VERSION && diagnostic.instanceID === instanceID && diagnostic.type === "diagnostic") {
+ logMapDiagnostic(diagnostic.code);
+ return;
+ }
const reply = parseAVMapReply(value, instanceID);
if (reply?.type === "ready" && !ready) {
ready = true;
@@ -273,6 +292,7 @@ export const createDesktopAVMapHost = (container: HTMLElement, options: AVMapHos
return;
}
if (reply?.version !== AV_MAP_PROTOCOL_VERSION || reply.instanceID !== instanceID || reply.error) {
+ logMapDiagnostic(reply?.diagnostic);
fail(reply?.error === "unsupportedEnvironment" ? "unsupportedEnvironment" : "hostUnavailable");
return;
}