An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Support connecting the desktop app to a remote kernel https://github.com/siyuan-note/siyuan/issues/18343
Danield64e5e079d34
diff --git a/app/electron/boot.html b/app/electron/boot.htmlindex 6dc7a5f2a1..e61971cf10 100644--- a/app/electron/boot.html+++ b/app/electron/boot.html@@ -164,19 +164,7 @@</div><script>const getSearch = (key) => {- if (window.location.search.indexOf('?') === -1) {- return ''- }- let value = ''- const data = window.location.search.split('?')[1].split('&')- data.find(item => {- const keyValue = item.split('=')- if (keyValue[0] === key) {- value = keyValue[1]- return true- }- })- return value+ return new URLSearchParams(window.location.search).get(key) || ''}const escapeBootAppearanceHTML = (value) => String(value).replace(/[&<>"']/g, (character) => ({@@ -318,7 +306,8 @@let bootAppearanceRequestID = 0;const loadBootAppearance = (port, frontend) => {- if (getSearch("appearance") === "0" || getSearch("safe") === "1") {+ const remoteOrigin = getSearch("remote");+ if (remoteOrigin || getSearch("appearance") === "0" || getSearch("safe") === "1") {return;}const normalizedPort = String(port);@@ -449,9 +438,11 @@(async () => {const v = getSearch('v')const port = getSearch('port') || '6806'+ const remoteOrigin = getSearch('remote')+ const serverURL = remoteOrigin || 'http://127.0.0.1:' + portconst progressEl = document.getElementById('progress')const detailsEl = document.getElementById('details')- detailsEl.textContent = "v" + v + ' Booting kernel...'+ detailsEl.textContent = "v" + v + (remoteOrigin ? ' Connecting to remote kernel...' : ' Booting kernel...')loadBootAppearance(port, "desktop");// 随机起始基数(15~25),等待内核进度时先平滑填充到此值@@ -527,7 +518,7 @@let progressing = falseconst subscribe = () => {- const es = new EventSource('http://127.0.0.1:' + port + '/api/system/bootProgressSSE')+ const es = new EventSource(serverURL + '/api/system/bootProgressSSE')es.onmessage = (event) => {const progressData = JSON.parse(event.data)// 内核进度按比例映射到 baseProgress~100 区间,从当前显示值继续递增@@ -563,7 +554,9 @@}}}- subscribe()+ if (!remoteOrigin) {+ subscribe()+ }})()</script></body>diff --git a/app/electron/main.js b/app/electron/main.jsindex b1e02753af..95c4c69f0e 100644--- a/app/electron/main.js+++ b/app/electron/main.js@@ -46,6 +46,22 @@ const {shouldDownloadAppleSilicon,shouldShowAppleSiliconWarning,} = require("./appleSilicon");+const {+ createRemoteDocumentContentSecurityPolicy,+ getArgFrom,+ getRemoteKernelRedirectDecision,+ getRemoteKernelRequestPolicy,+ getRemoteKernelWebRequestDestination,+ getRemoteKernelVersionStatus,+ getUnsafeRemoteChromiumSwitchName,+ isAllowedRemoteExternalURL,+ normalizeRemoteKernelOrigin,+ remoteKernelActiveStorageTypes,+ shouldBlockRemoteFrameNavigation,+ shouldForwardRemoteDeepLink,+ shouldTrustLocalKernelCertificate,+ unsafeRemoteChromiumSwitchNames,+} = require("./remoteKernel");process.noAsar = true;const appDir = path.dirname(app.getAppPath());@@ -73,6 +89,16 @@ let bootAppearanceFallback = false;let latestActiveWindow;let firstOpen = false;let workspaces = []; // workspaceDir, id, port, webContentsId, browserWindow, tray, hideShortcut+const windowKernelTargets = new Map();+const initializedWindowIds = new Set();+const pendingRemoteOpenURLs = [];++const flushPendingRemoteOpenURLs = (window) => {+ if (!window || window.isDestroyed()) {+ return;+ }+ pendingRemoteOpenURLs.splice(0).forEach((url) => window.webContents.send("siyuan-open-url", url));+};const getGlobalShortcutWorkspace = (fallbackWorkspace) => {const focusedWorkspace = workspaces.find(item => item.browserWindow &&@@ -105,10 +131,67 @@ const pendingSpellcheckRequests = new Map();const pendingNativeContextMenuRequests = new Map();const spellcheckContextMenuContents = new Set();const normalizeClipboardText = (text) => text.replace(/\r\n?/g, "\n");+const escapeHTML = (value) => String(value).replace(/[&<>"']/g, (character) => ({+ "&": "&",+ "<": "<",+ ">": ">",+ "\"": """,+ "'": "'",+})[character]);const isOpenAsHidden = function () {return 1 === workspaces.length && openAsHidden;};+const getArg = (name) => getArgFrom(process.argv, name);++const createLocalKernelTarget = (port = kernelPort) => ({+ mode: "local",+ origin: "https://127.0.0.1:" + port,+ ownsKernel: true,+ port: port.toString(),+});++let remoteKernelTarget;+let remoteKernelArgError;+const remoteKernelArg = getArg("--remote");+if (remoteKernelArg !== undefined) {+ try {+ const origin = normalizeRemoteKernelOrigin(remoteKernelArg);+ remoteKernelTarget = {+ mode: "remote",+ origin,+ ownsKernel: false,+ port: "",+ };+ } catch (error) {+ remoteKernelArgError = error;+ }+}++if (remoteKernelTarget) {+ const configuredUnsafeSwitchNames = new Set(process.argv.map(getUnsafeRemoteChromiumSwitchName).filter(Boolean));+ unsafeRemoteChromiumSwitchNames.forEach((switchName) => {+ if (app.commandLine.hasSwitch(switchName)) {+ configuredUnsafeSwitchNames.add(switchName);+ }+ });+ const disabledFeatures = app.commandLine.getSwitchValue("disable-features");+ if (getUnsafeRemoteChromiumSwitchName("--disable-features=" + disabledFeatures)) {+ configuredUnsafeSwitchNames.add("disable-features");+ }+ if (configuredUnsafeSwitchNames.size > 0) {+ configuredUnsafeSwitchNames.forEach((switchName) => app.commandLine.removeSwitch(switchName));+ remoteKernelArgError = new Error("--remote cannot be combined with switches that weaken web security: " ++ Array.from(configuredUnsafeSwitchNames).join(", "));+ remoteKernelArgError.code = "ERR_REMOTE_UNSAFE_CHROMIUM_SWITCH";+ }+}++const initialSiYuanOpenURL = process.argv.find((arg) => arg.startsWith("siyuan://"));+if (remoteKernelTarget && !remoteKernelArgError && initialSiYuanOpenURL) {+ pendingRemoteOpenURLs.push(initialSiYuanOpenURL);+}+const isMatchingContextMenuRequest = (context, request) => {return Number.isFinite(request.requestedAt) &&context.createdAt >= request.requestedAt &&@@ -249,9 +332,11 @@ if (isDevEnv && process.defaultApp && process.argv.length >= 2) {app.setAsDefaultProtocolClient("siyuan");}-app.commandLine.appendSwitch("disable-web-security");app.commandLine.appendSwitch("auto-detect", "false");-app.commandLine.appendSwitch("no-proxy-server");+if (!remoteKernelTarget) {+ app.commandLine.appendSwitch("disable-web-security");+ app.commandLine.appendSwitch("no-proxy-server");+}app.commandLine.appendSwitch("enable-features", "PlatformHEVCDecoderSupport");app.commandLine.appendSwitch("xdg-portal-required-version", "4");// 本地 HTTPS 页面加载 HTTP 外链图时,禁止自动升级为 HTTPS@@ -266,7 +351,10 @@ if (!app.isPackaged) {for (let i = argStart; i < process.argv.length; i++) {let arg = process.argv[i];- if (arg.startsWith("--workspace=") || arg.startsWith("--openAsHidden") || arg.startsWith("--port=") || arg.startsWith("--safe-mode=") || arg.startsWith("--lang=") || arg.startsWith("siyuan://")) {+ if (arg.startsWith("--workspace=") || arg.startsWith("--openAsHidden") || arg.startsWith("--port=") ||+ arg.startsWith("--safe-mode=") || arg.startsWith("--lang=") || arg === "--remote" ||+ arg.startsWith("--remote=") ||+ arg.startsWith("siyuan://")) {// 跳过内置参数if (arg.startsWith("--openAsHidden")) {openAsHidden = true;@@ -275,12 +363,16 @@ for (let i = argStart; i < process.argv.length; i++) {continue;}+ if (remoteKernelTarget && getUnsafeRemoteChromiumSwitchName(arg)) {+ continue;+ }+app.commandLine.appendSwitch(arg);writeLog("command line switch [" + arg + "]");}try {- firstOpen = !fs.existsSync(path.join(confDir, "workspace.json"));+ firstOpen = !remoteKernelTarget && !fs.existsSync(path.join(confDir, "workspace.json"));if (!fs.existsSync(confDir)) {fs.mkdirSync(confDir, {mode: 0o755, recursive: true});}@@ -290,20 +382,11 @@ try {app.exit();}-// 解析命令行参数,参数需以 `name=value` 形式传入 https://github.com/siyuan-note/siyuan/issues/14748-const getArg = (name) => {- for (let i = 0; i < process.argv.length; i++) {- if (process.argv[i].startsWith(name)) {- return process.argv[i].split("=")[1];- }- }-};-// 检测上次打开的工作空间是否丢失 https://github.com/siyuan-note/siyuan/issues/14748let lastWorkspaceMissing = false;let missingWorkspacePath = "";let availableWorkspaces = [];-if (!firstOpen && !getArg("--workspace")) {+if (!remoteKernelTarget && !firstOpen && !getArg("--workspace")) {// 显式通过命令行指定工作空间时尊重用户参数,跳过检测try {const wsFile = path.join(confDir, "workspace.json");@@ -326,7 +409,7 @@ if (!firstOpen && !getArg("--workspace")) {// 读取上次打开的工作空间路径,用于崩溃恢复时默认选中该工作空间let lastWorkspacePath = "";-if (!firstOpen && !getArg("--workspace")) {+if (!remoteKernelTarget && !firstOpen && !getArg("--workspace")) {try {const wsFile = path.join(confDir, "workspace.json");if (fs.existsSync(wsFile)) {@@ -340,27 +423,46 @@ if (!firstOpen && !getArg("--workspace")) {}}-const windowNavigate = (currentWindow, windowType) => {+const openExternalURL = (url, remoteMode = false) => {+ if (remoteMode && !isAllowedRemoteExternalURL(url)) {+ writeLog("blocked external protocol in remote kernel mode [url=" + url + "]");+ return;+ }+ shell.openExternal(url);+};++const windowNavigate = (currentWindow, windowType, kernelOrigin, remoteMode = false) => {currentWindow.webContents.on("will-navigate", (event) => {- const url = event.url;- if (url.startsWith(localServer)) {- try {- const pathname = new URL(url).pathname;- if (windowType === "app" && ["/", "/stage/build/app/", "/check-auth"].includes(pathname) ||- (windowType === "window" && ["/stage/build/app/window.html", "/check-auth"].includes(pathname)) ||- (windowType === "export" && pathname.startsWith("/export/temp/"))) {- return;- }- } catch (e) {+ try {+ const targetURL = new URL(event.url);+ if (targetURL.origin === kernelOrigin && (+ windowType === "app" && ["/stage/build/app/", "/check-auth"].includes(targetURL.pathname) ||+ windowType === "app" && !remoteMode && targetURL.pathname === "/" ||+ windowType === "window" && ["/stage/build/app/window.html", "/check-auth"].includes(targetURL.pathname) ||+ windowType === "export" && targetURL.pathname.startsWith("/export/temp/")+ )) {return;}+ } catch (e) {+ // 无效链接交给系统浏览器处理。}// 其他链接使用浏览器打开event.preventDefault();- shell.openExternal(url);+ openExternalURL(event.url, remoteMode);});};+const getWindowPathname = (window) => {+ if (!window || window.isDestroyed() || window.webContents.isDestroyed()) {+ return "";+ }+ try {+ return new URL(window.webContents.getURL()).pathname;+ } catch (error) {+ return "";+ }+};+const setProxy = (proxyURL, webContents, proxyMode) => {if (proxyMode === "system" || (!proxyMode && proxyURL.startsWith("://"))) {console.log("network proxy [system]");@@ -679,17 +781,20 @@ const markExpectedRendererExit = (window) => {}};-const exitApp = (port, errorWindowId) => {- const workspaceIndex = workspaces.findIndex((item) => port.toString() === item.port.toString());- const workspace = -1 < workspaceIndex ? workspaces[workspaceIndex] : undefined;- const mainWindow = workspace ? workspace.browserWindow : undefined;- const tray = workspace ? workspace.tray : undefined;+const exitWorkspace = (workspace, errorWindowId) => {+ if (!workspace) {+ return;+ }+ const workspaceIndex = workspaces.indexOf(workspace);+ const mainWindow = workspace.browserWindow;+ const tray = workspace.tray;+ const kernelOrigin = workspace.kernelTarget?.origin;- // 关闭端口相同的所有非主窗口+ // 关闭连接同一内核的所有非主窗口。BrowserWindow.getAllWindows().forEach((item) => {try {const currentURL = new URL(item.getURL());- if (port.toString() === currentURL.port.toString()) {+ if (kernelOrigin && kernelOrigin === currentURL.origin) {if (!mainWindow || mainWindow.id !== item.id) {item.destroy();}@@ -698,7 +803,7 @@ const exitApp = (port, errorWindowId) => {// load file is not a url}});- if (workspace) {+ if (workspaceIndex > -1) {if (workspaces.length > 1 && mainWindow && !mainWindow.isDestroyed()) {markExpectedRendererExit(mainWindow);mainWindow.destroy();@@ -752,12 +857,315 @@ const exitApp = (port, errorWindowId) => {}};+const exitApp = (port, errorWindowId) => {+ if (port === undefined || port === null) {+ return;+ }+ const workspace = workspaces.find((item) => item.ownsKernel && port.toString() === item.port.toString());+ exitWorkspace(workspace, errorWindowId);+};+const localServer = "https://127.0.0.1";const getServer = (port = kernelPort) => {return localServer + ":" + port;};+const getKernelTarget = (target = kernelPort) => {+ if (target && typeof target === "object" && target.origin) {+ return target;+ }+ return createLocalKernelTarget(target);+};++const rememberWindowKernelTarget = (window, target) => {+ const webContentsId = window.webContents.id;+ windowKernelTargets.set(webContentsId, target);+ if (target.mode === "remote") {+ window.webContents.on("will-frame-navigate", (event) => {+ if (shouldBlockRemoteFrameNavigation({isMainFrame: event.isMainFrame})) {+ event.preventDefault();+ writeLog("blocked subframe navigation in remote kernel mode [url=" + event.url + "]");+ }+ });+ window.webContents.on("will-attach-webview", (event) => {+ event.preventDefault();+ writeLog("blocked webview creation in remote kernel mode");+ });+ }+ window.webContents.on("did-start-navigation", (details) => {+ if (details.isMainFrame && !details.isSameDocument) {+ initializedWindowIds.delete(webContentsId);+ }+ });+ window.webContents.once("destroyed", () => {+ initializedWindowIds.delete(webContentsId);+ windowKernelTargets.delete(webContentsId);+ });+};++const getWindowKernelTarget = (webContentsId) => windowKernelTargets.get(webContentsId);++const getLocalRemoteResource = (pathname) => {+ let decodedPath;+ try {+ decodedPath = decodeURIComponent(pathname);+ } catch (error) {+ return;+ }+ if (decodedPath.includes("\0")) {+ return;+ }++ if (decodedPath === "/check-auth") {+ return isDevEnv+ ? path.join(appDir, "electron", "remote-auth.html")+ : path.join(appDir, "app", "electron", "remote-auth.html");+ }++ let resourceRoot;+ let relativePath;+ if (decodedPath.startsWith("/stage/")) {+ resourceRoot = path.join(appDir, "stage");+ relativePath = decodedPath.slice("/stage/".length);+ } else if (decodedPath.startsWith("/appearance/")) {+ resourceRoot = path.join(appDir, "appearance");+ relativePath = decodedPath.slice("/appearance/".length);+ } else {+ return;+ }++ let resourcePath = path.resolve(resourceRoot, relativePath);+ const relative = path.relative(resourceRoot, resourcePath);+ if (!relative || path.isAbsolute(relative) || relative === ".." || relative.startsWith(".." + path.sep)) {+ if (!relative && decodedPath.endsWith("/")) {+ resourcePath = path.join(resourcePath, "index.html");+ } else {+ return;+ }+ }+ try {+ if (fs.statSync(resourcePath).isDirectory()) {+ resourcePath = path.join(resourcePath, "index.html");+ }+ if (fs.statSync(resourcePath).isFile()) {+ return resourcePath;+ }+ } catch (error) {+ return;+ }+};++let remoteProtocolInstalled = false;+const installRemoteFrontendProtocol = (target) => {+ if (remoteProtocolInstalled) {+ return;+ }+ const scheme = new URL(target.origin).protocol.slice(0, -1);+ session.defaultSession.webRequest.onBeforeRequest((details, callback) => {+ const destination = getRemoteKernelWebRequestDestination(details.resourceType);+ let requestPolicy = "remote";+ if (destination) {+ try {+ const requestURL = new URL(details.url);+ const isTargetOrigin = requestURL.origin === target.origin;+ const localResource = isTargetOrigin ? getLocalRemoteResource(requestURL.pathname) : undefined;+ requestPolicy = getRemoteKernelRequestPolicy({+ method: details.method,+ pathname: requestURL.pathname,+ destination,+ localResourceAvailable: Boolean(localResource),+ isTargetOrigin,+ });+ } catch (error) {+ requestPolicy = "deny-active-content";+ }+ }+ callback({+ cancel: shouldBlockRemoteFrameNavigation({resourceType: details.resourceType}) ||+ requestPolicy === "deny-active-content",+ });+ });+ session.defaultSession.protocol.handle(scheme, async (request) => {+ const forwardRequest = (includeCredentials = false) => session.defaultSession.fetch(request, {+ bypassCustomProtocolHandlers: true,+ redirect: "manual",+ ...(includeCredentials ? {credentials: "include"} : {}),+ });+ let requestURL;+ try {+ requestURL = new URL(request.url);+ } catch (error) {+ requestURL = undefined;+ }++ const isTargetOrigin = requestURL?.origin === target.origin;+ const requestPathname = requestURL?.pathname || "/";+ const localDocumentRequest = isTargetOrigin && (request.method === "GET" || request.method === "HEAD") &&+ ["/check-auth", "/stage/build/app/", "/stage/build/app/window.html"].includes(requestURL.pathname);+ const localResource = isTargetOrigin && (request.method === "GET" || request.method === "HEAD")+ ? getLocalRemoteResource(requestURL.pathname)+ : undefined;+ const requestDestination = request.headers.get("sec-fetch-dest") || request.destination;+ const requestPolicy = getRemoteKernelRequestPolicy({+ method: request.method,+ pathname: requestPathname,+ destination: requestDestination,+ localResourceAvailable: Boolean(localResource),+ isTargetOrigin,+ });+ if (requestPolicy === "deny-api") {+ writeLog("blocked remote kernel lifecycle request [path=" + requestPathname + "]");+ return new Response(JSON.stringify({+ code: -1,+ msg: "This operation is unavailable in remote kernel mode.",+ }), {+ status: 403,+ headers: {"Content-Type": "application/json; charset=utf-8"},+ });+ }+ if (requestPolicy === "deny-active-content") {+ return new Response("Forbidden", {+ status: 403,+ headers: {"Content-Type": "text/plain; charset=utf-8"},+ });+ }+ if (!isTargetOrigin) {+ return forwardRequest();+ }+ if (requestPolicy === "local") {+ if (localDocumentRequest) {+ let versionData;+ try {+ versionData = await requestRemoteKernelVersion(target);+ } catch (error) {+ writeLog("verify remote kernel version before loading local UI failed: " + error.message);+ return new Response("Unable to verify the remote kernel version.", {+ status: 502,+ headers: {+ "Cache-Control": "no-store",+ "Content-Type": "text/plain; charset=utf-8",+ },+ });+ }+ const versionStatus = getRemoteKernelVersionStatus(versionData, appVer);+ if (versionStatus !== "compatible") {+ writeLog("blocked local UI for an incompatible remote kernel [status=" + versionStatus + "]");+ return new Response("The remote kernel version does not match this client.", {+ status: 409,+ headers: {+ "Cache-Control": "no-store",+ "Content-Type": "text/plain; charset=utf-8",+ },+ });+ }+ }+ if (localDocumentRequest &&+ ["/stage/build/app/", "/stage/build/app/window.html"].includes(requestURL.pathname)) {+ const authenticationResponse = await session.defaultSession.fetch(request, {+ bypassCustomProtocolHandlers: true,+ credentials: "include",+ redirect: "manual",+ });+ await authenticationResponse.body?.cancel();+ if (!authenticationResponse.ok) {+ const responseLocation = authenticationResponse.headers.get("location");+ let authenticationRequired = authenticationResponse.status === 401;+ if (responseLocation && authenticationResponse.status >= 300 && authenticationResponse.status < 400) {+ try {+ const redirectURL = new URL(responseLocation, target.origin);+ authenticationRequired = redirectURL.origin === target.origin &&+ redirectURL.pathname === "/check-auth";+ } catch (error) {+ authenticationRequired = false;+ }+ }+ if (authenticationRequired) {+ const authURL = new URL("/check-auth", target.origin);+ authURL.searchParams.set("to", requestURL.pathname + requestURL.search);+ authURL.searchParams.set("lang", resolveAppLanguage(app.getPreferredSystemLanguages()));+ authURL.searchParams.set("remote", "1");+ return new Response(null, {+ status: 302,+ headers: {+ "Cache-Control": "no-store",+ Location: authURL.href,+ },+ });+ }+ return new Response("Remote kernel UI probe failed.", {+ status: authenticationResponse.status >= 400 ? authenticationResponse.status : 502,+ headers: {+ "Cache-Control": "no-store",+ "Content-Type": "text/plain; charset=utf-8",+ },+ });+ }+ }+ const localResponse = await net.fetch(pathToFileURL(localResource).toString());+ if (localDocumentRequest) {+ const responseHeaders = new Headers(localResponse.headers);+ responseHeaders.set("Cache-Control", "no-store");+ responseHeaders.set("Content-Security-Policy",+ createRemoteDocumentContentSecurityPolicy(fs.readFileSync(localResource, "utf8"), target.origin));+ return new Response(localResponse.body, {+ status: localResponse.status,+ statusText: localResponse.statusText,+ headers: responseHeaders,+ });+ }+ return localResponse;+ }+ if (requestPolicy === "not-found") {+ return new Response("Not Found", {+ status: 404,+ headers: {"Content-Type": "text/plain; charset=utf-8"},+ });+ }+ const response = await forwardRequest(true);+ const redirectDecision = getRemoteKernelRedirectDecision({+ status: response.status,+ location: response.headers.get("location"),+ origin: target.origin,+ method: request.method,+ });+ if (redirectDecision.action === "none") {+ return response;+ }+ if (redirectDecision.action === "deny") {+ await response.body?.cancel();+ writeLog("blocked remote kernel redirect outside the configured origin [path=" + requestURL.pathname + "]");+ return new Response("Forbidden redirect", {+ status: 403,+ headers: {"Content-Type": "text/plain; charset=utf-8"},+ });+ }+ const redirectLocalResource = redirectDecision.method === "GET" || redirectDecision.method === "HEAD"+ ? getLocalRemoteResource(redirectDecision.url.pathname)+ : undefined;+ const redirectPolicy = getRemoteKernelRequestPolicy({+ method: redirectDecision.method,+ pathname: redirectDecision.url.pathname,+ destination: requestDestination,+ localResourceAvailable: Boolean(redirectLocalResource),+ isTargetOrigin: true,+ });+ if (redirectPolicy === "deny-api" || redirectPolicy === "deny-active-content" ||+ redirectPolicy === "not-found") {+ await response.body?.cancel();+ writeLog("blocked unsafe remote kernel redirect [path=" + redirectDecision.url.pathname ++ ", policy=" + redirectPolicy + "]");+ return new Response(redirectPolicy === "not-found" ? "Not Found" : "Forbidden redirect", {+ status: redirectPolicy === "not-found" ? 404 : 403,+ headers: {"Content-Type": "text/plain; charset=utf-8"},+ });+ }+ return response;+ });+ remoteProtocolInstalled = true;+ writeLog("installed local frontend handler for remote kernel [origin=" + target.origin + "]");+};+const requestKernelExit = (port, options = {}, signal) => {if (!port) {return Promise.resolve();@@ -844,7 +1252,7 @@ const closeKernelForUpdate = async (port, initiatingPort, setCurrentWorkspace) =const validateUpdateInstallRequest = (event, data) => {const workspace = workspaces.find((item) => item.webContentsId === event.sender.id);- if (!workspace || !workspace.workspaceDir || !data || !data.port ||+ if (!workspace || !workspace.ownsKernel || !workspace.workspaceDir || !data || !data.port ||workspace.port.toString() !== data.port.toString()) {writeLog("rejected update install request from an unknown workspace");return;@@ -1015,11 +1423,11 @@ const beginUpdateInstall = (event, data) => {const getSystemShutdownPorts = () => {const ports = new Set();workspaces.forEach((workspaceItem) => {- if (workspaceItem.port) {+ if (workspaceItem.ownsKernel && workspaceItem.port) {ports.add(workspaceItem.port);}});- if (bootWindow && !bootWindow.isDestroyed() && kernelPort) {+ if (!remoteKernelTarget && bootWindow && !bootWindow.isDestroyed() && kernelPort) {ports.add(kernelPort);}return Array.from(ports);@@ -1179,11 +1587,13 @@ const showErrorWindow = (titleZh, titleEn, content, emoji = "⚠️", logPath =return errWindow.id;};-const initMainWindow = (currentKernelPort = kernelPort) => {+const initMainWindow = (kernel = kernelPort, remoteAuthenticated = true) => {if (!app.isReady()) {writeLog("initMainWindow: app not ready, skipping");return;}+ const kernelTarget = getKernelTarget(kernel);+ const currentKernelPort = kernelTarget.port;// 恢复主窗体状态let oldWindowState = {};@@ -1269,8 +1679,10 @@ const initMainWindow = (currentKernelPort = kernelPort) => {trafficLightPosition: {x: 8, y: 8},webPreferences: {nodeIntegration: true,- webviewTag: true,- webSecurity: false,+ nodeIntegrationInSubFrames: false,+ nodeIntegrationInWorker: false,+ webviewTag: kernelTarget.mode !== "remote",+ webSecurity: kernelTarget.mode === "remote",contextIsolation: false,autoplayPolicy: "user-gesture-required" // 桌面端禁止自动播放多媒体 https://github.com/siyuan-note/siyuan/issues/7587},@@ -1280,6 +1692,7 @@ const initMainWindow = (currentKernelPort = kernelPort) => {});remote.enable(currentWindow.webContents);bindSpellcheckContextMenu(currentWindow.webContents);+ rememberWindowKernelTarget(currentWindow, kernelTarget);if (resetToCenter) {currentWindow.center();@@ -1293,26 +1706,43 @@ const initMainWindow = (currentKernelPort = kernelPort) => {// pending(既不 resolve 也不 reject),会导致 loadURL 永不执行,主窗口卡在启动页无法显示。// 这里无论 setProxy 是否完成,最多等待 5 秒后强制加载主界面。const loadMainURL = () => {- currentWindow.loadURL(getServer(currentKernelPort) + "/stage/build/app/?v=" + Date.now());+ const appURL = new URL("/stage/build/app/", kernelTarget.origin);+ appURL.searchParams.set("v", Date.now().toString());+ if (kernelTarget.mode === "remote") {+ appURL.searchParams.set("remote", "1");+ }+ if (kernelTarget.mode === "remote" && !remoteAuthenticated) {+ const authURL = new URL("/check-auth", kernelTarget.origin);+ authURL.searchParams.set("to", appURL.pathname + appURL.search);+ authURL.searchParams.set("lang", resolveAppLanguage(app.getPreferredSystemLanguages()));+ authURL.searchParams.set("remote", "1");+ currentWindow.loadURL(authURL.href);+ } else {+ currentWindow.loadURL(appURL.href);+ }};- net.fetch(getServer(currentKernelPort) + "/api/system/getNetwork", {method: "POST"}).then((response) => {- return response.json();- }).then((response) => {- const proxyMode = response.data.proxy.scheme === "system" ? "system" : response.data.proxy.scheme === "" ? "direct" : "fixed_servers";- const setProxyDone = setProxy(`${response.data.proxy.scheme}://${response.data.proxy.host}:${response.data.proxy.port}`,- currentWindow.webContents, proxyMode);- Promise.race([- Promise.resolve(setProxyDone),- new Promise((resolve) => setTimeout(resolve, 5000)), // setProxy 永久 pending 时的超时兜底- ]).then(loadMainURL).catch(() => {- writeLog("setProxy failed, load main UI without proxy");+ if (kernelTarget.mode === "remote") {+ loadMainURL();+ } else {+ net.fetch(getServer(currentKernelPort) + "/api/system/getNetwork", {method: "POST"}).then((response) => {+ return response.json();+ }).then((response) => {+ const proxyMode = response.data.proxy.scheme === "system" ? "system" : response.data.proxy.scheme === "" ? "direct" : "fixed_servers";+ const setProxyDone = setProxy(`${response.data.proxy.scheme}://${response.data.proxy.host}:${response.data.proxy.port}`,+ currentWindow.webContents, proxyMode);+ Promise.race([+ Promise.resolve(setProxyDone),+ new Promise((resolve) => setTimeout(resolve, 5000)), // setProxy 永久 pending 时的超时兜底+ ]).then(loadMainURL).catch(() => {+ writeLog("setProxy failed, load main UI without proxy");+ loadMainURL();+ });+ }).catch((e) => {+ // getNetwork 失败也要继续加载主界面,避免主窗口不加载导致卡在启动页+ writeLog("getNetwork failed, load main UI without proxy: " + e.message);loadMainURL();});- }).catch((e) => {- // getNetwork 失败也要继续加载主界面,避免主窗口不加载导致卡在启动页- writeLog("getNetwork failed, load main UI without proxy: " + e.message);- loadMainURL();- });+ }// 发起互联网服务请求时绕过安全策略 https://github.com/siyuan-note/siyuan/issues/5516currentWindow.webContents.session.webRequest.onBeforeSendHeaders((details, cb) => {@@ -1343,11 +1773,23 @@ const initMainWindow = (currentKernelPort = kernelPort) => {cb({requestHeaders: details.requestHeaders});});currentWindow.webContents.session.webRequest.onHeadersReceived((details, cb) => {+ let preserveRemoteDocumentCSP = false;+ if (kernelTarget.mode === "remote") {+ try {+ const responseURL = new URL(details.url);+ preserveRemoteDocumentCSP = responseURL.origin === kernelTarget.origin &&+ ["/check-auth", "/stage/build/app/", "/stage/build/app/window.html"].includes(responseURL.pathname);+ } catch (error) {+ preserveRemoteDocumentCSP = false;+ }+ }for (let key in details.responseHeaders) {if ("x-frame-options" === key.toLowerCase()) {delete details.responseHeaders[key];} else if ("content-security-policy" === key.toLowerCase()) {- delete details.responseHeaders[key];+ if (!preserveRemoteDocumentCSP) {+ delete details.responseHeaders[key];+ }} else if ("access-control-allow-origin" === key.toLowerCase()) {delete details.responseHeaders[key];}@@ -1356,6 +1798,15 @@ const initMainWindow = (currentKernelPort = kernelPort) => {});currentWindow.webContents.on("did-finish-load", () => {+ if (kernelTarget.mode === "remote") {+ if (getWindowPathname(currentWindow) === "/check-auth") {+ currentWindow.show();+ if (bootWindow && !bootWindow.isDestroyed()) {+ bootWindow.destroy();+ }+ }+ return;+ }let siyuanOpenURL = process.argv.find((arg) => arg.startsWith("siyuan://"));if (siyuanOpenURL) {if (currentWindow.isMinimized()) {@@ -1373,8 +1824,14 @@ const initMainWindow = (currentKernelPort = kernelPort) => {setNonDarwinApplicationMenu();}// 当前页面链接使用浏览器打开- windowNavigate(currentWindow, "app");+ windowNavigate(currentWindow, "app", kernelTarget.origin, kernelTarget.mode === "remote");currentWindow.on("close", (event) => {+ if (kernelTarget.mode === "remote" && (getWindowPathname(currentWindow) !== "/stage/build/app/" ||+ !initializedWindowIds.has(currentWindow.webContents.id))) {+ event.preventDefault();+ exitWorkspace(workspaces.find((item) => item.webContentsId === currentWindow.webContents.id));+ return;+ }if (currentWindow && !currentWindow.isDestroyed()) {currentWindow.webContents.send("siyuan-save-close", false);}@@ -1384,6 +1841,8 @@ const initMainWindow = (currentKernelPort = kernelPort) => {browserWindow: currentWindow,webContentsId: currentWindow.webContents.id,port: currentKernelPort,+ ownsKernel: kernelTarget.ownsKernel,+ kernelTarget,});// loadURL 后设置超时兜底:前端 app bundle 加载或初始化异常导致 siyuan-ready-to-show 迟迟不发时,// 强制销毁 boot 窗口并显示主窗口,避免永久卡在启动页@@ -1500,6 +1959,10 @@ const loadBootWindow = (disableAppearance = false) => {bootAppearanceFallback = true;}const query = {v: appVer, port: kernelPort};+ if (remoteKernelTarget) {+ query.remote = remoteKernelTarget.origin;+ query.appearance = "0";+ }if (bootAppearanceFallback) {query.appearance = "0";}@@ -1508,6 +1971,32 @@ const loadBootWindow = (disableAppearance = false) => {});};+const createBootWindow = () => {+ bootWindow = new BrowserWindow({+ show: false,+ width: Math.floor(screen.getPrimaryDisplay().size.width / 2),+ height: Math.floor(screen.getPrimaryDisplay().workAreaSize.height / 2),+ frame: false,+ backgroundColor: "#1e1e1e",+ resizable: false,+ icon: path.join(appDir, "stage", "icon-large.png"),+ webPreferences: {+ webSecurity: false,+ },+ });+ bootAppearanceFallback = false;+ bootIndexPath = path.join(appDir, "app", "electron", "boot.html");+ if (isDevEnv) {+ bootIndexPath = path.join(appDir, "electron", "boot.html");+ }+ bootWindow.on("unresponsive", () => {+ if (!bootAppearanceFallback) {+ writeLog("boot window is unresponsive, reload without custom appearance");+ loadBootWindow(true);+ }+ });+};+const initKernel = (workspace, port, lang, safeMode) => {return new Promise(async (resolve) => {const currentWorkspace = [workspace, process.env.SIYUAN_WORKSPACE_PATH, lastWorkspacePath]@@ -1515,29 +2004,7 @@ const initKernel = (workspace, port, lang, safeMode) => {const workspaceLogPath = currentWorkspace ? path.resolve(currentWorkspace, "temp", "siyuan.log") : "";const kernelLogPath = path.join(confDir, "kernel.log");// 必须在首次异步等待前创建窗口,避免工作空间选择窗口关闭后因无窗口触发应用退出。- bootWindow = new BrowserWindow({- show: false,- width: Math.floor(screen.getPrimaryDisplay().size.width / 2),- height: Math.floor(screen.getPrimaryDisplay().workAreaSize.height / 2),- frame: false,- backgroundColor: "#1e1e1e",- resizable: false,- icon: path.join(appDir, "stage", "icon-large.png"),- webPreferences: {- webSecurity: false,- },- });- bootAppearanceFallback = false;- bootIndexPath = path.join(appDir, "app", "electron", "boot.html");- if (isDevEnv) {- bootIndexPath = path.join(appDir, "electron", "boot.html");- }- bootWindow.on("unresponsive", () => {- if (!bootAppearanceFallback) {- writeLog("boot window is unresponsive, reload without custom appearance");- loadBootWindow(true);- }- });+ createBootWindow();if (!await showAppleSiliconWarning(lang)) {bootWindow.destroy();app.quit();@@ -1734,18 +2201,156 @@ const initKernel = (workspace, port, lang, safeMode) => {});};+const fetchWithTimeout = async (url, options = {}, timeout = 5000) => {+ const abortController = new AbortController();+ const timer = setTimeout(() => abortController.abort(), timeout);+ try {+ return await session.defaultSession.fetch(url, Object.assign({+ credentials: "include",+ bypassCustomProtocolHandlers: true,+ redirect: "manual",+ }, options, {signal: abortController.signal}));+ } finally {+ clearTimeout(timer);+ }+};++const requestRemoteKernelVersion = async (target) => {+ const response = await fetchWithTimeout(target.origin + "/api/system/version", {method: "GET"});+ if (!response.ok) {+ await response.body?.cancel();+ throw new Error("version request returned HTTP " + response.status);+ }+ return response.json();+};++const isRemoteKernelAuthenticated = async (target) => {+ const response = await fetchWithTimeout(target.origin + "/stage/build/app/", {+ method: "GET",+ redirect: "manual",+ });+ if (response.status === 401 || response.status >= 300 && response.status < 400) {+ await response.body?.cancel();+ return false;+ }+ if (!response.ok) {+ await response.body?.cancel();+ throw new Error("authentication probe returned HTTP " + response.status);+ }+ await response.body?.cancel();+ return true;+};++const initRemoteKernel = async (target) => {+ createBootWindow();+ if (!await showAppleSiliconWarning(getArg("--lang") || "")) {+ bootWindow.destroy();+ app.quit();+ return;+ }+ loadBootWindow();+ if (openAsHidden) {+ bootWindow.minimize();+ } else {+ bootWindow.show();+ }++ try {+ await session.defaultSession.clearStorageData({+ origin: target.origin,+ storages: remoteKernelActiveStorageTypes,+ });+ } catch (error) {+ throw new Error("failed to clear remote kernel active storage: " + error.message);+ }++ writeLog("connecting to remote kernel [origin=" + target.origin + "]");+ let versionData;+ for (let count = 0; count < 5; count++) {+ try {+ versionData = await requestRemoteKernelVersion(target);+ break;+ } catch (error) {+ writeLog("get remote kernel version failed: " + error.message);+ if (count < 4) {+ await sleep(500);+ }+ }+ }+ const versionStatus = getRemoteKernelVersionStatus(versionData, appVer);+ if (versionStatus === "invalid") {+ showErrorWindow("连接远程内核失败", "Failed to connect to the remote kernel",+ "<div>无法连接远程内核,请检查地址、网络和 TLS 证书。</div>" ++ "<div>Unable to connect to the remote kernel. Check the address, network, and TLS certificate.</div>");+ bootWindow.destroy();+ return;+ }+ writeLog("got remote kernel version [" + versionData.data + "]");+ if (versionStatus === "mismatch") {+ const remoteVersion = escapeHTML(versionData.data);+ showErrorWindow("远程内核版本不匹配", "Remote kernel version mismatch",+ "<div>客户端版本 " + appVer + " 与远程内核版本 " + remoteVersion + " 不一致。</div>" ++ "<div>Client version " + appVer + " does not match remote kernel version " + remoteVersion + ".</div>");+ bootWindow.destroy();+ return;+ }++ const bootShowStart = Date.now();+ let booted = false;+ while (Date.now() - bootShowStart <= 300000) {+ try {+ const response = await fetchWithTimeout(target.origin + "/api/system/bootProgress");+ if (!response.ok) {+ await response.body?.cancel();+ throw new Error("boot progress request returned HTTP " + response.status);+ }+ const progressData = await response.json();+ if (progressData?.data?.progress >= 100) {+ booted = true;+ break;+ }+ } catch (error) {+ writeLog("get remote boot progress failed: " + error.message);+ }+ await sleep(500);+ }+ if (!booted) {+ showErrorWindow("连接远程内核超时", "Remote kernel connection timed out",+ "<div>等待远程内核完成启动超时。</div><div>Timed out waiting for the remote kernel to finish booting.</div>");+ bootWindow.destroy();+ return;+ }++ let authenticated;+ try {+ authenticated = await isRemoteKernelAuthenticated(target);+ } catch (error) {+ writeLog("probe remote kernel authentication failed: " + error.message);+ showErrorWindow("检查远程内核鉴权失败", "Failed to check remote kernel authentication",+ "<div>无法检查远程内核的鉴权状态。</div><div>Unable to check the remote kernel authentication state.</div>");+ bootWindow.destroy();+ return;+ }+ installRemoteFrontendProtocol(target);+ return {+ target,+ authenticated,+ };+};+app.whenReady().then(() => {if ("darwin" === process.platform) {Menu.setApplicationMenu(Menu.buildFromTemplate([{role: "appMenu"}]));} else {setNonDarwinApplicationMenu();}- // Trust self-signed TLS certificates for local HTTPS server+ // 仅本进程启动的本地内核允许自签名证书,远程内核始终使用系统信任链。session.defaultSession.setCertificateVerifyProc((request, callback) => {- if (request.hostname === "127.0.0.1" || request.hostname === "localhost") {- callback(0); // VERIFY_OK+ const kernelMode = remoteKernelTarget ? "remote" : "local";+ if (shouldTrustLocalKernelCertificate(kernelMode, request.hostname)) {+ callback(0); // 验证通过} else {- callback(-3); // default Chromium handling+ callback(-3); // 交由 Chromium 默认处理}});@@ -1787,6 +2392,12 @@ app.whenReady().then(() => {}handledCrashWebContents.add(webContents.id);+ if (!workspace.ownsKernel) {+ writeLog("remote renderer exited without stopping the remote kernel [origin=" ++ workspace.kernelTarget.origin + "]");+ exitWorkspace(workspace);+ return;+ }writeAppCrashMarker(workspace, details);requestKernelExit(workspace.port, {force: true,@@ -1863,9 +2474,12 @@ app.whenReady().then(() => {if (!sync || !sync.i18n || typeof sync.i18n !== "object" || !sync.hotkey || typeof sync.hotkey !== "object") {return;}- const workspaceDir = (typeof sync.workspaceDir === "string" && sync.workspaceDir)- ? sync.workspaceDir- : ("webContents:" + event.sender.id);+ const kernelTarget = getWindowKernelTarget(event.sender.id);+ const workspaceDir = kernelTarget?.mode === "remote"+ ? "remote:" + kernelTarget.origin+ : (typeof sync.workspaceDir === "string" && sync.workspaceDir)+ ? sync.workspaceDir+ : ("webContents:" + event.sender.id);appMenuByWorkspaceDir.set(workspaceDir, sync);appMenuWorkspaceByWebContentsId.set(event.sender.id, workspaceDir);if (shouldApplyAppMenuFrom(event.sender.id, workspaceDir)) {@@ -1931,6 +2545,28 @@ app.whenReady().then(() => {app.exit();});ipcMain.handle("siyuan-get", (event, data) => {+ const remoteSender = getWindowKernelTarget(event.sender.id)?.mode === "remote";+ if (remoteSender && ["beginRichClipboard", "completeRichClipboard", "cancelRichClipboard", "clipboardRead"]+ .includes(data.cmd)) {+ writeLog("ignored local file clipboard processing in remote kernel mode");+ return false;+ }+ if (remoteSender && data.cmd === "showOpenDialog") {+ writeLog("ignored local open dialog in remote kernel mode");+ return {canceled: true, filePaths: []};+ }+ if (remoteSender && data.cmd === "showSaveDialog") {+ writeLog("ignored local save dialog in remote kernel mode");+ return {canceled: true, filePath: ""};+ }+ if (remoteSender && data.cmd === "printToPDF") {+ writeLog("ignored local PDF export in remote kernel mode");+ return;+ }+ if (remoteSender && data.cmd === "setProxy") {+ writeLog("ignored applying a server proxy to the remote client");+ return false;+ }if (data.cmd === "clipboardRead") {return clipboard.read(data.format);}@@ -2199,8 +2835,13 @@ app.whenReady().then(() => {}}const currentWindow = getWindowByContentId(webContentsId);+ const remoteSender = getWindowKernelTarget(event.sender.id)?.mode === "remote";switch (cmd) {case "showItemInFolder":+ if (remoteSender) {+ writeLog("ignored showing a server path in remote kernel mode");+ break;+ }shell.showItemInFolder(data.filePath);break;case "notification": {@@ -2222,6 +2863,10 @@ app.whenReady().then(() => {});break;case "openPath":+ if (remoteSender) {+ writeLog("ignored opening a server path in remote kernel mode");+ break;+ }shell.openPath(data.filePath);break;case "openDevTools": {@@ -2376,10 +3021,19 @@ app.whenReady().then(() => {});});ipcMain.on("siyuan-export-pdf", (event, data) => {+ if (getWindowKernelTarget(event.sender.id)?.mode === "remote") {+ writeLog("ignored local PDF export in remote kernel mode");+ return;+ }data.webContentsId = event.sender.id;getWindowByContentId(data.parentWindowId).send("siyuan-export-pdf", data);});ipcMain.on("siyuan-export-newwindow", (event, data) => {+ const kernelTarget = getWindowKernelTarget(event.sender.id);+ if (kernelTarget?.mode === "remote") {+ writeLog("ignored local PDF export window for remote kernel");+ return;+ }// The PDF/Word export preview window automatically adjusts according to the size of the main window https://github.com/siyuan-note/siyuan/issues/10554const wndBounds = getWindowByContentId(event.sender.id).getBounds();const wndScreen = screen.getDisplayNearestPoint({x: wndBounds.x, y: wndBounds.y});@@ -2401,11 +3055,24 @@ app.whenReady().then(() => {},});printWin.center();+ rememberWindowKernelTarget(printWin, kernelTarget || createLocalKernelTarget());printWin.webContents.userAgent = "SiYuan/" + appVer + " https://b3log.org/siyuan Electron " + printWin.webContents.userAgent;printWin.loadURL(data);- windowNavigate(printWin, "export");+ windowNavigate(printWin, "export", (kernelTarget || createLocalKernelTarget()).origin);});ipcMain.on("siyuan-quit", (event, port) => {+ const kernelTarget = getWindowKernelTarget(event.sender.id);+ const workspace = workspaces.find((item) => item.webContentsId === event.sender.id);+ if (kernelTarget?.mode === "remote") {+ if (workspace) {+ exitWorkspace(workspace);+ } else {+ const senderWindow = BrowserWindow.fromWebContents(event.sender);+ markExpectedRendererExit(senderWindow);+ senderWindow?.destroy();+ }+ return;+ }exitApp(port);});ipcMain.handle("siyuan-install-update", (event, data) => {@@ -2423,6 +3090,25 @@ app.whenReady().then(() => {mainWindow.show();});ipcMain.on("siyuan-open-window", (event, data) => {+ const kernelTarget = getWindowKernelTarget(event.sender.id);+ if (!kernelTarget) {+ writeLog("ignored opening a window without a kernel target");+ return;+ }+ let windowURL;+ try {+ windowURL = new URL(data.url);+ } catch (error) {+ writeLog("ignored opening a window with an invalid URL");+ return;+ }+ if (windowURL.origin !== kernelTarget.origin || windowURL.pathname !== "/stage/build/app/window.html") {+ writeLog("ignored opening a window outside the kernel origin");+ return;+ }+ if (kernelTarget.mode === "remote") {+ windowURL.searchParams.set("remote", "1");+ }const mainWindow = BrowserWindow.getFocusedWindow() || BrowserWindow.getAllWindows()[0];const mainBounds = mainWindow.getBounds();const mainScreen = screen.getDisplayNearestPoint({x: mainBounds.x, y: mainBounds.y});@@ -2441,13 +3127,16 @@ app.whenReady().then(() => {webPreferences: {contextIsolation: false,nodeIntegration: true,- webviewTag: true,- webSecurity: false,+ nodeIntegrationInSubFrames: false,+ nodeIntegrationInWorker: false,+ webviewTag: kernelTarget.mode !== "remote",+ webSecurity: kernelTarget.mode === "remote",autoplayPolicy: "user-gesture-required" // 桌面端禁止自动播放多媒体 https://github.com/siyuan-note/siyuan/issues/7587},});remote.enable(win.webContents);bindSpellcheckContextMenu(win.webContents);+ rememberWindowKernelTarget(win, kernelTarget);if (data.position) {win.setPosition(data.position.x, data.position.y);@@ -2457,9 +3146,16 @@ app.whenReady().then(() => {win.setAlwaysOnTop(data.alwaysOnTop);win.webContents.userAgent = "SiYuan/" + appVer + " https://b3log.org/siyuan Electron " + win.webContents.userAgent;win.webContents.session.setSpellCheckerLanguages(["en-US"]);- win.loadURL(data.url);- windowNavigate(win, "window");+ win.loadURL(windowURL.href);+ windowNavigate(win, "window", kernelTarget.origin, kernelTarget.mode === "remote");win.on("close", (event) => {+ if (kernelTarget.mode === "remote" && (getWindowPathname(win) !== "/stage/build/app/window.html" ||+ !initializedWindowIds.has(win.webContents.id))) {+ event.preventDefault();+ markExpectedRendererExit(win);+ win.destroy();+ return;+ }if (win && !win.isDestroyed()) {win.webContents.send("siyuan-save-close");}@@ -2471,6 +3167,10 @@ app.whenReady().then(() => {}});ipcMain.on("siyuan-open-workspace", (event, data) => {+ if (getWindowKernelTarget(event.sender.id)?.mode === "remote") {+ writeLog("ignored opening a local workspace in remote kernel mode");+ return;+ }if (updateInstallPromise) {writeLog("ignored opening workspace while installing update");return;@@ -2490,8 +3190,17 @@ app.whenReady().then(() => {}});ipcMain.handle("siyuan-init", async (event, data) => {+ const kernelTarget = getWindowKernelTarget(event.sender.id);+ if (kernelTarget) {+ initializedWindowIds.add(event.sender.id);+ }+ const capabilities = kernelTarget ? {+ kernelMode: kernelTarget.mode,+ ownsKernel: kernelTarget.ownsKernel,+ kernelOrigin: kernelTarget.origin,+ } : undefined;const exitWS = workspaces.find(item => {- if (event.sender.id === item.webContentsId && item.workspaceDir) {+ if (event.sender.id === item.webContentsId && item.initialized) {if (item.tray && ("win32" === process.platform || "linux" === process.platform)) {// Tray menu text does not change with the appearance language https://github.com/siyuan-note/siyuan/issues/7935resetTrayMenu(item.tray, data.languages, item.browserWindow);@@ -2500,17 +3209,23 @@ app.whenReady().then(() => {}});if (exitWS) {- return;+ if (!exitWS.ownsKernel) {+ setTimeout(() => flushPendingRemoteOpenURLs(exitWS.browserWindow), 100);+ }+ return capabilities;}const workspaceItem = workspaces.find((item) => event.sender.id === item.webContentsId);if (workspaceItem) {- workspaceItem.workspaceDir = data.workspaceDir;+ workspaceItem.initialized = true;+ workspaceItem.workspaceDir = workspaceItem.ownsKernel ? data.workspaceDir : "";let tray;if ("win32" === process.platform || "linux" === process.platform) {// 系统托盘tray = new Tray(path.join(appDir, "stage", "icon-large.png"));- tray.setToolTip(`${path.basename(data.workspaceDir)} - SiYuan v${appVer}`);+ const trayName = workspaceItem.ownsKernel ? path.basename(data.workspaceDir) :+ new URL(workspaceItem.kernelTarget.origin).host;+ tray.setToolTip(`${trayName} - SiYuan v${appVer}`);const mainWindow = getWindowByContentId(event.sender.id);if (!mainWindow || mainWindow.isDestroyed()) {tray.destroy();@@ -2524,7 +3239,12 @@ app.whenReady().then(() => {}workspaceItem.tray = tray;}- await net.fetch(getServer(data.port) + "/api/system/uiproc?pid=" + process.pid, {method: "POST"});+ if (workspaceItem?.ownsKernel) {+ await net.fetch(workspaceItem.kernelTarget.origin + "/api/system/uiproc?pid=" + process.pid, {method: "POST"});+ } else if (workspaceItem) {+ setTimeout(() => flushPendingRemoteOpenURLs(workspaceItem.browserWindow), 100);+ }+ return capabilities;});ipcMain.on("siyuan-hotkey", (event, data) => {if (!data.hotkeys || data.hotkeys.length === 0) {@@ -2589,13 +3309,44 @@ app.whenReady().then(() => {});});ipcMain.on("siyuan-auto-launch", (event, data) => {+ const kernelTarget = getWindowKernelTarget(event.sender.id);+ const args = [];+ if (kernelTarget?.mode === "remote") {+ args.push("--remote=" + kernelTarget.origin);+ }+ if (data.openAsHidden) {+ args.push("--openAsHidden");+ }app.setLoginItemSettings({openAtLogin: data.openAtLogin,- args: data.openAsHidden ? ["--openAsHidden"] : ""+ args,});});const appCrashInfo = readAppCrashInfo();- if (firstOpen) {+ if (remoteKernelArgError) {+ if (remoteKernelArgError.code === "ERR_REMOTE_UNSAFE_CHROMIUM_SWITCH") {+ showErrorWindow("远程内核启动参数不安全", "Unsafe remote kernel arguments",+ "<div>远程内核模式不能与弱化网页或 TLS 安全的参数同时使用。</div>" ++ "<div>Remote kernel mode cannot be used with arguments that weaken web or TLS security.</div>");+ } else {+ showErrorWindow("远程内核地址无效", "Invalid remote kernel address",+ "<div>--remote 仅接受不带路径、查询或凭据的 HTTPS origin。</div>" ++ "<div>--remote only accepts an HTTPS origin without a path, query, or credentials.</div>");+ }+ } else if (remoteKernelTarget) {+ initRemoteKernel(remoteKernelTarget).then((result) => {+ if (result) {+ initMainWindow(result.target, result.authenticated);+ }+ }).catch((error) => {+ writeLog("initialize remote kernel failed: " + error);+ if (bootWindow && !bootWindow.isDestroyed()) {+ bootWindow.destroy();+ }+ showErrorWindow("连接远程内核失败", "Failed to connect to the remote kernel",+ "<div>连接远程内核时发生意外错误。</div><div>An unexpected error occurred while connecting to the remote kernel.</div>");+ });+ } else if (firstOpen) {const firstOpenWindow = new BrowserWindow({width: Math.floor(screen.getPrimaryDisplay().size.width * 0.6),height: Math.floor(screen.getPrimaryDisplay().workAreaSize.height * 0.8),@@ -2779,10 +3530,14 @@ app.whenReady().then(() => {}workspaces.forEach(item => {- const currentURL = new URL(item.browserWindow.getURL());- const server = getServer(currentURL.port);+ const server = item.kernelTarget.origin;writeLog("sync after system resume [" + server + "/api/sync/performSync" + "]");- net.fetch(server + "/api/sync/performSync", {method: "POST"});+ session.defaultSession.fetch(server + "/api/sync/performSync", {+ method: "POST",+ credentials: item.ownsKernel ? "omit" : "include",+ bypassCustomProtocolHandlers: !item.ownsKernel,+ redirect: item.ownsKernel ? "follow" : "manual",+ });});});powerMonitor.on("shutdown", () => {@@ -2803,6 +3558,17 @@ app.on("open-url", async (event, url) => { // for macOSreturn;}if (url.startsWith("siyuan://")) {+ if (remoteKernelTarget) {+ const mainWorkspace = workspaces[0];+ if (mainWorkspace?.browserWindow && !mainWorkspace.browserWindow.isDestroyed() &&+ initializedWindowIds.has(mainWorkspace.webContentsId)) {+ showWindow(mainWorkspace.browserWindow);+ mainWorkspace.browserWindow.webContents.send("siyuan-open-url", url);+ } else {+ pendingRemoteOpenURLs.push(url);+ }+ return;+ }let isBackground = true;if (workspaces.length === 0) {isBackground = false;@@ -2832,21 +3598,61 @@ app.on("second-instance", (event, argv) => {writeLog("ignored second instance while installing update");return;}- let workspace = argv.find((arg) => arg.startsWith("--workspace="));+ if (remoteKernelArgError) {+ writeLog("ignored second instance because the primary remote kernel argument is invalid");+ return;+ }+ const secondRemoteArg = getArgFrom(argv, "--remote");+ if (secondRemoteArg !== undefined || remoteKernelTarget) {+ const siyuanURL = argv.find((arg) => arg.startsWith("siyuan://"));+ const localTargetRequested = getArgFrom(argv, "--workspace") !== undefined ||+ getArgFrom(argv, "--port") !== undefined;+ let secondRemoteOrigin;+ if (secondRemoteArg !== undefined) {+ try {+ secondRemoteOrigin = normalizeRemoteKernelOrigin(secondRemoteArg);+ writeLog("got second-instance remote kernel [origin=" + secondRemoteOrigin + "]");+ if (!remoteKernelTarget || secondRemoteOrigin !== remoteKernelTarget.origin) {+ writeLog("ignored a different remote kernel while another SiYuan instance is running");+ }+ } catch (error) {+ writeLog("ignored invalid second-instance remote kernel: " + error.message);+ }+ }+ if (remoteKernelTarget && localTargetRequested) {+ writeLog("ignored opening a local kernel target while remote kernel mode is running");+ }+ const allowDeepLink = shouldForwardRemoteDeepLink({+ currentOrigin: remoteKernelTarget?.origin,+ requestedOrigin: secondRemoteOrigin,+ remoteArgumentPresent: secondRemoteArg !== undefined,+ localTargetRequested,+ });+ if (workspaces.length > 0) {+ const mainWindow = workspaces[0].browserWindow;+ showWindow(mainWindow);+ if (siyuanURL && allowDeepLink && initializedWindowIds.has(mainWindow.webContents.id)) {+ mainWindow.webContents.send("siyuan-open-url", siyuanURL);+ } else if (siyuanURL && allowDeepLink) {+ pendingRemoteOpenURLs.push(siyuanURL);+ }+ } else if (siyuanURL && allowDeepLink) {+ pendingRemoteOpenURLs.push(siyuanURL);+ }+ return;+ }+ let workspace = getArgFrom(argv, "--workspace");if (workspace) {- workspace = workspace.split("=")[1];writeLog("got second-instance arg [--workspace=" + workspace + "]");}- let port = argv.find((arg) => arg.startsWith("--port="));+ let port = getArgFrom(argv, "--port");if (port) {- port = port.split("=")[1];writeLog("got second-instance arg [--port=" + port + "]");} else {port = 0;}- let lang = argv.find((arg) => arg.startsWith("--lang="));+ let lang = getArgFrom(argv, "--lang");if (lang) {- lang = lang.split("=")[1];writeLog("got second-instance arg [--lang=" + lang + "]");} else {lang = "";@@ -2884,7 +3690,7 @@ app.on("second-instance", (event, argv) => {});app.on("activate", () => {- if (updateInstallPromise) {+ if (updateInstallPromise || remoteKernelArgError) {return;}if (workspaces.length > 0) {@@ -2894,12 +3700,25 @@ app.on("activate", () => {}}if (BrowserWindow.getAllWindows().length === 0) {- initMainWindow();+ if (remoteKernelTarget) {+ initRemoteKernel(remoteKernelTarget).then((result) => {+ if (result) {+ initMainWindow(result.target, result.authenticated);+ }+ }).catch((error) => writeLog("reactivate remote kernel failed: " + error));+ } else {+ initMainWindow();+ }}});app.on("web-contents-created", (webContentsCreatedEvent, contents) => {contents.setWindowOpenHandler((details) => {+ const kernelTarget = getWindowKernelTarget(contents.id);+ if (kernelTarget?.mode === "remote") {+ openExternalURL(details.url, true);+ return {action: "deny"};+ }// https://github.com/siyuan-note/siyuan/issues/10567if (details.url.startsWith("file:///") && details.disposition === "foreground-tab") {return;@@ -2915,7 +3734,18 @@ app.on("before-quit", (event) => {event.preventDefault();return;}- workspaces.forEach(item => {+ workspaces.slice().forEach(item => {+ const pathname = getWindowPathname(item.browserWindow);+ if (!item.ownsKernel && (pathname !== "/stage/build/app/" ||+ !initializedWindowIds.has(item.webContentsId))) {+ const workspaceIndex = workspaces.indexOf(item);+ if (workspaceIndex > -1) {+ workspaces.splice(workspaceIndex, 1);+ }+ markExpectedRendererExit(item.browserWindow);+ item.browserWindow.destroy();+ return;+ }if (item.browserWindow && !item.browserWindow.isDestroyed()) {event.preventDefault();item.browserWindow.webContents.send("siyuan-save-close", true);diff --git a/app/electron/remote-auth.html b/app/electron/remote-auth.htmlnew file mode 100644index 0000000000..cf62a4d303--- /dev/null+++ b/app/electron/remote-auth.html@@ -0,0 +1,251 @@+<!DOCTYPE html>+<html style="height: 100%">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0">+ <meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src 'self' data:; style-src 'unsafe-inline'; script-src 'unsafe-inline'">+ <title>SiYuan</title>+ <style>+ :root {+ color-scheme: light dark;+ font-family: "Helvetica Neue", "Microsoft Yahei", sans-serif;+ }++ body {+ align-items: center;+ background: #fff;+ color: #202124;+ display: flex;+ height: 100%;+ justify-content: center;+ margin: 0;+ }++ #windowBar {+ -webkit-app-region: drag;+ height: 32px;+ left: 0;+ position: absolute;+ right: 0;+ top: 0;+ }++ #closeWindow {+ -webkit-app-region: no-drag;+ background: transparent;+ color: inherit;+ font-size: 20px;+ height: 32px;+ line-height: 32px;+ position: absolute;+ right: 0;+ top: 0;+ width: 44px;+ }++ @media (prefers-color-scheme: dark) {+ body {+ background: #1e1e1e;+ color: #c9d1d9;+ }+ }++ main {+ text-align: center;+ width: 280px;+ }++ #origin {+ font-size: 12px;+ opacity: .7;+ overflow-wrap: anywhere;+ }++ input[type="password"], input[type="text"] {+ border: 1px solid rgba(127, 127, 127, .6);+ border-radius: 4px;+ box-sizing: border-box;+ line-height: 28px;+ padding: 0 8px;+ width: 100%;+ }++ #captchaRow {+ display: none;+ margin-top: 8px;+ position: relative;+ }++ #captchaImg {+ cursor: pointer;+ height: 26px;+ position: absolute;+ right: 1px;+ top: 1px;+ }++ label {+ display: block;+ font-size: 12px;+ margin: 12px 0;+ text-align: left;+ }++ button {+ background: #3573f0;+ border: 0;+ border-radius: 4px;+ color: #fff;+ cursor: pointer;+ line-height: 28px;+ width: 100%;+ }++ #message {+ color: #d23f31;+ font-size: 12px;+ min-height: 18px;+ }+ </style>+</head>+<body>+<div id="windowBar"><button id="closeWindow" type="button">×</button></div>+<main hidden>+ <h1 id="title">SiYuan</h1>+ <p id="origin"></p>+ <form id="authForm">+ <input id="authCode" type="password" autocomplete="current-password">+ <div id="captchaRow">+ <img id="captchaImg">+ <input id="captcha" type="text" autocomplete="off">+ </div>+ <label><input id="rememberMe" type="checkbox"><span id="rememberLabel"></span></label>+ <button id="submit" type="submit"></button>+ </form>+ <p id="message" role="alert"></p>+</main>+<script>+ (() => {+ const params = new URLSearchParams(window.location.search);+ const allowedPaths = ["/stage/build/app/", "/stage/build/app/window.html"];+ let targetURL;+ try {+ targetURL = new URL(params.get("to") || "/stage/build/app/", window.location.origin);+ } catch (error) {+ targetURL = new URL("/stage/build/app/", window.location.origin);+ }+ if (targetURL.origin !== window.location.origin || !allowedPaths.includes(targetURL.pathname)) {+ targetURL = new URL("/stage/build/app/", window.location.origin);+ }+ targetURL.searchParams.set("remote", "1");++ const browserLanguage = navigator.language || "en";+ let language = params.get("lang");+ if (!language) {+ if (/^zh-(TW|HK|MO)|Hant/i.test(browserLanguage)) {+ language = "zh-TW";+ } else if (/^zh/i.test(browserLanguage)) {+ language = "zh-CN";+ } else if (/^pt-BR/i.test(browserLanguage)) {+ language = "pt-BR";+ } else {+ language = browserLanguage.split("-")[0];+ }+ }+ const authCodeElement = document.getElementById("authCode");+ const captchaElement = document.getElementById("captcha");+ const captchaRowElement = document.getElementById("captchaRow");+ const captchaImageElement = document.getElementById("captchaImg");+ const messageElement = document.getElementById("message");+ const submitElement = document.getElementById("submit");++ const authSocket = new WebSocket("wss://" + window.location.host + "/ws?app=siyuan" ++ Math.random().toString(36).substring(8) + "&id=auth&type=auth");+ authSocket.addEventListener("message", (event) => {+ try {+ const data = JSON.parse(event.data);+ if (data.cmd === "loginAuth") {+ window.location.href = targetURL.href;+ }+ } catch (error) {+ // 忽略无法识别的鉴权广播。+ }+ });++ let ipcRenderer;+ try {+ ({ipcRenderer} = require("electron"));+ ipcRenderer.on("siyuan-save-close", () => ipcRenderer.send("siyuan-quit", window.location.port));+ } catch (error) {+ // 远程访问授权页仅在 Electron 主窗口中启用宿主关闭通知。+ }+ document.getElementById("closeWindow").addEventListener("click", () => {+ if (ipcRenderer) {+ ipcRenderer.send("siyuan-quit", window.location.port);+ }+ });++ const refreshCaptcha = () => {+ captchaImageElement.src = "/api/system/getCaptcha?v=" + Date.now();+ };+ captchaImageElement.addEventListener("click", refreshCaptcha);++ document.getElementById("authForm").addEventListener("submit", async (event) => {+ event.preventDefault();+ const authCode = authCodeElement.value.trim();+ if (!authCode) {+ authCodeElement.focus();+ return;+ }+ submitElement.disabled = true;+ messageElement.textContent = "";+ try {+ const response = await fetch("/api/system/loginAuth", {+ method: "POST",+ body: JSON.stringify({+ authCode,+ captcha: captchaElement.value,+ rememberMe: document.getElementById("rememberMe").checked,+ }),+ });+ const result = await response.json();+ if (result.code === 0) {+ window.location.href = targetURL.href;+ return;+ }+ messageElement.textContent = result.msg || response.statusText;+ authCodeElement.value = "";+ captchaElement.value = "";+ if (result.code === 1) {+ captchaRowElement.style.display = "block";+ refreshCaptcha();+ } else {+ captchaRowElement.style.display = "none";+ }+ authCodeElement.focus();+ } catch (error) {+ messageElement.textContent = String(error.message || error);+ } finally {+ submitElement.disabled = false;+ }+ });++ fetch("/appearance/langs/" + encodeURIComponent(language) + ".json", {cache: "no-store"})+ .then((response) => response.json())+ .catch(() => fetch("/appearance/langs/en.json", {cache: "no-store"}).then((response) => response.json()))+ .then((languages) => {+ document.title = languages._kernel["178"];+ document.getElementById("closeWindow").ariaLabel = languages._kernel["177"];+ document.getElementById("title").textContent = languages._kernel["176"];+ document.getElementById("origin").textContent = window.location.origin;+ authCodeElement.placeholder = languages._kernel["173"];+ captchaElement.placeholder = languages._kernel["175"];+ document.getElementById("rememberLabel").textContent = languages._kernel["257"];+ submitElement.textContent = languages._kernel["174"];+ document.querySelector("main").hidden = false;+ authCodeElement.focus();+ });+ })();+</script>+</body>+</html>diff --git a/app/electron/remoteKernel.js b/app/electron/remoteKernel.jsnew file mode 100644index 0000000000..ebb40c0814--- /dev/null+++ b/app/electron/remoteKernel.js@@ -0,0 +1,413 @@+const crypto = require("node:crypto");++// 解析命令行参数时保留值中的等号,避免 URL 查询参数被截断。+const getArgFrom = (args, name) => {+ const prefix = name + "=";+ const arg = args.find((item) => item === name || item.startsWith(prefix));+ if (!arg) {+ return;+ }+ return arg === name ? "" : arg.slice(prefix.length);+};++const normalizeRemoteKernelOrigin = (value) => {+ if (!value) {+ throw new Error("--remote requires a URL");+ }+ const url = new URL(value);+ if (url.username || url.password) {+ throw new Error("--remote does not accept credentials in the URL");+ }+ if (url.pathname !== "/" || url.search || url.hash || value.includes("?") || value.includes("#")) {+ throw new Error("--remote only accepts an origin without a path, query, or fragment");+ }+ if (url.protocol !== "https:") {+ throw new Error("--remote requires HTTPS");+ }+ return url.origin;+};++const insecureCertificateSwitchNames = Object.freeze([+ "allow-insecure-localhost",+ "ignore-certificate-errors",+ "ignore-certificate-errors-spki-list",+ "ignore-ssl-errors",+ "ignore-ssl-errors-with-hosts",+]);+const insecureCertificateSwitches = new Set(insecureCertificateSwitchNames);+const unsafeRemoteChromiumSwitchNames = Object.freeze([+ ...insecureCertificateSwitchNames,+ "allow-running-insecure-content",+ "disable-site-isolation-for-policy",+ "disable-site-isolation-trials",+ "disable-web-security",+]);+const unsafeRemoteChromiumSwitches = new Set(unsafeRemoteChromiumSwitchNames);+const remoteKernelActiveStorageTypes = Object.freeze(["serviceworkers", "cachestorage"]);++const getInsecureCertificateSwitchName = (arg) => {+ if (typeof arg !== "string" || !arg.startsWith("--")) {+ return;+ }+ const name = arg.slice(2).split("=", 1)[0].toLowerCase();+ return insecureCertificateSwitches.has(name) ? name : undefined;+};++const getUnsafeRemoteChromiumSwitchName = (arg) => {+ if (typeof arg !== "string" || !arg.startsWith("--")) {+ return;+ }+ const name = arg.slice(2).split("=", 1)[0].toLowerCase();+ if (name === "disable-features") {+ const disabledFeatures = arg.slice(arg.indexOf("=") + 1).toLowerCase().split(",");+ if (disabledFeatures.some((feature) => ["isolateorigins", "site-per-process", "siteperprocess"]+ .includes(feature.trim()))) {+ return name;+ }+ }+ return unsafeRemoteChromiumSwitches.has(name) ? name : undefined;+};++const isAllowedRemoteExternalURL = (value) => {+ try {+ return ["http:", "https:"].includes(new URL(value).protocol);+ } catch (error) {+ return false;+ }+};++const deniedAPIPaths = new Set([+ "/api/system/checkUpdate",+ "/api/system/createWorkspaceDir",+ "/api/system/exit",+ "/api/system/removeWorkspaceDir",+ "/api/system/removeWorkspaceDirPhysically",+ "/api/system/setDownloadInstallPkg",+ "/api/system/setNetworkServe",+ "/api/system/setNetworkServeTLS",+ "/api/system/setUpdateChannel",+ "/api/system/setWorkspaceDir",+ "/api/system/uiproc",+]);+const documentDestinations = new Set(["document", "embed", "frame", "iframe", "object"]);+const executableDestinations = new Set([+ "audioworklet",+ "paintworklet",+ "script",+ "serviceworker",+ "sharedworker",+ "style",+ "worker",+ "worklet",+ "xslt",+]);+const localExecutableDestinations = new Set(["script", "style", "worker"]);+const localDocumentPaths = new Set([+ "/check-auth",+ "/stage/build/app/",+ "/stage/build/app/window.html",+]);+const webRequestDestinations = new Map([+ ["mainframe", "document"],+ ["object", "object"],+ ["script", "script"],+ ["serviceworker", "serviceworker"],+ ["sharedworker", "sharedworker"],+ ["stylesheet", "style"],+ ["subframe", "frame"],+ ["worker", "worker"],+]);++const getRemoteKernelWebRequestDestination = (resourceType) =>+ webRequestDestinations.get(String(resourceType || "").toLowerCase()) || "";++const normalizeRequestPathname = (pathname) => {+ const normalizedPathnames = [];+ let decoded = pathname;+ for (let count = 0; count < 8; count++) {+ let normalized = decoded.replaceAll("\\", "/").replace(/\/{2,}/g, "/");+ if (normalized.length > 1) {+ normalized = normalized.replace(/\/+$/, "");+ }+ if (!normalizedPathnames.includes(normalized)) {+ normalizedPathnames.push(normalized);+ }+ try {+ const next = decodeURIComponent(decoded);+ if (next === decoded) {+ break;+ }+ decoded = next;+ } catch (error) {+ break;+ }+ }+ return normalizedPathnames;+};++const isProtectedLocalPath = (pathname) => pathname === "/check-auth" || pathname === "/appearance" ||+ pathname.startsWith("/appearance/") || pathname === "/plugins" || pathname.startsWith("/plugins/") ||+ pathname === "/stage" || pathname.startsWith("/stage/") || pathname === "/widgets" ||+ pathname.startsWith("/widgets/");++const getRemoteKernelRequestPolicy = ({method, pathname, destination, localResourceAvailable, isTargetOrigin = true}) => {+ const requestedPathname = pathname;+ const normalizedPathnames = normalizeRequestPathname(pathname);+ if (isTargetOrigin && normalizedPathnames.some((candidate) => deniedAPIPaths.has(candidate))) {+ return "deny-api";+ }+ pathname = normalizedPathnames[normalizedPathnames.length - 1];+ const safeMethod = method === "GET" || method === "HEAD";+ if (documentDestinations.has(destination)) {+ return isTargetOrigin && safeMethod && localResourceAvailable && localDocumentPaths.has(requestedPathname)+ ? "local"+ : "deny-active-content";+ }+ if (executableDestinations.has(destination)) {+ return isTargetOrigin && safeMethod && localResourceAvailable && localExecutableDestinations.has(destination)+ ? "local"+ : "deny-active-content";+ }+ if (!isTargetOrigin) {+ return "remote";+ }+ if (!safeMethod) {+ return "remote";+ }+ if (localResourceAvailable) {+ return "local";+ }+ if (normalizedPathnames.some(isProtectedLocalPath)) {+ return "not-found";+ }+ return "remote";+};++const getRemoteKernelRedirectDecision = ({status, location, origin, method}) => {+ if (![301, 302, 303, 307, 308].includes(status)) {+ return {action: "none"};+ }+ if (!location) {+ return {action: "deny"};+ }+ let url;+ try {+ url = new URL(location, origin);+ } catch (error) {+ return {action: "deny"};+ }+ if (url.origin !== origin || url.username || url.password) {+ return {action: "deny"};+ }+ let redirectMethod = method;+ if ((status === 303 && method !== "HEAD") ||+ ((status === 301 || status === 302) && method === "POST")) {+ redirectMethod = "GET";+ }+ return {+ action: "follow",+ method: redirectMethod,+ url,+ };+};++const getRemoteKernelVersionStatus = (versionData, expectedVersion) => {+ if (!versionData || versionData.code !== 0 || typeof versionData.data !== "string") {+ return "invalid";+ }+ return versionData.data === expectedVersion ? "compatible" : "mismatch";+};++const shouldForwardRemoteDeepLink = ({currentOrigin, requestedOrigin, remoteArgumentPresent, localTargetRequested}) =>+ Boolean(currentOrigin) && !localTargetRequested &&+ (!remoteArgumentPresent || requestedOrigin === currentOrigin);++const shouldBlockRemoteFrameNavigation = ({isMainFrame, resourceType}) => isMainFrame === false ||+ ["object", "subFrame"].includes(resourceType);++const shouldTrustLocalKernelCertificate = (kernelMode, hostname) => kernelMode === "local" &&+ ["127.0.0.1", "localhost"].includes(String(hostname).toLowerCase());++const decodeHTMLAttributeValue = (value) => value.replace(/&(#(?:x[\da-f]+|\d+)|amp|apos|gt|lt|quot);?/gi,+ (match, entity) => {+ const normalizedEntity = entity.toLowerCase();+ if (normalizedEntity.startsWith("#x")) {+ const codePoint = Number.parseInt(normalizedEntity.slice(2), 16);+ return Number.isSafeInteger(codePoint) && codePoint <= 0x10FFFF+ ? String.fromCodePoint(codePoint)+ : match;+ }+ if (normalizedEntity.startsWith("#")) {+ const codePoint = Number.parseInt(normalizedEntity.slice(1), 10);+ return Number.isSafeInteger(codePoint) && codePoint <= 0x10FFFF+ ? String.fromCodePoint(codePoint)+ : match;+ }+ return {+ amp: "&",+ apos: "'",+ gt: ">",+ lt: "<",+ quot: "\"",+ }[normalizedEntity];+ });++const parseHTMLAttributes = (source) => {+ const attributes = [];+ let offset = 0;+ while (offset < source.length) {+ while (/\s/.test(source[offset])) {+ offset++;+ }+ if (offset >= source.length || source[offset] === "/") {+ break;+ }+ const nameStart = offset;+ while (offset < source.length && !/[\s=/>]/.test(source[offset])) {+ offset++;+ }+ if (offset === nameStart) {+ offset++;+ continue;+ }+ const name = source.slice(nameStart, offset).toLowerCase();+ while (/\s/.test(source[offset])) {+ offset++;+ }+ let value;+ if (source[offset] === "=") {+ offset++;+ while (/\s/.test(source[offset])) {+ offset++;+ }+ const quote = source[offset] === "\"" || source[offset] === "'" ? source[offset++] : undefined;+ const valueStart = offset;+ if (quote) {+ while (offset < source.length && source[offset] !== quote) {+ offset++;+ }+ value = source.slice(valueStart, offset);+ if (source[offset] === quote) {+ offset++;+ }+ } else {+ while (offset < source.length && !/[\s>]/.test(source[offset])) {+ offset++;+ }+ value = source.slice(valueStart, offset);+ }+ }+ attributes.push({name, value});+ }+ return attributes;+};++const findHTMLTagEnd = (html, start) => {+ let quote;+ for (let offset = start; offset < html.length; offset++) {+ const character = html[offset];+ if (quote) {+ if (character === quote) {+ quote = undefined;+ }+ } else if (character === "\"" || character === "'") {+ quote = character;+ } else if (character === ">") {+ return offset;+ }+ }+ return -1;+};++const normalizeHTMLScriptSource = (source) => source.replace(/\r\n?/g, "\n");++const getRemoteDocumentInlineScriptSources = (html) => {+ const inlineScripts = [];+ const eventHandlers = [];+ const lowerHTML = html.toLowerCase();+ const rawTextElements = new Set(["iframe", "noembed", "noframes", "noscript", "style", "textarea", "title", "xmp"]);+ let offset = 0;+ while (offset < html.length) {+ const tagStart = html.indexOf("<", offset);+ if (tagStart < 0) {+ break;+ }+ if (html.startsWith("<!--", tagStart)) {+ const commentEnd = html.indexOf("-->", tagStart + 4);+ offset = commentEnd < 0 ? html.length : commentEnd + 3;+ continue;+ }+ const tagEnd = findHTMLTagEnd(html, tagStart + 1);+ if (tagEnd < 0) {+ break;+ }+ const tagSource = html.slice(tagStart + 1, tagEnd);+ const tagMatch = /^\s*([a-z][\w:-]*)\b/i.exec(tagSource);+ if (!tagMatch) {+ offset = tagEnd + 1;+ continue;+ }+ const tagName = tagMatch[1].toLowerCase();+ const attributes = parseHTMLAttributes(tagSource.slice(tagMatch[0].length));+ for (const attribute of attributes) {+ if (attribute.name.startsWith("on") && attribute.name.length > 2 && attribute.value !== undefined) {+ eventHandlers.push(normalizeHTMLScriptSource(decodeHTMLAttributeValue(attribute.value)));+ }+ }+ if (tagName !== "script" && !rawTextElements.has(tagName)) {+ offset = tagEnd + 1;+ continue;+ }+ const closeTagStart = lowerHTML.indexOf("</" + tagName, tagEnd + 1);+ if (closeTagStart < 0) {+ offset = tagEnd + 1;+ continue;+ }+ if (tagName === "script" && !attributes.some((attribute) => attribute.name === "src")) {+ inlineScripts.push(normalizeHTMLScriptSource(html.slice(tagEnd + 1, closeTagStart)));+ }+ const closeTagEnd = html.indexOf(">", closeTagStart + tagName.length + 2);+ offset = closeTagEnd < 0 ? html.length : closeTagEnd + 1;+ }+ return {eventHandlers, inlineScripts};+};++const createRemoteDocumentContentSecurityPolicy = (html, origin) => {+ const {inlineScripts} = getRemoteDocumentInlineScriptSources(html);+ const hashes = [...new Set(inlineScripts.map((source) =>+ "'sha256-" + crypto.createHash("sha256").update(source, "utf8").digest("base64") + "'"))];+ const stageSource = new URL("/stage/", origin).href;+ const appearanceSource = new URL("/appearance/", origin).href;+ const defaultIconSource = new URL("/appearance/icons/litheness/icon.js", origin).href;+ const scriptSources = [stageSource, defaultIconSource, "blob:", "'wasm-unsafe-eval'", ...hashes];+ return [+ "base-uri " + new URL("/", origin).href,+ "child-src 'none'",+ "frame-src 'none'",+ "object-src 'none'",+ "script-src " + scriptSources.join(" "),+ "script-src-attr 'none'",+ "style-src 'unsafe-inline' " + stageSource + " " + appearanceSource,+ "worker-src " + stageSource,+ ].join("; ");+};++module.exports = {+ createRemoteDocumentContentSecurityPolicy,+ getArgFrom,+ getInsecureCertificateSwitchName,+ getRemoteKernelRedirectDecision,+ getRemoteKernelRequestPolicy,+ getRemoteKernelWebRequestDestination,+ getRemoteKernelVersionStatus,+ getUnsafeRemoteChromiumSwitchName,+ getRemoteDocumentInlineScriptSources,+ normalizeRemoteKernelOrigin,+ remoteKernelActiveStorageTypes,+ insecureCertificateSwitchNames,+ isAllowedRemoteExternalURL,+ shouldBlockRemoteFrameNavigation,+ shouldForwardRemoteDeepLink,+ shouldTrustLocalKernelCertificate,+ unsafeRemoteChromiumSwitchNames,+};diff --git a/app/electron/remoteKernel.test.js b/app/electron/remoteKernel.test.jsnew file mode 100644index 0000000000..a7940e8f0b--- /dev/null+++ b/app/electron/remoteKernel.test.js@@ -0,0 +1,389 @@+const assert = require("node:assert/strict");+const fs = require("node:fs");+const path = require("node:path");+const test = require("node:test");+const {+ createRemoteDocumentContentSecurityPolicy,+ getArgFrom,+ getInsecureCertificateSwitchName,+ getRemoteKernelRedirectDecision,+ getRemoteKernelRequestPolicy,+ getRemoteKernelWebRequestDestination,+ getRemoteKernelVersionStatus,+ getUnsafeRemoteChromiumSwitchName,+ getRemoteDocumentInlineScriptSources,+ insecureCertificateSwitchNames,+ isAllowedRemoteExternalURL,+ normalizeRemoteKernelOrigin,+ remoteKernelActiveStorageTypes,+ shouldBlockRemoteFrameNavigation,+ shouldForwardRemoteDeepLink,+ shouldTrustLocalKernelCertificate,+ unsafeRemoteChromiumSwitchNames,+} = require("./remoteKernel");++test("getArgFrom preserves equals signs in values", () => {+ assert.equal(getArgFrom(["--remote=https://example.com/?token=a=b"], "--remote"),+ "https://example.com/?token=a=b");+});++test("normalizeRemoteKernelOrigin accepts HTTPS origins", () => {+ assert.equal(normalizeRemoteKernelOrigin("https://example.com"), "https://example.com");+ assert.equal(normalizeRemoteKernelOrigin("https://example.com:443/"), "https://example.com");+ assert.equal(normalizeRemoteKernelOrigin("https://example.com:8443/"), "https://example.com:8443");+});++test("normalizeRemoteKernelOrigin rejects insecure or non-origin URLs", () => {+ [+ "",+ "http://example.com",+ "https://user:[email protected]",+ "https://example.com/path",+ "https://example.com/?query=value",+ "https://example.com?",+ "https://example.com/#fragment",+ "https://example.com#",+ ].forEach((value) => assert.throws(() => normalizeRemoteKernelOrigin(value)));+});++test("remote kernel request policy rejects lifecycle and workspace APIs", () => {+ [+ "/api/system/exit",+ "/api/system/uiproc",+ "/api/system/setWorkspaceDir",+ "/api/system/createWorkspaceDir",+ "/api/system/removeWorkspaceDir",+ "/api/system/removeWorkspaceDirPhysically",+ "/api/system/checkUpdate",+ "/api/system/setDownloadInstallPkg",+ "/api/system/setNetworkServe",+ "/api/system/setNetworkServeTLS",+ "/api/system/setUpdateChannel",+ ].forEach((pathname) => assert.equal(getRemoteKernelRequestPolicy({+ method: "POST",+ pathname,+ destination: "",+ localResourceAvailable: false,+ }), "deny-api"));+ assert.equal(getRemoteKernelRequestPolicy({+ method: "POST",+ pathname: "/api/system/%65xit/",+ destination: "",+ localResourceAvailable: false,+ }), "deny-api");+ assert.equal(getRemoteKernelRequestPolicy({+ method: "POST",+ pathname: "/api/system/%2565xit",+ destination: "",+ localResourceAvailable: false,+ }), "deny-api");+});++test("remote document CSP only permits hashed packaged inline scripts", () => {+ const html = "<!-- <button onclick=\"comment()\"> -->" ++ "<style>.example::after { content: '<button onclick=\"style()\">'; }</style>" ++ "<script src=\"/external.js\">ignored();</script>" ++ "<script>trusted();</script><button onclick=\"reload()\">Reload</button>";+ assert.deepEqual(getRemoteDocumentInlineScriptSources(html), {+ eventHandlers: ["reload()"],+ inlineScripts: ["trusted();"],+ });+ const policy = createRemoteDocumentContentSecurityPolicy(html, "https://example.com");+ assert.ok(policy.includes("'sha256-gy+T9mHal6aj/WinLcmWSKaGzIDuSIxPtm/8HDkG7f4='"));+ assert.equal(policy.includes("'sha256-sC0PQhdi5wMoECrBbPZDMcg4gm1Z2uOfLRLceVFG7RY='"), false);+ assert.ok(policy.includes("script-src https://example.com/stage/ " ++ "https://example.com/appearance/icons/litheness/icon.js blob: 'wasm-unsafe-eval'"));+ assert.ok(policy.includes("base-uri https://example.com/"));+ assert.ok(policy.includes("script-src-attr 'none'"));+ assert.ok(policy.includes("style-src 'unsafe-inline' https://example.com/stage/ " ++ "https://example.com/appearance/"));+ assert.equal(policy.includes("'unsafe-hashes'"), false);+ assert.ok(policy.includes("worker-src https://example.com/stage/"));+ assert.equal(policy.includes("worker-src https://example.com/stage/ blob:"), false);+ assert.equal(policy.includes("script-src 'self'"), false);+ assert.equal(policy.includes("worker-src 'self'"), false);+ assert.equal(policy.includes("https://example.com/appearance/icons/custom/icon.js"), false);+ assert.equal(policy.includes("'unsafe-eval'"), false);+ assert.equal(policy.includes("comment()"), false);+ assert.equal(policy.includes("style()"), false);+});++test("remote document CSP covers the packaged app, window, and authorization pages", () => {+ const documentPaths = [+ path.join(__dirname, "../stage/build/app/index.html"),+ path.join(__dirname, "../stage/build/app/window.html"),+ path.join(__dirname, "remote-auth.html"),+ ];+ documentPaths.forEach((documentPath) => {+ const html = fs.readFileSync(documentPath, "utf8");+ const {eventHandlers, inlineScripts} = getRemoteDocumentInlineScriptSources(html);+ const policy = createRemoteDocumentContentSecurityPolicy(html, "https://example.com");+ const uniqueScriptSources = new Set(inlineScripts);+ assert.equal((policy.match(/'sha256-/g) || []).length, uniqueScriptSources.size);+ assert.equal(eventHandlers.some((source) => policy.includes(source)), false);+ assert.equal(policy.includes("'unsafe-hashes'"), false);+ assert.equal(policy.includes("script-src 'unsafe-inline'"), false);+ assert.equal(policy.includes("'unsafe-eval'"), false);+ });+});++test("web request resource types map to enforceable active-content destinations", () => {+ assert.equal(getRemoteKernelWebRequestDestination("mainFrame"), "document");+ assert.equal(getRemoteKernelWebRequestDestination("subFrame"), "frame");+ assert.equal(getRemoteKernelWebRequestDestination("stylesheet"), "style");+ assert.equal(getRemoteKernelWebRequestDestination("script"), "script");+ assert.equal(getRemoteKernelWebRequestDestination("worker"), "worker");+ assert.equal(getRemoteKernelWebRequestDestination("xhr"), "");+ assert.equal(getRemoteKernelWebRequestDestination("image"), "");+});++test("remote kernel request policy rejects remotely supplied active content", () => {+ ["document", "frame", "iframe", "object", "embed", "script", "style", "worker", "sharedworker",+ "serviceworker", "audioworklet", "paintworklet", "xslt"].forEach((destination) => {+ assert.equal(getRemoteKernelRequestPolicy({+ method: "GET",+ pathname: "/untrusted/content",+ destination,+ localResourceAvailable: false,+ }), "deny-active-content");+ });+ assert.equal(getRemoteKernelRequestPolicy({+ method: "POST",+ pathname: "/stage/build/app/",+ destination: "document",+ localResourceAvailable: true,+ }), "deny-active-content");+ assert.equal(getRemoteKernelRequestPolicy({+ method: "GET",+ pathname: "/stage/build/%61pp/",+ destination: "document",+ localResourceAvailable: true,+ }), "deny-active-content");+ assert.equal(getRemoteKernelRequestPolicy({+ method: "GET",+ pathname: "/",+ destination: "document",+ localResourceAvailable: false,+ }), "deny-active-content");+});++test("remote kernel request policy serves trusted UI locally and forwards data", () => {+ assert.equal(getRemoteKernelRequestPolicy({+ method: "GET",+ pathname: "/stage/build/app/",+ destination: "document",+ localResourceAvailable: true,+ }), "local");+ assert.equal(getRemoteKernelRequestPolicy({+ method: "GET",+ pathname: "/stage/build/app/index.js",+ destination: "script",+ localResourceAvailable: true,+ }), "local");+ assert.equal(getRemoteKernelRequestPolicy({+ method: "GET",+ pathname: "/appearance/themes/daylight/theme.css",+ destination: "style",+ localResourceAvailable: true,+ }), "local");+ assert.equal(getRemoteKernelRequestPolicy({+ method: "GET",+ pathname: "/stage/build/app/layout-worker.js",+ destination: "worker",+ localResourceAvailable: true,+ }), "local");+ assert.equal(getRemoteKernelRequestPolicy({+ method: "POST",+ pathname: "/api/block/getBlockInfo",+ destination: "",+ localResourceAvailable: false,+ }), "remote");+ assert.equal(getRemoteKernelRequestPolicy({+ method: "GET",+ pathname: "/assets/image.png",+ destination: "image",+ localResourceAvailable: false,+ }), "remote");+});++test("remote protocol only accepts active content from packaged target resources", () => {+ ["document", "frame", "iframe", "object", "embed", "script", "style", "worker", "sharedworker",+ "serviceworker", "audioworklet", "paintworklet", "xslt"].forEach((destination) => {+ assert.equal(getRemoteKernelRequestPolicy({+ method: "GET",+ pathname: "/external/content",+ destination,+ localResourceAvailable: false,+ isTargetOrigin: false,+ }), "deny-active-content");+ });+ ["image", "media", "font", ""].forEach((destination) => {+ assert.equal(getRemoteKernelRequestPolicy({+ method: "GET",+ pathname: "/external/content",+ destination,+ localResourceAvailable: false,+ isTargetOrigin: false,+ }), "remote");+ });+ assert.equal(getRemoteKernelRequestPolicy({+ method: "GET",+ pathname: "/stage/build/app/local-worker.js",+ destination: "worker",+ localResourceAvailable: true,+ isTargetOrigin: true,+ }), "local");+ ["sharedworker", "serviceworker", "audioworklet", "paintworklet"].forEach((destination) => {+ assert.equal(getRemoteKernelRequestPolicy({+ method: "GET",+ pathname: "/stage/build/app/local-worker.js",+ destination,+ localResourceAvailable: true,+ isTargetOrigin: true,+ }), "deny-active-content");+ });+});++test("certificate trust exception only applies to an owned loopback kernel", () => {+ assert.equal(shouldTrustLocalKernelCertificate("local", "127.0.0.1"), true);+ assert.equal(shouldTrustLocalKernelCertificate("local", "localhost"), true);+ assert.equal(shouldTrustLocalKernelCertificate("remote", "127.0.0.1"), false);+ assert.equal(shouldTrustLocalKernelCertificate("remote", "localhost"), false);+ assert.equal(shouldTrustLocalKernelCertificate("local", "example.com"), false);+});++test("remote mode clears only active web storage that could replace the packaged frontend", () => {+ assert.deepEqual(remoteKernelActiveStorageTypes, ["serviceworkers", "cachestorage"]);+ ["cookies", "filesystem", "indexdb", "localstorage"].forEach((storageType) => {+ assert.equal(remoteKernelActiveStorageTypes.includes(storageType), false);+ });+});++test("remote mode recognizes Chromium switches that weaken certificate verification", () => {+ [+ "--ignore-certificate-errors",+ "--ignore-certificate-errors-spki-list=sha256/test",+ "--allow-insecure-localhost",+ "--ignore-ssl-errors",+ "--ignore-ssl-errors-with-hosts=example.com",+ ].forEach((arg) => assert.ok(getInsecureCertificateSwitchName(arg)));+ assert.equal(getInsecureCertificateSwitchName("--disable-gpu"), undefined);+ assert.equal(getInsecureCertificateSwitchName("ignore-certificate-errors"), undefined);+ assert.ok(insecureCertificateSwitchNames.includes("ignore-certificate-errors"));+ assert.ok(insecureCertificateSwitchNames.includes("allow-insecure-localhost"));+});++test("remote mode recognizes Chromium switches that weaken renderer security", () => {+ assert.equal(getUnsafeRemoteChromiumSwitchName("--disable-web-security"), "disable-web-security");+ assert.equal(getUnsafeRemoteChromiumSwitchName("--allow-running-insecure-content"),+ "allow-running-insecure-content");+ assert.equal(getUnsafeRemoteChromiumSwitchName("--disable-site-isolation-trials"),+ "disable-site-isolation-trials");+ assert.equal(getUnsafeRemoteChromiumSwitchName("--disable-site-isolation-for-policy"),+ "disable-site-isolation-for-policy");+ assert.equal(getUnsafeRemoteChromiumSwitchName("--disable-features=CalculateNativeWinOcclusion,IsolateOrigins"),+ "disable-features");+ assert.equal(getUnsafeRemoteChromiumSwitchName("--disable-features=AutoupgradeMixedContent"), undefined);+ assert.ok(unsafeRemoteChromiumSwitchNames.includes("ignore-certificate-errors"));+ assert.ok(unsafeRemoteChromiumSwitchNames.includes("disable-web-security"));+ assert.equal(getUnsafeRemoteChromiumSwitchName("--disable-gpu"), undefined);+});++test("remote mode only opens web URLs through the operating system", () => {+ assert.equal(isAllowedRemoteExternalURL("https://example.com/path"), true);+ assert.equal(isAllowedRemoteExternalURL("http://example.com/path"), true);+ assert.equal(isAllowedRemoteExternalURL("file:///tmp/document"), false);+ assert.equal(isAllowedRemoteExternalURL("javascript:alert(1)"), false);+ assert.equal(isAllowedRemoteExternalURL("siyuan://blocks/20200101000000-abcdefg"), false);+ assert.equal(isAllowedRemoteExternalURL("not a URL"), false);+});++test("remote mode blocks every nested frame navigation and load", () => {+ assert.equal(shouldBlockRemoteFrameNavigation({isMainFrame: true}), false);+ assert.equal(shouldBlockRemoteFrameNavigation({isMainFrame: false}), true);+ assert.equal(shouldBlockRemoteFrameNavigation({resourceType: "subFrame"}), true);+ assert.equal(shouldBlockRemoteFrameNavigation({resourceType: "object"}), true);+ assert.equal(shouldBlockRemoteFrameNavigation({resourceType: "image"}), false);+ assert.equal(shouldBlockRemoteFrameNavigation({resourceType: "xhr"}), false);+});++test("remote redirects stay on the configured origin and retain method semantics", () => {+ const exitRedirect = getRemoteKernelRedirectDecision({+ status: 307,+ location: "/api/system/exit",+ origin: "https://example.com",+ method: "POST",+ });+ assert.equal(exitRedirect.action, "follow");+ assert.equal(exitRedirect.method, "POST");+ assert.equal(getRemoteKernelRequestPolicy({+ method: exitRedirect.method,+ pathname: exitRedirect.url.pathname,+ destination: "",+ localResourceAvailable: false,+ }), "deny-api");+ assert.deepEqual(getRemoteKernelRedirectDecision({+ status: 302,+ location: "https://other.example/path",+ origin: "https://example.com",+ method: "GET",+ }), {action: "deny"});+ ["file:///tmp/payload", "data:text/html,payload", "javascript:alert(1)"].forEach((location) => {+ assert.deepEqual(getRemoteKernelRedirectDecision({+ status: 302,+ location,+ origin: "https://example.com",+ method: "GET",+ }), {action: "deny"});+ });+ assert.equal(getRemoteKernelRedirectDecision({+ status: 303,+ location: "/result",+ origin: "https://example.com",+ method: "POST",+ }).method, "GET");+ assert.deepEqual(getRemoteKernelRedirectDecision({+ status: 304,+ origin: "https://example.com",+ method: "GET",+ }), {action: "none"});+});++test("remote kernel version status requires an exact valid version", () => {+ assert.equal(getRemoteKernelVersionStatus({code: 0, data: "3.8.2"}, "3.8.2"), "compatible");+ assert.equal(getRemoteKernelVersionStatus({code: 0, data: "3.8.3"}, "3.8.2"), "mismatch");+ assert.equal(getRemoteKernelVersionStatus({code: -1, data: "3.8.2"}, "3.8.2"), "invalid");+ assert.equal(getRemoteKernelVersionStatus({code: 0, data: 382}, "3.8.2"), "invalid");+});++test("remote deep links only reach the matching active remote target", () => {+ const currentOrigin = "https://example.com";+ assert.equal(shouldForwardRemoteDeepLink({+ currentOrigin,+ remoteArgumentPresent: false,+ localTargetRequested: false,+ }), true);+ assert.equal(shouldForwardRemoteDeepLink({+ currentOrigin,+ requestedOrigin: currentOrigin,+ remoteArgumentPresent: true,+ localTargetRequested: false,+ }), true);+ assert.equal(shouldForwardRemoteDeepLink({+ currentOrigin,+ requestedOrigin: "https://other.example",+ remoteArgumentPresent: true,+ localTargetRequested: false,+ }), false);+ assert.equal(shouldForwardRemoteDeepLink({+ currentOrigin,+ requestedOrigin: currentOrigin,+ remoteArgumentPresent: true,+ localTargetRequested: true,+ }), false);+ assert.equal(shouldForwardRemoteDeepLink({+ requestedOrigin: currentOrigin,+ remoteArgumentPresent: true,+ localTargetRequested: false,+ }), false);+});diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o.syindex c6bf5923a4..8592c46e2b 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o.sy@@ -7,7 +7,7 @@"id": "20210808180303-xaduj2o","title": "General Operations","type": "doc",- "updated": "20260809232000"+ "updated": "20260903150000"},"Children": [{@@ -350,6 +350,23 @@}]},+ {+ "ID": "20260903150000-wowa4te",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260903150000-wowa4te",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeTextMark",+ "TextMarkType": "block-ref",+ "TextMarkBlockRefID": "20260903150000-s4hctea",+ "TextMarkBlockRefSubtype": "d",+ "TextMarkTextContent": "Connect to a Remote Kernel"+ }+ ]+ },{"ID": "20240508004528-jzh49m5","Type": "NodeParagraph",@@ -470,4 +487,4 @@]}]-}\ No newline at end of file+}diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201004194026-s8h2cog.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201004194026-s8h2cog.syindex 13367fce8c..be92305632 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201004194026-s8h2cog.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201004194026-s8h2cog.sy@@ -6,7 +6,7 @@"id": "20201004194026-s8h2cog","title": "Use on browser","type": "doc",- "updated": "20260804235500"+ "updated": "20260903150000"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20210104091447-8iiuxlt",- "updated": "20260804235500"+ "updated": "20260903150000"},"Children": [{@@ -190,6 +190,31 @@}]},+ {+ "ID": "20260903150000-cr1ft15",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260903150000-cr1ft15",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "To connect to a remote kernel from the desktop app, see "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "block-ref",+ "TextMarkBlockRefID": "20260903150000-s4hctea",+ "TextMarkBlockRefSubtype": "s",+ "TextMarkTextContent": "Connect to a Remote Kernel"+ },+ {+ "Type": "NodeText",+ "Data": "."+ }+ ]+ },{"ID": "20210104091447-dluat0m","Type": "NodeHeading",diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201227201128-m1wrouw.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201227201128-m1wrouw.syindex e6d83858df..51a4cb8f7d 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201227201128-m1wrouw.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201227201128-m1wrouw.sy@@ -6,7 +6,7 @@"id": "20201227201128-m1wrouw","title": "Docker hosting","type": "doc",- "updated": "20250926110627"+ "updated": "20260903150000"},"Children": [{@@ -790,7 +790,7 @@"HeadingLevel": 2,"Properties": {"id": "20230406105311-sq5f3qj",- "updated": "20250926110627"+ "updated": "20260903150000"},"Children": [{@@ -805,7 +805,7 @@"ListData": {},"Properties": {"id": "20230406105311-jvtmuhi",- "updated": "20250926110627"+ "updated": "20260903150000"},"Children": [{@@ -817,7 +817,7 @@},"Properties": {"id": "20230406105311-qz00ob2",- "updated": "20230406105311"+ "updated": "20260903150000"},"Children": [{@@ -825,12 +825,23 @@"Type": "NodeParagraph","Properties": {"id": "20230406105311-gvr6z7v",- "updated": "20230406105311"+ "updated": "20260903150000"},"Children": [{"Type": "NodeText",- "Data": "Does not support desktop and mobile application connections, only supports use on browsers"+ "Data": "Mobile app connections are not supported. The desktop app can connect in remote mode; see "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "block-ref",+ "TextMarkBlockRefID": "20260903150000-s4hctea",+ "TextMarkBlockRefSubtype": "s",+ "TextMarkTextContent": "Connect to a Remote Kernel"+ },+ {+ "Type": "NodeText",+ "Data": "."}]}@@ -867,4 +878,4 @@]}]-}\ No newline at end of file+}diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20260903150000-s4hctea.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20260903150000-s4hctea.synew file mode 100644index 0000000000..3b920093e3--- /dev/null+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20260903150000-s4hctea.sy@@ -0,0 +1,37 @@+{+ "ID": "20260903150000-s4hctea",+ "Spec": "2",+ "Type": "NodeDocument",+ "Properties": {+ "id": "20260903150000-s4hctea",+ "title": "Connect to a Remote Kernel",+ "type": "doc",+ "updated": "20260903150000"+ },+ "Children": [+ {"ID": "20260903150000-mz3r596", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-mz3r596", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "Overview"}]},+ {"ID": "20260903150000-dood0bb", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-dood0bb", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "The desktop app can connect to a SiYuan kernel running on another device and use the local desktop interface for editing. Remote mode only connects to an existing kernel and does not start a kernel on the local device."}]},+ {"ID": "20260903150000-c2oh8cr", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-c2oh8cr", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "Start"}]},+ {"ID": "20260903150000-601s61t", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-601s61t", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "After completely exiting the SiYuan desktop client, start the desktop app from a command line and append "}, {"Type": "NodeTextMark", "TextMarkType": "code", "TextMarkTextContent": "--remote=https://host[:port]"}, {"Type": "NodeText", "Data": ". If an instance is already running, the single-instance mechanism does not switch its current connection."}]},+ {"ID": "20260903150000-rir445a", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-rir445a", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "Security and Version"}]},+ {"ID": "20260903150000-0ekr8rg", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-0ekr8rg", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "Only HTTPS remote addresses are supported, and the client operating system must trust the TLS certificate used by the server. Connect only to a server you trust. The desktop client and remote kernel versions must match exactly; otherwise, the connection is rejected. The desktop client loads only the frontend bundled with the installation package and does not load executable frontend resources such as HTML or scripts from the remote server. Consequently, same-origin remote HTML embeds are also unavailable."}]},+ {"ID": "20260903150000-knpctlf", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-knpctlf", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "Limitations"}]},+ {"ID": "20260903150000-lazpxpz", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-lazpxpz", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "The initial version of remote mode does not support the following features. Local mode is not affected:"}]},+ {+ "ID": "20260903150000-x3th06t",+ "Type": "NodeList",+ "ListData": {},+ "Properties": {"id": "20260903150000-x3th06t", "updated": "20260903150000"},+ "Children": [+ {"ID": "20260903150000-b45enwi", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-b45enwi", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-gbt9mdf", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-gbt9mdf", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "Import and export"}]}]},+ {"ID": "20260903150000-mzhpk4r", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-mzhpk4r", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-88q1701", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-88q1701", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "File clipboard operations"}]}]},+ {"ID": "20260903150000-5amb0yu", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-5amb0yu", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-j9eobwv", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-j9eobwv", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "Operations that depend on a client-local path or a server absolute path, such as showing a file in the file manager or dragging in or opening a file by path; normal asset uploads through a file picker remain available"}]}]},+ {"ID": "20260903150000-hxh4cr0", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-hxh4cr0", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-1f4zzal", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-1f4zzal", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "Desktop plugins, Bazaar, and widgets are unavailable. Only the client's built-in appearance is used; remote custom themes, icon sets, fonts, and code snippets are not loaded"}]}]},+ {"ID": "20260903150000-88njhnb", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-88njhnb", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-p2n9ukv", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-p2n9ukv", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "Scripts in HTML and SVG blocks, database templates, and JavaScript query embeds are not executed; iframe blocks are unavailable. Chart, diagram, and math rendering results are sanitized"}]}]},+ {"ID": "20260903150000-ckttrsj", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-ckttrsj", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-8lxisgw", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-8lxisgw", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "Access authorization code sign-in only; OIDC sign-in is not supported"}]}]}+ ]+ },+ {"ID": "20260903150000-jx7db7j", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-jx7db7j", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "Lifecycle"}]},+ {"ID": "20260903150000-1uxmuev", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-1uxmuev", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "Start, stop, restart, upgrade, and switch the workspace of the remote kernel on the server. Closing the desktop client does not stop the remote kernel."}]}+ ]+}diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2.syindex a57da053e5..4613be2731 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2.sy@@ -7,7 +7,7 @@"id": "20210808180321-hbvl5c2","title": "通用操作","type": "doc",- "updated": "20260809232000"+ "updated": "20260903150000"},"Children": [{@@ -350,6 +350,23 @@}]},+ {+ "ID": "20260903150000-r25yic3",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260903150000-r25yic3",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeTextMark",+ "TextMarkType": "block-ref",+ "TextMarkBlockRefID": "20260903150000-u4065fm",+ "TextMarkBlockRefSubtype": "d",+ "TextMarkTextContent": "连接远程内核"+ }+ ]+ },{"ID": "20240507235849-l7rtlvx","Type": "NodeParagraph",@@ -470,4 +487,4 @@]}]-}\ No newline at end of file+}diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201004184819-nj8ibyg.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201004184819-nj8ibyg.syindex 14c0a0bb8c..1a0de2dd96 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201004184819-nj8ibyg.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201004184819-nj8ibyg.sy@@ -6,7 +6,7 @@"id": "20201004184819-nj8ibyg","title": "在浏览器上使用","type": "doc",- "updated": "20260804193000"+ "updated": "20260903150000"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20210104090909-6pyfjgx",- "updated": "20260804165001"+ "updated": "20260903150000"},"Children": [{@@ -197,6 +197,31 @@}]},+ {+ "ID": "20260903150000-l2tjvej",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260903150000-l2tjvej",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "如需使用桌面端连接远程内核,请参阅 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "block-ref",+ "TextMarkBlockRefID": "20260903150000-u4065fm",+ "TextMarkBlockRefSubtype": "s",+ "TextMarkTextContent": "连接远程内核"+ },+ {+ "Type": "NodeText",+ "Data": "。"+ }+ ]+ },{"ID": "20210104090909-9x9sqe8","Type": "NodeHeading",diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201227173504-847cs1q.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201227173504-847cs1q.syindex 1fa840e292..96be54d94f 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201227173504-847cs1q.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201227173504-847cs1q.sy@@ -6,7 +6,7 @@"id": "20201227173504-847cs1q","title": "Docker 伺服","type": "doc",- "updated": "20250926110513"+ "updated": "20260903150000"},"Children": [{@@ -798,7 +798,7 @@"HeadingLevel": 2,"Properties": {"id": "20230406104141-6o5jpu6",- "updated": "20250926110513"+ "updated": "20260903150000"},"Children": [{@@ -813,7 +813,7 @@"ListData": {},"Properties": {"id": "20230406104201-nbfn2p9",- "updated": "20250926110513"+ "updated": "20260903150000"},"Children": [{@@ -825,7 +825,7 @@},"Properties": {"id": "20230406104217-8m58gpo",- "updated": "20230406104217"+ "updated": "20260903150000"},"Children": [{@@ -833,12 +833,23 @@"Type": "NodeParagraph","Properties": {"id": "20230406104217-42a91na",- "updated": "20230406104310"+ "updated": "20260903150000"},"Children": [{"Type": "NodeText",- "Data": "不支持桌面端和移动端应用连接,仅支持在浏览器上使用"+ "Data": "移动端应用仍不支持连接。桌面端可以通过远程模式连接,详见 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "block-ref",+ "TextMarkBlockRefID": "20260903150000-u4065fm",+ "TextMarkBlockRefSubtype": "s",+ "TextMarkTextContent": "连接远程内核"+ },+ {+ "Type": "NodeText",+ "Data": "。"}]}@@ -875,4 +886,4 @@]}]-}\ No newline at end of file+}diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20260903150000-u4065fm.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20260903150000-u4065fm.synew file mode 100644index 0000000000..bfa9a9a6f4--- /dev/null+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20260903150000-u4065fm.sy@@ -0,0 +1,346 @@+{+ "ID": "20260903150000-u4065fm",+ "Spec": "2",+ "Type": "NodeDocument",+ "Properties": {+ "id": "20260903150000-u4065fm",+ "title": "连接远程内核",+ "type": "doc",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "ID": "20260903150000-7adxewf",+ "Type": "NodeHeading",+ "HeadingLevel": 2,+ "Properties": {+ "id": "20260903150000-7adxewf",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "概述"+ }+ ]+ },+ {+ "ID": "20260903150000-f38iwpd",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260903150000-f38iwpd",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "桌面端可以连接运行在其他设备上的思源内核,并使用本地桌面界面进行编辑。远程模式仅用于连接现有内核,不会在本机启动内核。"+ }+ ]+ },+ {+ "ID": "20260903150000-15zokfv",+ "Type": "NodeHeading",+ "HeadingLevel": 2,+ "Properties": {+ "id": "20260903150000-15zokfv",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "启动方式"+ }+ ]+ },+ {+ "ID": "20260903150000-y92771v",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260903150000-y92771v",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "完全退出思源桌面客户端后,从命令行启动桌面端并添加参数 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "--remote=https://host[:port]"+ },+ {+ "Type": "NodeText",+ "Data": "。如果已有实例正在运行,单实例机制不会切换当前连接。"+ }+ ]+ },+ {+ "ID": "20260903150000-fjznin7",+ "Type": "NodeHeading",+ "HeadingLevel": 2,+ "Properties": {+ "id": "20260903150000-fjznin7",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "安全与版本"+ }+ ]+ },+ {+ "ID": "20260903150000-54fwkfr",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260903150000-54fwkfr",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "仅支持 HTTPS 远程地址,客户端操作系统必须信任服务器使用的 TLS 证书。请只连接你信任的服务器;桌面客户端与远程内核的版本必须完全一致,否则无法连接。桌面客户端只加载安装包内置前端,不加载远端服务器提供的 HTML、脚本等可执行前端资源,因此同源的远端 HTML 嵌入内容也不可用。"+ }+ ]+ },+ {+ "ID": "20260903150000-bh8cy8d",+ "Type": "NodeHeading",+ "HeadingLevel": 2,+ "Properties": {+ "id": "20260903150000-bh8cy8d",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "功能限制"+ }+ ]+ },+ {+ "ID": "20260903150000-w1kgmix",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260903150000-w1kgmix",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "首版远程模式暂不支持以下功能,本地模式不受影响:"+ }+ ]+ },+ {+ "ID": "20260903150000-kvy0i58",+ "Type": "NodeList",+ "ListData": {},+ "Properties": {+ "id": "20260903150000-kvy0i58",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "ID": "20260903150000-1g1xw92",+ "Type": "NodeListItem",+ "ListData": {+ "BulletChar": 42,+ "Marker": "Kg=="+ },+ "Properties": {+ "id": "20260903150000-1g1xw92",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "ID": "20260903150000-zljclps",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260903150000-zljclps",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "导入和导出"+ }+ ]+ }+ ]+ },+ {+ "ID": "20260903150000-mxw5obc",+ "Type": "NodeListItem",+ "ListData": {+ "BulletChar": 42,+ "Marker": "Kg=="+ },+ "Properties": {+ "id": "20260903150000-mxw5obc",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "ID": "20260903150000-em9ib37",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260903150000-em9ib37",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "文件剪贴板"+ }+ ]+ }+ ]+ },+ {+ "ID": "20260903150000-dir6dv4",+ "Type": "NodeListItem",+ "ListData": {+ "BulletChar": 42,+ "Marker": "Kg=="+ },+ "Properties": {+ "id": "20260903150000-dir6dv4",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "ID": "20260903150000-z98z7dm",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260903150000-z98z7dm",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "依赖客户端本地路径或服务器绝对路径的操作,例如在文件管理器中显示,以及按路径拖入或打开文件;通过文件选择器进行普通资源上传仍可用"+ }+ ]+ }+ ]+ },+ {+ "ID": "20260903150000-5k7d57t",+ "Type": "NodeListItem",+ "ListData": {+ "BulletChar": 42,+ "Marker": "Kg=="+ },+ "Properties": {+ "id": "20260903150000-5k7d57t",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "ID": "20260903150000-4p58ioe",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260903150000-4p58ioe",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "桌面端插件、集市和挂件不可用;仅使用客户端内置外观,不加载远端自定义主题、图标、字体和代码片段"+ }+ ]+ }+ ]+ },+ {+ "ID": "20260903150000-c5tbiz0",+ "Type": "NodeListItem",+ "ListData": {+ "BulletChar": 42,+ "Marker": "Kg=="+ },+ "Properties": {+ "id": "20260903150000-c5tbiz0",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "ID": "20260903150000-0ptz2p4",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260903150000-0ptz2p4",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "HTML 和 SVG 块、数据库模板及 JavaScript 查询嵌入块中的脚本不会执行,iframe 块不可用;图表、图形和数学公式等渲染结果会进行安全净化"+ }+ ]+ }+ ]+ },+ {+ "ID": "20260903150000-up6xjxo",+ "Type": "NodeListItem",+ "ListData": {+ "BulletChar": 42,+ "Marker": "Kg=="+ },+ "Properties": {+ "id": "20260903150000-up6xjxo",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "ID": "20260903150000-zblcgsf",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260903150000-zblcgsf",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "仅支持访问授权码登录,不支持 OIDC 登录"+ }+ ]+ }+ ]+ }+ ]+ },+ {+ "ID": "20260903150000-ia08la1",+ "Type": "NodeHeading",+ "HeadingLevel": 2,+ "Properties": {+ "id": "20260903150000-ia08la1",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "生命周期"+ }+ ]+ },+ {+ "ID": "20260903150000-xv2k13i",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260903150000-xv2k13i",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "远程内核的启动、停止、重启、升级和工作空间切换均需在服务器端完成。关闭桌面客户端不会关闭远程内核。"+ }+ ]+ }+ ]+}diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz.syindex 6bff723c34..ad46a431ed 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz.sy@@ -7,7 +7,7 @@"id": "20211226121203-rjjngpz","title": "通用作業","type": "doc",- "updated": "20260809232000"+ "updated": "20260903150000"},"Children": [{@@ -350,6 +350,23 @@}]},+ {+ "ID": "20260903150000-jflwyxe",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260903150000-jflwyxe",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeTextMark",+ "TextMarkType": "block-ref",+ "TextMarkBlockRefID": "20260903150000-3qa6edk",+ "TextMarkBlockRefSubtype": "d",+ "TextMarkTextContent": "連線至遠端內核"+ }+ ]+ },{"ID": "20240508003130-2qsc91w","Type": "NodeParagraph",diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122459-08mi5cq.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122459-08mi5cq.syindex 5e8f17a3c8..bd2bdade94 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122459-08mi5cq.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122459-08mi5cq.sy@@ -6,7 +6,7 @@"id": "20211226122459-08mi5cq","title": "Docker 伺服","type": "doc",- "updated": "20250926110600"+ "updated": "20260903150000"},"Children": [{@@ -761,7 +761,7 @@"HeadingLevel": 2,"Properties": {"id": "20230406105213-yoyn08w",- "updated": "20250926110600"+ "updated": "20260903150000"},"Children": [{@@ -776,7 +776,7 @@"ListData": {},"Properties": {"id": "20230406105213-899tzed",- "updated": "20250926110600"+ "updated": "20260903150000"},"Children": [{@@ -788,7 +788,7 @@},"Properties": {"id": "20230406105213-n1iq0nk",- "updated": "20230406105213"+ "updated": "20260903150000"},"Children": [{@@ -796,12 +796,23 @@"Type": "NodeParagraph","Properties": {"id": "20230406105213-8dbq6l2",- "updated": "20230406105213"+ "updated": "20260903150000"},"Children": [{"Type": "NodeText",- "Data": "不支持桌面端和移動端應用連接,僅支持在瀏覽器上使用"+ "Data": "行動端應用仍不支援連線。桌面端可以透過遠端模式連線,詳見 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "block-ref",+ "TextMarkBlockRefID": "20260903150000-3qa6edk",+ "TextMarkBlockRefSubtype": "s",+ "TextMarkTextContent": "連線至遠端內核"+ },+ {+ "Type": "NodeText",+ "Data": "。"}]}@@ -838,4 +849,4 @@]}]-}\ No newline at end of file+}diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122523-rl8356a.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122523-rl8356a.syindex 5f57dfc7c8..6999bec10c 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122523-rl8356a.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122523-rl8356a.sy@@ -6,7 +6,7 @@"id": "20211226122523-rl8356a","title": "在瀏覽器上使用","type": "doc",- "updated": "20260804193000"+ "updated": "20260903150000"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20211226122545-a65v8e1",- "updated": "20260804165002"+ "updated": "20260903150000"},"Children": [{@@ -186,6 +186,31 @@}]},+ {+ "ID": "20260903150000-c65oi4q",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260903150000-c65oi4q",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "如需使用桌面端連線至遠端內核,請參閱 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "block-ref",+ "TextMarkBlockRefID": "20260903150000-3qa6edk",+ "TextMarkBlockRefSubtype": "s",+ "TextMarkTextContent": "連線至遠端內核"+ },+ {+ "Type": "NodeText",+ "Data": "。"+ }+ ]+ },{"ID": "20211226122545-lsv6dhu","Type": "NodeHeading",diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20260903150000-3qa6edk.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20260903150000-3qa6edk.synew file mode 100644index 0000000000..7812acdd87--- /dev/null+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20260903150000-3qa6edk.sy@@ -0,0 +1,37 @@+{+ "ID": "20260903150000-3qa6edk",+ "Spec": "2",+ "Type": "NodeDocument",+ "Properties": {+ "id": "20260903150000-3qa6edk",+ "title": "連線至遠端內核",+ "type": "doc",+ "updated": "20260903150000"+ },+ "Children": [+ {"ID": "20260903150000-jrf9aw4", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-jrf9aw4", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "概述"}]},+ {"ID": "20260903150000-6shebfx", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-6shebfx", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "桌面端可以連線至其他裝置上執行的思源內核,並使用本機桌面介面進行編輯。遠端模式僅用於連線至現有內核,不會在本機啟動內核。"}]},+ {"ID": "20260903150000-o9vrit3", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-o9vrit3", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "啟動方式"}]},+ {"ID": "20260903150000-m5fkfh5", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-m5fkfh5", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "完全結束思源桌面用戶端後,從命令列啟動桌面端並加入參數 "}, {"Type": "NodeTextMark", "TextMarkType": "code", "TextMarkTextContent": "--remote=https://host[:port]"}, {"Type": "NodeText", "Data": "。如果已有執行中的實例,單一實例機制不會切換目前的連線。"}]},+ {"ID": "20260903150000-l1lghrh", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-l1lghrh", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "安全性與版本"}]},+ {"ID": "20260903150000-dk8m7z0", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-dk8m7z0", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "僅支援 HTTPS 遠端位址,用戶端作業系統必須信任伺服器使用的 TLS 憑證。請只連線至你信任的伺服器;桌面用戶端與遠端內核的版本必須完全一致,否則無法連線。桌面用戶端僅載入安裝套件內建的前端,不會載入遠端伺服器提供的 HTML、指令碼等可執行前端資源,因此同源的遠端 HTML 嵌入內容也無法使用。"}]},+ {"ID": "20260903150000-uleg2f1", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-uleg2f1", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "功能限制"}]},+ {"ID": "20260903150000-ovlxdje", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-ovlxdje", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "首版遠端模式暫不支援以下功能,本機模式不受影響:"}]},+ {+ "ID": "20260903150000-lw8m6qj",+ "Type": "NodeList",+ "ListData": {},+ "Properties": {"id": "20260903150000-lw8m6qj", "updated": "20260903150000"},+ "Children": [+ {"ID": "20260903150000-iaab0bj", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-iaab0bj", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-rj4jvo4", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-rj4jvo4", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "匯入和匯出"}]}]},+ {"ID": "20260903150000-o4d17am", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-o4d17am", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-uqpqmld", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-uqpqmld", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "檔案剪貼簿操作"}]}]},+ {"ID": "20260903150000-7489c2g", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-7489c2g", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-gopw68q", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-gopw68q", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "依賴用戶端本機路徑或伺服器絕對路徑的操作,例如在檔案管理器中顯示,以及透過路徑拖入或開啟檔案;透過檔案選擇器進行一般資源上傳仍可使用"}]}]},+ {"ID": "20260903150000-yn3mxw7", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-yn3mxw7", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-m8ot8ql", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-m8ot8ql", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "桌面端外掛程式、集市和小工具不可用;僅使用用戶端內建外觀,不載入遠端自訂佈景主題、圖示、字型和程式碼片段"}]}]},+ {"ID": "20260903150000-3s12hif", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-3s12hif", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-pfjakt6", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-pfjakt6", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "HTML 和 SVG 區塊、資料庫範本及 JavaScript 查詢嵌入區塊中的指令碼不會執行,iframe 區塊不可用;圖表、圖解和數學公式等渲染結果會進行安全淨化"}]}]},+ {"ID": "20260903150000-kl3k0d9", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-kl3k0d9", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-c7bpnf2", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-c7bpnf2", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "僅支援存取授權碼登入,不支援 OIDC 登入"}]}]}+ ]+ },+ {"ID": "20260903150000-ie4h9hx", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-ie4h9hx", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "生命週期"}]},+ {"ID": "20260903150000-3bhf4xb", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-3bhf4xb", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "遠端內核的啟動、停止、重新啟動、升級和工作空間切換均需在伺服器端完成。關閉桌面用戶端不會關閉遠端內核。"}]}+ ]+}diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml.syindex 94cac69b1c..068faf69a0 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml.sy@@ -8,7 +8,7 @@"id": "20240530101000-g3ugxml","title": "基本操作","type": "doc",- "updated": "20260809232000"+ "updated": "20260903150000"},"Children": [{@@ -369,6 +369,23 @@}]},+ {+ "ID": "20260903150000-rzryr1j",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260903150000-rzryr1j",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeTextMark",+ "TextMarkType": "block-ref",+ "TextMarkBlockRefID": "20260903150000-hpfmx4t",+ "TextMarkBlockRefSubtype": "d",+ "TextMarkTextContent": "リモートカーネルへの接続"+ }+ ]+ },{"ID": "20240530101000-0pkmezm","Type": "NodeParagraph",@@ -493,4 +510,4 @@]}]-}\ No newline at end of file+}diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-40hohog.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-40hohog.syindex 206ca90d46..ea703af8aa 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-40hohog.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-40hohog.sy@@ -7,7 +7,7 @@"id": "20240530101000-40hohog","title": "ブラウザ","type": "doc",- "updated": "20260804193000"+ "updated": "20260903150000"},"Children": [{@@ -17,7 +17,7 @@"Properties": {"ID": "20240530101000-vn1tvf6","id": "20240530101000-yllodqo",- "updated": "20260804165003"+ "updated": "20260903150000"},"Children": [{@@ -212,6 +212,31 @@}]},+ {+ "ID": "20260903150000-kmzwzmc",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260903150000-kmzwzmc",+ "updated": "20260903150000"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "デスクトップ版からリモートカーネルに接続する方法については、"+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "block-ref",+ "TextMarkBlockRefID": "20260903150000-hpfmx4t",+ "TextMarkBlockRefSubtype": "s",+ "TextMarkTextContent": "リモートカーネルへの接続"+ },+ {+ "Type": "NodeText",+ "Data": "を参照してください。"+ }+ ]+ },{"ID": "20240530101000-b6ssy52","Type": "NodeHeading",diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-f16hpct.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-f16hpct.syindex fab70ad0fe..14c197ab50 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-f16hpct.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-f16hpct.sy@@ -7,7 +7,7 @@"id": "20240530101000-f16hpct","title": "Docker サーバー","type": "doc",- "updated": "20250926110655"+ "updated": "20260903150000"},"Children": [{@@ -906,7 +906,7 @@"Properties": {"ID": "20240530101000-8bjgcwz","id": "20240530101000-av0hc90",- "updated": "20250926110655"+ "updated": "20260903150000"},"Children": [{@@ -922,7 +922,7 @@"Properties": {"ID": "20240530101000-c39mqvp","id": "20240530101000-95f1jst",- "updated": "20250926110655"+ "updated": "20260903150000"},"Children": [{@@ -935,7 +935,7 @@"Properties": {"ID": "20240530101000-9bey4kd","id": "20240530101000-49rpkzp",- "updated": "20240530101000"+ "updated": "20260903150000"},"Children": [{@@ -944,12 +944,23 @@"Properties": {"ID": "20240530101000-ymg86bk","id": "20240530101000-790mb98",- "updated": "20240530101000"+ "updated": "20260903150000"},"Children": [{"Type": "NodeText",- "Data": "デスクトップ版やモバイル版アプリとの接続には対応しておらずブラウザでの使用に限られます"+ "Data": "モバイル版アプリからの接続には対応していません。デスクトップ版はリモートモードで接続できます。詳しくは、"+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "block-ref",+ "TextMarkBlockRefID": "20260903150000-hpfmx4t",+ "TextMarkBlockRefSubtype": "s",+ "TextMarkTextContent": "リモートカーネルへの接続"+ },+ {+ "Type": "NodeText",+ "Data": "を参照してください。"}]}@@ -987,4 +998,4 @@]}]-}\ No newline at end of file+}diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20260903150000-hpfmx4t.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20260903150000-hpfmx4t.synew file mode 100644index 0000000000..0ec32abbff--- /dev/null+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20260903150000-hpfmx4t.sy@@ -0,0 +1,37 @@+{+ "ID": "20260903150000-hpfmx4t",+ "Spec": "2",+ "Type": "NodeDocument",+ "Properties": {+ "id": "20260903150000-hpfmx4t",+ "title": "リモートカーネルへの接続",+ "type": "doc",+ "updated": "20260903150000"+ },+ "Children": [+ {"ID": "20260903150000-ekjy0ld", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-ekjy0ld", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "概要"}]},+ {"ID": "20260903150000-0adfpc3", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-0adfpc3", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "デスクトップ版では、別のデバイスで動作している SiYuan カーネルに接続し、ローカルのデスクトップ UI から編集できます。リモートモードは既存のカーネルへの接続専用であり、ローカルではカーネルを起動しません。"}]},+ {"ID": "20260903150000-c8khz3k", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-c8khz3k", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "起動方法"}]},+ {"ID": "20260903150000-bqc7crd", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-bqc7crd", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "SiYuan デスクトップクライアントを完全に終了してから、コマンドラインでデスクトップ版を起動し、"}, {"Type": "NodeTextMark", "TextMarkType": "code", "TextMarkTextContent": "--remote=https://host[:port]"}, {"Type": "NodeText", "Data": " パラメーターを追加します。既存のインスタンスが実行中の場合、シングルインスタンス機構によって現在の接続先が切り替わることはありません。"}]},+ {"ID": "20260903150000-csljqix", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-csljqix", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "セキュリティとバージョン"}]},+ {"ID": "20260903150000-1qj316h", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-1qj316h", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "リモートアドレスには HTTPS のみを使用でき、クライアントのオペレーティングシステムがサーバーの TLS 証明書を信頼している必要があります。信頼できるサーバーにのみ接続してください。デスクトップクライアントとリモートカーネルのバージョンは完全に一致している必要があります。一致しない場合は接続できません。デスクトップクライアントはインストールパッケージに内蔵されたフロントエンドのみを読み込み、リモートサーバーが提供する HTML やスクリプトなどの実行可能なフロントエンドリソースは読み込みません。そのため、同一オリジンのリモート HTML 埋め込みコンテンツも利用できません。"}]},+ {"ID": "20260903150000-uo7ekyt", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-uo7ekyt", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "機能制限"}]},+ {"ID": "20260903150000-zbe0bfm", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-zbe0bfm", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "リモートモードの初期バージョンでは、次の機能を一時的に利用できません。ローカルモードには影響しません。"}]},+ {+ "ID": "20260903150000-8orlk9f",+ "Type": "NodeList",+ "ListData": {},+ "Properties": {"id": "20260903150000-8orlk9f", "updated": "20260903150000"},+ "Children": [+ {"ID": "20260903150000-b5xb7ub", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-b5xb7ub", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-t5961l9", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-t5961l9", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "インポートとエクスポート"}]}]},+ {"ID": "20260903150000-xoz3jw0", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-xoz3jw0", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-rme1xbh", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-rme1xbh", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "ファイルのクリップボード操作"}]}]},+ {"ID": "20260903150000-3s8fcw7", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-3s8fcw7", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-p1m4g9q", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-p1m4g9q", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "クライアントのローカルパスまたはサーバーの絶対パスに依存する操作(ファイルマネージャーでの表示や、パスを使ったファイルのドラッグ&ドロップまたはオープンなど)。ファイル選択ダイアログからの通常のアセットアップロードは引き続き利用できます"}]}]},+ {"ID": "20260903150000-j3snjto", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-j3snjto", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-adyybel", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-adyybel", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "デスクトッププラグイン、マーケットプレイス、ウィジェットは利用できません。クライアント内蔵の外観のみを使用し、リモートのカスタムテーマ、アイコン、フォント、コードスニペットは読み込みません"}]}]},+ {"ID": "20260903150000-x0al0du", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-x0al0du", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-di7qo01", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-di7qo01", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "HTML/SVG ブロック、データベーステンプレート、JavaScript クエリ埋め込みブロック内のスクリプトは実行されません。iframe ブロックは利用できません。チャート、ダイアグラム、数式などのレンダリング結果は安全のためサニタイズされます"}]}]},+ {"ID": "20260903150000-mmdrbxv", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-mmdrbxv", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-nkf4jkp", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-nkf4jkp", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "アクセス認証コードによるログインのみをサポートし、OIDC ログインには対応していません"}]}]}+ ]+ },+ {"ID": "20260903150000-ttyurfu", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-ttyurfu", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "ライフサイクル"}]},+ {"ID": "20260903150000-ynskaea", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-ynskaea", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "リモートカーネルの起動、停止、再起動、アップグレード、ワークスペースの切り替えはサーバー側で行ってください。デスクトップクライアントを終了しても、リモートカーネルは停止しません。"}]}+ ]+}diff --git a/app/src/ai/editor.ts b/app/src/ai/editor.tsindex 43c4b04dc7..67e2cb1a82 100644--- a/app/src/ai/editor.ts+++ b/app/src/ai/editor.ts@@ -20,6 +20,7 @@ import {isMobile} from "../util/functions";import {Constants} from "../constants";import {bindThinkingCardToggle} from "./thinkingCard";import {BLOCK_SELECTION_MODE_CLASS} from "../protyle/wysiwyg/blockSelection";+import {normalizeHTMLAssetIFrameBlockDOM} from "../asset/html";type TAIEditorSourceKind = "selection" | "blocks" | "writing";type TAIEditorTaskStatus = "streaming" | "done" | "stopped" | "error";@@ -364,7 +365,7 @@ const renderTaskPreview = (task: IAIEditorTask, rich = false) => {return;}task.body.classList.remove("ai-editor-panel__body--streaming");- task.body.innerHTML = task.protyle.lute.Md2BlockDOM(task.content);+ task.body.innerHTML = normalizeHTMLAssetIFrameBlockDOM(task.protyle.lute.Md2BlockDOM(task.content));blockRender(task.protyle, task.body);processRender(task.body);highlightRender(task.body);diff --git a/app/src/asset/html.test.ts b/app/src/asset/html.test.tsindex 380d013a5b..dc997a12b5 100644--- a/app/src/asset/html.test.ts+++ b/app/src/asset/html.test.ts@@ -74,3 +74,81 @@ test("normalizes legacy local HTML IFrame sources", () => {null]);});++test("preserves remote IFrame attributes for serialization", () => {+ const attributes = new Map([+ ["src", "data:text/html,<script>alert(1)</script>"],+ ["srcdoc", "<script>alert(1)</script>"],+ ["sandbox", "allow-scripts allow-same-origin"],+ ["onload", "alert(1)"],+ ["allow", "camera"],+ ["allowfullscreen", "true"],+ ]);+ const iframe = {+ tagName: "IFRAME",+ get attributes() {+ return Array.from(attributes.entries()).map(([name, value]) => ({name, value}));+ },+ getAttribute: (name: string) => attributes.get(name) || null,+ setAttribute: (name: string, value: string) => attributes.set(name, value),+ removeAttribute: (name: string) => attributes.delete(name),+ };+ const root = {+ querySelectorAll: (selector: string) => selector === "*" ? [iframe] : [],+ } as unknown as ParentNode;++ const originalAttributes = new Map(attributes);++ assert.equal(normalizeHTMLAssetIFrameSources(root, true), false);+ assert.deepEqual(attributes, originalAttributes);+});++test("sanitizes active remote document content while preserving editor structure", () => {+ const createElement = (tagName: string, entries: [string, string][]) => {+ const attributes = new Map(entries);+ return {+ tagName,+ attributesMap: attributes,+ removed: false,+ get attributes() {+ return Array.from(attributes.entries()).map(([name, value]) => ({name, value}));+ },+ removeAttribute: (name: string) => attributes.delete(name),+ remove() {+ this.removed = true;+ },+ };+ };+ const customElement = createElement("PROTYLE-HTML", [+ ["data-content", "<strong>content</strong>"],+ ["data-node-id", "20260903150000-abcdefg"],+ ["onclick", "require('child_process').exec('calc')"],+ ]);+ const dangerousLink = createElement("A", [["href", " java\nscript:alert(1)"]]);+ const safeLink = createElement("A", [["href", "https://example.com"]]);+ const embeddedImage = createElement("IMG", [["src", "data:image/png;base64,AAAA"]]);+ const script = createElement("SCRIPT", []);+ const root = {+ querySelectorAll: (selector: string) => {+ if (selector === "iframe") {+ return [];+ }+ if (selector.startsWith("script,")) {+ return [script];+ }+ if (selector === "*") {+ return [customElement, dangerousLink, safeLink, embeddedImage];+ }+ return [];+ },+ } as unknown as ParentNode;++ assert.equal(normalizeHTMLAssetIFrameSources(root, true), true);+ assert.equal(script.removed, true);+ assert.equal(customElement.attributesMap.get("data-content"), "<strong>content</strong>");+ assert.equal(customElement.attributesMap.get("data-node-id"), "20260903150000-abcdefg");+ assert.equal(customElement.attributesMap.has("onclick"), false);+ assert.equal(dangerousLink.attributesMap.has("href"), false);+ assert.equal(safeLink.attributesMap.get("href"), "https://example.com");+ assert.equal(embeddedImage.attributesMap.get("src"), "data:image/png;base64,AAAA");+});diff --git a/app/src/asset/html.ts b/app/src/asset/html.tsindex 4f2d5453b7..b358d16453 100644--- a/app/src/asset/html.ts+++ b/app/src/asset/html.ts@@ -1,3 +1,27 @@+import {getHostCapabilities} from "../util/hostCapabilities";++const REMOTE_ACTIVE_CONTENT_SELECTOR = "script, object, embed, frame, frameset, portal, base, meta[http-equiv]";+const REMOTE_URL_ATTRIBUTES = new Set(["action", "formaction", "href", "poster", "src", "xlink:href"]);++const isDangerousRemoteURL = (element: Element, attributeName: string, value: string) => {+ if (!REMOTE_URL_ATTRIBUTES.has(attributeName)) {+ return false;+ }+ const normalized = Array.from(value).filter((character) => {+ const characterCode = character.charCodeAt(0);+ return characterCode > 0x20 && (characterCode < 0x7f || characterCode > 0x9f);+ }).join("").toLowerCase();+ if (normalized.startsWith("javascript:") || normalized.startsWith("vbscript:") ||+ normalized.startsWith("file:") || normalized.startsWith("blob:")) {+ return true;+ }+ if (!normalized.startsWith("data:")) {+ return false;+ }+ return element.tagName !== "IMG" ||+ !/^data:image\/(?:avif|bmp|gif|jpeg|png|webp);base64,/.test(normalized);+};+export const isHTMLFilePath = (value: string) => {const path = value.split(/[?#]/, 1)[0].toLowerCase();return path.endsWith(".html") || path.endsWith(".htm");@@ -24,29 +48,60 @@ export const getHTMLAssetIFrameSrc = (assetPath: string) => {return `${path}?${params.toString()}${hash}`;};-export const normalizeHTMLAssetIFrameSources = (root: ParentNode) => {+export const normalizeHTMLAssetIFrameSources = (+ root: ParentNode,+ remoteKernel = typeof window !== "undefined" && getHostCapabilities().remoteKernel,+) => {let changed = false;- root.querySelectorAll<HTMLIFrameElement>('[data-type="NodeIFrame"] iframe').forEach(item => {- const src = item.getAttribute("src");- if (!src) {- return;- }- const normalizedSrc = getHTMLAssetIFrameSrc(src);- if (normalizedSrc !== src) {- item.setAttribute("src", normalizedSrc);+ if (!remoteKernel) {+ root.querySelectorAll<HTMLIFrameElement>('[data-type="NodeIFrame"] iframe').forEach(item => {+ const src = item.getAttribute("src");+ if (!src) {+ return;+ }+ const normalizedSrc = getHTMLAssetIFrameSrc(src);+ if (normalizedSrc !== src) {+ item.setAttribute("src", normalizedSrc);+ changed = true;+ }+ });+ }+ if (remoteKernel) {+ root.querySelectorAll<Element>(REMOTE_ACTIVE_CONTENT_SELECTOR).forEach(item => {+ item.remove();changed = true;- }- });+ });+ root.querySelectorAll<Element>("*").forEach(item => {+ // 远程桌面由宿主 CSP 和导航拦截禁用 iframe,保留属性可避免编辑时写回禁用状态。+ if (item.tagName === "IFRAME") {+ return;+ }+ Array.from(item.attributes).forEach(attribute => {+ const name = attribute.name.toLowerCase();+ if (name.startsWith("on") || name === "srcdoc" ||+ isDangerousRemoteURL(item, name, attribute.value)) {+ item.removeAttribute(attribute.name);+ changed = true;+ }+ });+ });+ root.querySelectorAll<HTMLTemplateElement>("template").forEach(item => {+ if (normalizeHTMLAssetIFrameSources(item.content, true)) {+ changed = true;+ }+ });+ }return changed;};export const normalizeHTMLAssetIFrameBlockDOM = (html: string) => {- if (!html.includes("NodeIFrame") || !html.includes("<iframe")) {+ const remoteKernel = getHostCapabilities().remoteKernel;+ if (!remoteKernel && (!html.includes("NodeIFrame") || !html.includes("<iframe"))) {return html;}const template = document.createElement("template");template.innerHTML = html;- if (!normalizeHTMLAssetIFrameSources(template.content)) {+ if (!normalizeHTMLAssetIFrameSources(template.content, remoteKernel)) {return html;}return template.innerHTML;diff --git a/app/src/asset/renderAssets.ts b/app/src/asset/renderAssets.tsindex c1a24e1e49..74dc65c3e9 100644--- a/app/src/asset/renderAssets.ts+++ b/app/src/asset/renderAssets.ts@@ -4,7 +4,7 @@ import {getAllModels} from "../layout/getAll";/// #endifimport {getAssetExtension} from "../util/pathName";import * as dayjs from "dayjs";-import {escapeAttr} from "../util/escape";+import {escapeAttr, escapeHtml} from "../util/escape";import {getHTMLAssetIFrameSrc, isHTMLFilePath} from "./html";import {isBrowserRenderableImagePath} from "../util/imageURL";import {getAssetsPreviewPath} from "./previewPath";@@ -22,7 +22,7 @@ export const renderAssetsPreview = (pathString: string, dataPath?: string) => {} else if (Constants.SIYUAN_ASSETS_VIDEO.includes(type)) {return `<video style="max-width: 100%" controls="controls" src="${previewPath}"></video>`;} else {- return pathString;+ return escapeHtml(pathString);}};diff --git a/app/src/assets/template/app/index.tpl b/app/src/assets/template/app/index.tplindex c5649964d4..05c9613e74 100644--- a/app/src/assets/template/app/index.tpl+++ b/app/src/assets/template/app/index.tpl@@ -13,7 +13,7 @@<div id="loading" class="b3-dialog b3-dialog--open"><div class="b3-dialog__scrim" style="background-color: #1e1e1e"></div><img style="position: absolute;width: 24vh;" src="../../icon.svg">- <button onclick="window.location.reload()" id="loadingRefresh"+ <button id="loadingRefresh"style="display: none;position: absolute;bottom: 16px;background: transparent;border: 1px solid #4285f4;color: #4285f4;border-radius: 6px;line-height: 20px;padding: 4px 8px;">Click to Refresh<br>点 击 刷 新</button>@@ -47,12 +47,13 @@<div id="message" class="b3-snackbars"></div><div id="tooltip" class="tooltip fn__none"></div><script>- setTimeout(() => {- const refreshElement = document.getElementById("loadingRefresh")- if (refreshElement) {- refreshElement.style.display = ""- }- }, 7000)+ const refreshElement = document.getElementById("loadingRefresh");+ if (refreshElement) {+ refreshElement.addEventListener("click", () => window.location.reload());+ setTimeout(() => {+ refreshElement.style.display = "";+ }, 7000);+ }</script></body></html>diff --git a/app/src/block/util.ts b/app/src/block/util.tsindex 63ca8dcdc8..605384ab07 100644--- a/app/src/block/util.ts+++ b/app/src/block/util.ts@@ -24,6 +24,7 @@ import {} from "./cancelSuperBlock";import {shouldFocusJumpTarget, shouldFocusParentDocumentTitle} from "./jumpToParent";import {getHorizontalSuperBlockChild} from "./superBlock";+import {normalizeHTMLAssetIFrameBlockDOM} from "../asset/html";export const getCancelSBOperations = async (nodeElement: Element, options: {notebookID?: string,@@ -45,7 +46,7 @@ export const getCancelSBOperations = async (nodeElement: Element, options: {notebook: options.notebookID,});const template = document.createElement("template");- template.innerHTML = response.data?.dom || "";+ template.innerHTML = normalizeHTMLAssetIFrameBlockDOM(response.data?.dom || "");const fullSuperBlockElement = template.content.querySelector(`[data-node-id="${id}"]`);if (!fullSuperBlockElement) {return {diff --git a/app/src/boot/globalEvent/commonHotkey.ts b/app/src/boot/globalEvent/commonHotkey.tsindex 8c34af16c1..7cf29156e5 100644--- a/app/src/boot/globalEvent/commonHotkey.ts+++ b/app/src/boot/globalEvent/commonHotkey.ts@@ -8,6 +8,7 @@ import type {App} from "../../index";import {isMac, isNotCtrl, isOnlyMeta} from "../../protyle/util/compatibility";import {showPopover} from "../../block/popover";import {clearDisallowedKeymapItems} from "../../util/hotKeyPolicy";+import {getHostCapabilities} from "../../util/hostCapabilities";const matchKeymap = (keymap: Config.IKeys, key1: "general" | "editor", key2?: "general" | "insert" | "heading" | "list" | "table") => {if (key1 === "general") {@@ -182,7 +183,7 @@ export const syncAppMenuShortcuts = () => {}lastHotkeys = {...hotkey};ipcRenderer.send(Constants.SIYUAN_SYNC_APP_MENU, {- workspaceDir: window.siyuan.config.system.workspaceDir,+ workspaceDir: getHostCapabilities().workspaces ? window.siyuan.config.system.workspaceDir : "",lang: window.siyuan.config.lang,readonly: window.siyuan.config.readonly,hotkey,diff --git a/app/src/boot/globalEvent/searchKeydown.ts b/app/src/boot/globalEvent/searchKeydown.tsindex 30acd11b0f..86b019de18 100644--- a/app/src/boot/globalEvent/searchKeydown.ts+++ b/app/src/boot/globalEvent/searchKeydown.ts@@ -18,6 +18,7 @@ import {getUnRefList} from "../../search/unRef";import {toggleAssetHistory, toggleReplaceHistory, toggleSearchHistory} from "../../search/toggleHistory";import {Protyle} from "../../protyle";import {getKeysByLiElement} from "../../search/menu";+import {getHostCapabilities} from "../../util/hostCapabilities";export const searchKeydown = (app: App, event: KeyboardEvent) => {if (getSelection().rangeCount === 0) {@@ -237,7 +238,9 @@ export const searchKeydown = (app: App, event: KeyboardEvent) => {}} else {/// #if !BROWSER- useShell("showItemInFolder", path.join(window.siyuan.config.system.dataDir, currentList.lastElementChild.getAttribute("aria-label")));+ if (getHostCapabilities().localFileSystem) {+ useShell("showItemInFolder", path.join(window.siyuan.config.system.dataDir, currentList.lastElementChild.getAttribute("aria-label")));+ }/// #endif}return true;diff --git a/app/src/boot/onGetConfig.ts b/app/src/boot/onGetConfig.tsindex 49bf6d0837..6fd0ffd2be 100644--- a/app/src/boot/onGetConfig.ts+++ b/app/src/boot/onGetConfig.ts@@ -38,15 +38,19 @@ import {openDesktopOnboarding} from "../onboarding";import {ensureUILayout} from "../util/ensureUILayout";import {dispatchPluginGlobalShortcut} from "../plugin/globalShortcut";import {requestResponsiveDockLayout} from "../layout/dock/responsive";+import {getHostCapabilities, setHostConnection, type TKernelConnection} from "../util/hostCapabilities";export const onGetConfig = (isStart: boolean, app: App) => {correctHotkey(app);document.body.classList.toggle("body--windows", isWindows());/// #if !BROWSER- ipcRenderer.invoke(Constants.SIYUAN_INIT, {+ void ipcRenderer.invoke(Constants.SIYUAN_INIT, {languages: window.siyuan.languages["_trayMenu"],- workspaceDir: window.siyuan.config.system.workspaceDir,- port: location.port+ workspaceDir: getHostCapabilities().workspaces ? window.siyuan.config.system.workspaceDir : "",+ port: location.port,+ remote: getHostCapabilities().remoteKernel,+ }).then((connection: TKernelConnection | undefined) => setHostConnection(connection)).catch((error) => {+ console.error("initialize desktop host failed:", error);});webFrame.setZoomFactor(window.siyuan.storage[Constants.LOCAL_ZOOM]);const position = Constants.SIZE_ZOOM.find((item) => item.zoom === window.siyuan.storage[Constants.LOCAL_ZOOM]).position;@@ -215,6 +219,9 @@ export const initWindow = async (app: App) => {}});ipcRenderer.on(Constants.SIYUAN_EXPORT_PDF, async (e, ipcData) => {+ if (!getHostCapabilities().importExport) {+ return;+ }const msgId = showMessage(window.siyuan.languages.exporting, -1);window.siyuan.storage[Constants.LOCAL_EXPORTPDF] = {removeAssets: ipcData.removeAssets,diff --git a/app/src/boot/openChangelog.ts b/app/src/boot/openChangelog.tsindex 09fb2777b6..9672d36822 100644--- a/app/src/boot/openChangelog.ts+++ b/app/src/boot/openChangelog.ts@@ -3,6 +3,7 @@ import {Dialog} from "../dialog";import {highlightRender} from "../protyle/render/highlightRender";import {isMobile} from "../util/functions";import {Constants} from "../constants";+import {sanitizeKernelHTML} from "../util/hostCapabilities";export const openChangelog = () => {fetchPost("/api/system/getChangelog", {}, (response) => {@@ -13,7 +14,7 @@ export const openChangelog = () => {title: `✨ ${window.siyuan.languages.whatsNewInSiYuan} v${window.siyuan.config.system.kernelVersion}`,width: isMobile() ? "92vw" : "768px",height: isMobile() ? "80vh" : "70vh",- content: `<div style="overflow:auto;" class="b3-dialog__content b3-typography b3-typography--default">${response.data.html}</div>`+ content: `<div style="overflow:auto;" class="b3-dialog__content b3-typography b3-typography--default">${sanitizeKernelHTML(response.data.html)}</div>`});dialog.element.setAttribute("data-key", Constants.DIALOG_CHANGELOG);highlightRender(dialog.element);diff --git a/app/src/card/makeCard.ts b/app/src/card/makeCard.tsindex aa6895e4c7..13ceb56729 100644--- a/app/src/card/makeCard.ts+++ b/app/src/card/makeCard.ts@@ -11,10 +11,10 @@ import {transaction} from "../protyle/wysiwyg/transaction";import type {App} from "../index";export const genCardItem = (item: ICardPackage) => {- return `<li data-id="${item.id}" data-name="${escapeAttr(item.name)}" class="b3-list-item b3-list-item--narrow${isMobile() ? "" : " b3-list-item--hide-action"}">+ return `<li data-id="${escapeAttr(item.id)}" data-name="${escapeAttr(item.name)}" class="b3-list-item b3-list-item--narrow${isMobile() ? "" : " b3-list-item--hide-action"}"><span class="b3-list-item__text"><span>${escapeHtml(item.name)}</span>- <span class="b3-list-item__meta">${item.size}</span>+ <span class="b3-list-item__meta">${escapeHtml(String(item.size))}</span></span><span data-type="rename" class="b3-list-item__action b3-tooltips b3-tooltips__w" aria-label="${window.siyuan.languages.rename}"><svg><use xlink:href="#iconEdit"></use></svg>@@ -31,7 +31,7 @@ export const genCardItem = (item: ICardPackage) => {<span data-type="add" style="display: flex" class="b3-list-item__action b3-tooltips b3-tooltips__w" aria-label="${window.siyuan.languages.addDeck}"><svg><use xlink:href="#iconAdd"></use></svg></span>-<span class="b3-list-item__meta${isMobile() ? " fn__none" : ""}">${item.updated}</span>+<span class="b3-list-item__meta${isMobile() ? " fn__none" : ""}">${escapeHtml(String(item.updated))}</span></li>`;};diff --git a/app/src/card/openCard.ts b/app/src/card/openCard.tsindex 4c25b7b74f..a4775b57f7 100644--- a/app/src/card/openCard.ts+++ b/app/src/card/openCard.ts@@ -37,6 +37,7 @@ import {} from "./flashcardMode";import {setFold} from "../protyle/util/blockFold";import {forEachPluginSubscriber} from "../plugin/EventBusCore";+import {appendRemoteQuery} from "../util/hostCapabilities";const genCardCount = (cardsData: ICardData, allIndex = 0) => {let newIndex = 0;@@ -595,10 +596,10 @@ export const bindCardEvent = async (options: {}}}];- ipcRenderer.send(Constants.SIYUAN_OPEN_WINDOW, {- // 需要 encode, 否则 https://github.com/siyuan-note/siyuan/issues/9343- url: `${window.location.protocol}//${window.location.host}/stage/build/app/window.html?v=${Constants.SIYUAN_VERSION}&json=${encodeURIComponent(JSON.stringify(json))}`- });+ const url = new URL("/stage/build/app/window.html", window.location.origin);+ url.searchParams.set("v", Constants.SIYUAN_VERSION);+ url.searchParams.set("json", JSON.stringify(json));+ ipcRenderer.send(Constants.SIYUAN_OPEN_WINDOW, {url: appendRemoteQuery(url).href});options.dialog.destroy();}});diff --git a/app/src/config/assets.ts b/app/src/config/assets.tsindex c7de7dd252..5065719e7f 100644--- a/app/src/config/assets.ts+++ b/app/src/config/assets.ts@@ -17,6 +17,7 @@ import type {App} from "../index";import {disabledProtyle, onGet} from "../protyle/util/onGet";import {removeLoading} from "../protyle/ui/initUI";import {switchSettingPanelSubTab} from "./setting/mount";+import {getHostCapabilities} from "../util/hostCapabilities";/// #if MOBILEimport {openMobileFileById} from "../mobile/editor";/// #else@@ -343,7 +344,7 @@ const assets = {}[], element: Element, type: "unRefAV" | "unrefAssets" | "lostAssets") => {let html = "";let boxOpenHTML = "";- if (!isBrowser() && type !== "lostAssets") {+ if (!isBrowser() && getHostCapabilities().localFileSystem && type !== "lostAssets") {boxOpenHTML = `<span data-type="open" class="ariaLabel b3-list-item__action" aria-label="${window.siyuan.languages.showInFolder}"><svg><use xlink:href="#iconFolder"></use></svg></span>`;diff --git a/app/src/config/entryVisibility/ui.ts b/app/src/config/entryVisibility/ui.tsindex 2004ec9d9b..77c0d39c54 100644--- a/app/src/config/entryVisibility/ui.ts+++ b/app/src/config/entryVisibility/ui.ts@@ -30,6 +30,7 @@ import {normalizeEntryVisibilityImportProfile,TEntryVisibilityImportProfile,} from "./profile";+import {getHostCapabilities} from "../../util/hostCapabilities";type TImportFile = {type: "siyuan-entry-profile" | "siyuan-entry-profile-bundle";@@ -59,6 +60,9 @@ const uniqueName = (name: string, profiles = window.siyuan.config.appearance.ent};const downloadJSON = (name: string, data: unknown) => {+ if (!getHostCapabilities().importExport) {+ return;+ }const blob = new Blob([JSON.stringify(data, undefined, 2)], {type: "application/json"});const url = URL.createObjectURL(blob);const anchor = document.createElement("a");@@ -158,7 +162,7 @@ const profileCard = (<div class="b3-card__actions b3-card__actions--right">${active ? "" : `<button class="b3-button b3-button--outline" data-action="activate">${window.siyuan.languages.use}</button>`}<button class="block__icon block__icon--show ariaLabel" data-action="duplicate" data-position="north" aria-label="${window.siyuan.languages.duplicateCopy}"><svg><use xlink:href="#iconCopy"></use></svg></button>- ${builtin ? "" : `<button class="block__icon block__icon--show ariaLabel" data-action="export" data-position="north" aria-label="${window.siyuan.languages.export}"><svg><use xlink:href="#iconDownload"></use></svg></button>`}+ ${builtin || !getHostCapabilities().importExport ? "" : `<button class="block__icon block__icon--show ariaLabel" data-action="export" data-position="north" aria-label="${window.siyuan.languages.export}"><svg><use xlink:href="#iconDownload"></use></svg></button>`}<button class="block__icon block__icon--show${active || builtin ? " fn__none" : " block__icon--warning"} ariaLabel" data-action="delete" data-position="north" aria-label="${window.siyuan.languages.delete}"><svg><use xlink:href="#iconTrashcan"></use></svg></button></div></div>`;@@ -643,6 +647,9 @@ const openProfileEditor = (root: HTMLElement, profileID?: string) => {};const importProfiles = async (root: HTMLElement, file: File) => {+ if (!getHostCapabilities().importExport) {+ return;+ }try {const data = JSON.parse(await file.text()) as TImportFile;if (!isEntryVisibilityImportVersionSupported(data.version, ENTRY_VISIBILITY_VERSION)) {@@ -687,10 +694,10 @@ export const genEntryVisibilityHtml = () => `<div class="b3-label config-item" d<div class="fn__flex config-wrap"><div><div class="config-name">${window.siyuan.languages.entryVisibility}</div><div class="b3-label__text">${window.siyuan.languages.entryVisibilityTip}</div></div><span class="fn__space fn__flex-1"></span>- <button class="b3-button b3-button--outline" data-action="import"><svg class="b3-button__icon"><use xlink:href="#iconUpload"></use></svg>${window.siyuan.languages.import}</button>+ ${getHostCapabilities().importExport ? `<button class="b3-button b3-button--outline" data-action="import"><svg class="b3-button__icon"><use xlink:href="#iconUpload"></use></svg>${window.siyuan.languages.import}</button><span class="fn__space"></span><button class="b3-button b3-button--outline" data-action="export-all"><svg class="b3-button__icon"><use xlink:href="#iconDownload"></use></svg>${window.siyuan.languages.export}</button>- <span class="fn__space"></span>+ <span class="fn__space"></span>` : ""}<button class="b3-button b3-button--outline" data-action="create"><svg class="b3-button__icon"><use xlink:href="#iconAdd"></use></svg>${window.siyuan.languages.entryCreateProfile}</button><input class="fn__none" data-type="entry-import" type="file" accept="application/json,.json"></div>diff --git a/app/src/config/index.ts b/app/src/config/index.tsindex 726d9ae354..46529faf16 100644--- a/app/src/config/index.ts+++ b/app/src/config/index.ts@@ -19,6 +19,7 @@ import {clearSyncTabElement} from "./tabs/syncRuntime";import type {TSettingTab} from "./setting/tabs";import type {App} from "../index";import {unmountAssetsTab} from "./assets";+import {getHostCapabilities} from "../util/hostCapabilities";/// #if !MOBILEconst openSettingDialog = (app: App, initialTab: TSettingTab = "editor") => {@@ -94,6 +95,9 @@ export const openSetting = (app: App, tab?: TSettingTab) => {if (tab === "bazaar" && !isBazaarAvailable()) {return;}+ if (tab === "export" && !getHostCapabilities().importExport) {+ return;+ }/// #if MOBILEopenMobileSetting(app, tab);/// #elsediff --git a/app/src/config/setting/tabs.ts b/app/src/config/setting/tabs.tsindex 7026e8a082..50699e472c 100644--- a/app/src/config/setting/tabs.ts+++ b/app/src/config/setting/tabs.ts@@ -28,6 +28,7 @@ import {registerAccessTab} from "../tabs/accessTab";import {registerAppTab} from "../tabs/appTab";import {registerAboutTab} from "../tabs/aboutTab";import {isDisabledFeature} from "../../protyle/util/compatibility";+import {getHostCapabilities} from "../../util/hostCapabilities";const setting = new SettingBuilder();const settingTabs = {@@ -87,6 +88,7 @@ const settingTabs = {id: "export",icon: "iconUpload",title: () => window.siyuan.languages.export,+ hidden: () => !getHostCapabilities().importExport,defaultSave: exportConfigApi.patch,}, registerExportTab),search: setting.tab({diff --git a/app/src/config/tabs/aboutTab.ts b/app/src/config/tabs/aboutTab.tsindex d365a6838d..e5cebfc65b 100644--- a/app/src/config/tabs/aboutTab.ts+++ b/app/src/config/tabs/aboutTab.ts@@ -4,6 +4,7 @@ import {fetchPost} from "../../util/fetch";import {getCloudURL} from "../util/about";import {openLink} from "../../editor/openLink";import {sendAppSetting} from "./appRuntime";+import {getHostCapabilities} from "../../util/hostCapabilities";const registerAboutVersionGroup = (tab: SettingTabBuilder) => {const group = tab.group("version", "");@@ -21,7 +22,7 @@ const registerAboutVersionGroup = (tab: SettingTabBuilder) => {html: genAboutVersionHtml,afterMount: mountAboutVersionSlot,});- if (!window.siyuan.config.system.isMicrosoftStore) {+ if (!window.siyuan.config.system.isMicrosoftStore && getHostCapabilities().ownsKernel) {group.select("system.updateChannel", {title: window.siyuan.languages.updateChannel,desc: window.siyuan.languages.updateChannelTip,@@ -34,7 +35,8 @@ const registerAboutVersionGroup = (tab: SettingTabBuilder) => {});}/// #if !BROWSER- if (!window.siyuan.config.system.isMicrosoftStore && window.siyuan.config.system.container === "std" && window.siyuan.config.system.os !== "linux") {+ if (!window.siyuan.config.system.isMicrosoftStore && getHostCapabilities().ownsKernel &&+ window.siyuan.config.system.container === "std" && window.siyuan.config.system.os !== "linux") {group.switch("system.downloadInstallPkg", {title: window.siyuan.languages.autoDownloadUpdatePkg,desc: window.siyuan.languages.autoDownloadUpdatePkgTip,@@ -45,6 +47,13 @@ const registerAboutVersionGroup = (tab: SettingTabBuilder) => {};const genAboutVersionHtml = (): string => {+ if (!getHostCapabilities().ownsKernel) {+ return `<div class="fn__flex b3-label config-item config-wrap">+ <div class="fn__flex-1">+ <div class="config-name">${window.siyuan.languages.currentVer} v${Constants.SIYUAN_VERSION}</div>+ </div>+</div>`;+ }if (window.siyuan.config.system.isMicrosoftStore) {return `<div class="fn__flex b3-label config-item config-wrap"><div class="fn__flex-1">diff --git a/app/src/config/tabs/accessTab.ts b/app/src/config/tabs/accessTab.tsindex 5c308ff834..a760353b7b 100644--- a/app/src/config/tabs/accessTab.ts+++ b/app/src/config/tabs/accessTab.ts@@ -20,6 +20,7 @@ import {} from "./accessRuntime";import {sendAppSetting} from "./appRuntime";import zxcvbn = require("zxcvbn");+import {canOpenExternalURL, getHostCapabilities} from "../../util/hostCapabilities";const getPasswordStrength = (password: string) => {const score = zxcvbn(password).score;@@ -72,7 +73,7 @@ const registerAccessAuthGroup = (tab: SettingTabBuilder) => {save: (value) => sendAppSetting("system.lockScreenMode", value),});}- if (!window.siyuan.config.readonly) {+ if (!window.siyuan.config.readonly && getHostCapabilities().oidcAuthentication) {group.button({id: "oidcConfig",title: window.siyuan.languages.oidcLogin,@@ -91,6 +92,9 @@ const registerAccessAuthGroup = (tab: SettingTabBuilder) => {};const mountOIDCButton = (root: HTMLElement) => {+ if (!getHostCapabilities().oidcAuthentication) {+ return;+ }root.querySelector("#oidcConfig")?.addEventListener("click", () => {const config = window.siyuan.config.oidc;const escape = (value: string) => Lute.EscapeHTMLStr(value);@@ -272,6 +276,10 @@ const mountOIDCButton = (root: HTMLElement) => {window.handleOIDCAuthError = (message: string) => validationFailed(message, attempt);};const openValidationURL = (url: string, attempt: number) => {+ if (!canOpenExternalURL(url)) {+ validationFailed(window.siyuan.languages.oidcVerificationFailed, attempt);+ return;+ }if (validationWindow) {validationWindow.location.href = url;return;@@ -458,7 +466,7 @@ const bindApiTokenInput = (root: HTMLElement) => {const registerAccessServerGroup = (tab: SettingTabBuilder) => {const hideOnWeb = isBrowser() && !isInMobileApp();- if (hideOnWeb) {+ if (hideOnWeb || !getHostCapabilities().ownsKernel) {return;}const group = tab.group("server", window.siyuan.languages.configGroupServer);@@ -466,16 +474,25 @@ const registerAccessServerGroup = (tab: SettingTabBuilder) => {group.switch("system.networkServe", {title: window.siyuan.languages.about11,desc: window.siyuan.languages.about12,- save: (value) => sendAppSetting("system.networkServe", value),+ save: (value) => {+ if (getHostCapabilities().ownsKernel) {+ sendAppSetting("system.networkServe", value);+ }+ },});if (window.siyuan.config.system.networkServe) {group.switch("system.networkServeTLS", {title: window.siyuan.languages.networkServeTLS,desc: `${window.siyuan.languages.networkServeTLSTip}<div class="fn__hr--small"></div>${window.siyuan.languages.networkServeTLSTip2}`,- save: (value) => sendAppSetting("system.networkServeTLS", value),+ save: (value) => {+ if (getHostCapabilities().ownsKernel) {+ sendAppSetting("system.networkServeTLS", value);+ }+ },});}- if (window.siyuan.config.system.networkServe && window.siyuan.config.system.networkServeTLS) {+ if (window.siyuan.config.system.networkServe && window.siyuan.config.system.networkServeTLS &&+ getHostCapabilities().importExport) {group.button({id: "exportCACert",title: window.siyuan.languages.exportCACert,@@ -536,31 +553,36 @@ const registerAccessServerGroup = (tab: SettingTabBuilder) => {},});}- group.stack({- key: "localServer",- keywords: [- window.siyuan.languages.about2,- window.siyuan.languages.about3,- window.siyuan.languages.about4,- window.siyuan.languages.about18,- ],- afterMount: (root) => {- root.querySelector("#openLocalServer")?.addEventListener("click", () => {- const url = `http://127.0.0.1:${location.port}`;- openLink(window.siyuan.ws.app, url);+ if (getHostCapabilities().localFileSystem) {+ group.stack({+ key: "localServer",+ keywords: [+ window.siyuan.languages.about2,+ window.siyuan.languages.about3,+ window.siyuan.languages.about4,+ window.siyuan.languages.about18,+ ],+ afterMount: (root) => {+ root.querySelector("#openLocalServer")?.addEventListener("click", () => {+ if (!getHostCapabilities().localFileSystem) {+ return;+ }+ const url = `http://127.0.0.1:${location.port}`;+ openLink(window.siyuan.ws.app, url);+ });+ },+ }, (stack) => {+ stack.title(window.siyuan.languages.about2);+ stack.button({+ id: "openLocalServer",+ label: window.siyuan.languages.about4,+ icon: "iconLink",});- },- }, (stack) => {- stack.title(window.siyuan.languages.about2);- stack.button({- id: "openLocalServer",- label: window.siyuan.languages.about4,- icon: "iconLink",+ stack.desc(window.siyuan.languages.about3.replace("${port}", location.port));+ stack.desc(`<span id="serverAddresses">${genServerAddressesHTML(window.siyuan.config.serverAddrs)}</span>`);+ stack.desc(window.siyuan.languages.about18);});- stack.desc(window.siyuan.languages.about3.replace("${port}", location.port));- stack.desc(`<span id="serverAddresses">${genServerAddressesHTML(window.siyuan.config.serverAddrs)}</span>`);- stack.desc(window.siyuan.languages.about18);- });+ }};const registerAccessPublishGroup = (tab: SettingTabBuilder) => {@@ -679,6 +701,7 @@ const registerEncryptedNotebookGroup = (tab: SettingTabBuilder) => {if (window.siyuan.config.readonly) {return;}+ const disableImportExport = !getHostCapabilities().importExport;const group = tab.group("encryptedNotebook", window.siyuan.languages.encryptedNotebook);group.slot({key: "encryptedNotebookStatus",@@ -707,13 +730,13 @@ const registerEncryptedNotebookGroup = (tab: SettingTabBuilder) => {${window.siyuan.languages.changeMasterPassword}</button><span class="fn__space"></span>- <button class="b3-button b3-button--outline fn__flex-center fn__size200" id="exportCryptoBackupBtn">+ <button class="b3-button b3-button--outline fn__flex-center fn__size200${disableImportExport ? " fn__none" : ""}" id="exportCryptoBackupBtn"><svg class="svg"><use xlink:href="#iconDownload"></use></svg>${window.siyuan.languages.exportNotebookCryptoBackup}</button><span class="fn__space"></span></div>- <button class="b3-button b3-button--outline fn__flex-center fn__size200" id="importCryptoBackupBtn">+ <button class="b3-button b3-button--outline fn__flex-center fn__size200${disableImportExport ? " fn__none" : ""}" id="importCryptoBackupBtn"><svg class="svg"><use xlink:href="#iconUpload"></use></svg>${window.siyuan.languages.importNotebookCryptoBackup}</button>@@ -744,7 +767,7 @@ const mountEncryptedNotebook = (root: HTMLElement) => {window.siyuan.config.notebookCrypto.enabled = enabled;// 修改主密码和导出密钥仅在配置完整时可见;Disabled 或 RecoveryRequired 状态提供导入恢复入口。enabledActionsElement.classList.toggle("fn__none", !enabled);- importCryptoBackupBtnElement.classList.toggle("fn__none", enabled);+ importCryptoBackupBtnElement.classList.toggle("fn__none", enabled || !getHostCapabilities().importExport);actionsElement.classList.remove("fn__none");migrationAlertElement.classList.toggle("fn__none", !response.data.migrationPending);});@@ -756,6 +779,9 @@ const mountEncryptedNotebook = (root: HTMLElement) => {});actionsElement.querySelector("#exportCryptoBackupBtn")?.addEventListener("click", () => {+ if (!getHostCapabilities().importExport) {+ return;+ }fetchPost("/api/notebook/exportNotebookCryptoBackup", {}, async (response) => {if (response.code === -1) {showMessage(response.msg, 6000, "error");@@ -769,6 +795,9 @@ const mountEncryptedNotebook = (root: HTMLElement) => {});actionsElement.querySelector("#importCryptoBackupBtn")?.addEventListener("click", () => {+ if (!getHostCapabilities().importExport) {+ return;+ }// 用隐藏 file input 选备份文件,multipart 上传导入const fileInput = document.createElement("input");fileInput.type = "file";diff --git a/app/src/config/tabs/ai/aiUi.ts b/app/src/config/tabs/ai/aiUi.tsindex c129fa15fe..2f5e7906f9 100644--- a/app/src/config/tabs/ai/aiUi.ts+++ b/app/src/config/tabs/ai/aiUi.ts@@ -7,6 +7,7 @@ import {fetchPost} from "../../../util/fetch";import {escapeHtml} from "../../../util/escape";import {aiConfigApi} from "./aiRuntime";import {openByMobile} from "../../../editor/openLink";+import {canOpenExternalURL} from "../../../util/hostCapabilities";/// #if !BROWSERimport {shell} from "electron";/// #endif@@ -423,7 +424,8 @@ export const mountMcpServersBlock = (root: HTMLElement) => {connectedCount++;totalTools += item.tools;}- if (item.authorizationURL && openedMcpOAuthURLs.get(item.id) !== item.authorizationURL) {+ if (item.authorizationURL && canOpenExternalURL(item.authorizationURL) &&+ openedMcpOAuthURLs.get(item.id) !== item.authorizationURL) {openedMcpOAuthURLs.set(item.id, item.authorizationURL);/// #if !BROWSERvoid shell.openExternal(item.authorizationURL).catch((error: Error) => {diff --git a/app/src/config/tabs/appTab.ts b/app/src/config/tabs/appTab.tsindex 98f94ae733..2af0778b79 100644--- a/app/src/config/tabs/appTab.ts+++ b/app/src/config/tabs/appTab.ts@@ -23,10 +23,11 @@ import {afterExport} from "../../protyle/export/util";/// #endifimport {genConfigItemMainHtml, genConfigItemName} from "../render/fragments";import {sendAppSetting} from "./appRuntime";+import {getHostCapabilities} from "../../util/hostCapabilities";/// #if MOBILEconst registerAppWorkspaceGroup = (tab: SettingTabBuilder) => {- if (!isInMobileApp() || window.siyuan.config.readonly) {+ if (!isInMobileApp() || window.siyuan.config.readonly || !getHostCapabilities().workspaces) {return;}const group = tab.group("workspace", window.siyuan.languages.workspaceList);@@ -65,6 +66,9 @@ const renderWorkspaceList = (workspaceDirElement: Element) => {};const mountAppWorkspaceSlot = (root: HTMLElement) => {+ if (!getHostCapabilities().workspaces) {+ return;+ }const workspaceDirElement = root.querySelector("#workspaceDir");if (!workspaceDirElement) {return;@@ -286,6 +290,9 @@ const mountNetworkProxy = (root: HTMLElement) => {};const registerAppDataGroup = (tab: SettingTabBuilder) => {+ if (!getHostCapabilities().importExport) {+ return;+ }const group = tab.group("data", window.siyuan.languages.configGroupData);group.button({@@ -361,6 +368,9 @@ const registerAppDataGroup = (tab: SettingTabBuilder) => {};const mountExportData = (root: HTMLElement) => {+ if (!getHostCapabilities().importExport) {+ return;+ }root.querySelector("#exportData")?.addEventListener("click", async () => {/// #if BROWSERfetchPost("/api/export/exportData", {}, (response) => {@@ -436,20 +446,22 @@ const registerAppMaintenanceGroup = (tab: SettingTabBuilder) => {});},});- group.button({- id: "exportLog",- title: window.siyuan.languages.systemLog,- desc: window.siyuan.languages.systemLogTip,- label: window.siyuan.languages.export,- icon: "iconUpload",- afterMount: (root) => {- root.querySelector("#exportLog")?.addEventListener("click", () => {- fetchPost("/api/system/exportLog", {}, (response) => {- void saveExportFile(response.data.zip);+ if (getHostCapabilities().importExport) {+ group.button({+ id: "exportLog",+ title: window.siyuan.languages.systemLog,+ desc: window.siyuan.languages.systemLogTip,+ label: window.siyuan.languages.export,+ icon: "iconUpload",+ afterMount: (root) => {+ root.querySelector("#exportLog")?.addEventListener("click", () => {+ fetchPost("/api/system/exportLog", {}, (response) => {+ void saveExportFile(response.data.zip);+ });});- });- },- });+ },+ });+ }};export const registerAppTab = (tab: SettingTabBuilder) => {@@ -457,6 +469,8 @@ export const registerAppTab = (tab: SettingTabBuilder) => {registerAppWorkspaceGroup(tab);/// #endifregisterAppGeneralGroup(tab);- registerAppDataGroup(tab);+ if (getHostCapabilities().importExport) {+ registerAppDataGroup(tab);+ }registerAppMaintenanceGroup(tab);};diff --git a/app/src/config/tabs/appearanceTab.ts b/app/src/config/tabs/appearanceTab.tsindex e832db2d1d..93b43e41ee 100644--- a/app/src/config/tabs/appearanceTab.ts+++ b/app/src/config/tabs/appearanceTab.ts@@ -15,6 +15,7 @@ import {isInMobileApp} from "../../protyle/util/compatibility";import {fetchPost, fetchSyncPost} from "../../util/fetch";import {openLink} from "../../editor/openLink";import {openSnippets} from "../util/snippets";+import {getHostCapabilities} from "../../util/hostCapabilities";import {confirmDialog} from "../../dialog/confirmDialog";import {Dialog} from "../../dialog";import {Menu} from "../../plugin/Menu";@@ -101,19 +102,21 @@ const genFontConfigHtml = (configKey: FontFamiliesConfigKey, title: string, descconst registerAppearanceContentGroup = (tab: SettingTabBuilder) => {const group = tab.group("content", window.siyuan.languages.configGroupContent);- group.slot({- key: "fontFamilies",- keywords: [window.siyuan.languages.font, window.siyuan.languages.font1],- html: () => genFontConfigHtml("fontFamilies", window.siyuan.languages.font, window.siyuan.languages.font1),- afterMount: (root) => mountAppearanceFontFamily(root, "fontFamilies"),- });- group.slot({- key: "codeFontFamilies",- keywords: [window.siyuan.languages.monospaceFont, window.siyuan.languages.monospaceFontTip],- html: () => genFontConfigHtml("codeFontFamilies", window.siyuan.languages.monospaceFont,- window.siyuan.languages.monospaceFontTip),- afterMount: (root) => mountAppearanceFontFamily(root, "codeFontFamilies"),- });+ if (getHostCapabilities().customAppearance) {+ group.slot({+ key: "fontFamilies",+ keywords: [window.siyuan.languages.font, window.siyuan.languages.font1],+ html: () => genFontConfigHtml("fontFamilies", window.siyuan.languages.font, window.siyuan.languages.font1),+ afterMount: (root) => mountAppearanceFontFamily(root, "fontFamilies"),+ });+ group.slot({+ key: "codeFontFamilies",+ keywords: [window.siyuan.languages.monospaceFont, window.siyuan.languages.monospaceFontTip],+ html: () => genFontConfigHtml("codeFontFamilies", window.siyuan.languages.monospaceFont,+ window.siyuan.languages.monospaceFontTip),+ afterMount: (root) => mountAppearanceFontFamily(root, "codeFontFamilies"),+ });+ }group.range("editor.fontSize", {title: window.siyuan.languages.editorFontSize,desc: window.siyuan.languages.fontSizeTip,@@ -752,78 +755,80 @@ const registerAppearanceInterfaceGroup = (tab: SettingTabBuilder) => {afterMount: mountBootAppearance,});/// #endif- group.stack({- key: "theme",- keywords: [- window.siyuan.languages.theme,- window.siyuan.languages.theme11,- window.siyuan.languages.theme12,- window.siyuan.languages.appearance9,- ],- afterMount: (root) => {+ if (getHostCapabilities().customAppearance) {+ group.stack({+ key: "theme",+ keywords: [+ window.siyuan.languages.theme,+ window.siyuan.languages.theme11,+ window.siyuan.languages.theme12,+ window.siyuan.languages.appearance9,+ ],+ afterMount: (root) => {+ /// #if !BROWSER+ root.querySelector("#appearanceOpenTheme")?.addEventListener("click", () => {+ useShell("openPath", path.join(window.siyuan.config.system.confDir, "appearance", "themes"));+ });+ /// #endif+ },+ }, (stack) => {+ stack.title(window.siyuan.languages.theme);/// #if !BROWSER- root.querySelector("#appearanceOpenTheme")?.addEventListener("click", () => {- useShell("openPath", path.join(window.siyuan.config.system.confDir, "appearance", "themes"));+ stack.button({+ id: "appearanceOpenTheme",+ label: window.siyuan.languages.appearance9,+ icon: "iconFolder",});/// #endif- },- }, (stack) => {- stack.title(window.siyuan.languages.theme);- /// #if !BROWSER- stack.button({- id: "appearanceOpenTheme",- label: window.siyuan.languages.appearance9,- icon: "iconFolder",- });- /// #endif- stack.select("appearance.themeLight", {- desc: window.siyuan.languages.theme11,- options: window.siyuan.config.appearance.lightThemes.filter((item) =>- isThemeFrontendSupported(item.frontends, getFrontend())).map((item) => ({- value: item.name,- label: item.label,- })),- });- stack.select("appearance.themeDark", {- desc: window.siyuan.languages.theme12,- options: window.siyuan.config.appearance.darkThemes.filter((item) =>- isThemeFrontendSupported(item.frontends, getFrontend())).map((item) => ({- value: item.name,- label: item.label,- })),+ stack.select("appearance.themeLight", {+ desc: window.siyuan.languages.theme11,+ options: window.siyuan.config.appearance.lightThemes.filter((item) =>+ isThemeFrontendSupported(item.frontends, getFrontend())).map((item) => ({+ value: item.name,+ label: item.label,+ })),+ });+ stack.select("appearance.themeDark", {+ desc: window.siyuan.languages.theme12,+ options: window.siyuan.config.appearance.darkThemes.filter((item) =>+ isThemeFrontendSupported(item.frontends, getFrontend())).map((item) => ({+ value: item.name,+ label: item.label,+ })),+ });});- });- group.stack({- key: "icon",- keywords: [- window.siyuan.languages.icon,- window.siyuan.languages.theme2,- window.siyuan.languages.appearance8,- ],- afterMount: (root) => {+ group.stack({+ key: "icon",+ keywords: [+ window.siyuan.languages.icon,+ window.siyuan.languages.theme2,+ window.siyuan.languages.appearance8,+ ],+ afterMount: (root) => {+ /// #if !BROWSER+ root.querySelector("#appearanceOpenIcon")?.addEventListener("click", () => {+ useShell("openPath", path.join(window.siyuan.config.system.confDir, "appearance", "icons"));+ });+ /// #endif+ },+ }, (stack) => {+ stack.title(window.siyuan.languages.icon);/// #if !BROWSER- root.querySelector("#appearanceOpenIcon")?.addEventListener("click", () => {- useShell("openPath", path.join(window.siyuan.config.system.confDir, "appearance", "icons"));+ stack.button({+ id: "appearanceOpenIcon",+ label: window.siyuan.languages.appearance8,+ icon: "iconFolder",});/// #endif- },- }, (stack) => {- stack.title(window.siyuan.languages.icon);- /// #if !BROWSER- stack.button({- id: "appearanceOpenIcon",- label: window.siyuan.languages.appearance8,- icon: "iconFolder",- });- /// #endif- stack.select("appearance.icon", {- desc: window.siyuan.languages.theme2,- options: window.siyuan.config.appearance.icons.map((item) => ({- value: item.name,- label: item.label,- })),+ stack.select("appearance.icon", {+ desc: window.siyuan.languages.theme2,+ options: window.siyuan.config.appearance.icons.map((item) => ({+ value: item.name,+ label: item.label,+ })),+ });});- });+ }group.stack({key: "codeBlockTheme",keywords: [@@ -1160,6 +1165,9 @@ const mountAppearanceSetNotifications = (root: HTMLElement) => {};const registerAppearancePersonalizationGroup = (tab: SettingTabBuilder) => {+ if (!getHostCapabilities().customAppearance) {+ return;+ }const group = tab.group("personalization", window.siyuan.languages.configGroupPersonalization);/// #if !BROWSERdiff --git a/app/src/config/tabs/editorTab.ts b/app/src/config/tabs/editorTab.tsindex 6467165358..7bb6d7a27f 100644--- a/app/src/config/tabs/editorTab.ts+++ b/app/src/config/tabs/editorTab.ts@@ -6,6 +6,7 @@ import type {SettingTabBuilder} from "../setting/builder";import {controlSelect} from "../setting/control";import {genStackHtml} from "../render/render";import type {StackLine} from "../render/parts";+import {getHostCapabilities} from "../../util/hostCapabilities";/// #if !BROWSERimport {ipcRenderer} from "electron";/// #endif@@ -82,7 +83,7 @@ const registerEditorBehaviorGroup = (tab: SettingTabBuilder) => {{value: "new-window", label: window.siyuan.languages.openByNewWindow},{value: "app", label: window.siyuan.languages.useDefault},{value: "folder", label: window.siyuan.languages.showInFolder},- ];+ ].filter((item) => getHostCapabilities().localFileSystem || !["app", "folder"].includes(item.value));const assetOpenControls = [{key: "click",@@ -389,18 +390,20 @@ const registerEditorAdvancedGroup = (tab: SettingTabBuilder) => {desc: window.siyuan.languages.katexMacrosTip,mode: "textarea",});- group.switch("editor.dragHTMLFileToIframe", {- title: window.siyuan.languages.dragHTMLFileToIframe,- desc: window.siyuan.languages.dragHTMLFileToIframeTip,- });- group.switch("editor.allowSVGScript", {- title: window.siyuan.languages.allowSVGScript,- desc: window.siyuan.languages.allowSVGScriptTip,- });- group.switch("editor.allowHTMLBLockScript", {- title: window.siyuan.languages.allowHTMLBLockScript,- desc: window.siyuan.languages.allowHTMLBLockScriptTip,- });+ if (!getHostCapabilities().remoteKernel) {+ group.switch("editor.dragHTMLFileToIframe", {+ title: window.siyuan.languages.dragHTMLFileToIframe,+ desc: window.siyuan.languages.dragHTMLFileToIframeTip,+ });+ group.switch("editor.allowSVGScript", {+ title: window.siyuan.languages.allowSVGScript,+ desc: window.siyuan.languages.allowSVGScriptTip,+ });+ group.switch("editor.allowHTMLBLockScript", {+ title: window.siyuan.languages.allowHTMLBLockScript,+ desc: window.siyuan.languages.allowHTMLBLockScriptTip,+ });+ }};export const registerEditorTab = (tab: SettingTabBuilder) => {diff --git a/app/src/config/tabs/syncUi.ts b/app/src/config/tabs/syncUi.tsindex ec4367cd26..5aad6b1db6 100644--- a/app/src/config/tabs/syncUi.ts+++ b/app/src/config/tabs/syncUi.ts@@ -4,6 +4,7 @@ import {confirmDialog} from "../../dialog/confirmDialog";import {isInIOS, saveExportFile} from "../../protyle/util/compatibility";import {isPaidUser, needSubscribe} from "../../util/needSubscribe";import {getCloudURL} from "../util/about";+import {getHostCapabilities, sanitizeKernelHTML} from "../../util/hostCapabilities";/** 按当前配置刷新同步 Tab 可见性与动态面板(供 syncRuntime 调用) */export const refreshSyncTabPanels = (root: Element) => {@@ -327,7 +328,7 @@ const genProviderFlexSelect = (label: string, id: string, optionsHtml: string) =</div>`;const genProviderActionButtons = (dataType: SyncProviderConfigKey) => {- const importExportHtml = dataType === "s3" || dataType === "webdav" ? `<div class="fn__space"></div>+ const importExportHtml = getHostCapabilities().importExport && (dataType === "s3" || dataType === "webdav") ? `<div class="fn__space"></div><button class="b3-button b3-button--outline fn__size200" style="position: relative"><input id="importSyncConfig" class="b3-form__upload" type="file" data-type="${dataType}"><svg><use xlink:href="#iconDownload"></use></svg>${window.siyuan.languages.import}@@ -357,6 +358,9 @@ const bindProviderConfigEvent = (configElement: Element, root: Element) => {const importElement = configElement.querySelector("#importSyncConfig") as HTMLInputElement;importElement?.addEventListener("change", () => {+ if (!getHostCapabilities().importExport) {+ return;+ }const formData = new FormData();formData.append("file", importElement.files[0]);const isS3 = importElement.getAttribute("data-type") === "s3";@@ -373,6 +377,9 @@ const bindProviderConfigEvent = (configElement: Element, root: Element) => {const exportButton = configElement.querySelector("#exportSyncConfig");exportButton?.addEventListener("click", () => {+ if (!getHostCapabilities().importExport) {+ return;+ }fetchPost(exportButton.getAttribute("data-type") === "s3" ? "/api/sync/exportSyncProviderS3" : "/api/sync/exportSyncProviderWebDAV", {}, (response) => {void saveExportFile(response.data.zip);});@@ -474,7 +481,7 @@ const renderCloudSpace = (root: Element) => {);fetchSyncPost("/api/cloud/getCloudSpace").then((response) => {if (response.code === 1) {- cloudSpaceElement.innerHTML = `<span class="ft__error">${response.msg}</span>`;+ cloudSpaceElement.innerHTML = `<span class="ft__error">${sanitizeKernelHTML(response.msg)}</span>`;return;}if (response.code !== 0 || !response.data) {diff --git a/app/src/config/util/snippets.ts b/app/src/config/util/snippets.tsindex 8bf4b8a1cc..720cb2de14 100644--- a/app/src/config/util/snippets.ts+++ b/app/src/config/util/snippets.ts@@ -4,8 +4,12 @@ import {isMobile, objEquals} from "../../util/functions";import {confirmDialog} from "../../dialog/confirmDialog";import {Constants} from "../../constants";import {refreshHeadingNumberMeasurements} from "../../util/assets";+import {getHostCapabilities} from "../../util/hostCapabilities";export const renderSnippet = (timeout = 0) => {+ if (!getHostCapabilities().customAppearance) {+ return Promise.resolve();+ }const abortController = timeout > 0 ? new AbortController() : undefined;const timeoutId = abortController ? window.setTimeout(() => {abortController.abort();diff --git a/app/src/dialog/message.ts b/app/src/dialog/message.tsindex 1eb8335e7f..acd5db34b3 100644--- a/app/src/dialog/message.ts+++ b/app/src/dialog/message.ts@@ -1,5 +1,6 @@import {genUUID} from "../util/genID";import {Constants} from "../constants";+import {getHostCapabilities, sanitizeKernelHTML} from "../util/hostCapabilities";export const initMessage = () => {const messageElement = document.getElementById("message");@@ -37,6 +38,14 @@ export const showMessage = (message: string, timeout = 6000, type = "info", messreturn;}+ const remoteKernel = getHostCapabilities().remoteKernel;+ if (remoteKernel) {+ timeout = Number.isFinite(timeout) ? Math.max(-1, Math.min(Math.trunc(timeout), 2147483647)) : 6000;+ type = type === "error" ? "error" : "info";+ }+ const safeMessage = sanitizeKernelHTML(message);+ const safeMessageId = remoteKernel && messageId && !/^[\w-]+$/.test(messageId) ? undefined : messageId;+const messagesElement = document.getElementById("message").firstElementChild;if (!messagesElement) {let tempMessages = document.getElementById("tempMessage");@@ -48,12 +57,12 @@ id="tempMessage"></div>`);tempMessages.insertAdjacentHTML("beforeend", `<div style="background: white;padding: 8px 16px;border-radius: 6px;margin-bottom: 16px;"data-timeout="${timeout}"data-type="${type}"-data-message-id="${messageId || ""}">${message}</div>`);+data-message-id="${safeMessageId || ""}">${safeMessage}</div>`);return;}- const id = messageId || genUUID();+ const id = safeMessageId || genUUID();const existElement = messagesElement.querySelector(`.b3-snackbar[data-id="${id}"]`);- const messageVersion = message + (type === "error" ? " v" + Constants.SIYUAN_VERSION : "");+ const messageVersion = safeMessage + (type === "error" ? " v" + Constants.SIYUAN_VERSION : "");if (existElement) {window.clearTimeout(parseInt(existElement.getAttribute("data-timeoutid")));existElement.innerHTML = `<div data-type="textMenu" class="b3-snackbar__content${timeout === 0 ? " b3-snackbar__content--close" : ""}">${messageVersion}</div>${timeout === 0 ? '<svg class="b3-snackbar__close"><use xlink:href="#iconCloseRound"></use></svg>' : ""}`;diff --git a/app/src/dialog/processSystem.ts b/app/src/dialog/processSystem.tsindex dc5da5c2e8..5ff2d54338 100644--- a/app/src/dialog/processSystem.ts+++ b/app/src/dialog/processSystem.ts@@ -20,6 +20,7 @@ import {saveScroll} from "../protyle/scroll/saveScroll";import {isInAndroid, isInHarmony, isInIOS, setStorageVal} from "../protyle/util/compatibility";import {emitToPlugins} from "../plugin/EventBusCore";import {createHostQuitGuard} from "./hostQuit";+import {getHostCapabilities, sanitizeKernelHTML} from "../util/hostCapabilities";export const processBacklinkIndexCommit = (data: {rootIDs?: string[],@@ -46,7 +47,7 @@ export const setRefDynamicText = (data: {getAllEditor().forEach(editor => {// 不能对比 rootId,否则嵌入块中的锚文本无法更新editor.protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${data.blockID}"] span[data-type~="block-ref"][data-subtype="d"][data-id="${data.defBlockID}"]`).forEach(item => {- item.innerHTML = data.refText;+ item.innerHTML = sanitizeKernelHTML(data.refText);});});};@@ -171,6 +172,9 @@ export const forceQuit = () => {};const installNewVersion = (installPkgPath: string, setCurrentWorkspace: boolean) => {+ if (!getHostCapabilities().ownsKernel) {+ return;+ }if (!installPkgPath) {showMessage(window.siyuan.languages._kernel[104], 7000, "error");return;@@ -202,6 +206,10 @@ export const exitSiYuan = async (setCurrentWorkspace = true) => {await saveScroll(window.siyuan.mobile.editor.protyle);}/// #endif+ if (!getHostCapabilities().ownsKernel) {+ forceQuit();+ return;+ }fetchPost("/api/system/exit", {force: false, setCurrentWorkspace}, (response) => {if (response.code === 1) { // 同步执行失败const msgId = showMessage(response.msg, response.data.closeTimeout, "error");@@ -290,7 +298,7 @@ export const progressStatus = (data: IWebSocketData) => {const msgElement = document.querySelector("#status .status__msg");if (msgElement) {clearTimeout(statusTimeout);- msgElement.innerHTML = data.msg;+ msgElement.innerHTML = sanitizeKernelHTML(data.msg);statusTimeout = window.setTimeout(() => {msgElement.innerHTML = "";}, 12000);@@ -309,10 +317,14 @@ export const progressLoading = (data: IWebSocketData) => {return;}if (data.code === 0) {+ const current = Number(data.data.current);+ const total = Number(data.data.total);+ const safeCurrent = Number.isFinite(current) ? current : 0;+ const safeTotal = Number.isFinite(total) && total > 0 ? total : 1;progressElement.innerHTML = `<div class="b3-dialog__scrim" style="opacity: 1"></div><div class="b3-dialog__loading">- <div style="text-align: right">${data.data.current}/${data.data.total}</div>- <div style="margin: 8px 0;height: 8px;border-radius: var(--b3-border-radius);overflow: hidden;background-color:#fff;"><div style="width: ${data.data.current / data.data.total * 100}%;transition: var(--b3-transition);background-color: var(--b3-theme-primary);height: 8px;"></div></div>+ <div style="text-align: right">${safeCurrent}/${safeTotal}</div>+ <div style="margin: 8px 0;height: 8px;border-radius: var(--b3-border-radius);overflow: hidden;background-color:#fff;"><div style="width: ${safeCurrent / safeTotal * 100}%;transition: var(--b3-transition);background-color: var(--b3-theme-primary);height: 8px;"></div></div><div class="ft__breakword">${escapeHtml(data.msg)}</div></div>`;} else if (data.code === 1) {@@ -340,9 +352,13 @@ export const progressBackgroundTask = (tasks: { action: string }[]) => {window.siyuan.menus.menu.remove();}} else {+ const safeTasks = tasks.map((item) => ({+ ...item,+ action: sanitizeKernelHTML(item.action),+ }));backgroundTaskElement.classList.remove("fn__none");- backgroundTaskElement.setAttribute("data-tasks", JSON.stringify(tasks));- backgroundTaskElement.innerHTML = tasks[0].action + '<div class="fn__progress"><div></div></div>';+ backgroundTaskElement.setAttribute("data-tasks", JSON.stringify(safeTasks));+ backgroundTaskElement.innerHTML = safeTasks[0].action + '<div class="fn__progress"><div></div></div>';}};@@ -352,7 +368,7 @@ export const bootSync = () => {const dialog = new Dialog({width: isMobile() ? "92vw" : "50vw",title: "🌩️ " + window.siyuan.languages.bootSyncFailed,- content: `<div class="b3-dialog__content">${response.msg}</div>+ content: `<div class="b3-dialog__content">${sanitizeKernelHTML(response.msg)}</div><div class="b3-dialog__action"><button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div><button class="b3-button b3-button--text">${window.siyuan.languages.syncNow}</button>diff --git a/app/src/editor/assetOpen.test.ts b/app/src/editor/assetOpen.test.tsindex 2c10348356..acd80b381e 100644--- a/app/src/editor/assetOpen.test.ts+++ b/app/src/editor/assetOpen.test.ts@@ -4,6 +4,7 @@ import {DEFAULT_ASSET_OPEN,getAssetOpenGestures,normalizeAssetOpenConfig,+ resolveAvailableAssetOpenAction,resolveAssetOpenAction,resolveAssetOpenGesture,resolveExecutableAssetOpenAction,@@ -65,6 +66,13 @@ describe("asset opening", () => {});});+ it("maps host file actions to the internal preview when local files are unavailable", () => {+ assert.equal(resolveAvailableAssetOpenAction("app", false), "current");+ assert.equal(resolveAvailableAssetOpenAction("folder", false), "current");+ assert.equal(resolveAvailableAssetOpenAction("right", false), "right");+ assert.equal(resolveAvailableAssetOpenAction("app", true), "app");+ });+it("keeps each gesture separate when actions degrade to the default app", () => {assert.deepEqual(getAssetOpenGestures(undefined, "app", {previewable: false,diff --git a/app/src/editor/assetOpen.ts b/app/src/editor/assetOpen.tsindex c6a9cacc62..e3729ab35c 100644--- a/app/src/editor/assetOpen.ts+++ b/app/src/editor/assetOpen.ts@@ -75,6 +75,16 @@ export const resolveExecutableAssetOpenAction = (return action;};+export const resolveAvailableAssetOpenAction = (+ action: Config.TAssetOpenAction,+ localFileSystem: boolean,+): Config.TAssetOpenAction => {+ if (!localFileSystem && (action === "app" || action === "folder")) {+ return "current";+ }+ return action;+};+export const getAssetOpenGestures = (config: Config.IAssetOpen | undefined,action: Config.TAssetOpenAction,diff --git a/app/src/editor/openLink.ts b/app/src/editor/openLink.tsindex 5b792696ba..7a00398f73 100644--- a/app/src/editor/openLink.ts+++ b/app/src/editor/openLink.ts@@ -14,11 +14,13 @@ import type {App} from "../index";import {isBrowserRenderableImagePath} from "../util/imageURL";import {DEFAULT_ASSET_OPEN,+ resolveAvailableAssetOpenAction,resolveAssetOpenAction,resolveExecutableAssetOpenAction,} from "./assetOpen";import {emitOpenAsset, emitOpenLink, resolveOpenLinkEvent} from "./openLinkEvent";import {resolvePdfAssetLink} from "./pdfAssetLink";+import {canOpenExternalURL, getHostCapabilities} from "../util/hostCapabilities";/// #if !MOBILEimport {openAssetNewWindow} from "../window/openNewWindow";/// #endif@@ -42,10 +44,10 @@ export const openAssetByAction = (/// #if MOBILEopenByMobile(assetPath);/// #else- const resolvedAction = resolveExecutableAssetOpenAction(action, {+ const resolvedAction = resolveAvailableAssetOpenAction(resolveExecutableAssetOpenAction(action, {previewable: isPreviewableAsset(assetPath),noSplitScreen: window.siyuan.config.fileTree.noSplitScreenWhenOpenTab,- });+ }), getHostCapabilities().localFileSystem);if (resolvedAction === "current") {openAsset(app, assetPath, page);} else if (resolvedAction === "right") {@@ -103,10 +105,10 @@ export const openLink = (app: App, aLink: string, event?: MouseEvent, ctrlIsPresctrlKey: ctrlIsPressed,},);- let action = resolveExecutableAssetOpenAction(configuredAction, {+ let action = resolveAvailableAssetOpenAction(resolveExecutableAssetOpenAction(configuredAction, {previewable: isPreviewableAsset(linkAddress),noSplitScreen: window.siyuan.config.fileTree.noSplitScreenWhenOpenTab,- });+ }), getHostCapabilities().localFileSystem);/// #if BROWSERif (action === "folder" || action === "new-window") {action = "app";@@ -148,6 +150,9 @@ export const openLink = (app: App, aLink: string, event?: MouseEvent, ctrlIsPresopenAssetByAction(app, linkAddress, pdfParams, action);} else if (linkAddress) {/// #if !BROWSER+ if (!canOpenExternalURL(linkAddress)) {+ return;+ }shell.openExternal(linkAddress).catch((e) => {showMessage(e);});@@ -165,6 +170,9 @@ export const openByMobile = (uri: string) => {if (processSiYuanUri(window.siyuan.ws.app, uri)) {return;}+ if (!canOpenExternalURL(uri)) {+ return;+ }if (isInIOS()) {if (uri.startsWith("assets/")) {// iOS 16.7 之前的版本,uri 需要 encodeURIComponentdiff --git a/app/src/editor/util.ts b/app/src/editor/util.tsindex b148220724..940484226c 100644--- a/app/src/editor/util.ts+++ b/app/src/editor/util.ts@@ -36,6 +36,7 @@ import {Model} from "../layout/Model";import {hideElements} from "../protyle/ui/hideElements";import {isBrowserRenderableImagePath} from "../util/imageURL";import {forEachPluginSubscriber} from "../plugin/EventBusCore";+import {getHostCapabilities} from "../util/hostCapabilities";const isSameCustomTab = (type: string, data: any, options: IOpenFileOptions) => {if (!options.custom || (options.custom.id && options.custom.id !== type)) {@@ -809,6 +810,9 @@ export const updateBacklinkGraph = (models: IModels, protyle: IProtyle) => {};export const openBy = (url: string, type: "folder" | "app") => {+ if (!getHostCapabilities().localFileSystem) {+ return;+ }/// #if !BROWSERif (url.startsWith("assets/")) {fetchPost("/api/asset/resolveAssetPath", {path: url.replace(/\.pdf\?page=\d{1,}$/, ".pdf")}, (response) => {diff --git a/app/src/history/diff.ts b/app/src/history/diff.tsindex 6488278aa2..d35693dc4b 100644--- a/app/src/history/diff.ts+++ b/app/src/history/diff.ts@@ -523,13 +523,13 @@ const genHTML = (left: string, right: string, dialog: Dialog, direct: string, ficonst headElement = dialog.element.querySelector(".b3-dialog__header");headElement.innerHTML = `<div style="padding: 0;min-height: auto;" class="block__icons"><span class="fn__flex-1"></span>- <code class="fn__code${isPhone ? " fn__none" : ""}" data-snapshot="${left}" data-created="${response.data.left.created}">${left.substring(0, 7)}</code>+ <code class="fn__code${isPhone ? " fn__none" : ""}" data-snapshot="${escapeAttr(left)}" data-created="${escapeAttr(String(response.data.left.created))}">${escapeHtml(left.substring(0, 7))}</code>${isPhone ? "" : '<span class="fn__space"></span>'}${dayjs(response.data.left.created).format("YYYY-MM-DD HH:mm")}<span class="fn__space"></span><span class="block__icon block__icon--show b3-tooltips b3-tooltips__s" aria-label="${window.siyuan.languages.switchDirect}" data-direct="${direct}"><svg><use xlink:href="#iconScrollHoriz"></use></svg></span><span class="fn__space"></span>- <code class="fn__code${isPhone ? " fn__none" : ""}" data-snapshot="${right}" data-created="${response.data.right.created}">${right.substring(0, 7)}</code>+ <code class="fn__code${isPhone ? " fn__none" : ""}" data-snapshot="${escapeAttr(right)}" data-created="${escapeAttr(String(response.data.right.created))}">${escapeHtml(right.substring(0, 7))}</code>${isPhone ? "" : '<span class="fn__space"></span>'}${dayjs(response.data.right.created).format("YYYY-MM-DD HH:mm")}<span class="fn__flex-1"></span>@@ -540,14 +540,14 @@ const genHTML = (left: string, right: string, dialog: Dialog, direct: string, fi<div class="fn__flex-1 fn__flex" data-type="editors"><div class="fn__none fn__flex-1 fn__flex-column"><div class="history__date">${dayjs(response.data.left.created).format("YYYY-MM-DD HH:mm")}</div>- <div class="protyle-title__input ft__center ft__breakword">${response.data.left.title}</div>+ <div class="protyle-title__input ft__center ft__breakword">${escapeHtml(response.data.left.title)}</div><div class="ft__center"></div><textarea class="history__text fn__none fn__flex-1" readonly></textarea><div class="fn__flex-1"></div></div><div class="fn__none fn__flex-1 fn__flex-column" style="border-left: 1px solid var(--b3-border-color);">- <div class="history__date">${response.data.right.title} ${dayjs(response.data.right.created).format("YYYY-MM-DD HH:mm")}</div>- <div class="protyle-title__input ft__center ft__breakword">${response.data.right.title}</div>+ <div class="history__date">${escapeHtml(response.data.right.title)} ${dayjs(response.data.right.created).format("YYYY-MM-DD HH:mm")}</div>+ <div class="protyle-title__input ft__center ft__breakword">${escapeHtml(response.data.right.title)}</div><div class="ft__center"></div><textarea class="history__text fn__none fn__flex-1" readonly></textarea><div class="fn__flex-1"></div>diff --git a/app/src/history/repoFile.ts b/app/src/history/repoFile.tsindex 9d35b7e17b..062e2d5318 100644--- a/app/src/history/repoFile.ts+++ b/app/src/history/repoFile.ts@@ -8,6 +8,7 @@ import {disabledProtyle, onGet} from "../protyle/util/onGet";import {escapeAttr, escapeHtml} from "../util/escape";import {fetchPost} from "../util/fetch";import {pathPosix} from "../util/pathName";+import {getHostCapabilities} from "../util/hostCapabilities";import * as dayjs from "dayjs";interface IRepoFile {@@ -36,7 +37,7 @@ export const renderRepoFileList = (files: IRepoFile[], element: Element, showPat<span class="b3-list-item__action b3-tooltips b3-tooltips__w" data-type="rollback" aria-label="${window.siyuan.languages.rollback}"><svg><use xlink:href="#iconUndo"></use></svg></span>- <span class="b3-list-item__action b3-tooltips b3-tooltips__w" data-type="saveAs" aria-label="${window.siyuan.languages.saveAs}">+ <span class="b3-list-item__action b3-tooltips b3-tooltips__w${getHostCapabilities().importExport ? "" : " fn__none"}" data-type="saveAs" aria-label="${window.siyuan.languages.saveAs}"><svg><use xlink:href="#iconDownload"></use></svg></span><span class="b3-list-item__action b3-tooltips b3-tooltips__w" data-type="selectVersion" aria-pressed="false" aria-label="${window.siyuan.languages.compare}">@@ -57,7 +58,7 @@ export const renderRepoFileList = (files: IRepoFile[], element: Element, showPat</div><div class="fn__flex" style="height: 26px"><span class="fn__flex-1"></span>- <span class="b3-list-item__action" data-type="saveAs">+ <span class="b3-list-item__action${getHostCapabilities().importExport ? "" : " fn__none"}" data-type="saveAs"><svg><use xlink:href="#iconDownload"></use></svg><span class="fn__space"></span>${window.siyuan.languages.saveAs}</span>@@ -79,7 +80,7 @@ export const renderRepoFileList = (files: IRepoFile[], element: Element, showPat${dayjs(item.updated).format("YYYY-MM-DD HH:mm:ss")}</div></div>- <span class="b3-list-item__action b3-tooltips b3-tooltips__w" data-type="saveAs" aria-label="${window.siyuan.languages.saveAs}">+ <span class="b3-list-item__action b3-tooltips b3-tooltips__w${getHostCapabilities().importExport ? "" : " fn__none"}" data-type="saveAs" aria-label="${window.siyuan.languages.saveAs}"><svg><use xlink:href="#iconDownload"></use></svg></span><span class="b3-list-item__action b3-tooltips b3-tooltips__w" data-type="rollback" aria-label="${window.siyuan.languages.rollback}">@@ -108,6 +109,9 @@ export const rollbackRepoFile = (element: Element) => {};export const saveRepoFile = (element: Element) => {+ if (!getHostCapabilities().importExport) {+ return;+ }fetchPost("/api/repo/exportRepoFile", {id: element.getAttribute("data-id")}, (response) => {diff --git a/app/src/index.ts b/app/src/index.tsindex f893ffa7dc..0bb3e616f9 100644--- a/app/src/index.ts+++ b/app/src/index.ts@@ -301,7 +301,7 @@ export class App {};const notebookPromise = setNoteBook();fetchPost("/api/system/getConf", {}, async (response) => {- addScriptSync(`${Constants.PROTYLE_CDN}/js/lute/lute.min.js?v=${Constants.SIYUAN_VERSION}`, "protyleLuteScript");+ await addScriptSync(`${Constants.PROTYLE_CDN}/js/lute/lute.min.js?v=${Constants.SIYUAN_VERSION}`, "protyleLuteScript");addScript(`${Constants.PROTYLE_CDN}/js/protyle-html.js?v=${Constants.SIYUAN_VERSION}`, "protyleWcHtmlScript");window.siyuan.config = response.data.conf;ensureUILayout();diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.tsindex e80e69838d..3c9739bd07 100644--- a/app/src/layout/dock/Files.ts+++ b/app/src/layout/dock/Files.ts@@ -71,6 +71,7 @@ import {updateFileTreeSortMode} from "../../util/fileTreeSort";import {clearDocumentTabMovePreview} from "../tabDrag";+import {getHostCapabilities} from "../../util/hostCapabilities";export class Files extends Model {public element: HTMLElement;@@ -2048,20 +2049,22 @@ aria-label="${ariaLabel}">${getDocDisplayName(item.name, item.titleEmpty, true)}}}).element);}- window.siyuan.menus.menu.append(new MenuItem({- id: "importNotebook",- icon: "iconDownload",- label: `${window.siyuan.languages.importNotebook}<input class="b3-form__upload" type="file" accept="application/zip">`,- bind: (element) => {- element.querySelector<HTMLInputElement>(".b3-form__upload").addEventListener("change", (event) => {- const file = (event.target as HTMLInputElement).files?.[0];- if (file) {- window.siyuan.menus.menu.remove();- importNotebook(file);- }- });- },- }).element);+ if (getHostCapabilities().importExport) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "importNotebook",+ icon: "iconDownload",+ label: `${window.siyuan.languages.importNotebook}<input class="b3-form__upload" type="file" accept="application/zip">`,+ bind: (element) => {+ element.querySelector<HTMLInputElement>(".b3-form__upload").addEventListener("change", (event) => {+ const file = (event.target as HTMLInputElement).files?.[0];+ if (file) {+ window.siyuan.menus.menu.remove();+ importNotebook(file);+ }+ });+ },+ }).element);+ }}window.siyuan.menus.menu.append(new MenuItem({id: "rebuildDataIndex",diff --git a/app/src/layout/dock/Inbox.ts b/app/src/layout/dock/Inbox.tsindex 742c1e850b..4cead52edf 100644--- a/app/src/layout/dock/Inbox.ts+++ b/app/src/layout/dock/Inbox.ts@@ -16,6 +16,7 @@ import {getCloudURL} from "../../config/util/about";import {hasClosestByClassName} from "../../protyle/util/hasClosest";import {escapeHtml} from "../../util/escape";import {emitOpenMenu} from "../../plugin/EventBus";+import {sanitizeKernelHTML} from "../../util/hostCapabilities";export class Inbox extends Model {private element: Element;@@ -190,21 +191,21 @@ export class Inbox extends Model {<svg class="toolbar__icon" style="float: left"><use xlink:href="#iconLink"></use></svg></a>`;}- return `<div class="toolbar">+ return sanitizeKernelHTML(`<div class="toolbar"><svg data-type="back" class="toolbar__icon"><use xlink:href="#iconLeft"></use></svg><span data-type="back" class="toolbar__text fn__flex-1">${data.shorthandTitle}</span>${linkHTML}</div><div class="b3-typography b3-typography--default" style="padding: 0 8px 8px">${data.shorthandContent}-</div>`;+</div>`);/// #elseif (data.shorthandURL) {linkHTML = `<span class="fn__space"></span><a href="${data.shorthandURL}" target="_blank" class="block__icon block__icon--show ariaLabel" data-position="north" aria-label="${window.siyuan.languages.link}"><svg><use xlink:href="#iconLink"></use></svg></a>`;}- return `<div class="block__icons">+ return sanitizeKernelHTML(`<div class="block__icons"><div class="block__logo fn__pointer fn__flex-1" data-type="back"><svg class="block__logoicon"><use xlink:href="#iconLeft"></use></svg><span class="ft__breakword">${data.shorthandTitle}</span></div>@@ -212,19 +213,19 @@ ${data.shorthandContent}</div><div class="b3-typography b3-typography--default" style="padding: 0 8px 8px;user-select: text" data-type="textMenu">${data.shorthandContent}-</div>`;+</div>`);/// #endif}private genItemHTML(item: IInbox) {- return `<li style="padding-left: 0" data-id="${item.oId}" class="b3-list-item">+ return sanitizeKernelHTML(`<li style="padding-left: 0" data-id="${item.oId}" class="b3-list-item"><span data-type="select" class="b3-list-item__action"><svg><use xlink:href="#icon${this.selectIds.includes(item.oId) ? "Check" : "Uncheck"}"></use></svg></span><span class="fn__space--small"></span><span class="b3-list-item__text" title="${item.shorthandTitle}${item.shorthandTitle === item.shorthandDesc ? "" : "\n" + item.shorthandDesc}">${item.shorthandTitle}</span><span class="b3-list-item__meta">${item.hCreated}</span>-</li>`;+</li>`);}private more(event: MouseEvent, itemElement?: HTMLElement) {diff --git a/app/src/layout/dock/agent/AgentSessionPanel.ts b/app/src/layout/dock/agent/AgentSessionPanel.tsindex 0826b31de1..8b3ce442e6 100644--- a/app/src/layout/dock/agent/AgentSessionPanel.ts+++ b/app/src/layout/dock/agent/AgentSessionPanel.ts@@ -9,6 +9,7 @@ import * as path from "path";import {useShell} from "../../../util/pathName";/// #endif+import {getHostCapabilities} from "../../../util/hostCapabilities";export class AgentSessionPanel {private popup: HTMLElement | null = null;@@ -202,7 +203,7 @@ export class AgentSessionPanel {'<svg><use xlink:href="#iconMore"></use></svg>' +'<div class="b3-menu__submenu">' +'<div class="b3-menu__items">' +- (isDesktop ? '<button class="b3-menu__item" data-action="folder"><svg class="b3-menu__icon"><use xlink:href="#iconFolder"></use></svg><span class="b3-menu__label">' + escapeHtml(L.showInFolder) + "</span></button>" : "") ++ (isDesktop && getHostCapabilities().localFileSystem ? '<button class="b3-menu__item" data-action="folder"><svg class="b3-menu__icon"><use xlink:href="#iconFolder"></use></svg><span class="b3-menu__label">' + escapeHtml(L.showInFolder) + "</span></button>" : "") +'<button class="b3-menu__item b3-menu__item--warning" data-action="delete"><svg class="b3-menu__icon"><use xlink:href="#iconTrashcan"></use></svg><span class="b3-menu__label">' + escapeHtml(L.delete) + "</span></button>" +"</div>" +"</div>" +diff --git a/app/src/menus/commonMenuItem.ts b/app/src/menus/commonMenuItem.tsindex befcdedc07..9514f0909f 100644--- a/app/src/menus/commonMenuItem.ts+++ b/app/src/menus/commonMenuItem.ts@@ -40,6 +40,7 @@ import {type TAssetOpenGesture,} from "../editor/assetOpen";import {resolvePdfAssetLink} from "../editor/pdfAssetLink";+import {getHostCapabilities} from "../util/hostCapabilities";const bindAttrInput = (inputElement: HTMLInputElement, id: string) => {inputElement.addEventListener("change", () => {@@ -544,7 +545,7 @@ export const copySubMenu = (ids: string[], accelerator = true, focusElement?: El};export const exportMd = (id: string) => {- if (window.siyuan.isPublish) {+ if (window.siyuan.isPublish || !getHostCapabilities().importExport) {return;}return new MenuItem({@@ -930,43 +931,47 @@ export const openMenu = (app: App, src: string, onlyMenu: boolean, showAcceleratopenAssetNewWindow(src.trim());}});- submenu.push({- id: "useDefault",- label: window.siyuan.languages.useDefault,- accelerator: getAccelerator("app"),- click() {- openBy(src, "app");- }- });- submenu.push({- id: "showInFolder",- icon: "iconFolder",- label: window.siyuan.languages.showInFolder,- accelerator: getAccelerator("folder"),- click: () => {- openBy(src, "folder");- }- });+ if (getHostCapabilities().localFileSystem) {+ submenu.push({+ id: "useDefault",+ label: window.siyuan.languages.useDefault,+ accelerator: getAccelerator("app"),+ click() {+ openBy(src, "app");+ }+ });+ submenu.push({+ id: "showInFolder",+ icon: "iconFolder",+ label: window.siyuan.languages.showInFolder,+ accelerator: getAccelerator("folder"),+ click: () => {+ openBy(src, "folder");+ }+ });+ }/// #endif} else {/// #if !BROWSER- submenu.push({- id: "useDefault",- label: window.siyuan.languages.useDefault,- accelerator: getAccelerator("app"),- click() {- openBy(src, "app");- }- });- submenu.push({- id: "showInFolder",- icon: "iconFolder",- label: window.siyuan.languages.showInFolder,- accelerator: getAccelerator("folder"),- click: () => {- openBy(src, "folder");- }- });+ if (getHostCapabilities().localFileSystem) {+ submenu.push({+ id: "useDefault",+ label: window.siyuan.languages.useDefault,+ accelerator: getAccelerator("app"),+ click() {+ openBy(src, "app");+ }+ });+ submenu.push({+ id: "showInFolder",+ icon: "iconFolder",+ label: window.siyuan.languages.showInFolder,+ accelerator: getAccelerator("folder"),+ click: () => {+ openBy(src, "folder");+ }+ });+ }/// #elsesubmenu.push({id: isInAndroid() || isInHarmony() ? "useDefault" : "useBrowserView",diff --git a/app/src/menus/dataMigration.ts b/app/src/menus/dataMigration.tsindex 5a6076de75..7ffd04d4ac 100644--- a/app/src/menus/dataMigration.ts+++ b/app/src/menus/dataMigration.ts@@ -15,6 +15,7 @@ import {ipcRenderer} from "electron";import * as path from "path";import {afterExport} from "../protyle/export/util";/// #endif+import {getHostCapabilities} from "../util/hostCapabilities";interface IDataMigrationOptions {mode?: "manage" | "onboarding";@@ -83,6 +84,9 @@ const exportData = async () => {};export const openDataMigration = (options: IDataMigrationOptions = {}) => {+ if (!getHostCapabilities().importExport) {+ return;+ }const mode = options.mode || "manage";const hasRepoKey = Boolean(window.siyuan.config.repo.key);const helpNotebookIDs = Object.values(Constants.HELP_PATH);diff --git a/app/src/menus/importObsidian.ts b/app/src/menus/importObsidian.tsindex 9a72b4f40a..87c9d5866d 100644--- a/app/src/menus/importObsidian.ts+++ b/app/src/menus/importObsidian.ts@@ -2,6 +2,7 @@ import {Dialog} from "../dialog";import {showMessage} from "../dialog/message";import {escapeAttr, escapeHtml} from "../util/escape";import {fetchSyncPost} from "../util/fetch";+import {getHostCapabilities} from "../util/hostCapabilities";interface IObsidianAnalysis {vaultName: string;@@ -233,6 +234,9 @@ const showConfirmation = (taskID: string, analysis: IObsidianAnalysis, onComplet};export const importObsidianVault = async (localPath: string, onComplete?: () => void) => {+ if (!getHostCapabilities().importExport) {+ return;+ }const response = await fetchSyncPost("/api/import/startObsidianVaultAnalysis", {localPath});if (response.code !== 0) {return;diff --git a/app/src/menus/navigation.ts b/app/src/menus/navigation.tsindex c1539fdcee..f67752e2dd 100644--- a/app/src/menus/navigation.ts+++ b/app/src/menus/navigation.ts@@ -42,6 +42,7 @@ import {isCustomFileTreeList} from "../util/fileTreeSort";import {syncFileTreeItemDefaultIcon} from "../emoji/fileTreeIcon";+import {getHostCapabilities} from "../util/hostCapabilities";/// #if MOBILEimport {openEmojiPanel} from "../emoji";import {openMobileFileByIdInNewTab} from "../mobile/editor";@@ -179,35 +180,37 @@ const initMultiMenu = (selectItemElements: NodeListOf<HTMLElement>, app: App) =>}}).element);}- const ignoreExport = notebookIds.some((notebookId) => isEncryptedBox(notebookId));- window.siyuan.menus.menu.append(new MenuItem({- id: "separator_2",- type: "separator",- ignore: ignoreExport,- }).element);- window.siyuan.menus.menu.append(new MenuItem({- id: "export",- label: window.siyuan.languages.export,- type: "submenu",- icon: "iconUpload",- ignore: ignoreExport,- submenu: [{- id: "exportSiYuanZip",- label: "SiYuan .sy.zip",- icon: "iconSiYuan",- click: () => {- const msgId = showMessage(window.siyuan.languages.exporting, -1);- fetchPost("/api/export/exportNotebooksSY", {notebooks: notebookIds}, (response) => {- saveExportFile(response.data.zip, msgId);- });- }- }, {- id: "exportMarkdown",- label: "Markdown .zip",- icon: "iconMarkdown",- click: () => exportMarkdownZip({notebooks: notebookIds}),- }]- }).element);+ if (getHostCapabilities().importExport) {+ const ignoreExport = notebookIds.some((notebookId) => isEncryptedBox(notebookId));+ window.siyuan.menus.menu.append(new MenuItem({+ id: "separator_2",+ type: "separator",+ ignore: ignoreExport,+ }).element);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "export",+ label: window.siyuan.languages.export,+ type: "submenu",+ icon: "iconUpload",+ ignore: ignoreExport,+ submenu: [{+ id: "exportSiYuanZip",+ label: "SiYuan .sy.zip",+ icon: "iconSiYuan",+ click: () => {+ const msgId = showMessage(window.siyuan.languages.exporting, -1);+ fetchPost("/api/export/exportNotebooksSY", {notebooks: notebookIds}, (response) => {+ saveExportFile(response.data.zip, msgId);+ });+ }+ }, {+ id: "exportMarkdown",+ label: "Markdown .zip",+ icon: "iconMarkdown",+ click: () => exportMarkdownZip({notebooks: notebookIds}),+ }]+ }).element);+ }emitOpenMenu({type: "open-menu-doctree",detail: {elements: selectItemElements, type: "notebooks", items},@@ -335,37 +338,41 @@ const initMultiMenu = (selectItemElements: NodeListOf<HTMLElement>, app: App) =>icon: "iconRiffCard",submenu: riffCardMenu,}).element);- window.siyuan.menus.menu.append(new MenuItem({id: "separator_2", type: "separator"}).element);+ if (getHostCapabilities().importExport) {+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_2", type: "separator"}).element);+ }}openEditorTab(app, blockIDs);- window.siyuan.menus.menu.append(new MenuItem({- id: "export",- label: window.siyuan.languages.export,- type: "submenu",- icon: "iconUpload",- submenu: [{- id: "exportSiYuanZip",- label: "SiYuan .sy.zip",- icon: "iconSiYuan",- click: () => {- confirmEncryptedExport(notebookId, () => {- const msgId = showMessage(window.siyuan.languages.exporting, -1);- fetchPost("/api/export/exportSYs", {- ids: blockIDs,- }, response => {- saveExportFile(response.data.zip, msgId);+ if (getHostCapabilities().importExport) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "export",+ label: window.siyuan.languages.export,+ type: "submenu",+ icon: "iconUpload",+ submenu: [{+ id: "exportSiYuanZip",+ label: "SiYuan .sy.zip",+ icon: "iconSiYuan",+ click: () => {+ confirmEncryptedExport(notebookId, () => {+ const msgId = showMessage(window.siyuan.languages.exporting, -1);+ fetchPost("/api/export/exportSYs", {+ ids: blockIDs,+ }, response => {+ saveExportFile(response.data.zip, msgId);+ });});- });- }- }, {- id: "exportMarkdown",- label: "Markdown .zip",- icon: "iconMarkdown",- click: () => {- confirmEncryptedExport(notebookId, () => exportMarkdownZip({ids: blockIDs}));- }- }]- }).element);+ }+ }, {+ id: "exportMarkdown",+ label: "Markdown .zip",+ icon: "iconMarkdown",+ click: () => {+ confirmEncryptedExport(notebookId, () => exportMarkdownZip({ids: blockIDs}));+ }+ }]+ }).element);+ }emitOpenMenu({type: "open-menu-doctree",detail: {@@ -601,47 +608,53 @@ export const initNavigationMenu = (app: App, liElement: HTMLElement) => {}}).element);}- window.siyuan.menus.menu.append(new MenuItem({id: "separator_2", type: "separator"}).element);+ if (getHostCapabilities().localFileSystem || getHostCapabilities().importExport) {+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_2", type: "separator"}).element);+ }/// #if !BROWSER- window.siyuan.menus.menu.append(new MenuItem({- id: "showInFolder",- icon: "iconFolder",- label: window.siyuan.languages.showInFolder,- click: () => {- useShell("openPath", path.join(window.siyuan.config.system.dataDir, notebookId));- }- }).element);+ if (getHostCapabilities().localFileSystem) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "showInFolder",+ icon: "iconFolder",+ label: window.siyuan.languages.showInFolder,+ click: () => {+ useShell("openPath", path.join(window.siyuan.config.system.dataDir, notebookId));+ }+ }).element);+ }/// #endifgenImportMenu(notebookId, "/");- window.siyuan.menus.menu.append(new MenuItem({- id: "export",- label: window.siyuan.languages.export,- type: "submenu",- icon: "iconUpload",- submenu: [{- id: "exportSiYuanZip",- label: "SiYuan .sy.zip",- icon: "iconSiYuan",- click: () => {- confirmEncryptedExport(notebookId, () => {- const msgId = showMessage(window.siyuan.languages.exporting, -1);- fetchPost("/api/export/exportNotebookSY", {- id: notebookId,- }, response => {- saveExportFile(response.data.zip, msgId);+ if (getHostCapabilities().importExport) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "export",+ label: window.siyuan.languages.export,+ type: "submenu",+ icon: "iconUpload",+ submenu: [{+ id: "exportSiYuanZip",+ label: "SiYuan .sy.zip",+ icon: "iconSiYuan",+ click: () => {+ confirmEncryptedExport(notebookId, () => {+ const msgId = showMessage(window.siyuan.languages.exporting, -1);+ fetchPost("/api/export/exportNotebookSY", {+ id: notebookId,+ }, response => {+ saveExportFile(response.data.zip, msgId);+ });});- });- }- }, {- id: "exportMarkdown",- label: "Markdown .zip",- icon: "iconMarkdown",- click: () => {- confirmEncryptedExport(notebookId, () => exportMarkdownZip({notebook: notebookId}));- }- }]- }).element);+ }+ }, {+ id: "exportMarkdown",+ label: "Markdown .zip",+ icon: "iconMarkdown",+ click: () => {+ confirmEncryptedExport(notebookId, () => exportMarkdownZip({notebook: notebookId}));+ }+ }]+ }).element);+ }emitOpenMenu({type: "open-menu-doctree",detail: {@@ -984,7 +997,7 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, l};export const genImportMenu = (notebookId: string, pathString: string) => {- if (window.siyuan.config.readonly) {+ if (window.siyuan.config.readonly || !getHostCapabilities().importExport) {return;}const reloadDocTree = () => {diff --git a/app/src/menus/protyle.ts b/app/src/menus/protyle.tsindex b549165f39..543da7a3cd 100644--- a/app/src/menus/protyle.ts+++ b/app/src/menus/protyle.ts@@ -70,6 +70,7 @@ import {setPosition} from "../util/setPosition";import {setFold} from "../protyle/util/blockFold";import {isEncryptedBox} from "../util/pathName";import {getHTMLAssetIFrameSrc} from "../asset/html";+import {getHostCapabilities, sanitizeKernelHTML} from "../util/hostCapabilities";import {getDistributedTableColumnWidth,isDefaultTableColumnWidth,@@ -388,7 +389,7 @@ export const refMenu = (protyle: IProtyle, element: HTMLElement) => {element.innerHTML = Lute.EscapeHTMLStr(inputElement.value).trim() || refBlockId;} else {fetchPost("/api/block/getRefText", {id: refBlockId}, (response) => {- element.innerHTML = response.data;+ element.innerHTML = sanitizeKernelHTML(response.data);});}element.setAttribute("data-subtype", inputElement.value ? "s" : "d");@@ -528,7 +529,7 @@ export const refMenu = (protyle: IProtyle, element: HTMLElement) => {click() {element.setAttribute("data-subtype", "d");fetchPost("/api/block/getRefText", {id: refBlockId}, (response) => {- element.innerHTML = response.data;+ element.innerHTML = sanitizeKernelHTML(response.data);nodeElement.setAttribute("updated", dayjs().format("YYYYMMDDHHmmss"));updateTransaction(protyle, nodeElement, oldHTML);oldHTML = nodeElement.outerHTML;@@ -2109,6 +2110,9 @@ const genImageHeightMenu = (label: string, imgElement: HTMLElement, protyle: IPr};export const iframeMenu = (protyle: IProtyle, nodeElement: Element) => {+ if (getHostCapabilities().remoteKernel) {+ return [];+ }const iframeElement = nodeElement.querySelector("iframe");let html = nodeElement.outerHTML;const subMenus: IMenu[] = [{diff --git a/app/src/menus/util.ts b/app/src/menus/util.tsindex 8a6291fff2..26c4db9f96 100644--- a/app/src/menus/util.ts+++ b/app/src/menus/util.ts@@ -15,8 +15,12 @@ import {showMessage} from "../dialog/message";import type {Editor} from "../editor";import {setEditMode} from "../protyle/util/setEditMode";import {getDownloadURL} from "../util/imageURL";+import {getHostCapabilities} from "../util/hostCapabilities";export const exportAsset = (src: string) => {+ if (!getHostCapabilities().importExport) {+ return {ignore: true};+ }return {id: "export",label: window.siyuan.languages.export,@@ -44,6 +48,9 @@ export const exportAsset = (src: string) => {// 复制资源文件到系统剪贴板,在文件资源管理器中可粘贴为文件(仅 Windows、macOS 桌面端支持)export const writeAssetToClipboard = (src: string) => {+ if (!getHostCapabilities().localFileSystem) {+ return {ignore: true};+ }/// #if !BROWSERif (["windows", "darwin"].includes(window.siyuan.config.system.os)) {return {@@ -178,23 +185,25 @@ export const openEditorTab = (app: App, ids: string[], notebookId?: string, path}});/// #if !BROWSER- openSubmenus.push({id: "separator_2", type: "separator"});- openSubmenus.push({- id: "showInFolder",- icon: "iconFolder",- label: window.siyuan.languages.showInFolder,- click: () => {- if (notebookId) {- useShell("showItemInFolder", path.join(window.siyuan.config.system.dataDir, notebookId, pathString));- } else {- ids.forEach((id) => {- fetchPost("/api/block/getBlockInfo", {id}, (response) => {- useShell("showItemInFolder", path.join(window.siyuan.config.system.dataDir, response.data.box, response.data.path));+ if (getHostCapabilities().localFileSystem) {+ openSubmenus.push({id: "separator_2", type: "separator"});+ openSubmenus.push({+ id: "showInFolder",+ icon: "iconFolder",+ label: window.siyuan.languages.showInFolder,+ click: () => {+ if (notebookId) {+ useShell("showItemInFolder", path.join(window.siyuan.config.system.dataDir, notebookId, pathString));+ } else {+ ids.forEach((id) => {+ fetchPost("/api/block/getBlockInfo", {id}, (response) => {+ useShell("showItemInFolder", path.join(window.siyuan.config.system.dataDir, response.data.box, response.data.path));+ });});- });+ }}- }- });+ });+ }/// #endifif (onlyGetMenus) {return openSubmenus;diff --git a/app/src/menus/workspace.ts b/app/src/menus/workspace.tsindex f421e6d758..04c9245365 100644--- a/app/src/menus/workspace.ts+++ b/app/src/menus/workspace.ts@@ -38,6 +38,7 @@ import {upDownHint} from "../util/upDownHint";import {openDataMigration} from "./dataMigration";import {openLink} from "../editor/openLink";import {adjustEditorFontSize} from "../util/editorFontSize";+import {getHostCapabilities} from "../util/hostCapabilities";const editLayout = (layoutName?: string) => {const dialog = new Dialog({@@ -248,7 +249,7 @@ export const workspaceMenu = (app: App, rect: DOMRect) => {window.siyuan.menus.menu.remove();return;}- fetchPost("/api/system/getWorkspaces", {}, (response) => {+ const renderMenu = (workspaces: IWorkspace[]) => {window.siyuan.menus.menu.remove();window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_BAR_WORKSPACE);if (!window.siyuan.config.readonly) {@@ -287,7 +288,7 @@ export const workspaceMenu = (app: App, rect: DOMRect) => {type: "submenu",submenu: dockMenu}).element);- if (!window.siyuan.config.readonly) {+ if (!window.siyuan.config.readonly && getHostCapabilities().workspaces) {let workspaceSubMenu: IMenu[];/// #if !BROWSERworkspaceSubMenu = [{@@ -315,7 +316,7 @@ export const workspaceMenu = (app: App, rect: DOMRect) => {}}];workspaceSubMenu.push({id: "separator_1", type: "separator"});- response.data.forEach((item: IWorkspace) => {+ workspaces.forEach((item: IWorkspace) => {workspaceSubMenu.push(workspaceItem(item) as IMenu);});/// #else@@ -394,7 +395,7 @@ export const workspaceMenu = (app: App, rect: DOMRect) => {}}];workspaceSubMenu.push({id: "separator_1", type: "separator"});- response.data.forEach((item: IWorkspace) => {+ workspaces.forEach((item: IWorkspace) => {workspaceSubMenu.push({iconHTML: "",action: "iconCloseRound",@@ -650,7 +651,7 @@ export const workspaceMenu = (app: App, rect: DOMRect) => {openHistory(app);}}).element);- if (!window.siyuan.config.readonly) {+ if (!window.siyuan.config.readonly && getHostCapabilities().importExport) {window.siyuan.menus.menu.append(new MenuItem({id: "dataMigration",label: window.siyuan.languages.dataMigration,@@ -709,10 +710,18 @@ export const workspaceMenu = (app: App, rect: DOMRect) => {}).element);}window.siyuan.menus.menu.popup({x: rect.left, y: rect.bottom});- });+ };+ if (getHostCapabilities().workspaces) {+ fetchPost("/api/system/getWorkspaces", {}, (response) => renderMenu(response.data));+ } else {+ renderMenu([]);+ }};const openWorkspace = (workspace: string) => {+ if (!getHostCapabilities().workspaces) {+ return;+ }/// #if !BROWSERif (workspace === window.siyuan.config.system.workspaceDir) {return;diff --git a/app/src/mobile/index.ts b/app/src/mobile/index.tsindex 4aebeb13a5..e91a8147b7 100644--- a/app/src/mobile/index.ts+++ b/app/src/mobile/index.ts@@ -176,7 +176,7 @@ class App {activeBlur();});fetchPost("/api/system/getConf", {}, async (confResponse) => {- addScriptSync(`${Constants.PROTYLE_CDN}/js/lute/lute.min.js?v=${Constants.SIYUAN_VERSION}`, "protyleLuteScript");+ await addScriptSync(`${Constants.PROTYLE_CDN}/js/lute/lute.min.js?v=${Constants.SIYUAN_VERSION}`, "protyleLuteScript");addScript(`${Constants.PROTYLE_CDN}/js/protyle-html.js?v=${Constants.SIYUAN_VERSION}`, "protyleWcHtmlScript");window.siyuan.config = confResponse.data.conf;window.siyuan.isPublish = confResponse.data.isPublish;diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.tsindex f5a17818d0..4e88a5d95e 100644--- a/app/src/mobile/util/keyboardToolbar.ts+++ b/app/src/mobile/util/keyboardToolbar.ts@@ -45,6 +45,7 @@ import {} from "../../protyle/toolbar/inlineStyle";import {openInlineStyleDialog} from "../../protyle/toolbar/inlineStyleDialog";import {forEachPluginSubscriber} from "../../plugin/EventBusCore";+import {getHostCapabilities} from "../../util/hostCapabilities";import {getKeyboardHideResult,getMovingSelectionEndpoint,@@ -641,7 +642,7 @@ const renderSlashMenu = (protyle: IProtyle, toolbarElement: Element) => {utilElement.innerHTML = `<div class="keyboard__slash-title"></div><div class="keyboard__slash-block">${getSlashItem(Constants.ZWSP, "iconMarkdown", window.siyuan.languages.template)}- ${getSlashItem(Constants.ZWSP + 1, "iconBoth", window.siyuan.languages.widget)}+ ${getHostCapabilities().widgets ? getSlashItem(Constants.ZWSP + 1, "iconBoth", window.siyuan.languages.widget) : ""}${getSlashItem(Constants.ZWSP + 2, "iconImage", window.siyuan.languages.assets)}${getSlashItem("((", "iconRef", window.siyuan.languages.ref, "true")}${getSlashItem("{{", "iconSQL", window.siyuan.languages.blockEmbed, "true")}@@ -654,7 +655,7 @@ const renderSlashMenu = (protyle: IProtyle, toolbarElement: Element) => {${isInAndroid() ? getSlashItem(Constants.ZWSP + 3, "iconImage", window.siyuan.languages.insertImage + '<input class="b3-form__upload" type="file" multiple="multiple" accept="image/*,application/x-siyuan-image-picker"/>', "true") : ""}${isInAndroid() ? getSlashItem(Constants.ZWSP + 3, "iconCamera", window.siyuan.languages.insertPhoto + '<input class="b3-form__upload" capture="user" type="file"' + (protyle.options.upload.accept ? (' multiple="' + protyle.options.upload.accept + '"') : "") + "/>", "true") : ""}${getSlashItem(Constants.ZWSP + 3, "iconDownload", window.siyuan.languages.insertAsset + '<input class="b3-form__upload" type="file" multiple="multiple"' + (protyle.options.upload.accept ? (' accept="' + protyle.options.upload.accept + '"') : "") + "/>", "true")}- ${getSlashItem('<iframe sandbox="allow-forms allow-presentation allow-same-origin allow-scripts allow-modals allow-popups allow-storage-access-by-user-activation" src="" border="0" frameborder="no" framespacing="0" allowfullscreen="true"></iframe>', "iconGlobe", window.siyuan.languages.insertIframeURL, "true")}+ ${getHostCapabilities().remoteKernel ? "" : getSlashItem('<iframe sandbox="allow-forms allow-presentation allow-same-origin allow-scripts allow-modals allow-popups allow-storage-access-by-user-activation" src="" border="0" frameborder="no" framespacing="0" allowfullscreen="true"></iframe>', "iconGlobe", window.siyuan.languages.insertIframeURL, "true")}${getSlashItem("![]()", "iconImage", window.siyuan.languages.insertImgURL, "true")}${getSlashItem('<video controls="controls" src=""></video>', "iconVideo", window.siyuan.languages.insertVideoURL, "true")}${getSlashItem('<audio controls="controls" src=""></audio>', "iconRecord", window.siyuan.languages.insertAudioURL, "true")}diff --git a/app/src/mobile/util/onMessage.ts b/app/src/mobile/util/onMessage.tsindex c375dce107..a98a019b01 100644--- a/app/src/mobile/util/onMessage.ts+++ b/app/src/mobile/util/onMessage.ts@@ -23,6 +23,7 @@ import {appearanceConfigApi} from "../../config/tabs/appearanceRuntime";import {applyCloudUserState} from "../../config/tabs/accountUi";import {isInMobileApp} from "../../protyle/util/compatibility";import {handleMobileKernelExit} from "./kernelExit";+import {sanitizeKernelHTML} from "../../util/hostCapabilities";let statusTimeout: number;const statusElement = document.querySelector("#status") as HTMLElement;@@ -46,7 +47,7 @@ export const onMessage = (app: App, data: IWebSocketData) => {statusElement.style.bottom = "";} else {clearTimeout(statusTimeout);- statusElement.innerHTML = `<div class="fn__flex">${data.data.tasks[0].action}<div class="fn__progress"><div></div></div>`;+ statusElement.innerHTML = `<div class="fn__flex">${sanitizeKernelHTML(data.data.tasks[0].action)}<div class="fn__progress"><div></div></div>`;statusElement.style.bottom = "0";}break;@@ -195,7 +196,7 @@ export const onMessage = (app: App, data: IWebSocketData) => {return;}clearTimeout(statusTimeout);- statusElement.innerHTML = data.msg;+ statusElement.innerHTML = sanitizeKernelHTML(data.msg);statusElement.style.bottom = "var(--mobile-bottom-bar-safe-area)";statusTimeout = window.setTimeout(() => {statusElement.style.bottom = "";diff --git a/app/src/onboarding/index.ts b/app/src/onboarding/index.tsindex fb9fa814c8..42e6112083 100644--- a/app/src/onboarding/index.ts+++ b/app/src/onboarding/index.ts@@ -7,6 +7,7 @@ import {openSetting} from "../config";import {isPaidUser} from "../util/needSubscribe";import {parseUriInfo, setNoteBook} from "../util/pathName";import type {App} from "../index";+import {getHostCapabilities} from "../util/hostCapabilities";/// #if MOBILEimport {openMobileFileById} from "../mobile/editor";/// #else@@ -106,9 +107,9 @@ const renderOnboarding = (app: App) => {</button><div class="onboarding__title">🎉 ${window.siyuan.languages.onboardingWelcome}</div><div class="onboarding__desc">${window.siyuan.languages.onboardingDescription}</div>-<button class="b3-button b3-button--outline fn__block" data-type="import">+${getHostCapabilities().importExport ? `<button class="b3-button b3-button--outline fn__block" data-type="import"><svg><use xlink:href="#iconDownload"></use></svg>${window.siyuan.languages.importExistingData}-</button>+</button>` : ""}<button class="b3-button b3-button--outline fn__block" data-type="sync"><svg><use xlink:href="#iconCloud"></use></svg>${window.siyuan.languages.loginAndSync}</button>@@ -125,11 +126,13 @@ const renderOnboarding = (app: App) => {dismissOnboarding();break;case "import":- openDataMigration({- mode: "onboarding",- notebookID: window.siyuan.config.onboarding.notebookID,- onContentImportComplete: dismissOnboarding,- });+ if (getHostCapabilities().importExport) {+ openDataMigration({+ mode: "onboarding",+ notebookID: window.siyuan.config.onboarding.notebookID,+ onContentImportComplete: dismissOnboarding,+ });+ }break;case "sync":loginAndSync(app);diff --git a/app/src/plugin/loader.ts b/app/src/plugin/loader.tsindex 6b5a33745c..142f7b9e48 100644--- a/app/src/plugin/loader.ts+++ b/app/src/plugin/loader.ts@@ -23,6 +23,7 @@ import {activateCustomBlockPlugin,deactivateCustomBlockPlugin,} from "./customBlockRender";+import {getHostCapabilities} from "../util/hostCapabilities";const requireFunc = (key: string) => {const modules = {@@ -126,6 +127,9 @@ const createPluginDataLoader = () => {};export const loadPlugins = async (app: App, names?: string[], init = true) => {+ if (!getHostCapabilities().plugins) {+ return;+ }const manager = getLifecycleManager(app);let tasks: Promise<void>[];let shouldStart = true;@@ -169,6 +173,9 @@ const insertPluginCSS = (item: IPluginData, pluginsStyle: HTMLElement) => {// 启用插件export const loadPlugin = async (app: App, item: IPluginData) => {+ if (!getHostCapabilities().plugins) {+ return;+ }const manager = getLifecycleManager(app);manager.start();await manager.requestLoad(item.name, async () => item);@@ -335,6 +342,9 @@ export interface IPluginReloadData {}export const reloadPlugin = async (app: App, data: IPluginReloadData = {}) => {+ if (!getHostCapabilities().plugins) {+ return;+ }const manager = getLifecycleManager(app);const uninstallNames = new Set(data.uninstallPlugins || []);const unloadNames = new Set((data.unloadPlugins || []).filter(name => !uninstallNames.has(name)));diff --git a/app/src/protyle/breadcrumb/index.ts b/app/src/protyle/breadcrumb/index.tsindex b537ff3a25..7adb55040f 100644--- a/app/src/protyle/breadcrumb/index.ts+++ b/app/src/protyle/breadcrumb/index.ts@@ -39,6 +39,7 @@ import {refreshUndoButtons} from "../undo/globalUndo";import {getAllEditor} from "../../layout/getAll";import {genEmbedStatTip, type IBlockStat, type IEmbedStat} from "../../layout/status";import {mountBreadcrumbButtons} from "../../plugin/breadcrumbButton";+import {getHostCapabilities} from "../../util/hostCapabilities";const genDocumentStatLabel = (stat: IBlockStat, statWithEmbed?: IBlockStat, embedStat?: IEmbedStat) => {const runeEmbedAttrs = statWithEmbed ? ` class="ariaLabel" data-position="north" aria-label="${escapeAriaLabel(genEmbedStatTip(window.siyuan.languages.runeCountWithEmbed, statWithEmbed.runeCount, embedStat))}"` : "";@@ -718,25 +719,27 @@ ${padHTML}window.siyuan.menus.menu.remove();});window.siyuan.menus.menu.append(uploadMenu);- const htmlUploadMenu = new MenuItem({- id: "insertHTMLFile",- icon: "iconHTML5",- label: `${window.siyuan.languages.insertHTMLFile}<input class="b3-form__upload" type="file" multiple="multiple" accept=".html,.htm">`,- }).element;- htmlUploadMenu.querySelector("input").addEventListener("change", (event: InputEvent & {- target: HTMLInputElement- }) => {- if (event.target.files.length === 0) {- return;- }- uploadFiles(protyle, event.target.files, event.target, undefined, undefined, {- htmlAsIframe: true,- source: "file-picker",- target: "editor",+ if (getHostCapabilities().localFileSystem) {+ const htmlUploadMenu = new MenuItem({+ id: "insertHTMLFile",+ icon: "iconHTML5",+ label: `${window.siyuan.languages.insertHTMLFile}<input class="b3-form__upload" type="file" multiple="multiple" accept=".html,.htm">`,+ }).element;+ htmlUploadMenu.querySelector("input").addEventListener("change", (event: InputEvent & {+ target: HTMLInputElement+ }) => {+ if (event.target.files.length === 0) {+ return;+ }+ uploadFiles(protyle, event.target.files, event.target, undefined, undefined, {+ htmlAsIframe: true,+ source: "file-picker",+ target: "editor",+ });+ window.siyuan.menus.menu.remove();});- window.siyuan.menus.menu.remove();- });- window.siyuan.menus.menu.append(htmlUploadMenu);+ window.siyuan.menus.menu.append(htmlUploadMenu);+ }window.siyuan.menus.menu.append(new MenuItem({id: this.mediaRecorder?.isRecording ? "endRecord" : "startRecord",current: this.mediaRecorder && this.mediaRecorder.isRecording,@@ -823,12 +826,15 @@ ${padHTML}}}}).element);- if (window.siyuan.user) { // 登录链滴账号后即可使用 `分享到链滴` https://github.com/siyuan-note/siyuan/issues/7392+ if (window.siyuan.user && getHostCapabilities().importExport) { // 登录链滴账号后即可使用 `分享到链滴` https://github.com/siyuan-note/siyuan/issues/7392window.siyuan.menus.menu.append(new MenuItem({id: "share2Liandi",label: window.siyuan.languages.share2Liandi,icon: "iconLiandi",click() {+ if (!getHostCapabilities().importExport) {+ return;+ }confirmDialog("🤩 " + window.siyuan.languages.share2Liandi,window.siyuan.languages.share2LiandiConfirmTip.replace("${accountServer}", getCloudURL("")), () => {fetchPost("/api/export/export2Liandi", {id: protyle.block.parentID});diff --git a/app/src/protyle/export/exportMd.ts b/app/src/protyle/export/exportMd.tsindex c275faefd9..42f4ffc598 100644--- a/app/src/protyle/export/exportMd.ts+++ b/app/src/protyle/export/exportMd.ts@@ -5,6 +5,7 @@ import {showMessage} from "../../dialog/message";import {fetchPost, fetchSyncPost} from "../../util/fetch";import {isMobile} from "../../util/functions";import {isEncryptedBox} from "../../util/pathName";+import {getHostCapabilities} from "../../util/hostCapabilities";import {saveExportFile} from "../util/compatibility";// 导出参数对话框 https://github.com/siyuan-note/siyuan/issues/17031@@ -143,6 +144,9 @@ interface IExportMdOptionsPayload {// exportMarkdownZip 为 Markdown .zip 导出入口:弹参数对话框,确认后按文档、文档集合或笔记本集合调用对应 API。// 单文档时先查询文档信息,若无子文档/关联文档则隐藏对应配置项,减少干扰。export const exportMarkdownZip = async(options: IExportMdOptions) => {+ if (!getHostCapabilities().importExport) {+ return;+ }let showSubDocs = true;let showRelatedDocs = true;let encrypted = false;diff --git a/app/src/protyle/export/index.ts b/app/src/protyle/export/index.tsindex 44dcb17421..58826f84d7 100644--- a/app/src/protyle/export/index.ts+++ b/app/src/protyle/export/index.ts@@ -14,6 +14,7 @@ import {replaceLocalPath} from "../../editor/rename";import {getScreenWidth, isInMobileApp, saveExportFile, setStorageVal} from "../util/compatibility";import {getFrontend} from "../../util/functions";import {isEncryptedBox} from "../../util/pathName";+import {getHostCapabilities} from "../../util/hostCapabilities";const getPluginStyle = async () => {const response = await fetchSyncPost("/api/petal/loadPetals", {frontend: getFrontend()});@@ -32,6 +33,9 @@ const getIconScript = (servePath: string) => {};export const saveExport = (option: IExportOptions) => {+ if (!getHostCapabilities().importExport) {+ return;+ }/// #if BROWSERif (["html", "htmlmd"].includes(option.type)) {const startExport = () => {diff --git a/app/src/protyle/export/util.ts b/app/src/protyle/export/util.tsindex a527c505cf..48b6d4ef6a 100644--- a/app/src/protyle/export/util.ts+++ b/app/src/protyle/export/util.ts@@ -12,6 +12,7 @@ import {highlightRender, lineNumberRender} from "../render/highlightRender";import {processRender} from "../util/processCode";import {isInAndroid, isIPad, isIPhone, isSafari, saveExportFile, setStorageVal} from "../util/compatibility";import {useShell} from "../../util/pathName";+import {getHostCapabilities} from "../../util/hostCapabilities";import {copyPNGByLink, writePNGBlob} from "../../menus/util";// WebKit/Chromium 会拒绝宽度或高度超过此限制的 canvas,导致生成空白图像。@@ -34,6 +35,9 @@ export const afterExport = (exportPath: string, msgId: string) => {};export const exportImage = (id: string, copyOnly = false) => {+ if (!getHostCapabilities().importExport) {+ return;+ }const exportDialog = new Dialog({disableAnimation: true,title: copyOnly ? window.siyuan.languages.copyAsPNG : window.siyuan.languages.exportAsImage,diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.tsindex 53a824c6e1..80a318ed8c 100644--- a/app/src/protyle/gutter/index.ts+++ b/app/src/protyle/gutter/index.ts@@ -86,6 +86,7 @@ import {avContextmenu, duplicateCompletely} from "../render/av/action";import {genCellValueByElement} from "../render/av/cell";import {getPlainText} from "../util/paste";import {CODE_TAB_SPACE_VALUES} from "../wysiwyg/codeBlockUtil";+import {getHostCapabilities} from "../../util/hostCapabilities";import {getEditorFocusRangeOutsideElement, restoreEditorFocusRange} from "../util/editorFocus";import {getCrossBlockTextSelectionTarget,@@ -2282,7 +2283,7 @@ export class Gutter {window.siyuan.menus.menu.remove();});}- }, {+ }, ...(getHostCapabilities().importExport ? [{id: "saveCodeBlockAsFile",iconHTML: "",label: window.siyuan.languages.saveCodeBlockAsFile,@@ -2292,7 +2293,7 @@ export class Gutter {saveExportFile(response.data.path, msgId);});}- }]+ }] : [])]}).element);} else if (type === "NodeCodeBlock" && !protyle.disabled && ["echarts", "mindmap"].includes(nodeElement.getAttribute("data-subtype"))) {window.siyuan.menus.menu.append(new MenuItem({id: "separator_chart", type: "separator"}).element);@@ -2353,35 +2354,39 @@ export class Gutter {}).element);}} else if (type === "NodeAttributeView") {- window.siyuan.menus.menu.append(new MenuItem({id: "separator_exportCSV", type: "separator"}).element);- window.siyuan.menus.menu.append(new MenuItem({- id: "exportCSV",- icon: "iconDatabase",- label: window.siyuan.languages.export + " CSV",- click() {- fetchPost("/api/export/exportAttributeView", {- id: nodeElement.getAttribute("data-av-id"),- blockID: id,- }, response => {- saveExportFile(response.data.zip);- });- }- }).element);+ if (getHostCapabilities().importExport) {+ window.siyuan.menus.menu.append(new MenuItem({id: "separator_exportCSV", type: "separator"}).element);+ window.siyuan.menus.menu.append(new MenuItem({+ id: "exportCSV",+ icon: "iconDatabase",+ label: window.siyuan.languages.export + " CSV",+ click() {+ fetchPost("/api/export/exportAttributeView", {+ id: nodeElement.getAttribute("data-av-id"),+ blockID: id,+ }, response => {+ saveExportFile(response.data.zip);+ });+ }+ }).element);+ }/// #if !BROWSER- window.siyuan.menus.menu.append(new MenuItem({- id: "showDatabaseInFolder",- icon: "iconFolder",- label: window.siyuan.languages.showInFolder,- click() {- const avId = nodeElement.getAttribute("data-av-id");- const notebookId = protyle.notebookId;- // 加密笔记本的 AV 定义存笔记本级路径- const avDir = isEncryptedBox(notebookId)- ? path.join(window.siyuan.config.system.dataDir, notebookId, "storage", "av")- : path.join(window.siyuan.config.system.dataDir, "storage", "av");- useShell("showItemInFolder", path.join(avDir, avId) + ".json");- }- }).element);+ if (getHostCapabilities().localFileSystem) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "showDatabaseInFolder",+ icon: "iconFolder",+ label: window.siyuan.languages.showInFolder,+ click() {+ const avId = nodeElement.getAttribute("data-av-id");+ const notebookId = protyle.notebookId;+ // 加密笔记本的 AV 定义存笔记本级路径+ const avDir = isEncryptedBox(notebookId)+ ? path.join(window.siyuan.config.system.dataDir, notebookId, "storage", "av")+ : path.join(window.siyuan.config.system.dataDir, "storage", "av");+ useShell("showItemInFolder", path.join(avDir, avId) + ".json");+ }+ }).element);+ }/// #endif} else if ((type === "NodeVideo" || type === "NodeAudio") && !protyle.disabled) {window.siyuan.menus.menu.append(new MenuItem({id: "separator_VideoOrAudio", type: "separator"}).element);@@ -2392,7 +2397,7 @@ export class Gutter {label: window.siyuan.languages.assets,submenu: videoMenu(protyle, nodeElement, type)}).element);- } else if (type === "NodeIFrame" && !protyle.disabled) {+ } else if (type === "NodeIFrame" && !protyle.disabled && !getHostCapabilities().remoteKernel) {window.siyuan.menus.menu.append(new MenuItem({id: "separator_IFrame", type: "separator"}).element);window.siyuan.menus.menu.append(new MenuItem({id: "assetIFrame",@@ -3440,6 +3445,7 @@ export class Gutter {id: "copyAsPNG",iconHTML: "",label: window.siyuan.languages.copyAsPNG,+ ignore: !getHostCapabilities().importExport,click() {exportImage(id, true);}diff --git a/app/src/protyle/header/openTitleMenu.ts b/app/src/protyle/header/openTitleMenu.tsindex 10331a224e..f216ff9c08 100644--- a/app/src/protyle/header/openTitleMenu.ts+++ b/app/src/protyle/header/openTitleMenu.ts@@ -29,6 +29,7 @@ import {showMessage} from "../../dialog/message";import {buildBlockDOMClipboardRichData} from "../util/blockDOMClipboard";import {buildWebClipboardHTML} from "../util/clipboardData";import {exportImage} from "../export/util";+import {getHostCapabilities} from "../../util/hostCapabilities";export const openTitleMenu = (protyle: IProtyle, position: IPosition, from: string) => {hideTooltip();@@ -54,6 +55,7 @@ export const openTitleMenu = (protyle: IProtyle, position: IPosition, from: striid: "copyAsPNG",iconHTML: "",label: window.siyuan.languages.copyAsPNG,+ ignore: !getHostCapabilities().importExport,click() {exportImage(protyle.block.showAll ? protyle.block.id : protyle.block.rootID, true);}@@ -317,14 +319,16 @@ export const openTitleMenu = (protyle: IProtyle, position: IPosition, from: striopenNewWindowById(protyle.block.rootID);}}).element);- window.siyuan.menus.menu.append(new MenuItem({- id: "showInFolder",- icon: "iconFolder",- label: window.siyuan.languages.showInFolder,- click: () => {- useShell("showItemInFolder", path.join(window.siyuan.config.system.dataDir, protyle.notebookId, protyle.path));- }- }).element);+ if (getHostCapabilities().localFileSystem) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "showInFolder",+ icon: "iconFolder",+ label: window.siyuan.languages.showInFolder,+ click: () => {+ useShell("showItemInFolder", path.join(window.siyuan.config.system.dataDir, protyle.notebookId, protyle.path));+ }+ }).element);+ }/// #endifif (!protyle.disabled) {window.siyuan.menus.menu.append(new MenuItem({diff --git a/app/src/protyle/hint/extend.ts b/app/src/protyle/hint/extend.tsindex 3fbe6362af..61ca2a5932 100644--- a/app/src/protyle/hint/extend.ts+++ b/app/src/protyle/hint/extend.ts@@ -43,6 +43,7 @@ import {} from "../toolbar/inlineStyle";import {confirmDialog} from "../../dialog/confirmDialog";import {buildSemanticInlineHTML} from "../util/inlineElementMarker";+import {getHostCapabilities} from "../../util/hostCapabilities";import {getBlockSelectionModeElement,getBlockSelectionStatusIDs,@@ -105,12 +106,12 @@ export const getBuiltinSlashMenuItems = (protyle: IProtyle): IHintData[] => {id: "template",value: Constants.ZWSP,html: `<div class="b3-list-item__first"><svg class="b3-list-item__graphic"><use xlink:href="#iconMarkdown"></use></svg><span class="b3-list-item__text">${window.siyuan.languages.template}</span></div>`,- }, {+ }, ...(getHostCapabilities().widgets ? [{filter: [window.siyuan.languages.widget, "widget", "挂件", "guajian", "gj"],id: "widget",value: Constants.ZWSP + 1,html: `<div class="b3-list-item__first"><svg class="b3-list-item__graphic"><use xlink:href="#iconBoth"></use></svg><span class="b3-list-item__text">${window.siyuan.languages.widget}</span></div>`,- }, {+ }] : []), {filter: [window.siyuan.languages.assets, "assets", "资源", "ziyuan", "zy"],id: "assets",value: Constants.ZWSP + 2,@@ -343,18 +344,18 @@ export const getBuiltinSlashMenuItems = (protyle: IProtyle): IHintData[] => {value: Constants.ZWSP + 3,html: `<div class="b3-list-item__first"><svg class="b3-list-item__graphic"><use xlink:href="#iconDownload"></use></svg><span class="b3-list-item__text">${window.siyuan.languages.insertAsset}</span><input class="b3-form__upload" type="file" multiple="multiple"${protyle.options.upload.accept ? ' accept="' + protyle.options.upload.accept + '"' : ""}></div>`,- }, {+ }, ...(getHostCapabilities().localFileSystem ? [{filter: [window.siyuan.languages.insertHTMLFile, "embed html file", "iframe", "嵌入 html 文件", "qianruhtmlwenjian", "qrhtmlwj"],id: "insertHTMLFile",value: Constants.ZWSP + 3,html: `<div class="b3-list-item__first"><svg class="b3-list-item__graphic"><use xlink:href="#iconHTML5"></use></svg><span class="b3-list-item__text">${window.siyuan.languages.insertHTMLFile}</span><input class="b3-form__upload" data-upload-mode="html-iframe" type="file" multiple="multiple" accept=".html,.htm"></div>`,- }, {+ }] : []), ...(getHostCapabilities().remoteKernel ? [] : [{filter: [window.siyuan.languages.insertIframeURL, "insert iframe link", "插入 iframe 链接", "charuiframelianjie", "criframelj"],id: "insertIframeURL",value: '<iframe sandbox="allow-forms allow-presentation allow-same-origin allow-scripts allow-modals allow-popups allow-storage-access-by-user-activation" src="" border="0" frameborder="no" framespacing="0" allowfullscreen="true"></iframe>',html: `<div class="b3-list-item__first"><svg class="b3-list-item__graphic"><use xlink:href="#iconGlobe"></use></svg><span class="b3-list-item__text">${window.siyuan.languages.insertIframeURL}</span></div>`,- }, {+ }]), {filter: [window.siyuan.languages.insertImgURL, "insert image link", "image", "img", "插入图片链接", "charutupianlianjie", "crtplj"],id: "insertImgURL",value: "![]()",@@ -711,6 +712,9 @@ export const hintRenderTemplate = (value: string, protyle: IProtyle, nodeElement};export const hintRenderWidget = (value: string, protyle: IProtyle) => {+ if (!getHostCapabilities().widgets) {+ return;+ }focusByRange(protyle.toolbar.range);// src 地址以 / 结尾// Use the path ending with `/` when loading the widget https://github.com/siyuan-note/siyuan/issues/10520diff --git a/app/src/protyle/index.ts b/app/src/protyle/index.tsindex e9f3615954..3b85dbd413 100644--- a/app/src/protyle/index.ts+++ b/app/src/protyle/index.ts@@ -53,6 +53,7 @@ import {refreshSearchPathAfterRename,} from "../search/path";import {syncSearchConfigHPath} from "../search/config";+import {sanitizeKernelHTML} from "../util/hostCapabilities";/// #endifimport {isSupportCSSHL} from "./render/searchMarkRender";import {renderAVAttribute} from "./render/av/blockAttr";@@ -320,7 +321,7 @@ export class Protyle {this.protyle.wysiwyg.element.querySelectorAll(`[data-type~="block-ref"][data-id="${data.data.id}"]`).forEach(item => {if (item.getAttribute("data-subtype") === "d") {// 同 updateRef 一样处理 https://github.com/siyuan-note/siyuan/issues/10458- item.innerHTML = data.data.refText;+ item.innerHTML = sanitizeKernelHTML(data.data.refText);}});/// #if !MOBILEdiff --git a/app/src/protyle/preview/index.ts b/app/src/protyle/preview/index.tsindex 55fbbc1043..f7fe62e908 100644--- a/app/src/protyle/preview/index.ts+++ b/app/src/protyle/preview/index.ts@@ -27,6 +27,7 @@ import {getPadding} from "../ui/initUI";import {hasTopClosestByAttribute} from "../util/hasClosest";import {addScriptSync} from "../util/addScript";import {prepareWechatCopy, prepareZhihuCopy} from "./platformCopy";+import {getHostCapabilities} from "../../util/hostCapabilities";export class Preview {public element: HTMLElement;@@ -239,7 +240,8 @@ export class Preview {id: protyle.block.id || protyle.options.blockId || protyle.block.parentID,}, response => {const oldScrollTop = protyle.preview.previewElement.scrollTop;- protyle.preview.previewElement.innerHTML = response.data.html;+ protyle.preview.previewElement.innerHTML = getHostCapabilities().remoteKernel ?+ window.DOMPurify.sanitize(response.data.html) : response.data.html;/// #if MOBILEprotyle.preview.previewElement.querySelector(`#${CSS.escape(protyle.block.rootID)}`)?.classList.add("protyle-preview__title");diff --git a/app/src/protyle/render/abcRender.ts b/app/src/protyle/render/abcRender.tsindex fcd4d829bf..79b11fed92 100644--- a/app/src/protyle/render/abcRender.ts+++ b/app/src/protyle/render/abcRender.ts@@ -3,6 +3,8 @@ import {Constants} from "../../constants";import {genIconHTML} from "./util";import {hasClosestByClassName} from "../util/hasClosest";import {looseJsonParse} from "../../util/functions";+import {getHostCapabilities} from "../../util/hostCapabilities";+import {MERMAID_SANITIZE_OPTIONS} from "./mermaidSanitize";const ABCJS_PARAMS_KEY = "%%params";@@ -45,6 +47,10 @@ export const abcRender = (element: Element, cdn = Constants.PROTYLE_CDN) => {renderElement.innerHTML = `<span style="position: absolute;left:0;top:0;width: 1px;">${Constants.ZWSP}</span><div contenteditable="false"></div>`;const abcString = Lute.UnEscapeHTMLStr(e.getAttribute("data-content"));window.ABCJS.renderAbc(renderElement.lastElementChild, abcString, getAbcParams(abcString));+ if (getHostCapabilities().remoteKernel) {+ renderElement.lastElementChild.innerHTML = window.DOMPurify.sanitize(+ renderElement.lastElementChild.innerHTML, MERMAID_SANITIZE_OPTIONS);+ }});});};diff --git a/app/src/protyle/render/av/attributeValue.ts b/app/src/protyle/render/av/attributeValue.tsindex f031e89f47..e269755e80 100644--- a/app/src/protyle/render/av/attributeValue.ts+++ b/app/src/protyle/render/av/attributeValue.ts@@ -6,6 +6,7 @@ import {isBrowserRenderableImagePath} from "../../../util/imageURL";import {formatDateDisplay, formatDateValue} from "./dateFormat";import {cloneAVCellValueSnapshot, getAVBlockRefSubtype, hasAVRenderTemplateResult} from "./cellValue";import {getAVColorStyle} from "./color";+import {getHostCapabilities} from "../../../util/hostCapabilities";export const createEmptyAVValue = (keyID: string, type: TAVCol, blockID?: string) => ({type,@@ -29,7 +30,7 @@ export const createEmptyAVValue = (keyID: string, type: TAVCol, blockID?: string} as IAVCellValue);export const getAVTemplateHTML = (content: string) => {- if (window.siyuan.config.editor.allowHTMLBLockScript) {+ if (!getHostCapabilities().remoteKernel && window.siyuan.config.editor.allowHTMLBLockScript) {return content;}// 默认过滤危险标签和事件属性,避免数据库模板字段中的代码直接执行diff --git a/app/src/protyle/render/av/blockAttr.ts b/app/src/protyle/render/av/blockAttr.tsindex 31c3f317f2..bd4f810b60 100644--- a/app/src/protyle/render/av/blockAttr.ts+++ b/app/src/protyle/render/av/blockAttr.ts@@ -29,6 +29,7 @@ import {isLastPointerMouse} from "../../../util/touchDragBridge";import {getLocalDropFiles, hasDataTransferFiles} from "../../upload/localDropFiles";import {cloneAVCellValueSnapshot} from "./cellValue";import {getEditorFocusRange, restoreEditorFocusRange} from "../../util/editorFocus";+import {getHostCapabilities} from "../../../util/hostCapabilities";interface IAVAttributeTableData {avID: string;@@ -207,7 +208,7 @@ export const renderAVAttribute = (element: HTMLElement, id: string, protyle: IPrconst cellElement = element.querySelector(".custom-attr__avvalue--active") as HTMLElement;if (cellElement) {const position = {x: event.clientX, y: event.clientY};- if (!isBrowser()) {+ if (!isBrowser() && getHostCapabilities().localFileSystem) {/// #if !BROWSERconst files = getLocalDropFiles(event.dataTransfer.files,file => webUtils.getPathForFile(file));diff --git a/app/src/protyle/render/blockRender.ts b/app/src/protyle/render/blockRender.tsindex b9c6806846..f049227d87 100644--- a/app/src/protyle/render/blockRender.ts+++ b/app/src/protyle/render/blockRender.ts@@ -9,6 +9,7 @@ import {isEncryptedBox} from "../../util/pathName";import {disabledWYSIWYG} from "../util/disabledWYSIWYG";import {normalizeHTMLAssetIFrameBlockDOM} from "../../asset/html";import {finishCustomEmbedRender, finishEmptyEmbedRender, IEmbedRenderLoadingState} from "./embedRenderState";+import {getHostCapabilities} from "../../util/hostCapabilities";/*** 渲染嵌入块@@ -56,7 +57,7 @@ export const blockRender = (protyle: IProtyle, element: Element, top?: number, oif (content.startsWith("//!js")) {// 安全模式下禁用 JS 查询嵌入块,与代码片段(CSS/JS snippet)的处理保持一致- if (window.siyuan.config.system.safeMode) {+ if (window.siyuan.config.system.safeMode || getHostCapabilities().remoteKernel) {renderEmbed([], protyle, item, top, window.siyuan.languages.safeModeJSTip, onEmbedRender);return;}diff --git a/app/src/protyle/render/chartRender.ts b/app/src/protyle/render/chartRender.tsindex d08757cf45..856eefe9f3 100644--- a/app/src/protyle/render/chartRender.ts+++ b/app/src/protyle/render/chartRender.ts@@ -3,6 +3,49 @@ import {Constants} from "../../constants";import {hasClosestByClassName} from "../util/hasClosest";import {looseJsonParse} from "../../util/functions";import {genIconHTML} from "./util";+import {getHostCapabilities, isExternalURLAllowed} from "../../util/hostCapabilities";+import {escapeHtml} from "../../util/escape";++const secureEChartsOption = (option: any) => {+ if (!getHostCapabilities().remoteKernel || !option || typeof option !== "object") {+ return option;+ }+ const pending = [option];+ while (pending.length > 0) {+ const current = pending.pop();+ Object.entries(current).forEach(([key, value]) => {+ if (typeof value === "string" && ["href", "link", "src", "url"].includes(key) &&+ !isExternalURLAllowed(value, true)) {+ current[key] = "about:blank";+ return;+ }+ if (key === "tooltip" && value !== false) {+ if (Array.isArray(value)) {+ value.forEach((tooltip) => {+ if (tooltip && typeof tooltip === "object") {+ tooltip.renderMode = "richText";+ }+ });+ } else {+ current[key] = {+ ...(value && typeof value === "object" ? value : {}),+ renderMode: "richText",+ };+ }+ }+ if (value && typeof value === "object") {+ pending.push(value);+ }+ });+ }+ if (option.tooltip !== false && !Array.isArray(option.tooltip)) {+ option.tooltip = {+ ...(option.tooltip && !Array.isArray(option.tooltip) ? option.tooltip : {}),+ renderMode: "richText",+ };+ }+ return option;+};export const chartRender = (element: Element, cdn = Constants.PROTYLE_CDN) => {let echartsElements: Element[] | NodeListOf<Element> = [];@@ -38,7 +81,8 @@ export const chartRender = (element: Element, cdn = Constants.PROTYLE_CDN) => {renderElement.lastElementChild.classList.remove("ft__error");}const chartInstance = window.echarts.getInstanceById(renderElement.lastElementChild?.getAttribute("_echarts_instance_"));- const option = await looseJsonParse(Lute.UnEscapeHTMLStr(e.getAttribute("data-content")));+ const option = secureEChartsOption(await looseJsonParse(+ Lute.UnEscapeHTMLStr(e.getAttribute("data-content"))));if (chartInstance) {if (chartInstance.getOption().series[0]?.type !== option.series[0]?.type) {chartInstance.clear();@@ -48,7 +92,7 @@ export const chartRender = (element: Element, cdn = Constants.PROTYLE_CDN) => {window.echarts.init(renderElement.lastElementChild, window.siyuan.config.appearance.mode === 1 ? "dark" : undefined, {width}).setOption(option);} catch (error) {window.echarts.dispose(renderElement.lastElementChild);- renderElement.innerHTML = `<span style="position: absolute;left:0;top:0;width: 1px;">${Constants.ZWSP}</span><div class="ft__error" style="height:${e.style.height || "420px"}" contenteditable="false">echarts render error: <br>${error}</div>`;+ renderElement.innerHTML = `<span style="position: absolute;left:0;top:0;width: 1px;">${Constants.ZWSP}</span><div class="ft__error" style="height:${e.style.height || "420px"}" contenteditable="false">echarts render error: <br>${escapeHtml(String(error))}</div>`;}});});diff --git a/app/src/protyle/render/flowchartRender.ts b/app/src/protyle/render/flowchartRender.tsindex 853392ca63..8a0ec1f746 100644--- a/app/src/protyle/render/flowchartRender.ts+++ b/app/src/protyle/render/flowchartRender.ts@@ -2,6 +2,9 @@ import {addScript} from "../util/addScript";import {Constants} from "../../constants";import {hasClosestByAttribute, hasClosestByClassName} from "../util/hasClosest";import {genIconHTML} from "./util";+import {getHostCapabilities} from "../../util/hostCapabilities";+import {MERMAID_SANITIZE_OPTIONS} from "./mermaidSanitize";+import {escapeHtml} from "../../util/escape";declare const flowchart: {parse(text: string): { drawSVG: (type: Element) => void };@@ -66,8 +69,12 @@ const initFlowchart = (flowchartElements: Element[]) => {try {renderElement.innerHTML = `<span style="position: absolute;left:0;top:0;width: 1px;">${Constants.ZWSP}</span><div contenteditable="false"></div>`;flowchart.parse(Lute.UnEscapeHTMLStr(item.getAttribute("data-content"))).drawSVG(renderElement.lastElementChild);+ if (getHostCapabilities().remoteKernel) {+ renderElement.lastElementChild.innerHTML = window.DOMPurify.sanitize(+ renderElement.lastElementChild.innerHTML, MERMAID_SANITIZE_OPTIONS);+ }} catch (error) {- renderElement.innerHTML = `<span style="position: absolute;left:0;top:0;width: 1px;">${Constants.ZWSP}</span><div class="ft__error" contenteditable="false">Flow Chart render error: <br>${error}</div>`;+ renderElement.innerHTML = `<span style="position: absolute;left:0;top:0;width: 1px;">${Constants.ZWSP}</span><div class="ft__error" contenteditable="false">Flow Chart render error: <br>${escapeHtml(String(error))}</div>`;}});};diff --git a/app/src/protyle/render/graphvizRender.ts b/app/src/protyle/render/graphvizRender.tsindex 710d854351..fb76a321d1 100644--- a/app/src/protyle/render/graphvizRender.ts+++ b/app/src/protyle/render/graphvizRender.ts@@ -2,6 +2,9 @@ import {addScript} from "../util/addScript";import {Constants} from "../../constants";import {genIconHTML} from "./util";import {hasClosestByClassName} from "../util/hasClosest";+import {getHostCapabilities} from "../../util/hostCapabilities";+import {MERMAID_SANITIZE_OPTIONS} from "./mermaidSanitize";+import {escapeHtml} from "../../util/escape";export const graphvizRender = (element: Element, cdn = Constants.PROTYLE_CDN) => {let graphvizElements: Element[] | NodeListOf<Element> = [];@@ -28,9 +31,12 @@ export const graphvizRender = (element: Element, cdn = Constants.PROTYLE_CDN) =>try {Viz.instance().then((viz) => {const svgElement = viz.renderSVGElement(Lute.UnEscapeHTMLStr(e.getAttribute("data-content")));- renderElement.innerHTML = `<span style="position: absolute;left:0;top:0;width: 1px;">${Constants.ZWSP}</span><div contenteditable="false">${svgElement.outerHTML}</div>`;+ const svgHTML = getHostCapabilities().remoteKernel ?+ window.DOMPurify.sanitize(svgElement.outerHTML, MERMAID_SANITIZE_OPTIONS) :+ svgElement.outerHTML;+ renderElement.innerHTML = `<span style="position: absolute;left:0;top:0;width: 1px;">${Constants.ZWSP}</span><div contenteditable="false">${svgHTML}</div>`;}).catch((error) => {- renderElement.innerHTML = `<span style="position: absolute;left:0;top:0;width: 1px;">${Constants.ZWSP}</span><div class="ft__error" contenteditable="false">graphviz render error: <br>${error}</div>`;+ renderElement.innerHTML = `<span style="position: absolute;left:0;top:0;width: 1px;">${Constants.ZWSP}</span><div class="ft__error" contenteditable="false">graphviz render error: <br>${escapeHtml(String(error))}</div>`;});} catch (e) {console.error("Graphviz error", e);diff --git a/app/src/protyle/render/mathRender.ts b/app/src/protyle/render/mathRender.tsindex ff2f7a064c..338c9553a4 100644--- a/app/src/protyle/render/mathRender.ts+++ b/app/src/protyle/render/mathRender.ts@@ -5,6 +5,7 @@ import {hasNextSibling, hasPreviousSibling} from "../wysiwyg/getBlock";import {hasClosestBlock} from "../util/hasClosest";import {looseJsonParse} from "../../util/functions";import {genRenderFrame} from "./util";+import {getHostCapabilities} from "../../util/hostCapabilities";const fitMathWidth = (mathElement: HTMLElement, blockElement: HTMLElement | false, isBlock: boolean) => {return new Promise<void>((resolve) => {@@ -46,14 +47,18 @@ export const mathRender = (element: Element, cdn = Constants.PROTYLE_CDN, maxWidconsole.warn("KaTex macros is not JSON", e);}const isBlock = mathElement.tagName === "DIV";+ const remoteKernel = getHostCapabilities().remoteKernel;try {- const mathHTML = window.katex.renderToString(Lute.UnEscapeHTMLStr(mathElement.getAttribute("data-content")), {+ let mathHTML = window.katex.renderToString(Lute.UnEscapeHTMLStr(mathElement.getAttribute("data-content")), {displayMode: isBlock,output: "html",macros,- trust: true, // REF: https://katex.org/docs/supported#html+ trust: !remoteKernel, // REF: https://katex.org/docs/supported#htmlstrict: (errorCode) => errorCode === "unicodeTextInMathMode" ? "ignore" : "warn",});+ if (remoteKernel) {+ mathHTML = window.DOMPurify.sanitize(mathHTML);+ }const blockElement = hasClosestBlock(mathElement);if (isBlock) {genRenderFrame(mathElement);@@ -127,10 +132,10 @@ export const mathRender = (element: Element, cdn = Constants.PROTYLE_CDN, maxWidif (isBlock) {genRenderFrame(mathElement);mathElement.firstElementChild.firstElementChild.setAttribute("contenteditable", "false");- mathElement.firstElementChild.firstElementChild.innerHTML = e.message;+ mathElement.firstElementChild.firstElementChild.textContent = e.message;mathElement.firstElementChild.firstElementChild.classList.add("ft__error");} else {- mathElement.innerHTML = e.message;+ mathElement.textContent = e.message;mathElement.classList.add("ft__error");}}diff --git a/app/src/protyle/render/mermaidRender.ts b/app/src/protyle/render/mermaidRender.tsindex dae144d983..c63fbd6bf4 100644--- a/app/src/protyle/render/mermaidRender.ts+++ b/app/src/protyle/render/mermaidRender.ts@@ -5,6 +5,8 @@ import {genIconHTML} from "./util";import {applyMermaidLayout, getMermaidLayout, MERMAID_LAYOUT_ATTR} from "./mermaidLayout";import {MERMAID_SANITIZE_OPTIONS} from "./mermaidSanitize";import {isZenumlDiagram} from "./mermaidZenuml";+import {getHostCapabilities} from "../../util/hostCapabilities";+import {escapeHtml} from "../../util/escape";let mermaidTidyTreePromise: Promise<void>;let mermaidZenumlPromise: Promise<void>;@@ -60,7 +62,8 @@ export const mermaidRender = (element: Element, cdn = Constants.PROTYLE_CDN) =>},]);const config: any = {- securityLevel: "loose", // 升级后无 https://github.com/siyuan-note/siyuan/issues/3587,可使用该选项+ // 升级后无 https://github.com/siyuan-note/siyuan/issues/3587,可使用 loose+ securityLevel: getHostCapabilities().remoteKernel ? "strict" : "loose",altFontFamily: "sans-serif",fontFamily: "sans-serif",startOnLoad: false,@@ -142,8 +145,11 @@ const initMermaid = (mermaidElements: Element[]) => {renderElement.lastElementChild.innerHTML = svg;} catch (e) {const errorElement = document.querySelector("#" + id);- renderElement.lastElementChild.innerHTML = `${errorElement.outerHTML}<div class="fn__hr"></div><div class="ft__error">${e.message.replace(/\n/, "<br>")}</div>`;- errorElement.parentElement.remove();+ const errorDiagram = errorElement ?+ window.DOMPurify.sanitize(errorElement.outerHTML, MERMAID_SANITIZE_OPTIONS) : "";+ const errorMessage = escapeHtml(e instanceof Error ? e.message : String(e)).replace(/\n/g, "<br>");+ renderElement.lastElementChild.innerHTML = `${errorDiagram}<div class="fn__hr"></div><div class="ft__error">${errorMessage}</div>`;+ errorElement?.parentElement?.remove();}});};diff --git a/app/src/protyle/render/mindmapRender.ts b/app/src/protyle/render/mindmapRender.tsindex 3549e7c540..8d519bfa54 100644--- a/app/src/protyle/render/mindmapRender.ts+++ b/app/src/protyle/render/mindmapRender.ts@@ -2,6 +2,8 @@ import {addScript} from "../util/addScript";import {Constants} from "../../constants";import {hasClosestByClassName} from "../util/hasClosest";import {genIconHTML} from "./util";+import {escapeHtml} from "../../util/escape";+import {getHostCapabilities} from "../../util/hostCapabilities";export const mindmapRender = (element: Element, cdn = Constants.PROTYLE_CDN) => {let mindmapElements: Element[] | NodeListOf<Element> = [];@@ -73,6 +75,7 @@ export const mindmapRender = (element: Element, cdn = Constants.PROTYLE_CDN) =>},],tooltip: {+ ...(getHostCapabilities().remoteKernel ? {renderMode: "richText"} : {}),trigger: "item",triggerOn: "mousemove",},@@ -80,7 +83,7 @@ export const mindmapRender = (element: Element, cdn = Constants.PROTYLE_CDN) =>});} catch (error) {window.echarts.dispose(renderElement.lastElementChild);- renderElement.innerHTML = `<span style="position: absolute;left:0;top:0;width: 1px;">${Constants.ZWSP}</span><div class="ft__error" style="height:${e.style.height || "420px"}" contenteditable="false">Mindmap render error: <br>${error}</div>`;+ renderElement.innerHTML = `<span style="position: absolute;left:0;top:0;width: 1px;">${Constants.ZWSP}</span><div class="ft__error" style="height:${e.style.height || "420px"}" contenteditable="false">Mindmap render error: <br>${escapeHtml(String(error))}</div>`;}});});diff --git a/app/src/protyle/render/plantumlRender.ts b/app/src/protyle/render/plantumlRender.tsindex 6a9c0be143..20a86aabc1 100644--- a/app/src/protyle/render/plantumlRender.ts+++ b/app/src/protyle/render/plantumlRender.ts@@ -2,6 +2,7 @@ import {addScript} from "../util/addScript";import {Constants} from "../../constants";import {genIconHTML} from "./util";import {hasClosestByClassName} from "../util/hasClosest";+import {getHostCapabilities} from "../../util/hostCapabilities";export const plantumlRender = (element: Element, cdn = Constants.PROTYLE_CDN) => {let plantumlElements: Element[] | NodeListOf<Element> = [];@@ -27,14 +28,24 @@ export const plantumlRender = (element: Element, cdn = Constants.PROTYLE_CDN) =>}try {const url = `${window.siyuan.config.editor.plantUMLServePath}${window.plantumlEncoder.encode(Lute.UnEscapeHTMLStr(e.getAttribute("data-content")))}`;- renderElement.innerHTML = `<object type="image/svg+xml" data="${url}"/>`;+ const imageElement = document.createElement("img");+ imageElement.src = url;+ if (getHostCapabilities().remoteKernel) {+ renderElement.replaceChildren(imageElement);+ renderElement.classList.remove("ft__error");+ return;+ }+ const objectElement = document.createElement("object");+ objectElement.type = "image/svg+xml";+ objectElement.data = url;+ renderElement.replaceChildren(objectElement);renderElement.classList.remove("ft__error");- renderElement.firstElementChild.addEventListener("error", () => {- renderElement.innerHTML = `<img src=${url}">`;+ objectElement.addEventListener("error", () => {+ renderElement.replaceChildren(imageElement);});} catch (error) {renderElement.classList.add("ft__error");- renderElement.innerHTML = `plantuml render error: <br>${error}`;+ renderElement.textContent = `plantuml render error: ${error}`;}});});diff --git a/app/src/protyle/toolbar/index.ts b/app/src/protyle/toolbar/index.tsindex 47d1b14c9e..a8ba94a78f 100644--- a/app/src/protyle/toolbar/index.ts+++ b/app/src/protyle/toolbar/index.ts@@ -70,6 +70,7 @@ import {activeBlur, updateMobilePluginToolbar} from "../../mobile/util/keyboardTimport {FormatPainter} from "./FormatPainter";import {IFormatPainterSnapshot} from "./formatPainterCore";import {clearDisallowedTextInputHotkey} from "../../util/hotKeyPolicy";+import {getHostCapabilities} from "../../util/hostCapabilities";import {closeSubElement, SELECTION_TOOLBAR_SUB_ELEMENT_SOURCE} from "./subElementLifecycle";import {getDefaultToolbar, getToolbarEntryId, markPluginToolbarEntries} from "./defaults";import {applyToolbarEntryVisibility} from "../../config/entryVisibility/runtime";@@ -1477,8 +1478,8 @@ export class Toolbar {<span class="fn__space${protyle.disabled ? " fn__none" : ""}"></span><button data-type="after" class="block__icon block__icon--show b3-tooltips b3-tooltips__nw${protyle.disabled ? " fn__none" : ""}" aria-label="${window.siyuan.languages.insertAfter}"><svg><use xlink:href="#iconAfter"></use></svg></button><span class="fn__space${protyle.disabled ? " fn__none" : ""}"></span>- <button data-type="export" class="block__icon block__icon--show b3-tooltips b3-tooltips__nw" aria-label="${window.siyuan.languages.export} ${window.siyuan.languages.image}"><svg><use xlink:href="#iconImage"></use></svg></button>- <span class="fn__space"></span>+ <button data-type="export" class="block__icon block__icon--show b3-tooltips b3-tooltips__nw${getHostCapabilities().importExport ? "" : " fn__none"}" aria-label="${window.siyuan.languages.export} ${window.siyuan.languages.image}"><svg><use xlink:href="#iconImage"></use></svg></button>+ <span class="fn__space${getHostCapabilities().importExport ? "" : " fn__none"}"></span><button data-type="pin" class="block__icon block__icon--show b3-tooltips b3-tooltips__nw" aria-label="${window.siyuan.languages.pin}"><svg><use xlink:href="#iconPin"></use></svg></button><span class="fn__space"></span><button data-type="close" class="block__icon block__icon--show b3-tooltips b3-tooltips__nw" aria-label="${window.siyuan.languages.close}"><svg><use xlink:href="#iconClose"></use></svg></button>@@ -1596,6 +1597,9 @@ export class Toolbar {}});const exportImg = () => {+ if (!getHostCapabilities().importExport) {+ return;+ }const msgId = showMessage(window.siyuan.languages.exporting, 0);if (renderElement.getAttribute("data-subtype") === "plantuml") {fetch(renderElement.querySelector("object").getAttribute("data")).then(function (response) {@@ -2124,9 +2128,11 @@ export class Toolbar {searchHTML += `<div data-value="${item.path}" class="b3-list-item--hide-action b3-list-item${index === 0 ? " b3-list-item--focus" : ""}"><span class="b3-list-item__text">${item.content}</span>`;/// #if !BROWSER- searchHTML += `<span data-type="open" class="b3-list-item__action b3-tooltips b3-tooltips__w" aria-label="${window.siyuan.languages.showInFolder}">+ if (getHostCapabilities().localFileSystem) {+ searchHTML += `<span data-type="open" class="b3-list-item__action b3-tooltips b3-tooltips__w" aria-label="${window.siyuan.languages.showInFolder}"><svg><use xlink:href="#iconFolder"></use></svg></span>`;+ }/// #endifsearchHTML += `<span data-type="remove" class="b3-list-item__action b3-tooltips b3-tooltips__w" aria-label="${window.siyuan.languages.remove}"><svg><use xlink:href="#iconTrashcan"></use></svg>diff --git a/app/src/protyle/toolbar/util.ts b/app/src/protyle/toolbar/util.tsindex b472f40cf7..30d202fa53 100644--- a/app/src/protyle/toolbar/util.ts+++ b/app/src/protyle/toolbar/util.ts@@ -13,6 +13,7 @@ import {setSemanticInlineElementMarker,stripSemanticInternalMarkerPrefix} from "../util/inlineElementMarker";+import {normalizeHTMLAssetIFrameBlockDOM} from "../../asset/html";export const previewTemplate = (pathString: string, element: Element, parentId: string) => {if (!pathString) {@@ -25,7 +26,8 @@ export const previewTemplate = (pathString: string, element: Element, parentId:mode: "preview",preview: true}, (response) => {- element.innerHTML = `<div class="protyle-wysiwyg" style="padding: 8px">${response.data.content.replace(/contenteditable="true"/g, "")}</div>`;+ const content = normalizeHTMLAssetIFrameBlockDOM(response.data.content.replace(/contenteditable="true"/g, ""));+ element.innerHTML = `<div class="protyle-wysiwyg" style="padding: 8px">${content}</div>`;});};diff --git a/app/src/protyle/ui/initUI.ts b/app/src/protyle/ui/initUI.tsindex c0dd326474..c91a2c0d23 100644--- a/app/src/protyle/ui/initUI.ts+++ b/app/src/protyle/ui/initUI.ts@@ -20,6 +20,7 @@ import {hideElements} from "./hideElements";import {AVAttributePanel} from "../render/av/attributePanel";import {getEditorHorizontalPadding} from "./padding";import {callMobileAppShowKeyboard} from "../../mobile/util/mobileAppUtil";+import {sanitizeKernelHTML} from "../../util/hostCapabilities";const focusMobileAppEditor = (element: HTMLElement) => {if (window.JSAndroid?.showKeyboard || window.JSHarmony?.showKeyboard) {@@ -319,7 +320,7 @@ export const addLoading = (protyle: IProtyle, msg?: string) => {if (protyle.element.getAttribute("data-loading") !== "finished") {protyle.element.insertAdjacentHTML("beforeend", `<div style="background-color: var(--b3-theme-background);flex-direction: column;" class="fn__loading wysiwygLoading"><img width="48px" src="/stage/loading-pure.svg">- <div style="color: var(--b3-theme-on-surface);margin-top: 8px;">${msg || ""}</div>+ <div style="color: var(--b3-theme-on-surface);margin-top: 8px;">${sanitizeKernelHTML(msg || "")}</div></div>`);}}, Constants.TIMEOUT_LOAD);diff --git a/app/src/protyle/upload/htmlLocalAssets.test.ts b/app/src/protyle/upload/htmlLocalAssets.test.tsindex 89158962a1..dda7d292a0 100644--- a/app/src/protyle/upload/htmlLocalAssets.test.ts+++ b/app/src/protyle/upload/htmlLocalAssets.test.ts@@ -1,6 +1,11 @@import {describe, it} from "node:test";import * as assert from "node:assert/strict";-import {applyHTMLLocalAssetPaths, type IHTMLLocalAsset, isHTMLLocalAssetPath} from "./htmlLocalAssets";+import {+ applyHTMLLocalAssetPaths,+ type IHTMLLocalAsset,+ isHTMLLocalAssetPath,+ removeHTMLLocalAssetPaths,+} from "./htmlLocalAssets";describe("HTML local assets", () => {it("recognizes absolute paths without treating web and asset URLs as local", () => {@@ -28,4 +33,25 @@ describe("HTML local assets", () => {assert.deepEqual(values, ["file:///tmp/a.png", "assets/b.pdf"]);});++ it("removes local paths before remote HTML conversion", () => {+ const attributes = new Map([+ ["src", "file:///Users/test/private.png"],+ ["data-type", "NodeImage"],+ ]);+ const assets = [{+ element: {+ removeAttribute(attribute: string) {+ attributes.delete(attribute);+ },+ } as Element,+ attribute: "src",+ path: attributes.get("src"),+ }] as IHTMLLocalAsset[];++ removeHTMLLocalAssetPaths(assets);++ assert.equal(attributes.has("src"), false);+ assert.equal(attributes.get("data-type"), "NodeImage");+ });});diff --git a/app/src/protyle/upload/htmlLocalAssets.ts b/app/src/protyle/upload/htmlLocalAssets.tsindex 289dab2c82..35544cdcfb 100644--- a/app/src/protyle/upload/htmlLocalAssets.ts+++ b/app/src/protyle/upload/htmlLocalAssets.ts@@ -36,3 +36,7 @@ export const applyHTMLLocalAssetPaths = (assets: IHTMLLocalAsset[], paths: Array}});};++export const removeHTMLLocalAssetPaths = (assets: IHTMLLocalAsset[]) => {+ assets.forEach((asset) => asset.element.removeAttribute(asset.attribute));+};diff --git a/app/src/protyle/upload/index.ts b/app/src/protyle/upload/index.tsindex 38b7ccefaa..48c1933736 100644--- a/app/src/protyle/upload/index.ts+++ b/app/src/protyle/upload/index.ts@@ -26,6 +26,7 @@ import {} from "./pluginEvent";import {getAssetUploadResult, getAssetUploadSuccesses} from "./uploadResult";import {AssetUploadHandlerTimeoutError, waitForUploadHandler} from "./uploadHandler";+import {getHostCapabilities} from "../../util/hostCapabilities";interface FileWithPath extends File {path: string;@@ -177,7 +178,8 @@ const genUploadedLabel = async (responseText: string, protyle: IProtyle, optionscontent: success.path,name: name});- successFileText += genAssetHTML(type, success.path, name, filename, options?.htmlAsIframe);+ successFileText += genAssetHTML(type, success.path, name, filename,+ getHostCapabilities().localFileSystem && options?.htmlAsIframe);if (!Constants.SIYUAN_ASSETS_AUDIO.includes(type) && !Constants.SIYUAN_ASSETS_VIDEO.includes(type) &&successes.length - 1 !== index) {if (nodeElement && nodeElement.classList.contains("table")) {@@ -412,6 +414,10 @@ const finishSuccessfulUpload = (task: IAssetUploadTask | undefined, callbacks: Iconst uploadPreparedLocalFiles = (input: Extract<IAssetUploadInput, { kind: "local-files" }>,protyle: IProtyle, isUpload: boolean, callbacks: IAssetUploadCallbacks,task?: IAssetUploadTask, options?: IUploadInsertOptions) => {+ if (!getHostCapabilities().localFileSystem) {+ finishUpload(task, callbacks, {status: "canceled"});+ return;+ }let msg = "";const assetPaths: string[] = [];input.files.forEach(item => {diff --git a/app/src/protyle/util/addScript.ts b/app/src/protyle/util/addScript.tsindex 47dfdb9c1a..3f5c9f3577 100644--- a/app/src/protyle/util/addScript.ts+++ b/app/src/protyle/util/addScript.ts@@ -1,7 +1,30 @@+import {isRemoteKernel} from "../../util/hostCapabilities";+export const addScriptSync = async (path: string, id: string) => {if (document.getElementById(id)) {return false;}+ if (isRemoteKernel()) {+ return new Promise<boolean>((resolve) => {+ const scriptElement = document.createElement("script");+ scriptElement.type = "text/javascript";+ scriptElement.src = path;+ scriptElement.async = false;+ scriptElement.id = id;+ scriptElement.onload = () => {+ if (typeof Lute === "undefined") {+ // 鸿蒙系统上第一次加载会出现 Lute 未定义的情况,重新载入一次就好了,暂时没找到原因,先这样处理+ window.location.reload();+ }+ resolve(true);+ };+ scriptElement.onerror = () => {+ scriptElement.remove();+ resolve(false);+ };+ document.head.appendChild(scriptElement);+ });+ }const xhrObj = new XMLHttpRequest();xhrObj.open("GET", path, false);xhrObj.setRequestHeader("Accept",@@ -16,6 +39,7 @@ export const addScriptSync = async (path: string, id: string) => {// 鸿蒙系统上第一次加载会出现 Lute 未定义的情况,重新载入一次就好了,暂时没找到原因,先这样处理window.location.reload();}+ return true;};export const addScript = (path: string, id: string) => {diff --git a/app/src/protyle/util/compatibility.ts b/app/src/protyle/util/compatibility.tsindex 0cc7390e8d..1823fd2806 100644--- a/app/src/protyle/util/compatibility.ts+++ b/app/src/protyle/util/compatibility.ts@@ -14,6 +14,7 @@ import {buildBlockDOMClipboardData} from "./blockDOMClipboard";import {buildWebClipboardHTML, getTextSiyuanFromTextHTML} from "./clipboardData";import {prepareExternalClipboardHTML} from "./richClipboard";import {isIOSPlatform, isIPadOSPlatform} from "./browserCompatibility";+import {canOpenExternalURL, getHostCapabilities} from "../../util/hostCapabilities";export {encodeBase64, getTextSiyuanFromTextHTML} from "./clipboardData";@@ -62,6 +63,12 @@ export const isPhablet = () => {};export const saveExportFile = async (uri: string, msgId?: string): Promise<TSaveExportFileResult> => {+ if (!getHostCapabilities().importExport) {+ if (msgId) {+ hideMessage(msgId);+ }+ return {status: "error"};+ }if (!uri) {return {status: "error"};}@@ -210,6 +217,9 @@ export const readText = () => {export const getLocalFiles = async () => {// 不再支持 PC 浏览器 https://github.com/siyuan-note/siyuan/issues/7206let localFiles: ILocalFiles[] = [];+ if (!getHostCapabilities().localFileSystem) {+ return localFiles;+ }if ("darwin" === window.siyuan.config.system.os) {const xmlString = await ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "clipboardRead",@@ -932,6 +942,9 @@ export const initWindowOpenOverride = (app: App, openExternal?: (url: string) =>void import("../../util/uri").then(({processSiYuanUri}) => processSiYuanUri(app, urlStr));return null;}+ if (!canOpenExternalURL(urlStr)) {+ return null;+ }if (isInMobileApp() && urlStr && openExternal) {openExternal(urlStr);return null;diff --git a/app/src/protyle/util/editorCommonEvent.ts b/app/src/protyle/util/editorCommonEvent.tsindex d5b7e3c537..4c728e3c97 100644--- a/app/src/protyle/util/editorCommonEvent.ts+++ b/app/src/protyle/util/editorCommonEvent.ts@@ -56,6 +56,7 @@ import {clearSelect} from "./clear";import {dragoverTab} from "../render/av/view";import {setFold} from "./blockFold";import {isEncryptedBox} from "../../util/pathName";+import {getHostCapabilities} from "../../util/hostCapabilities";import {getAVRowDropTarget,getBlockDragInsertPosition,@@ -2114,7 +2115,8 @@ export const dropEvent = (protyle: IProtyle, editorElement: HTMLElement) => {const avElement = hasClosestByClassName(event.target, "av");if (!avElement) {focusByRange(getRangeByPoint(event.clientX, event.clientY));- if (event.dataTransfer.types.includes("Files") && !isBrowser()) {+ if (event.dataTransfer.types.includes("Files") && !isBrowser() &&+ getHostCapabilities().localFileSystem) {const files = getLocalDropFiles(event.dataTransfer.files, file => webUtils.getPathForFile(file));if (!files) {paste(protyle, event, {@@ -2140,9 +2142,7 @@ export const dropEvent = (protyle: IProtyle, editorElement: HTMLElement) => {if (cellElement) {if (getTypeByCellElement(cellElement) === "mAsset" && hasDataTransferFiles(event.dataTransfer.types)) {/// #if !BROWSER- const files = getLocalDropFiles(event.dataTransfer.files,- file => webUtils.getPathForFile(file));- if (!files) {+ if (!getHostCapabilities().localFileSystem) {focusBlock(hasClosestBlock(cellElement) as HTMLElement);uploadFiles(protyle, event.dataTransfer.files, undefined, undefined, undefined, {source: "drop",@@ -2150,7 +2150,18 @@ export const dropEvent = (protyle: IProtyle, editorElement: HTMLElement) => {position: {x: event.clientX, y: event.clientY},});} else {- dragUpload(files, protyle, cellElement, {x: event.clientX, y: event.clientY});+ const files = getLocalDropFiles(event.dataTransfer.files,+ file => webUtils.getPathForFile(file));+ if (!files) {+ focusBlock(hasClosestBlock(cellElement) as HTMLElement);+ uploadFiles(protyle, event.dataTransfer.files, undefined, undefined, undefined, {+ source: "drop",+ target: "av-cell",+ position: {x: event.clientX, y: event.clientY},+ });+ } else {+ dragUpload(files, protyle, cellElement, {x: event.clientX, y: event.clientY});+ }}/// #elsefocusBlock(hasClosestBlock(cellElement) as HTMLElement);diff --git a/app/src/protyle/util/insertHTML.ts b/app/src/protyle/util/insertHTML.tsindex 9d3b8b0d75..d2cd25eb64 100644--- a/app/src/protyle/util/insertHTML.ts+++ b/app/src/protyle/util/insertHTML.ts@@ -60,6 +60,7 @@ import {getAVSelectedCells, IAVSelectedCell} from "../render/av/selectionState";import {getAVSelectedTableCells} from "../render/av/virtualScroll";import {resetCodeBlockRenderState} from "./codeBlockRenderState";import {getTextWithoutSemanticMarkers} from "./inlineElementMarker";+import {normalizeHTMLAssetIFrameSources} from "../../asset/html";// 粘贴时临时插入的占位行标记,遍历结束后统一移除,避免污染虚拟滚动的 renderedStart/renderedEnd/spacer 状态const PLACEHOLDER_ROW_CLASS = "av__row--placeholder";@@ -1386,6 +1387,7 @@ export const insertHTML = (html: string, protyle: IProtyle, isBlock = false,if (tempElement.content.firstChild.nodeType === 3 || (tempElement.content.firstChild.nodeType === 1 && tempElement.content.firstElementChild.tagName !== "DIV")) {tempElement.innerHTML = protyle.lute.SpinBlockDOM(tempElement.innerHTML);}+ normalizeHTMLAssetIFrameSources(tempElement.content);markFoldHeadingChildren(tempElement.content);(insertBefore ? Array.from(tempElement.content.children) : Array.from(tempElement.content.children).reverse()).find((item) => {let addId = item.getAttribute("data-node-id");diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.tsindex 510378e887..0c7793349f 100644--- a/app/src/protyle/util/paste.ts+++ b/app/src/protyle/util/paste.ts@@ -24,7 +24,7 @@ import {fixAdjacentTags, getCalloutInfo, getContenteditableElement} from "../wysimport {clearBlockElement} from "./clear";import {removeZWJ} from "./normalizeText";import {base64ToURL, showBase64ImageSizeLimit} from "../upload/base64";-import {applyHTMLLocalAssetPaths, collectHTMLLocalAssets} from "../upload/htmlLocalAssets";+import {applyHTMLLocalAssetPaths, collectHTMLLocalAssets, removeHTMLLocalAssetPaths} from "../upload/htmlLocalAssets";import {applyHTMLEmbeddedAssetPaths,collectHTMLEmbeddedAssets,@@ -55,6 +55,7 @@ import {} from "./wpsPresentation";import {hasDataTransferFiles} from "../upload/localDropFiles";import {resetPastedQueryEmbedRenderState} from "../render/embedRenderState";+import {getHostCapabilities, sanitizeKernelHTML} from "../../util/hostCapabilities";import {eventBusHas, hasPluginSubscriber} from "../../plugin/EventBusCore";import {normalizeSemanticInlineElements, stripSemanticMarkersFromRangeText} from "./inlineElementMarker";/// #if !BROWSER@@ -572,7 +573,7 @@ const insertConvertedBlockDOM = (protyle: IProtyle, dom: string, range: Range) =protyle.wysiwyg.element.querySelectorAll('[data-type~="block-ref"]').forEach(item => {if (item.textContent === "") {fetchPost("/api/block/getRefText", {id: item.getAttribute("data-id")}, (response) => {- item.innerHTML = response.data;+ item.innerHTML = sanitizeKernelHTML(response.data);});}});@@ -1101,6 +1102,9 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvenif (isHTML) {const tempElement = document.createElement("div");tempElement.innerHTML = textHTML;+ if (!getHostCapabilities().localFileSystem) {+ removeHTMLLocalAssetPaths(collectHTMLLocalAssets(tempElement));+ }// 移除空的 A 标签tempElement.querySelectorAll("a").forEach((e) => {if (e.innerHTML.trim() === "") {@@ -1119,7 +1123,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvenlinkElement = tempElement.firstElementChild.firstElementChild;}}- if (linkElement) {+ if (linkElement?.getAttribute("href")) {const selectText = stripSemanticMarkersFromRangeText(range).split(Constants.ZWSP).join("");protyle.toolbar.range = range;const aElements = protyle.toolbar.setInlineMark(protyle, "a", "range", {@@ -1204,6 +1208,10 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven}tempElement.innerHTML = preflight.normalizedHTML;localAssets = collectHTMLLocalAssets(tempElement);+ if (!getHostCapabilities().localFileSystem) {+ removeHTMLLocalAssetPaths(localAssets);+ localAssets = [];+ }preparedHTML = true;}if (localAssets.length > 0) {diff --git a/app/src/protyle/util/richClipboard.ts b/app/src/protyle/util/richClipboard.tsindex 4c359130fc..1901e22a89 100644--- a/app/src/protyle/util/richClipboard.ts+++ b/app/src/protyle/util/richClipboard.ts@@ -1,5 +1,6 @@import {Constants} from "../../constants";import {looseJsonParse} from "../../util/functions";+import {getHostCapabilities} from "../../util/hostCapabilities";/// #if !BROWSERimport {ipcRenderer} from "electron";/// #endif@@ -537,6 +538,9 @@ export const hasRichClipboardImages = (html: string) => {};export const enhanceRichClipboard = (text: string, html: string, notebookID: string, options: IRichClipboardOptions = {}) => {+ if (!getHostCapabilities().localFileSystem) {+ return;+ }/// #if !BROWSERwindow.setTimeout(async () => {const template = document.createElement("template");diff --git a/app/src/protyle/util/viewFold.ts b/app/src/protyle/util/viewFold.tsindex 400beacc59..194872d8b2 100644--- a/app/src/protyle/util/viewFold.ts+++ b/app/src/protyle/util/viewFold.ts@@ -8,6 +8,7 @@ import {clearViewFoldDefaultsForOccurrence,clearViewFoldOccurrenceRuntimeState,} from "./viewFoldRuntimeState";+import {normalizeHTMLAssetIFrameBlockDOM} from "../../asset/html";const VIEW_FOLD_SOURCE = "data-view-fold-source";const VIEW_FOLD_VALUE = "data-view-fold";@@ -208,7 +209,7 @@ const ensureHeadingChildren = async (protyle: IProtyle, heading: Element, stateKreturn;}const template = document.createElement("template");- template.innerHTML = response.data;+ template.innerHTML = normalizeHTMLAssetIFrameBlockDOM(response.data);const elements = Array.from(template.content.children);if (!elements[0] || elements[0].getAttribute("data-node-id") !== heading.getAttribute("data-node-id")) {return;diff --git a/app/src/protyle/util/widgetCache.ts b/app/src/protyle/util/widgetCache.tsindex 7a8e55705c..1409fa207d 100644--- a/app/src/protyle/util/widgetCache.ts+++ b/app/src/protyle/util/widgetCache.ts@@ -1,3 +1,6 @@+import {getHostCapabilities} from "../../util/hostCapabilities";+import {normalizeHTMLAssetIFrameSources} from "../../asset/html";+export const addWidgetCacheVersion = (src: string, version: string) => {if (!src.startsWith("/widgets/")) {return src;@@ -16,6 +19,10 @@ export const addWidgetCacheVersion = (src: string, version: string) => {};export const updateWidgetCacheVersion = (root: ParentNode, version: string) => {+ if (!getHostCapabilities().widgets) {+ normalizeHTMLAssetIFrameSources(root, true);+ return;+ }root.querySelectorAll<HTMLIFrameElement>('[data-type="NodeWidget"] iframe').forEach(item => {const src = item.getAttribute("src");if (src) {diff --git a/app/src/protyle/wysiwyg/commonHotkey.ts b/app/src/protyle/wysiwyg/commonHotkey.tsindex 7fa5dbbd03..be611b4f2d 100644--- a/app/src/protyle/wysiwyg/commonHotkey.ts+++ b/app/src/protyle/wysiwyg/commonHotkey.ts@@ -16,6 +16,7 @@ import {hasClosestByTag, hasTopClosestByClassName} from "../util/hasClosest";import {removeEmbed} from "./removeEmbed";import {clearBlockElement} from "../util/clear";import {isEncryptedBox} from "../../util/pathName";+import {normalizeHTMLAssetIFrameBlockDOM} from "../../asset/html";export const commonHotkey = (protyle: IProtyle, event: KeyboardEvent, nodeElement?: HTMLElement) => {if (matchHotKey(window.siyuan.config.keymap.editor.general.netImg2LocalAsset.custom, event)) {@@ -291,7 +292,7 @@ export const duplicateBlock = async (nodeElements: Element[], protyle: IProtyle)notebook: protyle.notebookId,});const foldTempElement = document.createElement("template");- foldTempElement.innerHTML = response.data.dom;+ foldTempElement.innerHTML = normalizeHTMLAssetIFrameBlockDOM(response.data.dom);tempElement = foldTempElement.content.firstElementChild as HTMLElement;}if (item.getAttribute("data-type") === "NodeListItem" && !isSameLi) {@@ -347,7 +348,7 @@ export const duplicateBlock = async (nodeElements: Element[], protyle: IProtyle)removeFoldAttr: false,});const foldElement = document.createElement("template");- foldElement.innerHTML = responseHTML.data;+ foldElement.innerHTML = normalizeHTMLAssetIFrameBlockDOM(responseHTML.data);let previousID = newId;Array.from(foldElement.content.children).slice(1).forEach((childItem: HTMLElement) => {childItem.removeAttribute("parent-heading");diff --git a/app/src/protyle/wysiwyg/input.ts b/app/src/protyle/wysiwyg/input.tsindex 48eefe2aec..d79eaa6224 100644--- a/app/src/protyle/wysiwyg/input.ts+++ b/app/src/protyle/wysiwyg/input.ts@@ -30,6 +30,7 @@ import {removeEmptySemanticInlineElement} from "../util/inlineElementMarker";import {normalizeInlineFontFamilyStyle} from "../toolbar/fontFamilyCore";+import {sanitizeKernelHTML} from "../../util/hostCapabilities";interface IInputOperations {doOperations: IOperation[];@@ -231,7 +232,7 @@ export const input = async (protyle: IProtyle, blockElement: HTMLElement, range:blockElement.querySelectorAll('[data-type~="block-ref"][data-subtype="d"]').forEach(refItem => {if (refItem.textContent === "") {fetchPost("/api/block/getRefText", {id: refItem.getAttribute("data-id")}, (response) => {- refItem.innerHTML = response.data;+ refItem.innerHTML = sanitizeKernelHTML(response.data);});}});@@ -512,7 +513,7 @@ export const input = async (protyle: IProtyle, blockElement: HTMLElement, range:realElement.querySelectorAll('[data-type~="block-ref"][data-subtype="d"]').forEach(refItem => {if (refItem.textContent === "") {fetchPost("/api/block/getRefText", {id: refItem.getAttribute("data-id")}, (response) => {- refItem.innerHTML = response.data;+ refItem.innerHTML = sanitizeKernelHTML(response.data);});}});diff --git a/app/src/protyle/wysiwyg/list.ts b/app/src/protyle/wysiwyg/list.tsindex 0c50f4c6c2..b18b77b824 100644--- a/app/src/protyle/wysiwyg/list.ts+++ b/app/src/protyle/wysiwyg/list.ts@@ -24,6 +24,7 @@ import {Dialog} from "../../dialog";import {isMobile} from "../../util/functions";import {showMessage} from "../../dialog/message";import {activateTrackedRangeInsertion, type ITrackedRangeInsertion} from "../util/trackedRange";+import {normalizeHTMLAssetIFrameBlockDOM} from "../../asset/html";const getLastChildBlock = (element: Element) => {if (!element || !element.lastElementChild) {@@ -179,7 +180,7 @@ const getListElementByID = async (protyle: IProtyle, listID: string) => {notebook: protyle.notebookId,});const template = document.createElement("template");- template.innerHTML = response.data?.dom || "";+ template.innerHTML = normalizeHTMLAssetIFrameBlockDOM(response.data?.dom || "");const listElement = template.content.firstElementChild as HTMLElement;if (listElement?.getAttribute("data-type") !== "NodeList") {return;diff --git a/app/src/protyle/wysiwyg/renderBacklink.ts b/app/src/protyle/wysiwyg/renderBacklink.tsindex caeaebe9e7..f3f592c47e 100644--- a/app/src/protyle/wysiwyg/renderBacklink.ts+++ b/app/src/protyle/wysiwyg/renderBacklink.ts@@ -16,6 +16,7 @@ import {clearViewFoldOccurrenceState,markViewFoldDefault,} from "../util/viewFold";+import {normalizeHTMLAssetIFrameBlockDOM} from "../../asset/html";interface IBacklinkData {id?: string,@@ -209,7 +210,8 @@ export const loadBreadcrumb = (protyle: IProtyle, element: HTMLElement) => {nextElement = nextElement.nextElementSibling;tempElement.remove();}- element.parentElement.insertAdjacentHTML("afterend", setBacklinkFold(getResponse.data.content, true));+ element.parentElement.insertAdjacentHTML("afterend",+ normalizeHTMLAssetIFrameBlockDOM(setBacklinkFold(getResponse.data.content, true)));clearViewFoldDefaults(protyle, element.parentElement.getAttribute("data-backlink-id"));processRender(element.parentElement.parentElement);avRender(element.parentElement.parentElement, protyle);diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.tsindex 42172da301..6471589327 100644--- a/app/src/protyle/wysiwyg/transaction.ts+++ b/app/src/protyle/wysiwyg/transaction.ts@@ -50,6 +50,7 @@ import {getPartialUpdateCleanupElements, shouldDeferCodeBlockCaretRestore} fromimport {getMoveAffectedEmbedElements, shouldSyncMoveCopies} from "./transactionEmbed";import {cloneMoveElements, getVisibleMoveElements} from "./transactionMove";import {normalizeHTMLAssetIFrameBlockDOM} from "../../asset/html";+import {sanitizeKernelHTML} from "../../util/hostCapabilities";import {disposeCustomBlocksInElement} from "../../plugin/customBlockRender";import {applyViewFoldStates,@@ -1939,7 +1940,7 @@ const unfoldListHeadings = async (protyle: IProtyle, nodeElements: Element[]) =>}],}]});- foldedHeading.insertAdjacentHTML("afterend", response.data[0].doOperations[0].retData);+ foldedHeading.insertAdjacentHTML("afterend", normalizeHTMLAssetIFrameBlockDOM(response.data[0].doOperations[0].retData));foldOperations.push({action: "foldHeading",id: itemId@@ -2079,7 +2080,7 @@ export const turnListsRecursively = async (options: {options.protyle.wysiwyg.element.querySelectorAll('[data-type~="block-ref"]').forEach(item => {if (item.textContent === "") {fetchPost("/api/block/getRefText", {id: item.getAttribute("data-id")}, (response) => {- item.innerHTML = response.data;+ item.innerHTML = sanitizeKernelHTML(response.data);});}});@@ -2182,7 +2183,7 @@ export const turnsOneInto = async (options: {options.protyle.wysiwyg.element.querySelectorAll('[data-type~="block-ref"]').forEach(item => {if (item.textContent === "") {fetchPost("/api/block/getRefText", {id: item.getAttribute("data-id")}, (response) => {- item.innerHTML = response.data;+ item.innerHTML = sanitizeKernelHTML(response.data);});}});diff --git a/app/src/search/assets.ts b/app/src/search/assets.tsindex 9b5f883f96..424b4302b9 100644--- a/app/src/search/assets.ts+++ b/app/src/search/assets.ts@@ -9,6 +9,7 @@ import {Dialog} from "../dialog";import {addClearButton} from "../util/addClearButton";import {saveAssetKeyList} from "./toggleHistory";import {genAssetSearchResultItemHTML, IAssetSearchResultItem} from "./assetsResult";+import {getHostCapabilities} from "../util/hostCapabilities";export const openSearchAsset = (element: HTMLElement, isStick: boolean) => {/// #if !MOBILE@@ -25,7 +26,9 @@ export const openSearchAsset = (element: HTMLElement, isStick: boolean) => {loadingElement.style.top = "84px";let enterTip = "";/// #if !BROWSER- enterTip = `<kbd>${window.siyuan.languages.enterKey}/${window.siyuan.languages.doubleClick}</kbd> ${window.siyuan.languages.showInFolder}`;+ if (getHostCapabilities().localFileSystem) {+ enterTip = `<kbd>${window.siyuan.languages.enterKey}/${window.siyuan.languages.doubleClick}</kbd> ${window.siyuan.languages.showInFolder}`;+ }/// #endifelement.innerHTML = `<div class="block__icons"><span data-type="assetPrevious" class="block__icon block__icon--show ariaLabel" data-position="9south" disabled="disabled" aria-label="${window.siyuan.languages.previousLabel}"><svg><use xlink:href='#iconLeft'></use></svg></span>diff --git a/app/src/search/util.ts b/app/src/search/util.tsindex bedb7a3d33..d6c67a5b97 100644--- a/app/src/search/util.ts+++ b/app/src/search/util.ts@@ -49,6 +49,7 @@ import {isSupportCSSHL, searchMarkRender} from "../protyle/render/searchMarkRendimport {saveKeyList, toggleAssetHistory, toggleReplaceHistory, toggleSearchHistory} from "./toggleHistory";import {highlightById} from "../util/highlightById";import {getSelectionOffset} from "../protyle/util/selection";+import {getHostCapabilities} from "../util/hostCapabilities";import {electronUndo} from "../protyle/undo";import {getContenteditableElement} from "../protyle/wysiwyg/getBlock";import {IDatabaseItemOpenData, openDatabaseItem} from "../protyle/render/av/openDatabaseItem";@@ -920,7 +921,9 @@ export const genSearch = (app: App, config: Config.IUILayoutTabSearchConfig, eleclearTimeout(clickTimeout);if (searchType === "asset") {/// #if !BROWSER- useShell("showItemInFolder", path.join(window.siyuan.config.system.dataDir, target.lastElementChild.getAttribute("aria-label")));+ if (getHostCapabilities().localFileSystem) {+ useShell("showItemInFolder", path.join(window.siyuan.config.system.dataDir, target.lastElementChild.getAttribute("aria-label")));+ }/// #endif} else {openSearchEditor({diff --git a/app/src/sync/syncGuide.ts b/app/src/sync/syncGuide.tsindex e246ebf073..a0a76ec79c 100644--- a/app/src/sync/syncGuide.ts+++ b/app/src/sync/syncGuide.ts@@ -11,6 +11,7 @@ import {openSetting} from "../config";import type {App} from "../index";import {Constants} from "../constants";import {getCloudURL} from "../config/util/about";+import {sanitizeKernelHTML} from "../util/hostCapabilities";const openSyncSetting = (app?: App) => {if (!app) {@@ -102,7 +103,7 @@ export const renderSyncCloudList = (cloudListElement: Element, reload = false, cif (response.code === 1) {syncListHTML = `<ul><li class="b3-list--empty ft__error">- ${response.msg}+ ${sanitizeKernelHTML(response.msg)}</li><li class="b3-list--empty">${window.siyuan.languages.cloudConfigTip}diff --git a/app/src/util/assets.ts b/app/src/util/assets.tsindex 1cb453bcf2..fa1bdd5215 100644--- a/app/src/util/assets.ts+++ b/app/src/util/assets.ts@@ -28,6 +28,7 @@ import {loadInlineStyles} from "../protyle/toolbar/inlineStyle";import {refreshChartTheme} from "../protyle/render/chartRender";+import {getHostCapabilities} from "./hostCapabilities";let headingNumberMeasurementRefreshTimer: number;const DEJAVU_EMOJI_PRESENTATION_UNICODE_RANGE = "U+25fd-25fe, U+2614-2615, U+2648-2653, U+267f, U+2693, U+26a1, " +@@ -81,6 +82,9 @@ export const unloadThemeScript = async () => {};export const refreshThemeStyle = (themeAddress: string) => {+ if (!getHostCapabilities().customAppearance) {+ return;+ }const appearance = window.siyuan.config.appearance;if (!isCurrentThemeSupported(appearance, getFrontend())) {return;@@ -93,7 +97,14 @@ export const refreshThemeStyle = (themeAddress: string) => {}};-export const loadAssets = (data: Config.IAppearance) => {+export const loadAssets = (appearance: Config.IAppearance) => {+ const data = getHostCapabilities().customAppearance ? appearance : {+ ...appearance,+ themeLight: "daylight",+ themeDark: "midnight",+ icon: "litheness",+ themeJS: false,+ };const changedThemeStyleElements: HTMLLinkElement[] = [];let themeStylesChanged = false;const htmlElement = document.getElementsByTagName("html")[0];@@ -103,8 +114,8 @@ export const loadAssets = (data: Config.IAppearance) => {htmlElement.setAttribute("data-frontend", getFrontend()); // https://github.com/siyuan-note/siyuan/issues/12549htmlElement.setAttribute("data-backend", getBackend());htmlElement.setAttribute("data-theme-mode", themeMode);- htmlElement.setAttribute("data-light-theme", window.siyuan.config.appearance.themeLight);- htmlElement.setAttribute("data-dark-theme", window.siyuan.config.appearance.themeDark);+ htmlElement.setAttribute("data-light-theme", data.themeLight);+ htmlElement.setAttribute("data-dark-theme", data.themeDark);const OSTheme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";if (window.siyuan.config.appearance.modeOS && ((window.siyuan.config.appearance.mode === 1 && OSTheme === "light") ||@@ -281,17 +292,20 @@ export const initAssets = () => {};export const setInlineStyle = async (set = true, servePath = "../../../") => {- const editorFonts = window.siyuan.config.editor.fontFamilies || [];- const codeFonts = window.siyuan.config.editor.codeFontFamilies || [];+ const allowCustomAppearance = getHostCapabilities().customAppearance;+ const editorFonts = allowCustomAppearance ? window.siyuan.config.editor.fontFamilies || [] : [];+ const codeFonts = allowCustomAppearance ? window.siyuan.config.editor.codeFontFamilies || [] : [];let inlineStylesCSS = "";- try {- const inlineStyles = await loadInlineStyles();- inlineStylesCSS = getInlineStylesCSS(inlineStyles);- } catch (error) {- console.error("load inline styles error: " + error);- inlineStylesCSS = getInlineStylesCSS();+ if (allowCustomAppearance) {+ try {+ const inlineStyles = await loadInlineStyles();+ inlineStylesCSS = getInlineStylesCSS(inlineStyles);+ } catch (error) {+ console.error("load inline styles error: " + error);+ inlineStylesCSS = getInlineStylesCSS();+ }}- if (set) {+ if (set && allowCustomAppearance) {await ensureSelectedCustomFonts([...editorFonts, ...codeFonts]);}let style;@@ -407,6 +421,9 @@ export const setInlineStyle = async (set = true, servePath = "../../../") => {};export const reloadInlineStyles = async () => {+ if (!getHostCapabilities().customAppearance) {+ return;+ }try {await loadInlineStyles(true);} catch (error) {diff --git a/app/src/util/bazaarAvailability.ts b/app/src/util/bazaarAvailability.tsindex 53ca22a8d5..76e0642bd4 100644--- a/app/src/util/bazaarAvailability.ts+++ b/app/src/util/bazaarAvailability.ts@@ -1,11 +1,13 @@import {getFrontend} from "./functions";+import {getHostCapabilities} from "./hostCapabilities";export const isBazaarAvailableForFrontend = (frontend: string,disabledFeatures: readonly string[] | undefined,): boolean => frontend !== "mobile" || !disabledFeatures?.includes("bazaar");-export const isBazaarAvailable = (): boolean => isBazaarAvailableForFrontend(- getFrontend(),- window.siyuan.config.system.disabledFeatures,-);+export const isBazaarAvailable = (): boolean => getHostCapabilities().customAppearance &&+ getHostCapabilities().plugins && isBazaarAvailableForFrontend(+ getFrontend(),+ window.siyuan.config.system.disabledFeatures,+ );diff --git a/app/src/util/functions.ts b/app/src/util/functions.tsindex e8be6fad0e..33ed149368 100644--- a/app/src/util/functions.ts+++ b/app/src/util/functions.ts@@ -1,3 +1,5 @@+import {getHostCapabilities} from "./hostCapabilities";+const CONTAINER_BACKEND_SET = new Set(["docker", "ios", "android", "harmony"]);export const isKernelInContainer = (): boolean => {@@ -86,6 +88,9 @@ export const isValidCustomAttrName = (name: string) => {// REF https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/evalexport const looseJsonParse = (text: string) => {+ if (getHostCapabilities().remoteKernel) {+ return JSON.parse(text);+ }return Function(`"use strict";return (${text})`)();};diff --git a/app/src/util/hostCapabilities.test.ts b/app/src/util/hostCapabilities.test.tsnew file mode 100644index 0000000000..de3d567db1--- /dev/null+++ b/app/src/util/hostCapabilities.test.ts@@ -0,0 +1,53 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {detectRemoteKernel, hasRemoteArgument, isExternalURLAllowed, resolveRemoteKernel} from "./hostCapabilities";++describe("remote kernel detection", () => {+ it("detects the remote query", () => {+ assert.equal(detectRemoteKernel("?remote=1", []), true);+ assert.equal(detectRemoteKernel("?remote=0", []), false);+ });++ it("detects the remote command line argument", () => {+ assert.equal(hasRemoteArgument(["SiYuan", "--remote=https://example.com"]), true);+ assert.equal(hasRemoteArgument(["SiYuan", "--remote"]), true);+ assert.equal(hasRemoteArgument(["SiYuan", "--remote-proxy=https://example.com"]), false);+ });++ it("uses the command line as a fallback", () => {+ assert.equal(detectRemoteKernel("", ["--remote=https://example.com/path?a=b"]), true);+ });++ it("uses the host connection after initialization", () => {+ assert.equal(resolveRemoteKernel({+ kernelMode: "local",+ ownsKernel: true,+ kernelOrigin: "http://127.0.0.1:6806",+ }, "?remote=1", ["--remote=https://example.com"]), false);+ assert.equal(resolveRemoteKernel({+ kernelMode: "remote",+ ownsKernel: false,+ kernelOrigin: "https://example.com",+ }, "", []), true);+ });+});++describe("external URL capabilities", () => {+ it("allows only HTTP URLs for a remote kernel", () => {+ assert.equal(isExternalURLAllowed("https://example.com/auth", true), true);+ assert.equal(isExternalURLAllowed("http://127.0.0.1:3000/auth", true), true);+ assert.equal(isExternalURLAllowed("/assets/file.pdf", true), false);+ assert.equal(isExternalURLAllowed("assets/file.pdf", true), false);+ assert.equal(isExternalURLAllowed("\\\\server\\share\\note.txt", true), false);+ assert.equal(isExternalURLAllowed("javascript:alert(1)", true), false);+ assert.equal(isExternalURLAllowed("file:///tmp/note.txt", true), false);+ assert.equal(isExternalURLAllowed("data:text/html,<script>alert(1)</script>", true), false);+ assert.equal(isExternalURLAllowed("siyuan://blocks/20260903150000-abcdefg", true), false);+ assert.equal(isExternalURLAllowed("not a URL", true), false);+ });++ it("preserves local external URL handling", () => {+ assert.equal(isExternalURLAllowed("mailto:[email protected]", false), true);+ assert.equal(isExternalURLAllowed("file:///tmp/note.txt", false), true);+ });+});diff --git a/app/src/util/hostCapabilities.ts b/app/src/util/hostCapabilities.tsnew file mode 100644index 0000000000..5c16bda45c--- /dev/null+++ b/app/src/util/hostCapabilities.ts@@ -0,0 +1,95 @@+export type TKernelConnection = {+ kernelMode: "local" | "remote";+ ownsKernel: boolean;+ kernelOrigin: string;+};++export type THostCapabilities = {+ remoteKernel: boolean;+ ownsKernel: boolean;+ localFileSystem: boolean;+ importExport: boolean;+ plugins: boolean;+ workspaces: boolean;+ customAppearance: boolean;+ widgets: boolean;+ oidcAuthentication: boolean;+};++const hasRemoteQuery = (search: string) => new URLSearchParams(search).get("remote") === "1";++export const hasRemoteArgument = (args: readonly string[]) => args.some((arg) =>+ arg === "--remote" || arg.startsWith("--remote="));++export const detectRemoteKernel = (search: string, args: readonly string[]) =>+ hasRemoteQuery(search) || hasRemoteArgument(args);++export const resolveRemoteKernel = (connection: TKernelConnection | undefined, search: string, args: readonly string[]) =>+ connection ? connection.kernelMode === "remote" : detectRemoteKernel(search, args);++const getProcessArgs = () => {+ /// #if !BROWSER+ return process.argv;+ /// #else+ return [];+ /// #endif+};++let hostConnection: TKernelConnection | undefined;++export const setHostConnection = (connection: TKernelConnection | undefined) => {+ if (!connection || !["local", "remote"].includes(connection.kernelMode)) {+ return;+ }+ hostConnection = connection;+};++export const isRemoteKernel = () => resolveRemoteKernel(hostConnection, window.location.search, getProcessArgs());++export const getHostCapabilities = (): THostCapabilities => {+ const remoteKernel = isRemoteKernel();+ const ownsKernel = !remoteKernel && hostConnection?.ownsKernel !== false;+ return {+ remoteKernel,+ ownsKernel,+ localFileSystem: !remoteKernel,+ importExport: !remoteKernel,+ plugins: !remoteKernel,+ workspaces: !remoteKernel,+ customAppearance: !remoteKernel,+ widgets: !remoteKernel,+ oidcAuthentication: !remoteKernel,+ };+};++export const appendRemoteQuery = (url: URL) => {+ if (isRemoteKernel()) {+ url.searchParams.set("remote", "1");+ }+ return url;+};++export const isExternalURLAllowed = (+ url: string,+ remoteKernel: boolean,+) => {+ if (!remoteKernel) {+ return true;+ }+ try {+ const parsed = new URL(url);+ return parsed.protocol === "http:" || parsed.protocol === "https:";+ } catch {+ return false;+ }+};++export const canOpenExternalURL = (url: string) =>+ isExternalURLAllowed(url, isRemoteKernel());++export const sanitizeKernelHTML = (html: string) => {+ if (!isRemoteKernel()) {+ return html;+ }+ return window.DOMPurify.sanitize(String(html ?? ""));+};diff --git a/app/src/util/mount.ts b/app/src/util/mount.tsindex 49e69b5a48..2822f303f3 100644--- a/app/src/util/mount.ts+++ b/app/src/util/mount.ts@@ -11,6 +11,7 @@ import {openFileById} from "../editor/util";import {openMobileFileById} from "../mobile/editor";import type {App} from "../index";import {getLastDailyNoteNotebookId} from "./dailyNote";+import {getHostCapabilities} from "./hostCapabilities";/// #if !BROWSERimport {ipcRenderer} from "electron";import {importObsidianVault} from "../menus/importObsidian";@@ -114,6 +115,9 @@ export const mountHelp = () => {};export const importNotebook = (file: File) => {+ if (!getHostCapabilities().importExport) {+ return;+ }const formData = new FormData();formData.append("file", file);fetchPost("/api/import/importSYNotebook", formData);@@ -122,21 +126,24 @@ export const importNotebook = (file: File) => {export const newNotebook = () => {let nativeImportHTML = "";/// #if !BROWSER- nativeImportHTML = `<div class="b3-list-item fn__pointer" data-type="import-markdown-file" role="button" tabindex="0"><svg class="b3-list-item__graphic"><use xlink:href="#iconMarkdown"></use></svg><span class="b3-list-item__text">Markdown ${window.siyuan.languages.doc}</span></div>+ if (getHostCapabilities().localFileSystem) {+ nativeImportHTML = `<div class="b3-list-item fn__pointer" data-type="import-markdown-file" role="button" tabindex="0"><svg class="b3-list-item__graphic"><use xlink:href="#iconMarkdown"></use></svg><span class="b3-list-item__text">Markdown ${window.siyuan.languages.doc}</span></div><div class="b3-list-item fn__pointer" data-type="import-markdown-folder" role="button" tabindex="0"><svg class="b3-list-item__graphic"><use xlink:href="#iconFolder"></use></svg><span class="b3-list-item__text">Markdown ${window.siyuan.languages.folder}</span></div><div class="b3-list-item fn__pointer" data-type="import-obsidian" role="button" tabindex="0"><svg class="b3-list-item__graphic"><use xlink:href="#iconObsidian"></use></svg><span class="b3-list-item__text">Obsidian Vault</span></div>`;+ }/// #endif- const dialog = new Dialog({- title: window.siyuan.languages.newNotebook,- content: `<div class="b3-dialog__content">- <input placeholder="${window.siyuan.languages.notebookName}" class="b3-text-field fn__block" data-type="notebook-name">- <div class="fn__hr"></div>+ const importHTML = getHostCapabilities().importExport ? `<div class="fn__hr"></div><div class="b3-label__text fn__pointer fn__flex" style="align-items: center;gap: 4px" data-type="toggle-import" role="button" tabindex="0" aria-expanded="false"><svg class="b3-list-item__arrow" style="display: block;flex: none;height: 14px;width: 14px" data-type="import-arrow"><use xlink:href="#iconRight"></use></svg><span style="line-height: 20px">${window.siyuan.languages.importFromMoreApps}</span></div><div class="b3-list--background fn__none" data-type="import-options" style="padding-top: 8px"><label class="b3-list-item fn__pointer" data-type="import-sy"><svg class="b3-list-item__graphic"><use xlink:href="#iconSiYuan"></use></svg><span class="b3-list-item__text">SiYuan .sy.zip</span><input class="b3-form__upload" type="file" accept="application/zip"></label><label class="b3-list-item fn__pointer" data-type="import-markdown-zip"><svg class="b3-list-item__graphic"><use xlink:href="#iconMarkdown"></use></svg><span class="b3-list-item__text">Markdown .zip</span><input class="b3-form__upload" type="file" accept="application/zip"></label>${nativeImportHTML}- </div>+ </div>` : "";+ const dialog = new Dialog({+ title: window.siyuan.languages.newNotebook,+ content: `<div class="b3-dialog__content">+ <input placeholder="${window.siyuan.languages.notebookName}" class="b3-text-field fn__block" data-type="notebook-name">+ ${importHTML}</div><div class="b3-dialog__action"><button class="b3-button b3-button--cancel" data-type="cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div>@@ -165,6 +172,9 @@ export const newNotebook = () => {});dialog.destroy();});+ if (!getHostCapabilities().importExport) {+ return;+ }const createNotebookForImport = (fallbackName: string, callback: (notebookID: string) => void) => {let name = notebookNameElement.value.trim();if (!name) {diff --git a/app/src/util/pathName.ts b/app/src/util/pathName.tsindex 890c107747..aeb77d05f0 100644--- a/app/src/util/pathName.ts+++ b/app/src/util/pathName.ts@@ -18,8 +18,12 @@ import {Menu} from "../plugin/Menu";import {hasClosestByClassName} from "../protyle/util/hasClosest";import {mergePathSegments} from "./mergePathSegments";import {expandFileTree} from "../layout/dock/fileTreeAnimation";+import {getHostCapabilities} from "./hostCapabilities";export const useShell = (cmd: "showItemInFolder" | "openPath", filePath: string) => {+ if (!getHostCapabilities().localFileSystem) {+ return;+ }/// #if !BROWSERipcRenderer.send(Constants.SIYUAN_CMD, {cmd,@@ -119,6 +123,10 @@ export const redirectToCheckAuth = async (to: string = window.location.href) =>const url = new URL(window.location.origin);url.pathname = "/check-auth";url.searchParams.set("to", to);+ if (getHostCapabilities().remoteKernel) {+ url.searchParams.set("lang", window.siyuan.config.appearance.lang);+ url.searchParams.set("remote", "1");+ }window.location.href = url.href;};diff --git a/app/src/window/index.ts b/app/src/window/index.tsindex df802b8891..84c76c283b 100644--- a/app/src/window/index.ts+++ b/app/src/window/index.ts@@ -208,7 +208,7 @@ class App {};const notebookPromise = setNoteBook();fetchPost("/api/system/getConf", {}, async (response) => {- addScriptSync(`${Constants.PROTYLE_CDN}/js/lute/lute.min.js?v=${Constants.SIYUAN_VERSION}`, "protyleLuteScript");+ await addScriptSync(`${Constants.PROTYLE_CDN}/js/lute/lute.min.js?v=${Constants.SIYUAN_VERSION}`, "protyleLuteScript");addScript(`${Constants.PROTYLE_CDN}/js/protyle-html.js?v=${Constants.SIYUAN_VERSION}`, "protyleWcHtmlScript");window.siyuan.config = response.data.conf;ensureUILayout();diff --git a/app/src/window/openNewWindow.ts b/app/src/window/openNewWindow.tsindex f2e2d4f037..38e0b544e5 100644--- a/app/src/window/openNewWindow.ts+++ b/app/src/window/openNewWindow.ts@@ -9,6 +9,7 @@ import {showMessage} from "../dialog/message";import {getAssetExtension, getDisplayName} from "../util/pathName";import {getSearch} from "../util/functions";import {isBrowserRenderableImagePath} from "../util/imageURL";+import {appendRemoteQuery} from "../util/hostCapabilities";interface windowOptions {position?: {@@ -20,6 +21,13 @@ interface windowOptions {alwaysOnTop?: boolean,}+const getWindowURL = (layout: unknown) => {+ const url = new URL("/stage/build/app/window.html", window.location.origin);+ url.searchParams.set("v", Constants.SIYUAN_VERSION);+ url.searchParams.set("json", JSON.stringify(layout));+ return appendRemoteQuery(url).href;+};+export const openNewWindow = (tab: Tab, options: windowOptions = {}) => {const json = {};layoutToJSON(tab, json);@@ -29,8 +37,7 @@ export const openNewWindow = (tab: Tab, options: windowOptions = {}) => {width: options.width,height: options.height,alwaysOnTop: !!options.alwaysOnTop,- // 需要 encode, 否则 https://github.com/siyuan-note/siyuan/issues/9343- url: `${window.location.protocol}//${window.location.host}/stage/build/app/window.html?v=${Constants.SIYUAN_VERSION}&json=${encodeURIComponent(JSON.stringify([json]))}`+ url: getWindowURL([json]),});/// #endiftab.parent.removeTab(tab.id);@@ -71,7 +78,7 @@ export const openNewWindowById = async (id: string | string[], options: windowOpwidth: options.width,height: options.height,alwaysOnTop: !!options.alwaysOnTop,- url: `${window.location.protocol}//${window.location.host}/stage/build/app/window.html?v=${Constants.SIYUAN_VERSION}&json=${encodeURIComponent(JSON.stringify(json))}`+ url: getWindowURL(json),});/// #endif};@@ -111,7 +118,7 @@ export const openAssetNewWindow = (width: options.width,height: options.height,alwaysOnTop: !!options.alwaysOnTop,- url: `${window.location.protocol}//${window.location.host}/stage/build/app/window.html?v=${Constants.SIYUAN_VERSION}&json=${encodeURIComponent(JSON.stringify(json))}`+ url: getWindowURL(json),});}/// #endifdiff --git a/app/stage/protyle/js/protyle-html.js b/app/stage/protyle/js/protyle-html.jsindex 846230cac2..fb119e2d16 100644--- a/app/stage/protyle/js/protyle-html.js+++ b/app/stage/protyle/js/protyle-html.js@@ -16,8 +16,12 @@ class ProtyleHtml extends HTMLElement {if (name === 'data-content') {// data-content 保留原始 HTML 源码,确保 DOM 反复序列化和解析后内容不变。let dataContent = newValue || ''+ const remoteKernel = new URLSearchParams(window.location.search).get('remote') === '1' ||+ (typeof process !== 'undefined' && Array.isArray(process.argv) && process.argv.some((arg) =>+ arg === '--remote' || arg.startsWith('--remote=')))+ const allowScripts = !remoteKernel && window.siyuan.config.editor.allowHTMLBLockScript- if (!window.siyuan.config.editor.allowHTMLBLockScript) {+ if (!allowScripts) {// Do not execute scripts in HTML blocks by default to prevent XSS https://github.com/siyuan-note/siyuan/issues/11172dataContent = DOMPurify.sanitize(dataContent);}@@ -26,7 +30,7 @@ class ProtyleHtml extends HTMLElement {const el = document.createElement('div')el.innerHTML = dataContent- const scripts = el.getElementsByTagName('script')+ const scripts = allowScripts ? el.getElementsByTagName('script') : []let fatalHTML = ''for (const script of scripts) {if (script.textContent.indexOf('document.write') > -1) {diff --git a/app/webpack.config.js b/app/webpack.config.jsindex 9d00e1bfd5..935104a7dc 100644--- a/app/webpack.config.js+++ b/app/webpack.config.js@@ -10,7 +10,7 @@ module.exports = (env, argv) => {return {mode: argv.mode || "development",watch: argv.mode !== "production",- devtool: argv.mode !== "production" ? "eval-source-map" : false,+ devtool: argv.mode !== "production" ? "source-map" : false,target: "electron-renderer",output: {globalObject: "globalThis",