Skip to content

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

:bug: Preserve safe map SDK failure stages across the host boundary https://github.com/siyuan-note/siyuan/issues/20129

Daniel4c34e29b3202
diff --git a/app/electron/mapHostPolicy.js b/app/electron/mapHostPolicy.js
index 01ec7e2f28..a75316018a 100644
--- a/app/electron/mapHostPolicy.js
+++ b/app/electron/mapHostPolicy.js
@@ -96,7 +96,8 @@ const parseMapReply = (value, instanceID) => {
return {...base, type: value.type, id: value.id, revision: value.revision};
}
if (value.type === "error" && ["unsupportedEnvironment", "missingCredentials", "invalidConfiguration",
- "hostUnavailable", "sdkUnavailable", "mapUnavailable"].includes(value.code)) {
+ "hostUnavailable", "sdkUnavailable", "mapUnavailable", "sdkScriptLoadFailed", "sdkCallbackTimeout",
+ "sdkGlobalMissing", "mapCreationFailed", "mapReadyTimeout"].includes(value.code)) {
return {...base, type: "error", code: value.code};
}
};
diff --git a/app/electron/mapHostPolicy.test.js b/app/electron/mapHostPolicy.test.js
index c55f3ac248..17e0c26e98 100644
--- a/app/electron/mapHostPolicy.test.js
+++ b/app/electron/mapHostPolicy.test.js
@@ -68,6 +68,14 @@ test("point count is bounded and provider coordinate systems remain consistent",
assert.equal(parseMapCommand({...envelope, type: "setPoints", revision: 0, points}, instanceID, "amap").points.length, 0);
});
+test("map loading failures retain only fixed stage codes across the desktop boundary", () => {
+ for (const code of ["sdkScriptLoadFailed", "sdkCallbackTimeout", "sdkGlobalMissing", "mapCreationFailed", "mapReadyTimeout"]) {
+ assert.deepEqual(parseMapReply({...envelope, type: "error", code, message: "https://private.invalid/?key=secret",
+ stack: "secret"}, instanceID), {...envelope, type: "error", code});
+ }
+ assert.equal(parseMapReply({...envelope, type: "error", code: "https://private.invalid/?key=secret"}, instanceID), undefined);
+});
+
test("map creation fails closed for effective process security bypasses", () => {
const commandLine = switches => ({hasSwitch: name => switches.has(name), getSwitchValue: name => switches.get(name)});
assert.equal(hasUnsafeMapSwitches(commandLine(new Map())), false);
diff --git a/app/src/protyle/render/av/map/hostRuntime.test.ts b/app/src/protyle/render/av/map/hostRuntime.test.ts
index dbf8ec5c83..2b32c8f301 100644
--- a/app/src/protyle/render/av/map/hostRuntime.test.ts
+++ b/app/src/protyle/render/av/map/hostRuntime.test.ts
@@ -2,6 +2,7 @@ import * as assert from "node:assert/strict";
import {describe, it} from "node:test";
import {connectAVMapRuntime, startAVMapRuntime} from "./hostRuntime";
import {AVMapAdapter, AVMapAdapterCallbacks} from "./providers";
+import {AVMapLoadError} from "./protocol";
const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
const fixture = () => {
@@ -90,6 +91,31 @@ describe("isolated map runtime lifecycle", () => {
await send({type: "init", provider: "openfreemap", credentials: {}, theme: "light"});
assert.deepEqual(replies, [{version: 1, instanceID: "one", type: "error", code: "sdkUnavailable"}]);
});
+ it("preserves only controlled loading stages without passing exception fields to the owner", async () => {
+ for (const code of ["sdkScriptLoadFailed", "sdkCallbackTimeout", "sdkGlobalMissing", "mapCreationFailed", "mapReadyTimeout"] as const) {
+ const {port, replies, send} = fixture();
+ startAVMapRuntime(port as unknown as MessagePort, "one", "amap", {} as HTMLElement,
+ async () => { throw Object.assign(new AVMapLoadError(code), {message: "https://sdk.invalid?key=secret"}); });
+ await send({type: "init", provider: "amap", credentials: {apiKey: "fixture-key", securityCode: "fixture-code"}, theme: "light"});
+ assert.deepEqual(replies, [{version: 1, instanceID: "one", type: "error", code}]);
+ }
+ const {port, replies, send} = fixture();
+ startAVMapRuntime(port as unknown as MessagePort, "one", "openfreemap", {} as HTMLElement,
+ async () => { throw Object.assign(new Error("https://sdk.invalid?key=secret"), {code: "mapCreationFailed"}); });
+ await send({type: "init", provider: "openfreemap", credentials: {}, theme: "light"});
+ assert.deepEqual(replies, [{version: 1, instanceID: "one", type: "error", code: "sdkUnavailable"}]);
+ });
+ it("does not report a provider rejection caused by teardown", async () => {
+ const {port, replies, send} = fixture();
+ startAVMapRuntime(port as unknown as MessagePort, "one", "openfreemap", {} as HTMLElement,
+ async (_init, _container, _callbacks, signal) => new Promise<AVMapAdapter>((_resolve, reject) => {
+ signal.addEventListener("abort", () => reject(new AVMapLoadError("mapReadyTimeout")), {once: true});
+ }));
+ const pending = send({type: "init", provider: "openfreemap", credentials: {}, theme: "light"});
+ await send({type: "destroy"});
+ await pending;
+ assert.deepEqual(replies, []);
+ });
});
describe("isolated map bootstrap ordering", () => {
diff --git a/app/src/protyle/render/av/map/hostRuntime.ts b/app/src/protyle/render/av/map/hostRuntime.ts
index b333519f1b..3bae09f24b 100644
--- a/app/src/protyle/render/av/map/hostRuntime.ts
+++ b/app/src/protyle/render/av/map/hostRuntime.ts
@@ -1,5 +1,6 @@
import {
- AV_MAP_PROTOCOL_VERSION, AVMapErrorCode, AVMapInit, AVMapReply, isAVMapHandshake, isAVMapProvider, parseAVMapCommand,
+ AV_MAP_PROTOCOL_VERSION, AVMapErrorCode, AVMapInit, AVMapReply, getAVMapLoadErrorCode, isAVMapHandshake, isAVMapProvider,
+ parseAVMapCommand,
} from "./protocol";
import {AVMapAdapter, AVMapAdapterCallbacks} from "./providers";
import {loadAVMapAdapter} from "./providersLoader";
@@ -108,8 +109,8 @@ export const startAVMapRuntime = (port: MessagePort, instanceID: string, provide
} else if (adapter && command.type === "resize") {
adapter.resize();
}
- } catch (_error) {
- fail(adapter ? "mapUnavailable" : "sdkUnavailable");
+ } catch (error) {
+ fail(getAVMapLoadErrorCode(error) || (adapter ? "mapUnavailable" : "sdkUnavailable"));
}
};
port.start();
diff --git a/app/src/protyle/render/av/map/protocol.test.ts b/app/src/protyle/render/av/map/protocol.test.ts
index 7b516fda83..bdba8dd40b 100644
--- a/app/src/protyle/render/av/map/protocol.test.ts
+++ b/app/src/protyle/render/av/map/protocol.test.ts
@@ -1,7 +1,8 @@
import * as assert from "node:assert/strict";
import {describe, it} from "node:test";
import {
- AV_MAP_ATTRIBUTION_LINKS, AV_MAP_MERCATOR_MAX_LATITUDE, AVMapProvider, isAVMapHandshake, isAVMapProjectionSupported,
+ AV_MAP_ATTRIBUTION_LINKS, AV_MAP_MERCATOR_MAX_LATITUDE, AVMapLoadError, AVMapProvider, getAVMapLoadErrorCode,
+ isAVMapHandshake, isAVMapProjectionSupported,
parseAVMapCommand, parseAVMapReply, sanitizeAVMapCredentials, sanitizeAVMapPoints,
} from "./protocol";
@@ -91,4 +92,16 @@ describe("isolated map protocol", () => {
assert.equal(isAVMapHandshake({...handshake, ...invalid}, "hello", "instance", "nonce"), false);
}
});
+ it("admits only fixed loading stages and never treats arbitrary SDK exceptions as controlled errors", () => {
+ for (const code of ["sdkScriptLoadFailed", "sdkCallbackTimeout", "sdkGlobalMissing", "mapCreationFailed", "mapReadyTimeout"] as const) {
+ const error = new AVMapLoadError(code);
+ assert.equal(getAVMapLoadErrorCode(error), code);
+ assert.equal(error.message, "Map loading failed");
+ const reply = {version: 1, instanceID: "one", type: "error", code};
+ assert.deepEqual(parseAVMapReply({...reply, message: "https://sdk.invalid?key=secret", stack: "secret"}, "one"), reply);
+ }
+ assert.equal(getAVMapLoadErrorCode(Object.assign(new Error("secret"), {code: "mapCreationFailed"})), undefined);
+ assert.equal(getAVMapLoadErrorCode({code: "mapCreationFailed"}), undefined);
+ assert.equal(getAVMapLoadErrorCode(Object.assign(new AVMapLoadError("mapCreationFailed"), {code: "secret"})), undefined);
+ });
});
diff --git a/app/src/protyle/render/av/map/protocol.ts b/app/src/protyle/render/av/map/protocol.ts
index b55f18e879..1983b1db1d 100644
--- a/app/src/protyle/render/av/map/protocol.ts
+++ b/app/src/protyle/render/av/map/protocol.ts
@@ -5,8 +5,26 @@ export const AV_MAP_MERCATOR_MAX_LATITUDE = 85.0511287798066;
export type AVMapProvider = "openfreemap" | "amap" | "tencent" | "baidu";
export type AVMapTheme = "light" | "dark";
export type AVMapCoordinateSystem = "wgs84" | "gcj02" | "bd09";
+export type AVMapLoadErrorCode = "sdkScriptLoadFailed" | "sdkCallbackTimeout" | "sdkGlobalMissing" |
+ "mapCreationFailed" | "mapReadyTimeout";
export type AVMapErrorCode = "unsupportedEnvironment" | "missingCredentials" | "invalidConfiguration" |
- "hostUnavailable" | "sdkUnavailable" | "mapUnavailable";
+ "hostUnavailable" | "sdkUnavailable" | "mapUnavailable" | AVMapLoadErrorCode;
+
+const mapLoadErrorCodes = new Set<AVMapLoadErrorCode>([
+ "sdkScriptLoadFailed", "sdkCallbackTimeout", "sdkGlobalMissing", "mapCreationFailed", "mapReadyTimeout",
+]);
+const isAVMapLoadErrorCode = (value: unknown): value is AVMapLoadErrorCode =>
+ typeof value === "string" && mapLoadErrorCodes.has(value as AVMapLoadErrorCode);
+
+// 内部加载阶段只保留固定错误码,不保存 SDK 原始异常、地址或凭据。
+export class AVMapLoadError extends Error {
+ constructor(readonly code: AVMapLoadErrorCode) {
+ super("Map loading failed");
+ }
+}
+
+export const getAVMapLoadErrorCode = (error: unknown): AVMapLoadErrorCode | undefined =>
+ error instanceof AVMapLoadError && isAVMapLoadErrorCode(error.code) ? error.code : undefined;
// 父页面仅展示固定官方署名链接,不接受隔离框架返回的 URL 或 HTML。
export const AV_MAP_ATTRIBUTION_LINKS: Readonly<Record<AVMapProvider, ReadonlyArray<{label: string; href: string}>>> = {
@@ -163,8 +181,8 @@ export const parseAVMapReply = (value: unknown, instanceID: string): AVMapReply
if (input.type === "markerClick" && isAVMapIdentifier(input.id) && isAVMapRevision(input.revision)) {
return {...envelope, type: "markerClick", id: input.id, revision: input.revision};
}
- if (input.type === "error" && ["unsupportedEnvironment", "missingCredentials", "invalidConfiguration",
- "hostUnavailable", "sdkUnavailable", "mapUnavailable"].includes(input.code as string)) {
+ if (input.type === "error" && (["unsupportedEnvironment", "missingCredentials", "invalidConfiguration",
+ "hostUnavailable", "sdkUnavailable", "mapUnavailable"].includes(input.code as string) || isAVMapLoadErrorCode(input.code))) {
return {...envelope, type: "error", code: input.code as AVMapErrorCode};
}
};
diff --git a/app/src/protyle/render/av/map/providersLoader.test.ts b/app/src/protyle/render/av/map/providersLoader.test.ts
index 19601d9680..c3fdce0b55 100644
--- a/app/src/protyle/render/av/map/providersLoader.test.ts
+++ b/app/src/protyle/render/av/map/providersLoader.test.ts
@@ -1,14 +1,20 @@
import * as assert from "node:assert/strict";
import {describe, it} from "node:test";
-import {AVMapInit, AVMapProvider} from "./protocol";
+import {AVMapInit, AVMapLoadError, AVMapLoadErrorCode, AVMapProvider} from "./protocol";
import {loadAVMapAdapter} from "./providersLoader";
import {getAVMapLockedPolicy, prepareAVMapBootstrap} from "./bootstrap";
-const fixture = (ready = true, scriptError = false) => {
+const fixture = (ready = true, scriptError = false,
+ options: {skipCallback?: boolean; missingSDK?: boolean; mapError?: boolean; appendError?: boolean} = {}) => {
const requested: any[] = [];
let destroyed = 0;
class FakeMap {
- constructor() { requested.push({mapCreated: true}); }
+ constructor() {
+ requested.push({mapCreated: true});
+ if (options.mapError) {
+ throw new Error("https://fixture.invalid?key=private");
+ }
+ }
on(type: string, callback: () => void) {
if (ready && ["load", "complete", "tilesloaded"].includes(type)) {
queueMicrotask(callback);
@@ -36,7 +42,7 @@ const fixture = (ready = true, scriptError = false) => {
removeEventListener() {}
}, MarkerStyle: class {}, LatLng: class {}, Point: class {}, setWorkerUrl: (url: string) => requested.push({worker: url})};
const scope: any = {
- setTimeout, clearTimeout, AMap: sdk, TMap: sdk, BMap: sdk, maplibregl: sdk,
+ setTimeout, clearTimeout, maplibregl: sdk,
BMAP_COORD_BD09: "official-bd09", BMAP_COORD_GCJ02: "official-gcj02",
fetch: async (url: string, options: unknown) => {
requested.push({url, options});
@@ -53,14 +59,23 @@ const fixture = (ready = true, scriptError = false) => {
queueMicrotask(() => element.onload?.());
}
if (element.tag === "script") {
+ if (options.appendError) {
+ throw new Error("https://fixture.invalid?key=private");
+ }
queueMicrotask(() => {
if (scriptError) {
element.onerror?.(new Error("https://fixture.invalid?key=private"));
return;
}
- const callback = new URL(element.src, "https://fixture.invalid").searchParams.get("callback");
+ const url = new URL(element.src, "https://fixture.invalid");
+ const callback = url.searchParams.get("callback");
if (callback) {
- scope[callback]?.();
+ if (!options.skipCallback) {
+ if (!options.missingSDK) {
+ scope[{"webapi.amap.com": "AMap", "map.qq.com": "TMap", "api.map.baidu.com": "BMap"}[url.hostname]] = sdk;
+ }
+ scope[callback]?.();
+ }
} else {
element.onload?.();
}
@@ -158,7 +173,64 @@ describe("isolated provider loading", () => {
const {container, destroyed} = fixture(true, true);
await prepareAVMapBootstrap(container.ownerDocument.defaultView, "amap", new AbortController().signal);
await assert.rejects(loadAVMapAdapter(init("amap"), container, {onMarkerClick() {}, onError() {}},
- new AbortController().signal), {message: "sdkUnavailable"});
+ new AbortController().signal), {code: "sdkScriptLoadFailed", message: "Map loading failed"});
+ assert.equal(destroyed(), 0);
+ });
+ it("retains distinct script, callback, SDK global, map construction and ready timeout failures", async () => {
+ const cases: Array<{code: AVMapLoadErrorCode; ready?: boolean;
+ options: {skipCallback?: boolean; missingSDK?: boolean; mapError?: boolean; appendError?: boolean};
+ timeout?: boolean; callbackAssignmentError?: boolean}> = [
+ {code: "sdkScriptLoadFailed", options: {appendError: true}},
+ {code: "sdkScriptLoadFailed", options: {}, callbackAssignmentError: true},
+ {code: "sdkCallbackTimeout", options: {skipCallback: true}, timeout: true},
+ {code: "sdkGlobalMissing", options: {missingSDK: true}},
+ {code: "mapCreationFailed", options: {mapError: true}},
+ {code: "mapReadyTimeout", ready: false, options: {}, timeout: true},
+ ];
+ for (const item of cases) {
+ const {scope, container, destroyed} = fixture(item.ready, false, item.options);
+ const timers = new Map<number, () => void>();
+ let timerID = 0;
+ scope.setTimeout = (callback: () => void) => { timers.set(++timerID, callback); return timerID; };
+ scope.clearTimeout = (id: number) => timers.delete(id);
+ const signal = new AbortController().signal;
+ await prepareAVMapBootstrap(scope, "amap", signal);
+ if (item.callbackAssignmentError) {
+ Object.defineProperty(scope, "__siyuanMapSDKReady", {
+ set() { throw new Error("https://fixture.invalid?key=private"); },
+ });
+ }
+ const pending = loadAVMapAdapter(init("amap"), container, {onMarkerClick() {}, onError() {}}, signal);
+ const rejected = assert.rejects(pending, (error: unknown) => {
+ assert.ok(error instanceof AVMapLoadError);
+ assert.equal(error.code, item.code);
+ assert.equal(error.message, "Map loading failed");
+ assert.equal(JSON.stringify(error).includes("private"), false);
+ return true;
+ });
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ if (item.timeout) {
+ assert.equal(timers.size, 1);
+ timers.values().next().value();
+ }
+ await rejected;
+ assert.equal(timers.size, 0);
+ assert.equal(scope.__siyuanMapSDKReady, undefined);
+ assert.equal(destroyed(), item.code === "mapReadyTimeout" ? 1 : 0);
+ }
+ });
+ it("does not report an aborted SDK callback wait as a load failure or timeout", async () => {
+ const {scope, container, destroyed} = fixture(true, false, {skipCallback: true});
+ const abort = new AbortController();
+ await prepareAVMapBootstrap(scope, "amap", abort.signal);
+ const pending = loadAVMapAdapter(init("amap"), container, {onMarkerClick() {}, onError() {}}, abort.signal);
+ abort.abort();
+ await assert.rejects(pending, (error: unknown) => {
+ assert.ok(error instanceof Error && !(error instanceof AVMapLoadError));
+ assert.equal(error.message, "sdkUnavailable");
+ return true;
+ });
+ assert.equal(scope.__siyuanMapSDKReady, undefined);
assert.equal(destroyed(), 0);
});
it("prepares local files before locking and only creates a worker blob/map after locking", async () => {
diff --git a/app/src/protyle/render/av/map/providersLoader.ts b/app/src/protyle/render/av/map/providersLoader.ts
index 80063672eb..f0780d5dd3 100644
--- a/app/src/protyle/render/av/map/providersLoader.ts
+++ b/app/src/protyle/render/av/map/providersLoader.ts
@@ -1,4 +1,4 @@
-import {AVMapInit, AVMapProvider} from "./protocol";
+import {AVMapInit, AVMapLoadError, AVMapLoadErrorCode, AVMapProvider, getAVMapLoadErrorCode} from "./protocol";
import {AVMapAdapter, AVMapAdapterCallbacks, createAVMapAdapter} from "./providers";
const SDK_CALLBACK = "__siyuanMapSDKReady";
@@ -16,10 +16,17 @@ const preparedAssets = new WeakMap<Window, AVMapPreparedAssets>();
const loadScript = (scope: Window, source: string, signal: AbortSignal, callback = false): Promise<void> => {
return new Promise((resolve, reject) => {
- const script = scope.document.createElement("script");
+ let script: HTMLScriptElement;
+ try {
+ script = scope.document.createElement("script");
+ } catch (_error) {
+ reject(new AVMapLoadError("sdkScriptLoadFailed"));
+ return;
+ }
const globals = scope as unknown as Record<string, any>;
let settled = false;
- const finish = (success: boolean) => {
+ let callbackInstalled = false;
+ const finish = (success: boolean, code?: AVMapLoadErrorCode) => {
if (settled) {
return;
}
@@ -28,32 +35,37 @@ const loadScript = (scope: Window, source: string, signal: AbortSignal, callback
script.onload = null;
script.onerror = null;
signal.removeEventListener("abort", abort);
- if (callback) {
+ if (callbackInstalled) {
delete globals[SDK_CALLBACK];
}
if (success) {
resolve();
} else {
script.remove();
- reject(new Error("sdkUnavailable"));
+ reject(code ? new AVMapLoadError(code) : new Error("sdkUnavailable"));
}
};
const abort = () => finish(false);
- const timer = scope.setTimeout(() => finish(false), 20000);
+ const timer = scope.setTimeout(() => finish(false, callback ? "sdkCallbackTimeout" : "sdkScriptLoadFailed"), 20000);
signal.addEventListener("abort", abort, {once: true});
- if (callback) {
- globals[SDK_CALLBACK] = () => finish(true);
- } else {
- script.onload = () => finish(true);
- }
- script.onerror = () => finish(false);
- script.src = source;
- script.referrerPolicy = "strict-origin-when-cross-origin";
- script.async = true;
- if (signal.aborted) {
- finish(false);
- } else {
- scope.document.head.appendChild(script);
+ try {
+ if (callback) {
+ globals[SDK_CALLBACK] = () => finish(true);
+ callbackInstalled = true;
+ } else {
+ script.onload = () => finish(true);
+ }
+ script.onerror = () => finish(false, "sdkScriptLoadFailed");
+ script.src = source;
+ script.referrerPolicy = "strict-origin-when-cross-origin";
+ script.async = true;
+ if (signal.aborted) {
+ finish(false);
+ } else {
+ scope.document.head.appendChild(script);
+ }
+ } catch (_error) {
+ finish(false, "sdkScriptLoadFailed");
}
});
};
@@ -162,13 +174,16 @@ export const loadAVMapAdapter = async (init: AVMapInit, container: HTMLElement,
await loadScript(scope, scriptURL.href, signal, true);
sdk = globals[provider === "amap" ? "AMap" : provider === "tencent" ? "TMap" : "BMap"];
}
- if (signal.aborted || !sdk) {
+ if (signal.aborted) {
throw new Error("sdkUnavailable");
}
+ if (!sdk) {
+ throw new AVMapLoadError("sdkGlobalMissing");
+ }
let adapter: AVMapAdapter;
await new Promise<void>((resolve, reject) => {
let settled = false;
- const finish = (success: boolean) => {
+ const finish = (success: boolean, code?: AVMapLoadErrorCode) => {
if (settled) {
return;
}
@@ -181,12 +196,12 @@ export const loadAVMapAdapter = async (init: AVMapInit, container: HTMLElement,
try {
adapter?.destroy();
} finally {
- reject(new Error("mapUnavailable"));
+ reject(code ? new AVMapLoadError(code) : new Error("mapUnavailable"));
}
}
};
const abort = () => finish(false);
- const timer = scope.setTimeout(abort, 20000);
+ const timer = scope.setTimeout(() => finish(false, "mapReadyTimeout"), 20000);
signal.addEventListener("abort", abort, {once: true});
try {
adapter = createAVMapAdapter(provider, sdk, container, {...callbacks,
@@ -198,7 +213,7 @@ export const loadAVMapAdapter = async (init: AVMapInit, container: HTMLElement,
finish(false);
}
} catch (_error) {
- finish(false);
+ finish(false, "mapCreationFailed");
}
});
const destroy = adapter.destroy;
@@ -210,8 +225,12 @@ export const loadAVMapAdapter = async (init: AVMapInit, container: HTMLElement,
}
};
return adapter;
- } catch (_error) {
+ } catch (error) {
assets.destroy();
+ const code = getAVMapLoadErrorCode(error);
+ if (code) {
+ throw new AVMapLoadError(code);
+ }
throw new Error("sdkUnavailable");
}
};