Skip to content

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

:bug: Prevent plugin storage change notification loops https://github.com/siyuan-note/siyuan/issues/19187

Daniel4a3a40de79f4
diff --git a/app/src/index.ts b/app/src/index.ts
index 0bb3e616f9..d388a31e4d 100644
--- a/app/src/index.ts
+++ b/app/src/index.ts
@@ -58,6 +58,7 @@ import {ensureUILayout} from "./util/ensureUILayout";
import {applyEntryVisibility} from "./config/entryVisibility/runtime";
import {removeBlockPanelEditors} from "./block/panelRemoval";
import {initializeEnglishCommandTranslations} from "./command/english";
+import {installPluginStorageFetchAppId} from "./util/fetchAppId";
export class App {
public plugins: import("./plugin").Plugin[] = [];
@@ -344,6 +345,7 @@ export class App {
}
}
+installPluginStorageFetchAppId(window, Constants.SIYUAN_APPID, window.location.href);
const siyuanApp = new App();
window.openFileByURL = (openURL) => {
diff --git a/app/src/mobile/index.ts b/app/src/mobile/index.ts
index 27c601a26a..d668d31e56 100644
--- a/app/src/mobile/index.ts
+++ b/app/src/mobile/index.ts
@@ -62,6 +62,7 @@ import {updateMobileTopBarLayout} from "./util/mobileTopBar";
import {showMobileBars} from "./util/mobileBars";
import {initializeEnglishCommandTranslations} from "../command/english";
import {scrollInputIntoView} from "./util/visibleViewport";
+import {installPluginStorageFetchAppId} from "../util/fetchAppId";
class App {
public plugins: import("../plugin").Plugin[] = [];
@@ -267,6 +268,7 @@ class App {
}
}
+installPluginStorageFetchAppId(window, Constants.SIYUAN_APPID, window.location.href);
const siyuanApp = new App();
initWindowOpenOverride(siyuanApp, openByMobile);
diff --git a/app/src/util/fetchAppId.test.ts b/app/src/util/fetchAppId.test.ts
new file mode 100644
index 0000000000..9e7643457b
--- /dev/null
+++ b/app/src/util/fetchAppId.test.ts
@@ -0,0 +1,107 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {
+ injectPluginStorageAppId,
+ installPluginStorageFetchAppId,
+ isPluginStorageWriteRequest,
+ SIYUAN_APP_ID_HEADER,
+} from "./fetchAppId";
+
+const baseURL = "http://127.0.0.1:6806/stage/build/app/";
+
+const createMockFetch = () => {
+ const calls: Array<{input: RequestInfo | URL; init?: RequestInit}> = [];
+ const fetcher = ((input: RequestInfo | URL, init?: RequestInit) => {
+ calls.push({input, init});
+ return Promise.resolve(new Response(null, {status: 200}));
+ }) as typeof fetch;
+ return {calls, fetcher};
+};
+
+const getHeader = (init: RequestInit | undefined, name: string) =>
+ init?.headers === undefined ? null : new Headers(init.headers).get(name);
+
+describe("plugin storage fetch app id", () => {
+ it("matches only same-origin POST requests to exact write endpoints", () => {
+ assert.equal(isPluginStorageWriteRequest("/api/file/putFile", {method: "POST"}, baseURL), true);
+ assert.equal(isPluginStorageWriteRequest("/api/file/removeFile?path=test", {method: "post"}, baseURL), true);
+ assert.equal(isPluginStorageWriteRequest(
+ "http://127.0.0.1:6806/api/file/putFile", {method: "POST"}, baseURL), true);
+ assert.equal(isPluginStorageWriteRequest(
+ new URL("/api/file/removeFile", baseURL), {method: "POST"}, baseURL), true);
+ assert.equal(isPluginStorageWriteRequest("/api/file/putFile", {method: "GET"}, baseURL), false);
+ assert.equal(isPluginStorageWriteRequest("/api/file/putFile/extra", {method: "POST"}, baseURL), false);
+ assert.equal(isPluginStorageWriteRequest("/api/file/getFile?next=/api/file/putFile", {method: "POST"},
+ baseURL), false);
+ assert.equal(isPluginStorageWriteRequest(
+ "https://example.com/api/file/putFile", {method: "POST"}, baseURL), false);
+ });
+
+ it("injects the current app id and preserves init options", async () => {
+ const {calls, fetcher} = createMockFetch();
+ const wrappedFetch = injectPluginStorageAppId(fetcher, "app-current", baseURL);
+ const controller = new AbortController();
+ const init: RequestInit = {
+ method: "POST",
+ body: "data",
+ cache: "no-store",
+ headers: {Accept: "application/json", [SIYUAN_APP_ID_HEADER]: "app-forged"},
+ signal: controller.signal,
+ };
+
+ await wrappedFetch("/api/file/putFile", init);
+
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0].input, "/api/file/putFile");
+ assert.equal(calls[0].init?.method, "POST");
+ assert.equal(calls[0].init?.body, "data");
+ assert.equal(calls[0].init?.cache, "no-store");
+ assert.equal(calls[0].init?.signal, controller.signal);
+ assert.equal(getHeader(calls[0].init, "Accept"), "application/json");
+ assert.equal(getHeader(calls[0].init, SIYUAN_APP_ID_HEADER), "app-current");
+ assert.equal(new Headers(init.headers).get(SIYUAN_APP_ID_HEADER), "app-forged");
+ });
+
+ it("preserves headers and method supplied by a Request object", async () => {
+ const {calls, fetcher} = createMockFetch();
+ const wrappedFetch = injectPluginStorageAppId(fetcher, "app-current", baseURL);
+ const request = new Request("http://127.0.0.1:6806/api/file/removeFile", {
+ method: "POST",
+ headers: {Authorization: "Token test", "Content-Type": "application/json"},
+ body: "{}",
+ });
+
+ await wrappedFetch(request);
+
+ assert.equal(calls[0].input, request);
+ assert.equal(getHeader(calls[0].init, "Authorization"), "Token test");
+ assert.equal(getHeader(calls[0].init, "Content-Type"), "application/json");
+ assert.equal(getHeader(calls[0].init, SIYUAN_APP_ID_HEADER), "app-current");
+ });
+
+ it("passes unrelated requests through without replacing their arguments", async () => {
+ const {calls, fetcher} = createMockFetch();
+ const wrappedFetch = injectPluginStorageAppId(fetcher, "app-current", baseURL);
+ const init: RequestInit = {method: "POST", headers: {Accept: "application/json"}};
+
+ await wrappedFetch("/api/transactions", init);
+
+ assert.equal(calls[0].input, "/api/transactions");
+ assert.equal(calls[0].init, init);
+ assert.equal(getHeader(calls[0].init, SIYUAN_APP_ID_HEADER), null);
+ });
+
+ it("installs the wrapper only once", async () => {
+ const {calls, fetcher} = createMockFetch();
+ const target = {fetch: fetcher};
+
+ installPluginStorageFetchAppId(target, "app-current", baseURL);
+ const installedFetch = target.fetch;
+ installPluginStorageFetchAppId(target, "app-current", baseURL);
+
+ assert.equal(target.fetch, installedFetch);
+ await target.fetch("/api/file/putFile", {method: "POST"});
+ assert.equal(calls.length, 1);
+ assert.equal(getHeader(calls[0].init, SIYUAN_APP_ID_HEADER), "app-current");
+ });
+});
diff --git a/app/src/util/fetchAppId.ts b/app/src/util/fetchAppId.ts
new file mode 100644
index 0000000000..111b0e6ca6
--- /dev/null
+++ b/app/src/util/fetchAppId.ts
@@ -0,0 +1,77 @@
+const pluginStorageWritePaths = new Set([
+ "/api/file/putFile",
+ "/api/file/removeFile",
+]);
+
+const fetchAppIdMarker = Symbol.for("siyuan.fetchAppId");
+
+export const SIYUAN_APP_ID_HEADER = "X-SiYuan-App-ID";
+
+type TFetchTarget = {
+ fetch: typeof fetch;
+};
+
+const getRequestURL = (input: RequestInfo | URL) => {
+ if (typeof input === "string") {
+ return input;
+ }
+ return "url" in input ? input.url : input.href;
+};
+
+const getRequestMethod = (input: RequestInfo | URL, init?: RequestInit) => {
+ if (init?.method !== undefined) {
+ return init.method;
+ }
+ if (typeof input !== "string" && "method" in input) {
+ return input.method;
+ }
+ return "GET";
+};
+
+const getRequestHeaders = (input: RequestInfo | URL, init?: RequestInit) => {
+ if (init?.headers !== undefined) {
+ return init.headers;
+ }
+ if (typeof input !== "string" && "headers" in input) {
+ return input.headers;
+ }
+ return undefined;
+};
+
+export const isPluginStorageWriteRequest = (input: RequestInfo | URL, init: RequestInit | undefined,
+ baseURL: string) => {
+ if (getRequestMethod(input, init).toUpperCase() !== "POST") {
+ return false;
+ }
+ try {
+ const frontendURL = new URL(baseURL);
+ const requestURL = new URL(getRequestURL(input), frontendURL);
+ // 只处理当前思源前端对应的精确接口,避免向插件访问的外部服务发送应用标识。
+ return requestURL.origin === frontendURL.origin && pluginStorageWritePaths.has(requestURL.pathname);
+ } catch {
+ return false;
+ }
+};
+
+export const injectPluginStorageAppId = (inputFetch: typeof fetch, appId: string, baseURL: string): typeof fetch => {
+ return ((input: RequestInfo | URL, init?: RequestInit) => {
+ if (!isPluginStorageWriteRequest(input, init, baseURL)) {
+ return inputFetch(input, init);
+ }
+ const headers = new Headers(getRequestHeaders(input, init));
+ headers.set(SIYUAN_APP_ID_HEADER, appId);
+ return inputFetch(input, {...(init || {}), headers});
+ }) as typeof fetch;
+};
+
+// 插件与宿主共享 window,提前包装原生 fetch 后可覆盖插件直接调用文件接口的场景。
+export const installPluginStorageFetchAppId = (target: TFetchTarget, appId: string, baseURL: string) => {
+ const currentFetch = target.fetch as typeof fetch & Record<symbol, boolean | undefined>;
+ if (currentFetch[fetchAppIdMarker]) {
+ return;
+ }
+ const wrappedFetch = injectPluginStorageAppId(currentFetch.bind(target), appId, baseURL) as
+ typeof fetch & Record<symbol, boolean | undefined>;
+ Object.defineProperty(wrappedFetch, fetchAppIdMarker, {value: true});
+ target.fetch = wrappedFetch;
+};
diff --git a/app/src/window/index.ts b/app/src/window/index.ts
index 84c76c283b..4e8ac607a4 100644
--- a/app/src/window/index.ts
+++ b/app/src/window/index.ts
@@ -38,6 +38,7 @@ import {updateServerAddresses} from "../config/tabs/accessRuntime";
import {applyCloudUserState} from "../config/tabs/accountUi";
import {emitToPlugins} from "../plugin/EventBusCore";
import {initializeEnglishCommandTranslations} from "../command/english";
+import {installPluginStorageFetchAppId} from "../util/fetchAppId";
class App {
public plugins: import("../plugin").Plugin[] = [];
@@ -240,4 +241,5 @@ class App {
}
}
+installPluginStorageFetchAppId(window, Constants.SIYUAN_APPID, window.location.href);
new App();
diff --git a/kernel/api/file.go b/kernel/api/file.go
index 288a4e53c1..9577b0a2b2 100644
--- a/kernel/api/file.go
+++ b/kernel/api/file.go
@@ -38,7 +38,18 @@ import (
)
// errMsgSeeKernelLog 接在 API 错误提示末尾,引导用户查看内核日志以获取完整信息(避免在 Msg 暴露工作空间绝对路径)。
-const errMsgSeeKernelLog = ". For details, see the SiYuan kernel log."
+const (
+ errMsgSeeKernelLog = ". For details, see the SiYuan kernel log."
+ siyuanAppIDHeader = "X-SiYuan-App-ID"
+)
+
+// resolveFileAPIAppID 优先使用宿主统一注入的应用标识,同时兼容旧请求体中的 app。
+func resolveFileAPIAppID(c *gin.Context, bodyApp string) string {
+ if headerApp := c.GetHeader(siyuanAppIDHeader); headerApp != "" {
+ return headerApp
+ }
+ return bodyApp
+}
// rejectEncryptedBoxPath 检查 absPath 是否落在加密笔记本目录下(含 symlink 绕过),是则返回 true。
// 原始文件 API(getFile/putFile/copyFile/renameFile/removeFile)是绕过加密层的逃生口,
@@ -827,6 +838,7 @@ func removeFile(c *gin.Context) {
) {
return
}
+ app = resolveFileAPIAppID(c, app)
fileAbsPath, err := util.GetAbsPathInWorkspace(filePath)
if err != nil {
@@ -878,7 +890,7 @@ func putFile(c *gin.Context) {
isDirStr := c.PostForm("isDir")
isDir, _ := strconv.ParseBool(isDirStr)
- app := c.PostForm("app")
+ app := resolveFileAPIAppID(c, c.PostForm("app"))
var err error
filePath := c.PostForm("path")
diff --git a/kernel/api/file_test.go b/kernel/api/file_test.go
index 7dd8de8346..6eaa6a15d7 100644
--- a/kernel/api/file_test.go
+++ b/kernel/api/file_test.go
@@ -13,6 +13,32 @@ import (
"github.com/siyuan-note/siyuan/kernel/util"
)
+func TestResolveFileAPIAppID(t *testing.T) {
+ tests := []struct {
+ name string
+ header string
+ body string
+ expected string
+ }{
+ {name: "header takes precedence", header: "header-app", body: "body-app", expected: "header-app"},
+ {name: "body remains compatible", body: "body-app", expected: "body-app"},
+ {name: "missing app remains external", expected: ""},
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ context, _ := gin.CreateTestContext(httptest.NewRecorder())
+ context.Request = httptest.NewRequest(http.MethodPost, "/api/file/putFile", nil)
+ if test.header != "" {
+ context.Request.Header.Set(siyuanAppIDHeader, test.header)
+ }
+ if actual := resolveFileAPIAppID(context, test.body); actual != test.expected {
+ t.Fatalf("expected app [%s], got [%s]", test.expected, actual)
+ }
+ })
+ }
+}
+
func TestGetFileAllowsWorkspaceTemp(t *testing.T) {
originalWorkspaceDir := util.WorkspaceDir
originalTempDir := util.TempDir
diff --git a/kernel/server/serve.go b/kernel/server/serve.go
index 538343b701..d8297d271a 100644
--- a/kernel/server/serve.go
+++ b/kernel/server/serve.go
@@ -2074,7 +2074,7 @@ func corsMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Credentials", "true")
- c.Header("Access-Control-Allow-Headers", "origin, Content-Length, Content-Type, Authorization")
+ c.Header("Access-Control-Allow-Headers", "origin, Content-Length, Content-Type, Authorization, X-SiYuan-App-ID")
c.Header("Access-Control-Allow-Private-Network", "false")
if strings.HasPrefix(c.Request.RequestURI, "/webdav") {
diff --git a/kernel/server/serve_cors_test.go b/kernel/server/serve_cors_test.go
new file mode 100644
index 0000000000..49ba253ed3
--- /dev/null
+++ b/kernel/server/serve_cors_test.go
@@ -0,0 +1,43 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package server
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+)
+
+func TestCORSMiddlewareAllowsAppIDHeader(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ recorder := httptest.NewRecorder()
+ context, _ := gin.CreateTestContext(recorder)
+ context.Request = httptest.NewRequest(http.MethodOptions, "/api/file/putFile", nil)
+
+ corsMiddleware()(context)
+
+ if recorder.Code != http.StatusNoContent {
+ t.Fatalf("expected status %d, got %d", http.StatusNoContent, recorder.Code)
+ }
+ allowedHeaders := strings.ToLower(recorder.Header().Get("Access-Control-Allow-Headers"))
+ if !strings.Contains(allowedHeaders, strings.ToLower("X-SiYuan-App-ID")) {
+ t.Fatalf("app id header is not allowed by CORS: %s", allowedHeaders)
+ }
+}