An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Reject plugin storage names that escape the private directory https://github.com/siyuan-note/siyuan/issues/20849
Weidong Qia3f9f356ef56
diff --git a/app/src/plugin/index.test.ts b/app/src/plugin/index.test.tsnew file mode 100644index 0000000000..c119d3f7d4--- /dev/null+++ b/app/src/plugin/index.test.ts@@ -0,0 +1,54 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import * as path from "node:path";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+import * as mergePathSegments from "../util/mergePathSegments";++const compile = (file: string) => transpileModule(require("ifdef-loader/preprocessor").parse(+ readFileSync(file, "utf8"), {MOBILE: false, BROWSER: false}, false, true), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;++const loadPlugin = () => {+ const requests: Array<{url: string; data: unknown}> = [];+ const window = {siyuan: {config: {readonly: false}, isPublish: false, languages: {}}};+ const pathName = {};+ runInNewContext(compile("src/util/pathName.ts"), {exports: pathName, window,+ require: (id: string) => id === "path" ? path : id === "./mergePathSegments" ? mergePathSegments : {}});+ const exports: Record<string, any> = {};+ runInNewContext(compile("src/plugin/index.ts"), {exports, window, Promise,+ require: (id: string) => id === "../util/pathName" ? pathName :+ id === "../constants" ? {Constants: {SIYUAN_APPID: "app"}} : id === "../util/fetch" ? {+ fetchPost: (url: string, data: unknown, callback: (response: unknown) => void) => {+ requests.push({url, data});+ callback({code: 0, msg: "", data: null});+ },+ } : {}});+ const plugin = Object.create(exports.Plugin.prototype);+ Object.assign(plugin, {name: "sample", data: {}});+ return {plugin, requests};+};++test("plugin storage rejects names without a file segment before sending requests", async () => {+ for (const storageName of ["..", "../", "..\\", "./..", ".", "", "/"]) {+ const {plugin, requests} = loadPlugin();+ for (const call of [() => plugin.loadData(storageName), () => plugin.saveData(storageName, "value"),+ () => plugin.removeData(storageName)]) {+ await assert.rejects(call(), {code: 400, msg: "Invalid storage name", data: null}, JSON.stringify(storageName));+ }+ assert.deepEqual(requests, [], JSON.stringify(storageName));+ assert.deepEqual(Object.keys(plugin.data), [], JSON.stringify(storageName));+ }+});++test("plugin storage keeps normalized subdirectory names inside the plugin directory", async () => {+ const {plugin, requests} = loadPlugin();+ await plugin.loadData("../folder/config.json");+ await plugin.removeData("folder\\config.json");+ assert.deepEqual(requests.map(request => (request.data as {path: string}).path), [+ "/data/storage/petal/sample/folder/config.json",+ "/data/storage/petal/sample/folder/config.json",+ ]);+});diff --git a/app/src/plugin/index.ts b/app/src/plugin/index.tsindex 590c704fc9..60f5a77678 100644--- a/app/src/plugin/index.ts+++ b/app/src/plugin/index.ts@@ -48,6 +48,14 @@ const disposedPlugins = new WeakSet<Plugin>();const isPluginDisposed = (plugin: Plugin) => disposedPlugins.has(plugin);+// 存储名不含有效文件段时返回 null,调用方据此拒绝,避免操作插件目录自身或其上级。+const getPluginStoragePath = (plugin: Plugin, storageName: string) => {+ const storagePath = normalizeStoragePath(storageName);+ return storagePath === null ? null : `/data/storage/petal/${plugin.name}/${storagePath}`;+};++const getInvalidStorageNameError = (): IWebSocketData => ({code: 400, msg: "Invalid storage name", data: null});+export const markPluginDisposed = (plugin: Plugin) => {disposedPlugins.add(plugin);clearPluginToolbarItems(plugin);@@ -462,18 +470,23 @@ export class Plugin {* 负数错误码被请求层拦截等未触发回调的情况会使 Promise 持续等待,需要调用方自行设置超时。* 只读或发布会话不会在此方法中直接拒绝,但私有文件读取仍受内核权限限制;公开快照应使用 loadPublishData。* @returns 文件内容(解析后的 JSON 值或文本),或读取失败时的缓存值,不是统一的内核响应封装。- * @throws 调用时插件实例已销毁则拒绝 Promise,值为 {code: 410, msg, data: null}。+ * @throws 调用时插件实例已销毁为 410,存储名不含有效文件段(如 ".."、"."、空串)为 400;+ * 拒绝值均为 {code, msg, data: null},生命周期检查优先于存储名检查。*/public loadData(storageName: string): Promise<any> {if (isPluginDisposed(this)) {return Promise.reject({code: 410, msg: "Plugin lifecycle has ended", data: null});}+ const storagePath = getPluginStoragePath(this, storageName);+ if (storagePath === null) {+ return Promise.reject(getInvalidStorageNameError());+ }if (typeof this.data[storageName] === "undefined") {this.data[storageName] = "";}return new Promise((resolve) => {fetchPost("/api/file/getFile", {- path: `/data/storage/petal/${this.name}/${normalizeStoragePath(storageName)}`+ path: storagePath}, (response) => {this.data[storageName] = response;resolve(this.data[storageName]);@@ -489,8 +502,8 @@ export class Plugin {* 未设置请求失败回调,网络异常或内核负数错误码(如 -1、-3)可能使 Promise 持续等待;* 调用方需要自行设置超时,不能仅依赖捕获拒绝来处理写入失败。* @returns 内核响应 {code, msg, data},调用方仍需检查 code,不能将兑现视为写入成功。- * @throws 调用时插件实例已销毁为 410,只读或发布会话为 403,序列化或创建文件失败为 400;- * 拒绝值均为 {code, msg, data: null},生命周期检查优先于只读或发布会话检查。+ * @throws 调用时插件实例已销毁为 410,只读或发布会话为 403,存储名不含有效文件段、序列化或创建文件失败为 400;+ * 拒绝值均为 {code, msg, data: null},检查顺序为生命周期、只读或发布会话、存储名。*/public saveData(storageName: string, data: any): Promise<any | IWebSocketData> {if (isPluginDisposed(this)) {@@ -503,8 +516,11 @@ export class Plugin {data: null});}+ const pathString = getPluginStoragePath(this, storageName);+ if (pathString === null) {+ return Promise.reject(getInvalidStorageNameError());+ }return new Promise((resolve, reject) => {- const pathString = `/data/storage/petal/${this.name}/${normalizeStoragePath(storageName)}`;let file: File;try {const fileName = pathString.split("/").pop();@@ -542,8 +558,8 @@ export class Plugin {* 不会直接清除其他前端实例的缓存,这些实例再次 loadData 时可能回退到旧内容。* 未设置请求失败回调,网络异常或内核负数错误码可能使 Promise 持续等待,调用方需要自行设置超时。* @returns 内核响应 {code, msg, data},调用方仍需检查 code,不能将兑现视为删除成功。- * @throws 调用时插件实例已销毁为 410,只读或发布会话为 403,拒绝值为 {code, msg, data: null};- * 生命周期检查优先于只读或发布会话检查。+ * @throws 调用时插件实例已销毁为 410,只读或发布会话为 403,存储名不含有效文件段为 400,拒绝值为 {code, msg, data: null};+ * 检查顺序为生命周期、只读或发布会话、存储名。*/public removeData(storageName: string): Promise<IWebSocketData> {if (isPluginDisposed(this)) {@@ -556,12 +572,16 @@ export class Plugin {data: null} as IWebSocketData);}+ const storagePath = getPluginStoragePath(this, storageName);+ if (storagePath === null) {+ return Promise.reject(getInvalidStorageNameError());+ }return new Promise((resolve) => {if (!this.data) {this.data = {};}fetchPost("/api/file/removeFile", {- path: `/data/storage/petal/${this.name}/${normalizeStoragePath(storageName)}`,+ path: storagePath,app: Constants.SIYUAN_APPID,}, (response) => {delete this.data[storageName];diff --git a/app/src/util/pathName.test.ts b/app/src/util/pathName.test.tsindex 73644de872..d85af8204e 100644--- a/app/src/util/pathName.test.ts+++ b/app/src/util/pathName.test.ts@@ -5,6 +5,7 @@ import {test} from "node:test";import {runInNewContext} from "node:vm";import {ModuleKind, ScriptTarget, transpileModule} from "typescript";import * as escape from "./escape";+import * as mergePathSegments from "./mergePathSegments";const names = {} as typeof import("./pathName");runInNewContext(transpileModule(readFileSync("src/util/pathName.ts", "utf8"), {@@ -12,7 +13,8 @@ runInNewContext(transpileModule(readFileSync("src/util/pathName.ts", "utf8"), {}).outputText, {exports: names,window: {siyuan: {languages: {_kernel: {16: "Untitled"}}}},- require: (id: string) => id === "path" ? path : id === "./escape" ? escape : {},+ require: (id: string) => id === "path" ? path : id === "./escape" ? escape :+ id === "./mergePathSegments" ? mergePathSegments : {},});test("document display names preserve complete literal titles", () => {@@ -50,3 +52,24 @@ test("asset names and extensions ignore query strings and fragments", () => {assert.equal(names.getAssetName(assetPath), name, assetPath);}});++test("storage paths keep valid segments inside the root", () => {+ for (const [storageName, expected] of [+ ["config.json", "config.json"],+ ["folder/config.json", "folder/config.json"],+ ["folder\\config.json", "folder/config.json"],+ ["./folder//config.json", "folder/config.json"],+ ["a/../b.json", "b.json"],+ ["../x.json", "x.json"],+ ["../../a/../b/c.json", "b/c.json"],+ ["...", "..."],+ ]) {+ assert.equal(names.normalizeStoragePath(storageName), expected, storageName);+ }+});++test("storage paths without a file segment are rejected instead of addressing the root or its parent", () => {+ for (const storageName of ["", ".", "..", "../", "..\\", "./..", "../..", "a/..", "/", "\\", "./"]) {+ assert.equal(names.normalizeStoragePath(storageName), null, JSON.stringify(storageName));+ }+});diff --git a/app/src/util/pathName.ts b/app/src/util/pathName.tsindex 6493638e5f..ea83b477ac 100644--- a/app/src/util/pathName.ts+++ b/app/src/util/pathName.ts@@ -878,10 +878,10 @@ export const isEncryptedBox = (boxId: string): boolean => {/*** 规范化并校验相对路径:允许子目录,但禁止通过 ".." 穿越到根外。* 用于插件存储,确保路径不逃出指定根目录。- * @returns 规范化后的相对路径(使用 /),若路径非法则返回替换后的合法路径+ * @returns 规范化后的相对路径(使用 /);不含有效文件段(如 ".."、"."、空串)时返回 null,避免指向根目录自身或其上级*/export const normalizeStoragePath = (storageName: string): string | null => {const segments = storageName.replace(/\\/g, "/").split("/");const merged = mergePathSegments([], segments);- return merged.length > 0 ? merged.join("/") : storageName.replace(/[\/\\]+/g, "");+ return merged.length > 0 ? merged.join("/") : null;};