An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:lock: Harden encrypted notebook security boundaries https://github.com/siyuan-note/siyuan/issues/18034
Daniel77850d5bc968
diff --git a/app/src/boot/globalEvent/command/global.ts b/app/src/boot/globalEvent/command/global.tsindex 3904a9e64e..572819018b 100644--- a/app/src/boot/globalEvent/command/global.ts+++ b/app/src/boot/globalEvent/command/global.ts@@ -42,8 +42,7 @@ import {Wnd} from "../../../layout/Wnd";import {unsplitWnd} from "../../../menus/tab";import {openFile} from "../../../editor/util";import {fetchPost} from "../../../util/fetch";-import {isSensitiveSearchConfig, setStorageVal} from "../../../protyle/util/compatibility";-import {isEncryptedBox} from "../../../util/pathName";+import {sanitizeClosedTabs, setStorageVal} from "../../../protyle/util/compatibility";export const globalCommand = (command: string, app: App) => {/// #if MOBILE@@ -155,14 +154,7 @@ export const globalCommand = (command: string, app: App) => {case "recentClosed": {const closedTabsLength = window.siyuan.storage[Constants.LOCAL_CLOSED_TABS].length;window.siyuan.storage[Constants.LOCAL_CLOSED_TABS] =- window.siyuan.storage[Constants.LOCAL_CLOSED_TABS].filter((tab: {- children?: ILayoutJSON & {- notebookId?: string,- config?: Config.IUILayoutTabSearchConfig,- }- }) =>- !(tab.children?.instance === "Editor" && isEncryptedBox(tab.children.notebookId)) &&- !(tab.children?.instance === "Search" && isSensitiveSearchConfig(tab.children.config)));+ sanitizeClosedTabs(window.siyuan.storage[Constants.LOCAL_CLOSED_TABS]);if (closedTabsLength !== window.siyuan.storage[Constants.LOCAL_CLOSED_TABS].length) {setStorageVal(Constants.LOCAL_CLOSED_TABS, window.siyuan.storage[Constants.LOCAL_CLOSED_TABS]);}@@ -229,6 +221,7 @@ export const globalCommand = (command: string, app: App) => {app,blockId: childData.blockId,rootId: childData.rootId,+ notebookId: childData.notebookId,title: closeData.title,});} else if (childData.instance === "Graph") {@@ -236,12 +229,14 @@ export const globalCommand = (command: string, app: App) => {app,blockId: childData.blockId,rootId: childData.rootId,+ notebookId: childData.notebookId,title: closeData.title});} else if (childData.instance === "Outline") {openOutline({app,rootId: childData.blockId,+ notebookId: childData.notebookId,title: closeData.title,isPreview: childData.isPreview});diff --git a/app/src/boot/globalEvent/keydown.ts b/app/src/boot/globalEvent/keydown.tsindex ba740e03bb..93f302f18e 100644--- a/app/src/boot/globalEvent/keydown.ts+++ b/app/src/boot/globalEvent/keydown.ts@@ -415,6 +415,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {openBacklink({app: protyle.app,blockId: refElement.dataset.id,+ notebookId: protyle.notebookId,});return true;}@@ -423,6 +424,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {app: protyle.app,blockId: protyle.block.id,rootId: protyle.block.rootID,+ notebookId: protyle.notebookId,useBlockId: protyle.block.showAll,title: protyle.title ? (protyle.title.editElement.textContent || window.siyuan.languages.untitled) : null,});@@ -436,6 +438,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {openGraph({app: protyle.app,blockId: refElement.dataset.id,+ notebookId: protyle.notebookId,});return true;}@@ -444,6 +447,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {app: protyle.app,blockId: protyle.block.id,rootId: protyle.block.rootID,+ notebookId: protyle.notebookId,useBlockId: protyle.block.showAll,title: protyle.title ? (protyle.title.editElement.textContent || window.siyuan.languages.untitled) : null,});@@ -454,6 +458,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {openOutline({app,rootId: protyle.block.rootID,+ notebookId: protyle.notebookId,title: protyle.options.render.title ? (protyle.title.editElement.textContent || window.siyuan.languages.untitled) : "",isPreview: !protyle.preview.element.classList.contains("fn__none")});diff --git a/app/src/editor/index.ts b/app/src/editor/index.tsindex d606337b80..aed4433bb0 100644--- a/app/src/editor/index.ts+++ b/app/src/editor/index.ts@@ -113,6 +113,7 @@ export class Editor extends Model {app: this.app,blockId: this.getBacklinkBlockId(),rootId: this.editor.protyle.block.rootID,+ notebookId: this.editor.protyle.notebookId,type: "bottom",element: backlinkElement,ownerProtyle: this.editor.protyle,diff --git a/app/src/editor/util.ts b/app/src/editor/util.tsindex bb0ae5edfe..5632060a73 100644--- a/app/src/editor/util.ts+++ b/app/src/editor/util.ts@@ -686,7 +686,7 @@ export const updateOutline = (models: IModels, protyle: IProtyle, reload = falsereturn;}item.isPreview = !protyle.preview.element.classList.contains("fn__none");- item.update(response, blockId);+ item.update(response, blockId, protyle?.notebookId || "");if (protyle) {item.updateDocTitle(protyle.background.ial, response.data?.length || 0);if (getSelection().rangeCount > 0) {@@ -724,9 +724,11 @@ export const updateBacklinkGraph = (models: IModels, protyle: IProtyle) => {if (protyle && protyle.block) {blockId = protyle.block.showAll ? protyle.block.id : protyle.block.parentID;}- if (blockId === item.blockId) {+ const notebookId = protyle?.notebookId || "";+ if (blockId === item.blockId && notebookId === item.notebookId) {return;}+ item.notebookId = notebookId;item.searchGraph(true, blockId);}});diff --git a/app/src/layout/Wnd.ts b/app/src/layout/Wnd.tsindex 5e96358ad8..71062884a7 100644--- a/app/src/layout/Wnd.ts+++ b/app/src/layout/Wnd.ts@@ -5,6 +5,7 @@ import {getInstanceById,getWndByLayout,JSONToCenter, layoutToJSON,+ isSensitiveTab,newModelByInitData,pdfIsLoading,saveLayout,@@ -43,7 +44,6 @@ import {focusByOffset, getSelectionOffset} from "../protyle/util/selection";import {Custom} from "./dock/Custom";import type {App} from "../index";import {unicode2Emoji} from "../emoji";-import {isEncryptedBox} from "../util/pathName";import {closeWindow} from "../window/closeWin";import {newCenterEmptyTab, resizeTabs, setTabPosition} from "./tabUtil";import {fullscreen} from "../protyle/breadcrumb/action";@@ -51,7 +51,7 @@ import {setPadding} from "../protyle/ui/initUI";import {setPosition} from "../util/setPosition";import {clearOBG} from "./dock/util";import {recordBeforeResizeTop} from "../protyle/util/resize";-import {setStorageVal} from "../protyle/util/compatibility";+import {sanitizeClosedTabs, setStorageVal} from "../protyle/util/compatibility";import {setTitle} from "../util/processTitle";import {dragOverScroll} from "../boot/globalEvent/dragover";@@ -773,14 +773,11 @@ export class Wnd {return;}window.siyuan.storage[Constants.LOCAL_CLOSED_TABS] =- window.siyuan.storage[Constants.LOCAL_CLOSED_TABS].filter((tab: {children?: {notebookId?: string}}) =>- !isEncryptedBox(tab.children?.notebookId));+ sanitizeClosedTabs(window.siyuan.storage[Constants.LOCAL_CLOSED_TABS]);if (window.siyuan.storage[Constants.LOCAL_CLOSED_TABS].length > Constants.SIZE_UNDO) {window.siyuan.storage[Constants.LOCAL_CLOSED_TABS].pop();}- const isEncryptedEditor = item.model instanceof Editor &&- isEncryptedBox(item.model.editor.protyle.notebookId);- if (item.headElement && !isEncryptedEditor) {+ if (item.headElement && !isSensitiveTab(item)) {const tabJSON = {};layoutToJSON(item, tabJSON);window.siyuan.storage[Constants.LOCAL_CLOSED_TABS].push(tabJSON);diff --git a/app/src/layout/dock/Backlink.ts b/app/src/layout/dock/Backlink.tsindex 015af14550..32d64200f1 100644--- a/app/src/layout/dock/Backlink.ts+++ b/app/src/layout/dock/Backlink.ts@@ -73,7 +73,7 @@ export class Backlink extends Model {public rootId: string; // "local" 和 "bottom" 必传public ownerProtyle?: IProtyle;public tree: Tree;- private notebookId: string;+ public notebookId: string;public mTree: Tree;public editors: Protyle[] = [];public status: {@@ -115,6 +115,7 @@ export class Backlink extends Model {element?: HTMLElement,blockId: string,rootId?: string,+ notebookId?: string,type: "pin" | "local" | "bottom",ownerProtyle?: IProtyle,emptyChange?: (empty: boolean) => void,@@ -132,6 +133,7 @@ export class Backlink extends Model {this.blockId = options.blockId;this.rootId = options.rootId;+ this.notebookId = options.notebookId || "";this.type = options.type;this.ownerProtyle = options.ownerProtyle;this.emptyChange = options.emptyChange;@@ -1042,7 +1044,7 @@ export class Backlink extends Model {this.resetRenderedData(true);this.blockId = blockId;this.rootId = rootId;- this.notebookId = isEncryptedBox(notebookId) ? notebookId : "";+ this.notebookId = notebookId || "";const status = this.status[blockId];this.tree.element.previousElementSibling.querySelector('[data-type="sort"]').setAttribute("data-sort",diff --git a/app/src/layout/dock/Graph.ts b/app/src/layout/dock/Graph.tsindex d1d911763d..1d5a69e3d7 100644--- a/app/src/layout/dock/Graph.ts+++ b/app/src/layout/dock/Graph.ts@@ -13,7 +13,7 @@ import {openGlobalSearch} from "../../search/util";import type {App} from "../../index";import {checkFold} from "../../util/noRelyPCFunction";import {Editor} from "../../editor";-import {getDocDisplayName} from "../../util/pathName";+import {getDocDisplayName, isEncryptedBox} from "../../util/pathName";declare const vis: any;@@ -25,6 +25,7 @@ export class Graph extends Model {private network: any;public blockId: string; // "local" / "pin" 必填public rootId: string; // "local" 必填+ public notebookId: string;public graphData: {nodes: { box: string, id: string, path: string, type: string, color: IObject }[],links: Record<string, unknown>[],@@ -37,6 +38,7 @@ export class Graph extends Model {tab: TabblockId?: stringrootId?: string+ notebookId?: stringtype: "local" | "pin" | "global"}) {super({app: options.app});@@ -49,6 +51,7 @@ export class Graph extends Model {this.element = options.tab.panelElement;this.blockId = options.blockId;this.rootId = options.rootId;+ this.notebookId = options.notebookId || "";this.type = options.type;this.element.classList.add("graph", "file-tree", this.type === "global" ? "sy__globalGraph" : "sy__graph", "dockPanel");@@ -471,6 +474,7 @@ export class Graph extends Model {type: this.type, // 用于如下场景:当打开文档A的关系图、关系图、文档A后刷新,由于防止请求重复处理,文档A关系图无法渲染。k: this.inputElement.value,id: id || this.blockId,+ notebook: isEncryptedBox(this.notebookId) ? this.notebookId : undefined,conf: {type,d3,@@ -478,6 +482,11 @@ export class Graph extends Model {},}, response => {element.classList.remove("fn__rotate");+ if (response.code !== 0) {+ this.graphData = undefined;+ this.onGraph(false);+ return;+ }if (id) {this.blockId = id;}diff --git a/app/src/layout/dock/Outline.ts b/app/src/layout/dock/Outline.tsindex b9254445b6..b8f1074630 100644--- a/app/src/layout/dock/Outline.ts+++ b/app/src/layout/dock/Outline.ts@@ -42,6 +42,7 @@ export class Outline extends Model {public headerElement: HTMLElement;public type: "pin" | "local";public blockId: string;+ public notebookId: string;public isPreview: boolean;public protyle: IProtyle;private preFilterExpandIds: string[] | null = null;@@ -51,6 +52,7 @@ export class Outline extends Model {app: App,tab: Tab,blockId: string,+ notebookId?: string,type: "pin" | "local",isPreview: boolean}) {@@ -63,6 +65,7 @@ export class Outline extends Model {});this.isPreview = options.isPreview;this.blockId = options.blockId;+ this.notebookId = options.notebookId || "";this.type = options.type;options.tab.panelElement.classList.add("fn__flex-column", "file-tree", "sy__outline", "dockPanel");options.tab.panelElement.innerHTML = `<div class="block__icons fn__hidescrollbar">@@ -306,14 +309,7 @@ export class Outline extends Model {id: this.blockId,preview: this.isPreview};- // 解析当前大纲面板所属 box:按 blockId 在已打开的编辑器里查找- let notebookId: string;- getAllModels().editor.some(item => {- if (item.editor.protyle.block.rootID === this.blockId) {- notebookId = item.editor.protyle.notebookId;- return true;- }- });+ const notebookId = this.getNotebookId();if (isEncryptedBox(notebookId)) {outlineParam.notebook = notebookId;}@@ -572,14 +568,7 @@ export class Outline extends Model {id: this.blockId,preview: this.isPreview};- // 解析当前大纲面板所属 box:按 blockId 在已打开的编辑器里查找- let notebookId: string;- getAllModels().editor.some(item => {- if (item.editor.protyle.block.rootID === this.blockId) {- notebookId = item.editor.protyle.notebookId;- return true;- }- });+ const notebookId = this.getNotebookId();if (isEncryptedBox(notebookId)) {outlineParam.notebook = notebookId;}@@ -628,14 +617,7 @@ export class Outline extends Model {id: nodeElement.getAttribute("data-node-id"),excludeTypes: []};- // 解析当前大纲面板所属 box:按 blockId 在已打开的编辑器里查找- let notebookId: string;- getAllModels().editor.some(editorItem => {- if (editorItem.editor.protyle.block.rootID === this.blockId) {- notebookId = editorItem.editor.protyle.notebookId;- return true;- }- });+ const notebookId = this.getNotebookId();if (isEncryptedBox(notebookId)) {breadcrumbParam.notebook = notebookId;}@@ -698,7 +680,7 @@ export class Outline extends Model {}}- public update(data: IWebSocketData, callbackId?: string) {+ public update(data: IWebSocketData, callbackId?: string, notebookId?: string) {let currentElement = this.element.querySelector(".b3-list-item--focus");let currentId;if (currentElement) {@@ -707,6 +689,7 @@ export class Outline extends Model {const scrollTop = this.element.scrollTop;if (typeof callbackId !== "undefined") {this.blockId = callbackId;+ this.notebookId = typeof notebookId === "undefined" ? "" : notebookId;}this.tree.updateData(data.data);@@ -730,6 +713,19 @@ export class Outline extends Model {this.element.removeAttribute("data-loading");}+ private getNotebookId() {+ if (this.notebookId) {+ return this.notebookId;+ }+ getAllModels().editor.some(item => {+ if (item.editor.protyle.block.rootID === this.blockId) {+ this.notebookId = item.editor.protyle.notebookId;+ return true;+ }+ });+ return this.notebookId;+ }+public refresh() {if (!this.blockId) {return;@@ -747,8 +743,9 @@ export class Outline extends Model {return true;}});- if (isEncryptedBox(protyle?.notebookId)) {- outlineParam.notebook = protyle.notebookId;+ const notebookId = this.getNotebookId();+ if (isEncryptedBox(notebookId)) {+ outlineParam.notebook = notebookId;}fetchPost("/api/outline/getDocOutline", outlineParam, response => {if (refreshId !== this.refreshId || blockId !== this.blockId) {diff --git a/app/src/layout/dock/index.ts b/app/src/layout/dock/index.tsindex e6a75c4b1a..af96fbd65d 100644--- a/app/src/layout/dock/index.ts+++ b/app/src/layout/dock/index.ts@@ -577,6 +577,7 @@ export class Dock {type: "pin",tab,blockId: editor?.protyle?.block?.rootID,+ notebookId: editor?.protyle?.notebookId,isPreview: editor?.protyle?.preview ? !editor.protyle.preview.element.classList.contains("fn__none") : false});if (editor?.protyle?.block?.rootID) {@@ -593,6 +594,7 @@ export class Dock {app: this.app,tab,blockId: editor?.protyle?.block?.rootID,+ notebookId: editor?.protyle?.notebookId,type: "pin"}));}@@ -617,6 +619,7 @@ export class Dock {type: "pin",tab,blockId: editor?.protyle?.block?.rootID,+ notebookId: editor?.protyle?.notebookId,}));}});diff --git a/app/src/layout/dock/util.ts b/app/src/layout/dock/util.tsindex 26d8e30a17..00073f8053 100644--- a/app/src/layout/dock/util.ts+++ b/app/src/layout/dock/util.ts@@ -11,12 +11,14 @@ import {fetchSyncPost} from "../../util/fetch";import {Files} from "./Files";import {Editor} from "../../editor";import {Constants} from "../../constants";-import {getDocDisplayName} from "../../util/pathName";+import {getDocDisplayName, isEncryptedBox} from "../../util/pathName";+import {showMessage} from "../../dialog/message";export const openBacklink = async (options: {app: App,blockId: string,rootId?: string,+ notebookId?: string,title?: string,useBlockId?: boolean,}) => {@@ -38,7 +40,10 @@ export const openBacklink = async (options: {wnd = getWndByLayout(window.siyuan.layout.centerLayout);}if (!options.rootId) {- const response = await fetchSyncPost("/api/block/getDocInfo", {id: options.blockId});+ const response = await fetchSyncPost("/api/block/getDocInfo", {+ id: options.blockId,+ notebook: isEncryptedBox(options.notebookId) ? options.notebookId : undefined,+ });if (response.code === -1) {return;}@@ -46,7 +51,10 @@ export const openBacklink = async (options: {options.useBlockId = response.data.rootID !== response.data.id;options.title = getDocDisplayName(response.data.name, response.data.ial[Constants.CUSTOM_SY_TITLE_EMPTY] === "true");} else if (!options.title) {- const response = await fetchSyncPost("/api/block/getDocInfo", {id: options.blockId});+ const response = await fetchSyncPost("/api/block/getDocInfo", {+ id: options.blockId,+ notebook: isEncryptedBox(options.notebookId) ? options.notebookId : undefined,+ });if (response.code === -1) {return;}@@ -64,6 +72,7 @@ export const openBacklink = async (options: {// 通过搜索打开的包含上下文,但不是缩放,因此需要传 rootID https://ld246.com/article/1666786639708blockId: options.useBlockId ? options.blockId : options.rootId,rootId: options.rootId,+ notebookId: options.notebookId,}));}}));@@ -73,9 +82,14 @@ export const openGraph = async (options: {app: App,blockId: string,rootId?: string,+ notebookId?: string,title?: string,useBlockId?: boolean,}) => {+ if (isEncryptedBox(options.notebookId)) {+ showMessage(window.siyuan.languages._kernel[313]);+ return;+ }const graph = getAllModels().graph.find(item => {if (item.blockId === options.blockId && item.type === "local") {item.parent.parent.removeTab(item.parent.id);@@ -119,6 +133,7 @@ export const openGraph = async (options: {tab,blockId: options.blockId,rootId: options.rootId,+ notebookId: options.notebookId,}));}}));@@ -127,6 +142,7 @@ export const openGraph = async (options: {export const openOutline = async (options: {app: App,rootId: string,+ notebookId?: string,isPreview: boolean,title: string}) => {@@ -150,7 +166,10 @@ export const openOutline = async (options: {const newWnd = wnd.split("lr", false);if (!options.title) {- const response = await fetchSyncPost("/api/block/getDocInfo", {id: options.rootId});+ const response = await fetchSyncPost("/api/block/getDocInfo", {+ id: options.rootId,+ notebook: isEncryptedBox(options.notebookId) ? options.notebookId : undefined,+ });options.title = getDocDisplayName(response.data.name, response.data.ial[Constants.CUSTOM_SY_TITLE_EMPTY] === "true");}newWnd.element.style.width = "200px";@@ -165,6 +184,7 @@ export const openOutline = async (options: {type: "local",tab,blockId: options.rootId,+ notebookId: options.notebookId,isPreview: options.isPreview,}));}diff --git a/app/src/layout/tabUtil.ts b/app/src/layout/tabUtil.tsindex 6bbef996e2..d74d85cf97 100644--- a/app/src/layout/tabUtil.ts+++ b/app/src/layout/tabUtil.ts@@ -379,6 +379,7 @@ export const copyTab = (app: App, tab: Tab) => {tab: newTab,blockId: tab.model.blockId,rootId: tab.model.rootId,+ notebookId: tab.model.notebookId,type: tab.model.type,});} else if (tab.model instanceof Files) {@@ -391,6 +392,7 @@ export const copyTab = (app: App, tab: Tab) => {app,tab: newTab,blockId: tab.model.blockId,+ notebookId: tab.model.notebookId,type: tab.model.type,isPreview: tab.model.isPreview});@@ -400,6 +402,7 @@ export const copyTab = (app: App, tab: Tab) => {tab: newTab,blockId: tab.model.blockId,rootId: tab.model.rootId,+ notebookId: tab.model.notebookId,type: tab.model.type});} else if (tab.model instanceof Bookmark) {diff --git a/app/src/layout/util.ts b/app/src/layout/util.tsindex 166a4f133a..b7c408790b 100644--- a/app/src/layout/util.ts+++ b/app/src/layout/util.ts@@ -29,7 +29,7 @@ import {newDatabaseRowModel} from "../editor/databaseRow";import type {App} from "../index";import {afterLayoutReady} from "../plugin/loader";import {newCenterEmptyTab, resizeTabs, setTabPosition} from "./tabUtil";-import {isSensitiveSearchConfig, setStorageVal} from "../protyle/util/compatibility";+import {isSensitiveLayoutData, isSensitiveSearchConfig, setStorageVal} from "../protyle/util/compatibility";import {adjustDockPadding} from "./dock/util";import {setTitle} from "../util/processTitle";import {activateQueuedAVLocate, queueAVLocateRequest} from "../protyle/render/av/locate";@@ -38,6 +38,23 @@ const isBuiltInCustomModel = (type: string) => {return type === "siyuan-card" || type === "siyuan-database-row";};+export const isSensitiveTab = (tab: Tab) => {+ if (tab.model instanceof Editor) {+ return isEncryptedBox(tab.model.editor.protyle.notebookId);+ }+ if (tab.model instanceof Search) {+ return isSensitiveSearchConfig(tab.model.config);+ }+ if ((tab.model instanceof Backlink || tab.model instanceof Graph || tab.model instanceof Outline) &&+ tab.model.type === "local") {+ return !tab.model.notebookId || isEncryptedBox(tab.model.notebookId);+ }+ if (!tab.model && tab.headElement) {+ return isSensitiveLayoutData(JSON.parse(tab.headElement.getAttribute("data-initdata") || "{}"));+ }+ return false;+};+export const setPanelFocus = (element: Element, isSaveLayout = true) => {if (element.getAttribute("data-type") === "wnd") {const title = element.querySelector('.layout-tab-bar .item--focus[data-type="tab-header"] .item__text')?.textContent || "";@@ -386,8 +403,7 @@ export const JSONToCenter = (}(layout as Wnd).addTab(child, false, false, json.activeTime);} else if (json.instance === "Editor" && json.blockId) {- const notebook = window.siyuan.notebooks.find((item) => item.id === json.notebookId);- if (notebook?.closed && isEncryptedBox(json.notebookId)) {+ if (isSensitiveLayoutData(json)) {(layout as Tab).headElement.removeAttribute("data-init-active");removedTabs.push(layout as Tab);return;@@ -404,11 +420,17 @@ export const JSONToCenter = (page: json.page,}));} else if (json.instance === "Backlink") {+ if (isSensitiveLayoutData(json)) {+ (layout as Tab).headElement.removeAttribute("data-init-active");+ removedTabs.push(layout as Tab);+ return;+ }(layout as Tab).addModel(new Backlink({app,tab: (layout as Tab),blockId: json.blockId,rootId: json.rootId,+ notebookId: json.notebookId,type: json.type as "pin" | "local",}));} else if (json.instance === "Bookmark") {@@ -419,24 +441,41 @@ export const JSONToCenter = (tab: (layout as Tab),}));} else if (json.instance === "Graph") {+ if (isSensitiveLayoutData(json)) {+ (layout as Tab).headElement.removeAttribute("data-init-active");+ removedTabs.push(layout as Tab);+ return;+ }(layout as Tab).addModel(new Graph({app,tab: (layout as Tab),blockId: json.blockId,rootId: json.rootId,+ notebookId: json.notebookId,type: json.type as "pin" | "local" | "global",}));} else if (json.instance === "Outline") {+ if (isSensitiveLayoutData(json)) {+ (layout as Tab).headElement.removeAttribute("data-init-active");+ removedTabs.push(layout as Tab);+ return;+ }(layout as Tab).addModel(new Outline({app,tab: (layout as Tab),blockId: json.blockId,+ notebookId: json.notebookId,type: json.type as "pin" | "local",isPreview: json.isPreview,}));} else if (json.instance === "Tag") {(layout as Tab).addModel(new Tag(app, (layout as Tab)));} else if (json.instance === "Search") {+ if (isSensitiveLayoutData(json)) {+ (layout as Tab).headElement.removeAttribute("data-init-active");+ removedTabs.push(layout as Tab);+ return;+ }(layout as Tab).addModel(new Search({app,tab: (layout as Tab),@@ -654,6 +693,7 @@ export const layoutToJSON = (layout: Layout | Wnd | Tab | Model, json: any, brea} else if (layout instanceof Backlink) {json.blockId = layout.blockId;json.rootId = layout.rootId;+ json.notebookId = layout.notebookId;json.type = layout.type;json.instance = "Backlink";} else if (layout instanceof Bookmark) {@@ -663,10 +703,12 @@ export const layoutToJSON = (layout: Layout | Wnd | Tab | Model, json: any, brea} else if (layout instanceof Graph) {json.blockId = layout.blockId;json.rootId = layout.rootId;+ json.notebookId = layout.notebookId;json.type = layout.type;json.instance = "Graph";} else if (layout instanceof Outline) {json.blockId = layout.blockId;+ json.notebookId = layout.notebookId;json.type = layout.type;json.isPreview = layout.isPreview;json.instance = "Outline";@@ -708,19 +750,9 @@ export const layoutToJSON = (layout: Layout | Wnd | Tab | Model, json: any, breajson.children = [];layout.children.forEach((item: Layout | Wnd | Tab) => {if (item instanceof Tab) {- if (item.model instanceof Editor && isEncryptedBox(item.model.editor.protyle.notebookId)) {+ if (isSensitiveTab(item)) {return;}- if (item.model instanceof Search && isSensitiveSearchConfig(item.model.config)) {- return;- }- if (!item.model && item.headElement) {- const initData = JSON.parse(item.headElement.getAttribute("data-initdata") || "{}");- if ((initData.instance === "Editor" && isEncryptedBox(initData.notebookId)) ||- (initData.instance === "Search" && isSensitiveSearchConfig(initData.config))) {- return;- }- }}const itemJSON = {};json.children.push(itemJSON);diff --git a/app/src/menus/protyle.ts b/app/src/menus/protyle.tsindex b3d4671152..aadaee3719 100644--- a/app/src/menus/protyle.ts+++ b/app/src/menus/protyle.ts@@ -480,6 +480,7 @@ export const refMenu = (protyle: IProtyle, element: HTMLElement) => {openBacklink({app: protyle.app,blockId: refBlockId,+ notebookId: protyle.notebookId,});}}).element);@@ -492,6 +493,7 @@ export const refMenu = (protyle: IProtyle, element: HTMLElement) => {openGraph({app: protyle.app,blockId: refBlockId,+ notebookId: protyle.notebookId,});}}).element);diff --git a/app/src/protyle/header/openTitleMenu.ts b/app/src/protyle/header/openTitleMenu.tsindex da0df751bb..daace31746 100644--- a/app/src/protyle/header/openTitleMenu.ts+++ b/app/src/protyle/header/openTitleMenu.ts@@ -122,6 +122,7 @@ export const openTitleMenu = (protyle: IProtyle, position: IPosition, from: striopenOutline({app: protyle.app,rootId: protyle.block.rootID,+ notebookId: protyle.notebookId,title: protyle.options.render.title ? (protyle.title.editElement.textContent || window.siyuan.languages.untitled) : "",isPreview: !protyle.preview.element.classList.contains("fn__none")});@@ -137,6 +138,7 @@ export const openTitleMenu = (protyle: IProtyle, position: IPosition, from: striapp: protyle.app,blockId: protyle.block.id,rootId: protyle.block.rootID,+ notebookId: protyle.notebookId,useBlockId: protyle.block.showAll,title: protyle.title ? (protyle.title.editElement.textContent || window.siyuan.languages.untitled) : null});@@ -152,6 +154,7 @@ export const openTitleMenu = (protyle: IProtyle, position: IPosition, from: striapp: protyle.app,blockId: protyle.block.id,rootId: protyle.block.rootID,+ notebookId: protyle.notebookId,useBlockId: protyle.block.showAll,title: protyle.title ? (protyle.title.editElement.textContent || window.siyuan.languages.untitled) : null});diff --git a/app/src/protyle/util/compatibility.ts b/app/src/protyle/util/compatibility.tsindex 0f19e24e71..ed3466358b 100644--- a/app/src/protyle/util/compatibility.ts+++ b/app/src/protyle/util/compatibility.ts@@ -648,6 +648,12 @@ export const getLocalStorage = (cb: () => void) => {Object.keys(window.siyuan.storage[Constants.LOCAL_SEARCHDATA].subTypes).length === 0) {window.siyuan.storage[Constants.LOCAL_SEARCHDATA].subTypes = getDefaultSubType();}+ const closedTabs = window.siyuan.storage[Constants.LOCAL_CLOSED_TABS];+ const sanitizedClosedTabs = sanitizeClosedTabs(closedTabs);+ if (sanitizedClosedTabs.length !== closedTabs.length) {+ window.siyuan.storage[Constants.LOCAL_CLOSED_TABS] = sanitizedClosedTabs;+ setStorageVal(Constants.LOCAL_CLOSED_TABS, sanitizedClosedTabs);+ }cb();});};@@ -665,6 +671,34 @@ export const isSensitiveSearchConfig = (config?: Config.IUILayoutTabSearchConfig}) || false;};+export const isSensitiveLayoutData = (data?: {+ instance?: string,+ type?: string,+ notebookId?: string,+ config?: Config.IUILayoutTabSearchConfig,+}) => {+ if (!data) {+ return false;+ }+ if (data.instance === "Editor") {+ return isEncryptedBox(data.notebookId);+ }+ if (data.instance === "Search") {+ return isSensitiveSearchConfig(data.config);+ }+ if (data.type === "local" && ["Backlink", "Graph", "Outline"].includes(data.instance)) {+ return !data.notebookId || isEncryptedBox(data.notebookId);+ }+ return false;+};++export const sanitizeClosedTabs = (tabs: Array<{children?: Parameters<typeof isSensitiveLayoutData>[0]}>) => {+ if (!Array.isArray(tabs)) {+ return [];+ }+ return tabs.filter((tab) => !isSensitiveLayoutData(tab.children));+};+const sanitizeSearchConfig = (config: Config.IUILayoutTabSearchConfig) => {if (!isSensitiveSearchConfig(config)) {return config;@@ -695,8 +729,10 @@ export const setStorageVal = (key: string, val: any, cb?: () => void) => {storageVal = sanitizeSearchConfig(val);} else if (key === Constants.LOCAL_FILESPATHS) {storageVal = sanitizeFilesPaths(val);+ } else if (key === Constants.LOCAL_CLOSED_TABS) {+ storageVal = sanitizeClosedTabs(val);}- if (key === Constants.LOCAL_SEARCHDATA || key === Constants.LOCAL_FILESPATHS) {+ if ([Constants.LOCAL_SEARCHDATA, Constants.LOCAL_FILESPATHS, Constants.LOCAL_CLOSED_TABS].includes(key)) {window.siyuan.storage[key] = storageVal;}fetchPost("/api/storage/setLocalStorageVal", {diff --git a/app/src/search/util.ts b/app/src/search/util.tsindex 51256a6eea..0a79223509 100644--- a/app/src/search/util.ts+++ b/app/src/search/util.ts@@ -54,8 +54,10 @@ import {scheduleSearchRequest} from "./request";export const openGlobalSearch = (app: App, text: string, replace: boolean, searchData?: Config.IUILayoutTabSearchConfig) => {text = text.trim();- const sensitive = searchData?.sensitive || (!!text && getAllModels().editor.some((item) =>- isEncryptedBox(item.editor.protyle.notebookId)));+ const sensitive = searchData?.sensitive || getAllModels().editor.some((item) =>+ isEncryptedBox(item.editor.protyle.notebookId) &&+ item.parent.headElement?.classList.contains("item--focus") &&+ item.parent.parent.element.classList.contains("layout__wnd--active"));const searchModel = getAllModels().search.find((item) => {if (sensitive) {item.config.sensitive = true;diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.tsindex acb0a6452b..45ac4489df 100644--- a/app/src/types/config.d.ts+++ b/app/src/types/config.d.ts@@ -2204,6 +2204,10 @@ declare namespace Config {* (Backlink) Document block ID*/rootId: string;+ /**+ * (Backlink) Notebook ID+ */+ notebookId?: string;/*** (Backlink) Tab type* - `pin`: Pinned panel@@ -2302,6 +2306,10 @@ declare namespace Config {* (Graph) Block ID*/blockId: string;+ /**+ * (Graph) Notebook ID+ */+ notebookId?: string;/*** Object name*/@@ -2336,6 +2344,10 @@ declare namespace Config {* (Outline) Block ID*/blockId: string;+ /**+ * (Outline) Notebook ID+ */+ notebookId?: string;/*** Object name*/diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.tsindex 355f2c4f9a..23dcf9b5bd 100644--- a/app/src/types/index.d.ts+++ b/app/src/types/index.d.ts@@ -736,6 +736,7 @@ interface ILayoutJSON extends ILayoutOptions {page?: stringpath?: stringblockId?: string+ notebookId?: stringmode?: TEditorModeaction?: TProtyleActionicon?: string@@ -1016,6 +1017,11 @@ interface IBazaarItem {modes?: string[]; // 仅 theme}+interface IUpdatedBazaarItem {+ installed: IBazaarItem;+ available: IBazaarItem;+}+interface IAV {id: string;name: string;diff --git a/kernel/api/asset.go b/kernel/api/asset.goindex 42fd11a3f3..ce89b8c2a5 100644--- a/kernel/api/asset.go+++ b/kernel/api/asset.go@@ -295,6 +295,12 @@ func setFileAnnotation(c *gin.Context) {ret.Msg = err.Error()return}+ boxID := model.ExtractBoxIDFromAssetsPath(writePath)+ if err = holdEncryptedBoxRequest(c, boxID); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }if "{}" == data {if err = filelock.Remove(writePath); err != nil {ret.Code = -1@@ -304,9 +310,7 @@ func setFileAnnotation(c *gin.Context) {} else {// 加密笔记本的 .sya 写盘前必须加密;加密笔记本未解锁时拒绝写入(fail-closed,避免明文落盘)writeData := []byte(data)- if boxID := model.ExtractBoxIDFromAssetsPath(writePath); boxID != "" && model.IsEncryptedBox(boxID) {- model.HoldBoxReadLock(boxID)- defer model.ReleaseBoxReadLock(boxID)+ if boxID != "" && model.IsEncryptedBox(boxID) {dek, dekErr := model.GetDEKIfUnlocked(boxID)if dekErr != nil {ret.Code = -1@@ -362,6 +366,12 @@ func getFileAnnotation(c *gin.Context) {ret.Code = 1return}+ boxID := model.ExtractBoxIDFromAssetsPath(readPath)+ if err = holdEncryptedBoxRequest(c, boxID); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }data, err := filelock.ReadFile(readPath)if err != nil {@@ -370,9 +380,7 @@ func getFileAnnotation(c *gin.Context) {return}// 加密笔记本的 .sya 读盘后必须解密;未解锁时拒绝返回(fail-closed,避免返回密文或误判)- if boxID := model.ExtractBoxIDFromAssetsPath(readPath); boxID != "" && model.IsEncryptedBox(boxID) {- model.HoldBoxReadLock(boxID)- defer model.ReleaseBoxReadLock(boxID)+ if boxID != "" && model.IsEncryptedBox(boxID) {dek, dekErr := model.GetDEKIfUnlocked(boxID)if dekErr != nil {ret.Code = -1diff --git a/kernel/api/asset_crypto_test.go b/kernel/api/asset_crypto_test.gonew file mode 100644index 0000000000..000f43464e--- /dev/null+++ b/kernel/api/asset_crypto_test.go@@ -0,0 +1,95 @@+// SiYuan - Refactor your thinking+// 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 api++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestSetFileAnnotationDoesNotDeleteFromLockedEncryptedNotebook(t *testing.T) {+ gin.SetMode(gin.TestMode)++ oldWorkspaceDir, oldDataDir := util.WorkspaceDir, util.DataDir+ workspaceDir := t.TempDir()+ util.WorkspaceDir = workspaceDir+ util.DataDir = filepath.Join(workspaceDir, "data")+ t.Cleanup(func() {+ util.WorkspaceDir, util.DataDir = oldWorkspaceDir, oldDataDir+ })++ const boxID = "20260731180000-abcdefg"+ boxConf := conf.NewBoxConf()+ boxConf.Encrypted = true+ confData, err := json.Marshal(boxConf)+ if err != nil {+ t.Fatal(err)+ }+ confPath := filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json")+ if err = os.MkdirAll(filepath.Dir(confPath), 0755); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(confPath, confData, 0644); err != nil {+ t.Fatal(err)+ }++ assetPath := filepath.Join(util.DataDir, boxID, "assets", "document.pdf")+ annotationPath := assetPath + ".sya"+ if err = os.MkdirAll(filepath.Dir(assetPath), 0755); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(assetPath, []byte("encrypted asset"), 0600); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(annotationPath, []byte("encrypted annotation"), 0600); err != nil {+ t.Fatal(err)+ }++ engine := gin.New()+ engine.Use(boxLeaseMiddleware)+ engine.POST("/api/asset/setFileAnnotation", setFileAnnotation)+ recorder := httptest.NewRecorder()+ request := httptest.NewRequest(+ http.MethodPost,+ "/api/asset/setFileAnnotation",+ strings.NewReader(`{"path":"assets/document.pdf?box=`+boxID+`.sya","data":"{}"}`),+ )+ request.Header.Set("Content-Type", "application/json")+ engine.ServeHTTP(recorder, request)++ response := &struct {+ Code int `json:"code"`+ }{}+ if err = json.Unmarshal(recorder.Body.Bytes(), response); err != nil {+ t.Fatalf("unmarshal response failed: %v", err)+ }+ if response.Code == 0 {+ t.Fatalf("locked encrypted annotation deletion unexpectedly succeeded: %s", recorder.Body.String())+ }+ if _, err = os.Stat(annotationPath); err != nil {+ t.Fatalf("locked encrypted annotation was removed: %v", err)+ }+}diff --git a/kernel/api/block.go b/kernel/api/block.goindex 59e6d68ada..fb949def60 100644--- a/kernel/api/block.go+++ b/kernel/api/block.go@@ -166,6 +166,9 @@ func getBlockTreeInfos(c *gin.Context) {}boxID := encryptedNotebookFromArg(arg)+ if !holdBlockRequest(c, ret, boxID) {+ return+ }ids = filterBlockIDsByPublishAccess(c, ids, boxID)ret.Data = model.GetBlockTreeInfosInBox(ids, boxID)}@@ -181,6 +184,9 @@ func getBlockSiblingID(c *gin.Context) {id := arg["id"].(string)boxID := encryptedNotebookFromArg(arg)+ if !holdBlockRequest(c, ret, boxID) {+ return+ }if !isBlockPublishAccessible(c, id, boxID) {ret.Data = map[string]string{"parent": "",@@ -209,6 +215,9 @@ func getBlockRelevantIDs(c *gin.Context) {id := arg["id"].(string)boxID := encryptedNotebookFromArg(arg)+ if !holdBlockRequest(c, ret, boxID) {+ return+ }if !isBlockPublishAccessible(c, id, boxID) {ret.Data = map[string]string{"parentID": "",@@ -557,6 +566,9 @@ func getDocInfo(c *gin.Context) {id := arg["id"].(string)boxID := encryptedNotebookFromArg(arg)+ if !holdBlockRequest(c, ret, boxID) {+ return+ }if !checkBlockPublishAccessInBox(c, id, boxID, ret) {return}@@ -718,6 +730,9 @@ func getRefText(c *gin.Context) {}boxID := encryptedNotebookFromArg(arg)+ if !holdBlockRequest(c, ret, boxID) {+ return+ }if !isBlockPublishAccessible(c, id, boxID) {ret.Data = model.ErrBlockNotFound.Error()return@@ -769,7 +784,11 @@ func getRefIDs(c *gin.Context) {}return}- refDefs, originalRefBlockIDs := model.GetBlockRefsInBox(id, encryptedNotebookFromArg(arg))+ boxID := encryptedNotebookFromArg(arg)+ if !holdBlockRequest(c, ret, boxID) {+ return+ }+ refDefs, originalRefBlockIDs := model.GetBlockRefsInBox(id, boxID)if model.IsReadOnlyRoleContext(c) {publishAccess := model.GetPublishAccess()refDefs, originalRefBlockIDs = model.FilterRefDefsByPublishAccess(c, publishAccess, refDefs)@@ -848,6 +867,9 @@ func getBlockBreadcrumb(c *gin.Context) {}boxID := encryptedNotebookFromArg(arg)+ if !holdBlockRequest(c, ret, boxID) {+ return+ }if !isBlockPublishAccessible(c, id, boxID) {ret.Data = []*model.BlockPath{}return@@ -899,6 +921,9 @@ func getBlockBreadcrumbChildren(c *gin.Context) {limit = int(limitArg.(float64))}boxID := encryptedNotebookFromArg(arg)+ if !holdBlockRequest(c, ret, boxID) {+ return+ }if !isBlockPublishAccessible(c, id, boxID) {ret.Data = &model.BlockBreadcrumbChildren{Items: []*model.BlockPath{}}return@@ -988,6 +1013,9 @@ func getBlockInfo(c *gin.Context) {return}boxID := encryptedNotebookFromArg(arg)+ if !holdBlockRequest(c, ret, boxID) {+ return+ }if !checkBlockPublishAccessInBox(c, id, boxID, ret) {return}@@ -1120,6 +1148,9 @@ func getBlockDOM(c *gin.Context) {return}boxID := encryptedNotebookFromArg(arg)+ if !holdBlockRequest(c, ret, boxID) {+ return+ }dom := model.GetBlockDOMInBox(id, boxID)if model.IsReadOnlyRoleContext(c) {@@ -1163,6 +1194,9 @@ func getBlockDOMs(c *gin.Context) {return}boxID := encryptedNotebookFromArg(arg)+ if !holdBlockRequest(c, ret, boxID) {+ return+ }doms := model.GetBlockDOMsInBox(ids, boxID)if model.IsReadOnlyRoleContext(c) {@@ -1190,6 +1224,9 @@ func getBlockDOMWithEmbed(c *gin.Context) {return}boxID := encryptedNotebookFromArg(arg)+ if !holdBlockRequest(c, ret, boxID) {+ return+ }isReadOnlyRole := model.IsReadOnlyRoleContext(c)var publishAccess model.PublishAccessvar accessChecker model.EmbedBlockAccessChecker@@ -1241,6 +1278,9 @@ func getBlockDOMsWithEmbed(c *gin.Context) {return}boxID := encryptedNotebookFromArg(arg)+ if !holdBlockRequest(c, ret, boxID) {+ return+ }isReadOnlyRole := model.IsReadOnlyRoleContext(c)var publishAccess model.PublishAccessvar accessChecker model.EmbedBlockAccessChecker@@ -1268,6 +1308,15 @@ func encryptedNotebookFromArg(arg map[string]any) string {return ""}+func holdBlockRequest(c *gin.Context, ret *gulu.Result, boxID string) bool {+ if err := holdEncryptedBoxRequest(c, boxID); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return false+ }+ return true+}+func isEncryptedNotebookDeniedForPublish(c *gin.Context, notebook string) bool {return notebook != "" && model.IsReadOnlyRoleContext(c) && model.IsEncryptedBoxDeniedByPublishAccess(notebook)}@@ -1322,6 +1371,9 @@ func getBlockKramdown(c *gin.Context) {return}boxID := encryptedNotebookFromArg(arg)+ if !holdBlockRequest(c, ret, boxID) {+ return+ }var kramdown stringif boxID != "" {kramdown = model.GetBlockKramdownInBox(id, mode, boxID)@@ -1387,6 +1439,9 @@ func getBlockKramdowns(c *gin.Context) {return}boxID := encryptedNotebookFromArg(arg)+ if !holdBlockRequest(c, ret, boxID) {+ return+ }var kramdowns map[string]stringif boxID != "" {kramdowns = model.GetBlockKramdownsInBox(ids, mode, boxID)@@ -1434,7 +1489,11 @@ func getChildBlocks(c *gin.Context) {return}- ret.Data = model.GetChildBlocks(id)+ boxID := encryptedNotebookFromArg(arg)+ if !holdBlockRequest(c, ret, boxID) {+ return+ }+ ret.Data = model.GetChildBlocksInBox(id, boxID)}func getTailChildBlocks(c *gin.Context) {@@ -1460,5 +1519,9 @@ func getTailChildBlocks(c *gin.Context) {n = 7}- ret.Data = model.GetTailChildBlocks(id, n)+ boxID := encryptedNotebookFromArg(arg)+ if !holdBlockRequest(c, ret, boxID) {+ return+ }+ ret.Data = model.GetTailChildBlocksInBox(id, n, boxID)}diff --git a/kernel/api/box_lease.go b/kernel/api/box_lease.gonew file mode 100644index 0000000000..a201664dc3--- /dev/null+++ b/kernel/api/box_lease.go@@ -0,0 +1,69 @@+// SiYuan - Refactor your thinking+// 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 api++import (+ "errors"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/model"+)++const requestBoxLeasesKey = "siyuan-request-box-leases"++func boxLeaseMiddleware(c *gin.Context) {+ defer releaseRequestBoxLeases(c)+ c.Next()+}++func holdEncryptedBoxRequest(c *gin.Context, boxID string) error {+ if boxID == "" || !model.IsEncryptedBox(boxID) {+ return nil+ }+ leases := requestBoxLeases(c)+ for _, heldBoxID := range leases {+ if heldBoxID == boxID {+ return nil+ }+ }++ model.HoldBoxReadLock(boxID)+ if !model.IsBoxUnlocked(boxID) {+ model.ReleaseBoxReadLock(boxID)+ return errors.New("encrypted notebook is locked, please unlock it first")+ }+ leases = append(leases, boxID)+ c.Set(requestBoxLeasesKey, leases)+ return nil+}++func requestBoxLeases(c *gin.Context) []string {+ value, ok := c.Get(requestBoxLeasesKey)+ if !ok {+ return nil+ }+ leases, _ := value.([]string)+ return leases+}++func releaseRequestBoxLeases(c *gin.Context) {+ leases := requestBoxLeases(c)+ for i := len(leases) - 1; i >= 0; i-- {+ model.ReleaseBoxReadLock(leases[i])+ }+ c.Set(requestBoxLeasesKey, []string{})+}diff --git a/kernel/api/extension.go b/kernel/api/extension.goindex d6048f13a4..2724800227 100644--- a/kernel/api/extension.go+++ b/kernel/api/extension.go@@ -59,6 +59,11 @@ func extensionCopy(c *gin.Context) {}}}+ if err := holdEncryptedBoxRequest(c, boxID); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }if err := os.MkdirAll(assets, 0755); err != nil {logging.LogErrorf("create assets folder [%s] failed: %s", assets, err)diff --git a/kernel/api/filetree.go b/kernel/api/filetree.goindex 900d18de3c..a148108084 100644--- a/kernel/api/filetree.go+++ b/kernel/api/filetree.go@@ -78,14 +78,10 @@ func listDocTree(c *gin.Context) {}// 加密笔记本锁定时拒绝直接列举磁盘目录,防止泄漏文档 ID、层级和数量- if model.IsEncryptedBox(notebook) {- model.HoldBoxReadLock(notebook)- defer model.ReleaseBoxReadLock(notebook)- if _, dekErr := model.GetDEKIfUnlocked(notebook); dekErr != nil {- ret.Code = -1- ret.Msg = model.Conf.Language(314)- return- }+ if err := holdEncryptedBoxRequest(c, notebook); err != nil {+ ret.Code = -1+ ret.Msg = model.Conf.Language(314)+ return}p := arg["path"].(string)@@ -1368,6 +1364,11 @@ func getDoc(c *gin.Context) {ret.Code = 3return}+ if err := holdEncryptedBoxRequest(c, requestedNotebook); err != nil {+ ret.Code = 1+ ret.Msg = err.Error()+ return+ }idx := arg["index"]index := 0if nil != idx {diff --git a/kernel/api/graph.go b/kernel/api/graph.goindex 3f47ded44c..fef0436302 100644--- a/kernel/api/graph.go+++ b/kernel/api/graph.go@@ -23,6 +23,7 @@ import ("github.com/gin-gonic/gin""github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util")@@ -128,6 +129,17 @@ func getLocalGraph(c *gin.Context) {) {return}+ notebook, _ := arg["notebook"].(string)+ if model.IsEncryptedBox(notebook) {+ ret.Code = -1+ ret.Msg = model.Conf.Language(313)+ return+ }+ if bt := treenode.GetBlockTree(id); bt != nil && model.IsEncryptedBox(bt.BoxID) {+ ret.Code = -1+ ret.Msg = model.Conf.Language(313)+ return+ }graphConf, err := gulu.JSON.MarshalJSON(confArg)if err != nil {diff --git a/kernel/api/lute.go b/kernel/api/lute.goindex add3ee8547..290507a49e 100644--- a/kernel/api/lute.go+++ b/kernel/api/lute.go@@ -95,6 +95,11 @@ func html2BlockDOM(c *gin.Context) {boxID = notebook}}+ if err := holdEncryptedBoxRequest(c, boxID); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }luteEngine := util.NewLute()luteEngine.SetHTMLTag2TextMark(true)luteEngine.SetHTML2MarkdownAttrs([]string{"alias", "memo", "bookmark", "custom-*"})diff --git a/kernel/api/outline.go b/kernel/api/outline.goindex a12c7e8b7c..0729928a65 100644--- a/kernel/api/outline.go+++ b/kernel/api/outline.go@@ -54,6 +54,11 @@ func getDocOutline(c *gin.Context) {ret.Data = []*model.Path{}return}+ if err := holdEncryptedBoxRequest(c, notebook); err != nil {+ ret.Code = 1+ ret.Msg = err.Error()+ return+ }var headings []*model.Pathvar err errorif notebook != "" && model.IsEncryptedBox(notebook) {@@ -102,6 +107,11 @@ func getDocHeadingNumbers(c *gin.Context) {ret.Data = map[string]string{}return}+ if err := holdEncryptedBoxRequest(c, notebook); err != nil {+ ret.Code = 1+ ret.Msg = err.Error()+ return+ }numbers := map[string]string{}var err errorif notebook != "" && model.IsEncryptedBox(notebook) {diff --git a/kernel/api/ref.go b/kernel/api/ref.goindex 3ee30c3e33..891d6a566a 100644--- a/kernel/api/ref.go+++ b/kernel/api/ref.go@@ -72,6 +72,13 @@ func getBackmentionDoc(c *gin.Context) {if notebook != "" && !model.IsEncryptedBox(notebook) {notebook = ""}+ if !encryptedNotebookDenied {+ if err := holdEncryptedBoxRequest(c, notebook); err != nil {+ ret.Code = 1+ ret.Msg = err.Error()+ return+ }+ }containChildren := model.Conf.Editor.BacklinkContainChildrenif val, ok := arg["containChildren"]; ok {containChildren = val.(bool)@@ -130,6 +137,13 @@ func getBacklinkDoc(c *gin.Context) {if notebook != "" && !model.IsEncryptedBox(notebook) {notebook = ""}+ if !encryptedNotebookDenied {+ if err := holdEncryptedBoxRequest(c, notebook); err != nil {+ ret.Code = 1+ ret.Msg = err.Error()+ return+ }+ }containChildren := model.Conf.Editor.BacklinkContainChildrenif val, ok := arg["containChildren"]; ok {containChildren = val.(bool)@@ -204,6 +218,11 @@ func getBacklink2(c *gin.Context) {// 加密笔记本的反链面板走 InBox 版(查加密 content db)notebook, _ := arg["notebook"].(string)if !isEncryptedNotebookDeniedForPublish(c, notebook) {+ if err := holdEncryptedBoxRequest(c, notebook); err != nil {+ ret.Code = 1+ ret.Msg = err.Error()+ return+ }if notebook != "" && model.IsEncryptedBox(notebook) {boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2InBox(id, keyword, mentionKeyword, sort, mentionSort, containChildren, notebook)} else {@@ -292,6 +311,11 @@ func getBacklink(c *gin.Context) {// 加密笔记本的反链面板走 InBox 版(查加密 content db)notebook, _ := arg["notebook"].(string)if !isEncryptedNotebookDeniedForPublish(c, notebook) {+ if err := holdEncryptedBoxRequest(c, notebook); err != nil {+ ret.Code = 1+ ret.Msg = err.Error()+ return+ }if notebook != "" && model.IsEncryptedBox(notebook) {boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklinkInBox(id, keyword, mentionKeyword, beforeLen, containChildren, notebook)} else {diff --git a/kernel/api/router.go b/kernel/api/router.goindex 353a3f7523..f4dd5deae3 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -27,6 +27,8 @@ import ()func ServeAPI(ginServer *gin.Engine) {+ ginServer.Use(boxLeaseMiddleware)+// 不需要鉴权ginServer.Handle("GET", "/api/system/bootProgress", bootProgress)@@ -481,7 +483,9 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/bazaar/installBazaarTheme", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, installBazaarTheme)ginServer.Handle("POST", "/api/bazaar/uninstallBazaarTheme", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, uninstallBazaarTheme)ginServer.Handle("POST", "/api/bazaar/getBazaarPackageREADME", model.CheckAuth, getBazaarPackageREADME)+ ginServer.Handle("POST", "/api/bazaar/getInstalledPackageSize", model.CheckAuth, getInstalledPackageSize)ginServer.Handle("POST", "/api/bazaar/getUpdatedPackage", model.CheckAuth, getUpdatedPackage)+ ginServer.Handle("POST", "/api/bazaar/updateBazaarPackage", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, updateBazaarPackage)ginServer.Handle("POST", "/api/bazaar/batchUpdatePackage", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, batchUpdatePackage)ginServer.Handle("POST", "/api/repo/initRepoKey", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, initRepoKey)diff --git a/kernel/api/search.go b/kernel/api/search.goindex cda426b052..c07d359864 100644--- a/kernel/api/search.go+++ b/kernel/api/search.go@@ -200,9 +200,9 @@ func findReplace(c *gin.Context) {boxID := ""if 1 == len(boxes) && model.IsEncryptedBox(boxes[0]) {boxID = boxes[0]- if !model.IsBoxUnlocked(boxID) {+ if err := holdEncryptedBoxRequest(c, boxID); err != nil {ret.Code = 1- ret.Msg = model.Conf.Language(309)+ ret.Msg = err.Error()return}}@@ -478,6 +478,11 @@ func searchRefBlock(c *gin.Context) {}return}+ if err := holdEncryptedBoxRequest(c, notebook); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }isSquareBrackets := falseif isSquareBracketsArg := arg["isSquareBrackets"]; nil != isSquareBracketsArg {@@ -552,9 +557,9 @@ func fullTextSearchBlock(c *gin.Context) {}// 加密笔记本的全文搜索走 InBox 版(查加密 content db + blocks_fts)if notebook != "" && model.IsEncryptedBox(notebook) {- if !model.IsBoxUnlocked(notebook) {+ if err := holdEncryptedBoxRequest(c, notebook); err != nil {ret.Code = -1- ret.Msg = "encrypted notebook locked"+ ret.Msg = err.Error()return}blocks, matchedBlockCount, matchedRootCount, pageCount, docMode = model.FullTextSearchBlockInBoxWithHPathContext(c.Request.Context(), query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize, notebook, searchHPath)diff --git a/kernel/av/av.go b/kernel/av/av.goindex a8fbeb8f8f..ab9cbdcb31 100644--- a/kernel/av/av.go+++ b/kernel/av/av.go@@ -560,6 +560,11 @@ func GetAttributeViewSearchInfoInBox(avID, boxID string) (ret *AttributeViewSearif avJSONPath == "" {return}+ release, lockErr := holdAVBoxReadLock(avBoxID)+ if lockErr != nil {+ return nil, lockErr+ }+ defer release()if cached, ok := cache.GetAVSearchDataInBox[*AttributeViewSearchInfo](avID, avBoxID); ok {return cached, nil@@ -576,7 +581,7 @@ func GetAttributeViewSearchInfoInBox(avID, boxID string) (ret *AttributeViewSearreturn}if avBoxID != "" {- if data, err = decryptAVData(avBoxID, avID, data); err != nil {+ if data, err = decryptAVDataLocked(avBoxID, avID, data); err != nil {logging.LogErrorf("decrypt attribute view [%s] failed: %s", avJSONPath, err)return}@@ -700,6 +705,11 @@ func parseAttributeViewByPathInBox(avJSONPath, boxID string) (ret *AttributeViewerr = ErrViewNotFoundreturn}+ release, lockErr := holdAVBoxReadLock(boxID)+ if lockErr != nil {+ return nil, lockErr+ }+ defer release()avID := filepath.Base(avJSONPath)avID = strings.TrimSuffix(avID, filepath.Ext(avID))@@ -716,7 +726,7 @@ func parseAttributeViewByPathInBox(avJSONPath, boxID string) (ret *AttributeView}// 加密笔记本的 AV 定义是密文,按路径反查 boxID 后解密if boxID != "" {- data, readErr = decryptAVData(boxID, avID, data)+ data, readErr = decryptAVDataLocked(boxID, avID, data)if readErr != nil {logging.LogErrorf("decrypt attribute view [%s] failed: %s", avID, readErr)returndiff --git a/kernel/av/encrypted_hook.go b/kernel/av/encrypted_hook.goindex a829136785..4ee093550d 100644--- a/kernel/av/encrypted_hook.go+++ b/kernel/av/encrypted_hook.go@@ -8,6 +8,7 @@package avimport (+ "errors""os""path/filepath""strings"@@ -36,10 +37,31 @@ var AVEncryptedBoxIDs func() []string// AVIsEncryptedBox 由 model 层注入,判断 boxID 是否为加密笔记本。var AVIsEncryptedBox func(boxID string) bool+// AVIsBoxUnlocked 由 model 层注入,判断加密笔记本是否仍持有 DEK。+var AVIsBoxUnlocked func(boxID string) bool+// AVGetBlockBoxID 由 model 层注入,返回 blockID 所在的 boxID(查 blocktree)。// 用于镜像写入时校验源块与 AV 定义是否处于同一加密边界。var AVGetBlockBoxID func(blockID string) string+func holdAVBoxReadLock(boxID string) (release func(), err error) {+ release = func() {}+ if boxID == "" || AVIsEncryptedBox == nil || !AVIsEncryptedBox(boxID) {+ return+ }+ if AVLockAcquire == nil || AVLockRelease == nil || AVIsBoxUnlocked == nil {+ return nil, errors.New("encrypted notebook lock callbacks are not initialized")+ }+ AVLockAcquire(boxID)+ if !AVIsBoxUnlocked(boxID) {+ AVLockRelease(boxID)+ return nil, errors.New("encrypted notebook is locked, please unlock it first")+ }+ return func() {+ AVLockRelease(boxID)+ }, nil+}+// pendingAVBox 记录首次创建的 AV 归属哪个加密 box。// handler 层创建 AV 前调 SetAVBoxID(avID, boxID),SaveAttributeView 时// findAttributeViewPath 会先查 pending 映射,找到则写入对应加密笔记本路径。@@ -343,11 +365,11 @@ func decryptAVDataLocked(boxID, avID string, data []byte) ([]byte, error) {func avAAD(boxID, avID string) string {switch avID {case "mirror":- return "siyuan:v1:av-mirror:" + boxID+ return "siyuan:av-mirror:" + boxIDcase "relation":- return "siyuan:v1:av-relation:" + boxID+ return "siyuan:av-relation:" + boxIDdefault:- return "siyuan:v1:av:" + boxID + ":" + avID+ return "siyuan:av:" + boxID + ":" + avID}}diff --git a/kernel/conf/notebook_crypto.go b/kernel/conf/notebook_crypto.goindex c4d8d2b29b..ade0b87c3d 100644--- a/kernel/conf/notebook_crypto.go+++ b/kernel/conf/notebook_crypto.go@@ -49,15 +49,7 @@ func NewNotebookCrypto() *NotebookCrypto {// CurrentNotebookCryptoSpec 是当前备份规范版本号。const CurrentNotebookCryptoSpec = 1-// UpgradeSpec 集中处理 NotebookCrypto 备份规范的逐版本升级。-// 当前没有受支持的旧版本迁移;后续新增规范时,应在此按版本顺序完成字段转换,-// 每一步仅在前一版本数据校验成功后推进 Spec,并由调用方持久化升级结果。-func UpgradeSpec(nc *NotebookCrypto) (upgraded bool) {- // 后续升级模式:- // if nc.Spec == 1 {- // // 校验并迁移 v1 → v2。- // nc.Spec = 2- // upgraded = true- // }- return+// UpgradeSpec 当前不执行迁移。+func UpgradeSpec(*NotebookCrypto) bool {+ return false}diff --git a/kernel/filesys/crypto_hook.go b/kernel/filesys/crypto_hook.goindex 56b7b55cea..198a6a4e65 100644--- a/kernel/filesys/crypto_hook.go+++ b/kernel/filesys/crypto_hook.go@@ -118,14 +118,14 @@ func SyObjectBase(relativePath string) (string, error) {return base, nil}-// SyAAD 构造 .sy 密文的 AAD:siyuan:v1:file:<boxID>:<稳定文件基名>。+// SyAAD 构造 .sy 密文的 AAD:siyuan:file:<boxID>:<稳定文件基名>。// 父目录不进 AAD——同 box 内文件名不变的移动允许原样 Rename 密文,内容/box/类型/对象 ID 仍受认证。func SyAAD(boxID, relativePath string) (string, error) {base, err := SyObjectBase(relativePath)if err != nil {return "", err}- return "siyuan:v1:file:" + boxID + ":" + base, nil+ return "siyuan:file:" + boxID + ":" + base, nil}// encryptedBox 判断 boxID 是否为已解锁的加密 box,供 filesys 内部分流(如静默修正禁用)。diff --git a/kernel/filesys/crypto_hook_test.go b/kernel/filesys/crypto_hook_test.goindex 9f58df7eb5..878313862f 100644--- a/kernel/filesys/crypto_hook_test.go+++ b/kernel/filesys/crypto_hook_test.go@@ -97,7 +97,7 @@ func TestSyAADIndependentOfParentDir(t *testing.T) {aadBare, aadWithDir, aadDeepDir, aadWithBackslash, aadWithMixedSeparators)}// AAD 不应包含目录分隔符,只含基名- if strings.ContainsAny(strings.TrimPrefix(aadBare, "siyuan:v1:file:"+boxID+":"), "/\\") {+ if strings.ContainsAny(strings.TrimPrefix(aadBare, "siyuan:file:"+boxID+":"), "/\\") {t.Fatalf("AAD must not contain path separator: %q", aadBare)}}diff --git a/kernel/filesys/stat.go b/kernel/filesys/stat.goindex 3f48b6703b..5b20241ae3 100644--- a/kernel/filesys/stat.go+++ b/kernel/filesys/stat.go@@ -90,6 +90,19 @@ func StatTree(id string) (ret *util.BlockStatResult) {return statTree(tree)}+// StatTreeInBox 只统计指定笔记本边界内的文档。+func StatTreeInBox(id, boxID string) (ret *util.BlockStatResult) {+ bt := treenode.GetBlockTreeInExactBox(id, boxID)+ if bt == nil {+ return nil+ }+ tree, err := LoadTree(bt.BoxID, bt.Path, util.NewLute())+ if err != nil {+ return nil+ }+ return statTree(tree)+}+func statTree(tree *parse.Tree) (ret *util.BlockStatResult) {blockCount := 0var databaseBlockNodes []*ast.Node@@ -117,7 +130,12 @@ func statTree(tree *parse.Tree) (ret *util.BlockStatResult) {continue}- attrView, _ := av.ParseAttributeView(n.AttributeViewID)+ var attrView *av.AttributeView+ if av.AVIsEncryptedBox != nil && av.AVIsEncryptedBox(tree.Box) {+ attrView, _ = av.ParseAttributeViewInBox(n.AttributeViewID, tree.Box)+ } else {+ attrView, _ = av.ParseAttributeView(n.AttributeViewID)+ }if nil == attrView {continue}diff --git a/kernel/mcp/tools/block.go b/kernel/mcp/tools/block.goindex 5505b8585f..eff14c399c 100644--- a/kernel/mcp/tools/block.go+++ b/kernel/mcp/tools/block.go@@ -33,6 +33,7 @@ var BlockTool = &Tool{Type: "object",Properties: map[string]Property{"action": {Type: "string", Description: "Operation", Enum: []string{"get", "get_kramdown", "get_children", "tree_stat", "dom", "insert", "append", "prepend", "update", "delete", "move", "breadcrumb", "batch_get", "batch_kramdown"}},+ "notebook": {Type: "string", Description: "Notebook ID that owns the target blocks; required for encrypted notebooks"},"id": {Type: "string", Description: "Block ID"},"ids": {Type: "string", Description: "Comma-separated block IDs (for batch_get, batch_kramdown)"},"data": {Type: "string", Description: "Content (markdown or dom)"},@@ -95,7 +96,19 @@ func blockGet(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id is required"}}, IsError: true}, nil}- b, err := model.GetBlock(id, nil)+ boxID, release, scopeErr := beginBlockToolScope(args, false, id)+ if scopeErr != nil {+ return blockToolError(scopeErr.Error())+ }+ defer release()++ var b *model.Block+ var err error+ if boxID != "" {+ b, err = model.GetBlockInBox(id, boxID)+ } else {+ b, err = model.GetBlock(id, nil)+ }if err != nil {return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("get block failed: %s", err)}}, IsError: true}, nil}@@ -115,7 +128,13 @@ func blockGetKramdown(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id is required"}}, IsError: true}, nil}- kramdown := model.GetBlockKramdown(id, "md")+ boxID, release, scopeErr := beginBlockToolScope(args, false, id)+ if scopeErr != nil {+ return blockToolError(scopeErr.Error())+ }+ defer release()++ kramdown := model.GetBlockKramdownInBox(id, "md", boxID)if kramdown == "" {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "block not found or empty: " + id}}, IsError: true}, nil}@@ -129,7 +148,13 @@ func blockGetChildren(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id is required"}}, IsError: true}, nil}- children := model.GetChildBlocks(id)+ boxID, release, scopeErr := beginBlockToolScope(args, false, id)+ if scopeErr != nil {+ return blockToolError(scopeErr.Error())+ }+ defer release()++ children := model.GetChildBlocksInBox(id, boxID)if len(children) == 0 {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "no child blocks found"}}}, nil}@@ -164,6 +189,11 @@ func blockInsert(args map[string]any) (CallToolResult, error) {if v, ok := args["nextID"].(string); ok {nextID = v}+ boxID, release, scopeErr := beginBlockToolScope(args, true, parentID, previousID, nextID)+ if scopeErr != nil {+ return blockToolError(scopeErr.Error())+ }+ defer release()// 仅靠 parentID 定位目标时,目标必须是容器块,否则非法嵌套if parentID != "" && previousID == "" && nextID == "" {@@ -201,7 +231,7 @@ func blockInsert(args map[string]any) (CallToolResult, error) {reloadID = parentID}if reloadID != "" {- if bt := treenode.GetBlockTree(reloadID); bt != nil {+ if bt := treenode.GetBlockTreeInExactBox(reloadID, boxID); bt != nil {util.PushReloadProtyle(bt.RootID)}}@@ -218,6 +248,11 @@ func blockAppend(args map[string]any) (CallToolResult, error) {if parentID == "" {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "parentID is required"}}, IsError: true}, nil}+ boxID, release, scopeErr := beginBlockToolScope(args, true, parentID)+ if scopeErr != nil {+ return blockToolError(scopeErr.Error())+ }+ defer release()// append 只用 parentID 定位目标,目标必须是容器块,否则非法嵌套if err := treenode.CheckContainerParent(parentID); err != nil {return CallToolResult{Content: []ContentItem{{Type: "text", Text: err.Error()}}, IsError: true}, nil@@ -242,7 +277,7 @@ func blockAppend(args map[string]any) (CallToolResult, error) {model.PerformTransactions(&transactions)model.FlushTxQueue()- if bt := treenode.GetBlockTree(parentID); bt != nil {+ if bt := treenode.GetBlockTreeInExactBox(parentID, boxID); bt != nil {util.PushReloadProtyle(bt.RootID)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: "block appended"}}}, nil@@ -257,6 +292,11 @@ func blockPrepend(args map[string]any) (CallToolResult, error) {if parentID == "" {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "parentID is required"}}, IsError: true}, nil}+ boxID, release, scopeErr := beginBlockToolScope(args, true, parentID)+ if scopeErr != nil {+ return blockToolError(scopeErr.Error())+ }+ defer release()// prepend 只用 parentID 定位目标,目标必须是容器块,否则非法嵌套if err := treenode.CheckContainerParent(parentID); err != nil {return CallToolResult{Content: []ContentItem{{Type: "text", Text: err.Error()}}, IsError: true}, nil@@ -281,7 +321,7 @@ func blockPrepend(args map[string]any) (CallToolResult, error) {model.PerformTransactions(&transactions)model.FlushTxQueue()- if bt := treenode.GetBlockTree(parentID); bt != nil {+ if bt := treenode.GetBlockTreeInExactBox(parentID, boxID); bt != nil {util.PushReloadProtyle(bt.RootID)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: "block prepended"}}}, nil@@ -297,6 +337,11 @@ func blockUpdate(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "data is required"}}, IsError: true}, nil}lockType, _ := args["lockType"].(bool)+ _, release, scopeErr := beginBlockToolScope(args, true, id)+ if scopeErr != nil {+ return blockToolError(scopeErr.Error())+ }+ defer release()_, rootIDs, err := model.PerformBlockUpdates([]model.BlockUpdateInput{{ID: id,@@ -320,7 +365,13 @@ func blockDelete(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id is required"}}, IsError: true}, nil}- bt := treenode.GetBlockTree(id)+ boxID, release, scopeErr := beginBlockToolScope(args, true, id)+ if scopeErr != nil {+ return blockToolError(scopeErr.Error())+ }+ defer release()++ bt := treenode.GetBlockTreeInExactBox(id, boxID)transactions := []*model.Transaction{{DoOperations: []*model.Operation{{@@ -367,6 +418,11 @@ func blockMove(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "parentID is required"}}, IsError: true}, nil}previousID, _ := args["previousID"].(string)+ boxID, release, scopeErr := beginBlockToolScope(args, true, id, parentID, previousID)+ if scopeErr != nil {+ return blockToolError(scopeErr.Error())+ }+ defer release()// 仅靠 parentID 定位目标时(无 previousID),目标必须是容器块,否则 doMove parent-only 分支会形成非法嵌套if previousID == "" {@@ -390,7 +446,7 @@ func blockMove(args map[string]any) (CallToolResult, error) {model.PerformTransactions(&transactions)model.FlushTxQueue()- if bt := treenode.GetBlockTree(id); bt != nil {+ if bt := treenode.GetBlockTreeInExactBox(id, boxID); bt != nil {util.PushReloadProtyle(bt.RootID)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: "block moved: " + id}}}, nil@@ -402,7 +458,13 @@ func blockBreadcrumb(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id is required"}}, IsError: true}, nil}- paths, err := model.BuildBlockBreadcrumb(id, nil)+ boxID, release, scopeErr := beginBlockToolScope(args, false, id)+ if scopeErr != nil {+ return blockToolError(scopeErr.Error())+ }+ defer release()++ paths, err := model.BuildBlockBreadcrumbInBox(id, nil, boxID)if err != nil {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "breadcrumb failed: " + err.Error()}}, IsError: true}, nil}@@ -419,7 +481,13 @@ func blockTreeStat(args map[string]any) (CallToolResult, error) {if id == "" {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id is required"}}, IsError: true}, nil}- stat := filesys.StatTree(id)+ boxID, release, scopeErr := beginBlockToolScope(args, false, id)+ if scopeErr != nil {+ return blockToolError(scopeErr.Error())+ }+ defer release()++ stat := filesys.StatTreeInBox(id, boxID)if stat == nil {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "document not found or empty"}}, IsError: true}, nil}@@ -433,7 +501,13 @@ func blockDom(args map[string]any) (CallToolResult, error) {if id == "" {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id is required"}}, IsError: true}, nil}- dom := model.GetBlockDOM(id)+ boxID, release, scopeErr := beginBlockToolScope(args, false, id)+ if scopeErr != nil {+ return blockToolError(scopeErr.Error())+ }+ defer release()++ dom := model.GetBlockDOMInBox(id, boxID)if dom == "" {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "block not found or empty: " + id}}, IsError: true}, nil}@@ -455,7 +529,23 @@ func blockBatchGet(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "no valid IDs provided"}}, IsError: true}, nil}- infos := model.GetDocsInfo(ids, false, false)+ boxID, release, scopeErr := beginBlockToolScope(args, false, ids...)+ if scopeErr != nil {+ return blockToolError(scopeErr.Error())+ }+ defer release()++ var infos []*model.BlockInfo+ if boxID == "" {+ infos = model.GetDocsInfo(ids, false, false)+ } else {+ for _, id := range ids {+ info, err := model.GetDocInfoInBox(id, boxID)+ if err == nil && info != nil {+ infos = append(infos, info)+ }+ }+ }var sb strings.Buildersb.WriteString(fmt.Sprintf("Batch get %d blocks (found %d):\n\n", len(ids), len(infos)))@@ -493,7 +583,13 @@ func blockBatchKramdown(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "no valid IDs provided"}}, IsError: true}, nil}- kramdowns := model.GetBlockKramdowns(ids, "md")+ boxID, release, scopeErr := beginBlockToolScope(args, false, ids...)+ if scopeErr != nil {+ return blockToolError(scopeErr.Error())+ }+ defer release()++ kramdowns := model.GetBlockKramdownsInBox(ids, "md", boxID)var sb strings.Buildersb.WriteString(fmt.Sprintf("Batch kramdown %d blocks (found %d):\n\n", len(ids), len(kramdowns)))@@ -507,3 +603,60 @@ func blockBatchKramdown(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}++func beginBlockToolScope(args map[string]any, mutation bool, ids ...string) (boxID string, release func(), err error) {+ release = func() {}+ notebook, _ := args["notebook"].(string)+ notebook = strings.TrimSpace(notebook)+ encrypted := notebook != "" && model.IsEncryptedBox(notebook)+ if encrypted {+ model.HoldBoxReadLock(notebook)+ if !model.IsBoxUnlocked(notebook) {+ model.ReleaseBoxReadLock(notebook)+ return "", release, fmt.Errorf("encrypted notebook is locked, please unlock it first")+ }+ release = func() {+ model.ReleaseBoxReadLock(notebook)+ }+ boxID = notebook+ }++ fail := func(format string, values ...any) (string, func(), error) {+ release()+ return "", func() {}, fmt.Errorf(format, values...)+ }+ for _, id := range ids {+ if id == "" {+ continue+ }+ queryBoxID := ""+ if encrypted {+ queryBoxID = notebook+ }+ bt := treenode.GetBlockTreeInExactBox(id, queryBoxID)+ if bt == nil || (notebook != "" && bt.BoxID != notebook) {+ if notebook == "" {+ return fail("block %s was not found in a normal notebook; provide notebook for encrypted targets", id)+ }+ return fail("block %s does not belong to notebook %s", id, notebook)+ }+ if mutation && encrypted {+ if treenode.GetBlockTreeInExactBox(id, "") != nil {+ return fail("block ID %s is ambiguous across notebook boundaries", id)+ }+ for _, openedBoxID := range treenode.GetOpenedEncryptedBoxIDs() {+ if openedBoxID != notebook && treenode.GetBlockTreeInExactBox(id, openedBoxID) != nil {+ return fail("block ID %s is ambiguous across notebook boundaries", id)+ }+ }+ }+ }+ return+}++func blockToolError(message string) (CallToolResult, error) {+ return CallToolResult{+ Content: []ContentItem{{Type: "text", Text: message}},+ IsError: true,+ }, nil+}diff --git a/kernel/mcp/tools/search.go b/kernel/mcp/tools/search.goindex 16870dc77a..0431f4c0ef 100644--- a/kernel/mcp/tools/search.go+++ b/kernel/mcp/tools/search.go@@ -110,9 +110,33 @@ func fulltextSearch(args map[string]any) (CallToolResult, error) {groupBy = int(v)}- blocks, matchedCount, matchedRootCount, pageCount, docMode := model.FullTextSearchBlock(- query, notebooks, paths, types, subtypes, method, orderBy, groupBy, page, pageSize,- )+ var blocks []*model.Block+ var matchedCount, matchedRootCount, pageCount int+ var docMode bool+ encryptedNotebook := encryptedSearchNotebook(notebooks)+ if encryptedNotebook != "" {+ if len(notebooks) != 1 {+ return CallToolResult{+ Content: []ContentItem{{Type: "text", Text: "encrypted full-text search must target exactly one notebook"}},+ IsError: true,+ }, nil+ }+ model.HoldBoxReadLock(encryptedNotebook)+ defer model.ReleaseBoxReadLock(encryptedNotebook)+ if !model.IsBoxUnlocked(encryptedNotebook) {+ return CallToolResult{+ Content: []ContentItem{{Type: "text", Text: "encrypted notebook is locked, please unlock it first"}},+ IsError: true,+ }, nil+ }+ blocks, matchedCount, matchedRootCount, pageCount, docMode = model.FullTextSearchBlockInBox(+ query, notebooks, paths, types, subtypes, method, orderBy, groupBy, page, pageSize, encryptedNotebook,+ )+ } else {+ blocks, matchedCount, matchedRootCount, pageCount, docMode = model.FullTextSearchBlock(+ query, notebooks, paths, types, subtypes, method, orderBy, groupBy, page, pageSize,+ )+ }if matchedCount == 0 {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "No results found."}}}, nil@@ -156,6 +180,12 @@ func semanticSearch(args map[string]any) (CallToolResult, error) {}notebooks := parseStringSlice(args["notebook"])+ if encryptedSearchNotebook(notebooks) != "" {+ return CallToolResult{+ Content: []ContentItem{{Type: "text", Text: "semantic search is not available for encrypted notebooks"}},+ IsError: true,+ }, nil+ }paths := parseStringSlice(args["path"])types := parseStringSet(args["type"])subtypes := parseStringSet(args["subtype"])@@ -305,3 +335,12 @@ func parseStringSet(v any) map[string]bool {}return m}++func encryptedSearchNotebook(notebooks []string) string {+ for _, notebook := range notebooks {+ if model.IsEncryptedBox(notebook) {+ return notebook+ }+ }+ return ""+}diff --git a/kernel/model/block.go b/kernel/model/block.goindex 9567700f92..9632115537 100644--- a/kernel/model/block.go+++ b/kernel/model/block.go@@ -1259,12 +1259,23 @@ type ChildBlock struct {}func GetChildBlocks(id string) (ret []*ChildBlock) {+ return GetChildBlocksInBox(id, "")+}++// GetChildBlocksInBox 返回指定笔记本边界内的直接子块。+func GetChildBlocksInBox(id, boxID string) (ret []*ChildBlock) {ret = []*ChildBlock{}if "" == id {return}- tree, err := LoadTreeByBlockID(id)+ var tree *parse.Tree+ var err error+ if boxID == "" {+ tree, err = LoadTreeByBlockID(id)+ } else {+ tree, err = LoadTreeByBlockIDInExactBox(id, boxID)+ }if err != nil {return}@@ -1311,12 +1322,23 @@ func GetChildBlocks(id string) (ret []*ChildBlock) {}func GetTailChildBlocks(id string, n int) (ret []*ChildBlock) {+ return GetTailChildBlocksInBox(id, n, "")+}++// GetTailChildBlocksInBox 返回指定笔记本边界内末尾的子块。+func GetTailChildBlocksInBox(id string, n int, boxID string) (ret []*ChildBlock) {ret = []*ChildBlock{}if "" == id {return}- tree, err := LoadTreeByBlockID(id)+ var tree *parse.Tree+ var err error+ if boxID == "" {+ tree, err = LoadTreeByBlockID(id)+ } else {+ tree, err = LoadTreeByBlockIDInExactBox(id, boxID)+ }if err != nil {return}@@ -1375,6 +1397,15 @@ func GetBlock(id string, tree *parse.Tree) (ret *Block, err error) {return}+// GetBlockInBox 返回指定笔记本边界内的块。+func GetBlockInBox(id, boxID string) (ret *Block, err error) {+ tree, err := LoadTreeByBlockIDInExactBox(id, boxID)+ if err != nil {+ return nil, err+ }+ return getBlock(id, tree)+}+func getBlock(id string, tree *parse.Tree) (ret *Block, err error) {if "" == id {returndiff --git a/kernel/model/blockinfo.go b/kernel/model/blockinfo.goindex 14728612b7..fc2ad703c2 100644--- a/kernel/model/blockinfo.go+++ b/kernel/model/blockinfo.go@@ -126,7 +126,13 @@ func GetDocInfoInBox(blockID, boxID string) (ret *BlockInfo, err error) {continue}- avName, getErr := av.GetAttributeViewName(avID)+ var avName string+ var getErr error+ if boxID != "" && IsEncryptedBox(boxID) {+ avName, getErr = av.GetAttributeViewNameInBox(avID, boxID)+ } else {+ avName, getErr = av.GetAttributeViewName(avID)+ }if nil != getErr {continue}diff --git a/kernel/model/crypto.go b/kernel/model/crypto.goindex c7d58d5778..968a3cd3ee 100644--- a/kernel/model/crypto.go+++ b/kernel/model/crypto.go@@ -47,7 +47,7 @@ import ()// kekVerifierMagic 是写入 KEKVerifier 的固定魔数。启用时用 KEK 加密它,校验主密码时解密比对。-var kekVerifierMagic = []byte("siyuan-enc-v1")+var kekVerifierMagic = []byte("siyuan-encrypted-notebook")const boxEncryptionSpec = 1@@ -256,7 +256,7 @@ func ImportNotebookCryptoBackup(data []byte, password string) error {if !verifyKEKMAC(nc, kek) {return errors.New(Conf.Language(317))}- decrypted, dErr := util.DecryptWithAAD(kek, nc.KEKVerifier, []byte("siyuan:v1:kek-verifier"))+ decrypted, dErr := util.DecryptWithAAD(kek, nc.KEKVerifier, []byte("siyuan:kek-verifier"))if dErr != nil || string(decrypted) != string(kekVerifierMagic) {return errors.New(Conf.Language(311)) // 主密码错误}@@ -719,7 +719,7 @@ func EnableEncryptedNotebook(password string) error {defer zeroAndClear(kek)// 用 KEK 加密固定魔数作为校验值,落盘后供后续 UnlockBox 离线校验- verifierCT, err := util.EncryptWithAAD(kek, kekVerifierMagic, []byte("siyuan:v1:kek-verifier"))+ verifierCT, err := util.EncryptWithAAD(kek, kekVerifierMagic, []byte("siyuan:kek-verifier"))if err != nil {return err}@@ -866,7 +866,7 @@ func deriveNotebookCryptoBackupCandidate(password string) (backup *conf.Notebookreturn nil, nil, errors.New(Conf.Language(317))}kek = util.DeriveKey(password, backup.MasterSalt, params)- decrypted, decryptErr := util.DecryptWithAAD(kek, backup.KEKVerifier, []byte("siyuan:v1:kek-verifier"))+ decrypted, decryptErr := util.DecryptWithAAD(kek, backup.KEKVerifier, []byte("siyuan:kek-verifier"))if decryptErr != nil || string(decrypted) != string(kekVerifierMagic) {zeroAndClear(kek)return nil, nil, errors.New(Conf.Language(311))@@ -905,7 +905,7 @@ func deriveKEK(password string) ([]byte, error) {}kek := util.DeriveKey(password, nc.MasterSalt, params)- decrypted, err := util.DecryptWithAAD(kek, nc.KEKVerifier, []byte("siyuan:v1:kek-verifier"))+ decrypted, err := util.DecryptWithAAD(kek, nc.KEKVerifier, []byte("siyuan:kek-verifier"))localPasswordValid := err == nil && string(decrypted) == string(kekVerifierMagic)mig, migErr := readMasterPasswordMigration()if !localPasswordValid {@@ -1090,9 +1090,9 @@ func IsBoxUnlocked(boxID string) bool {func LockBox(boxID string) {FlushTxQueue()acquireBoxWriteLock(boxID)+ defer releaseBoxWriteLock(boxID)lockBoxHeld(boxID)- releaseBoxWriteLock(boxID)- // 单 box 锁定后需要刷新全局缓存(树/Block/IAL/AV)+ // 单 box 锁定时需要在写锁保护下刷新全局缓存,避免锁定与缓存读取之间出现明文窗口。cache.ClearTreeCache()sql.ClearCache()cache.ClearDocsIAL()@@ -1178,13 +1178,10 @@ func WrapNewDEK(boxID string, kek []byte) (*conf.BoxEncryption, []byte, error) {}func wrappedDEKAAD(boxID string) []byte {- return []byte("siyuan:v1:wrapped-dek:" + boxID)+ return []byte("siyuan:wrapped-dek:" + boxID)}func decryptWrappedDEK(boxID string, enc *conf.BoxEncryption, kek []byte) ([]byte, error) {- if enc.Spec >= boxEncryptionSpec {- return util.DecryptWithAAD(kek, enc.WrappedDEK, wrappedDEKAAD(boxID))- }return util.DecryptWithAAD(kek, enc.WrappedDEK, wrappedDEKAAD(boxID))}@@ -1260,7 +1257,7 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {}newKEK := util.DeriveKey(newPassword, nc.MasterSalt, params)defer zeroAndClear(newKEK)- newVerifier, err := util.EncryptWithAAD(newKEK, kekVerifierMagic, []byte("siyuan:v1:kek-verifier"))+ newVerifier, err := util.EncryptWithAAD(newKEK, kekVerifierMagic, []byte("siyuan:kek-verifier"))if err != nil {return err}diff --git a/kernel/model/crypto_test.go b/kernel/model/crypto_test.goindex 2597d24e63..c699a58993 100644--- a/kernel/model/crypto_test.go+++ b/kernel/model/crypto_test.go@@ -373,7 +373,7 @@ func TestDeriveKEKRejectsTamperedBackupMAC(t *testing.T) {salt, _ := util.GenerateSalt()params := util.DefaultArgon2Params()kek := util.DeriveKey(password, salt, params)- verifier, _ := util.EncryptWithAAD(kek, kekVerifierMagic, []byte("siyuan:v1:kek-verifier"))+ verifier, _ := util.EncryptWithAAD(kek, kekVerifierMagic, []byte("siyuan:kek-verifier"))nc := conf.NotebookCrypto{Enabled: true,MasterSalt: salt,@@ -415,7 +415,7 @@ func TestDeriveKEKAllowsLocalAutoLockChange(t *testing.T) {params := util.DefaultArgon2Params()kek := util.DeriveKey(password, salt, params)defer zeroAndClear(kek)- verifier, _ := util.EncryptWithAAD(kek, kekVerifierMagic, []byte("siyuan:v1:kek-verifier"))+ verifier, _ := util.EncryptWithAAD(kek, kekVerifierMagic, []byte("siyuan:kek-verifier"))backup := &conf.NotebookCrypto{Enabled: true,MasterSalt: salt,@@ -451,7 +451,7 @@ func TestDeriveKEKKeepsAuthenticatedLocalCandidateWithDifferentBackup(t *testingparams := util.DefaultArgon2Params()localKEK := util.DeriveKey(localPassword, localSalt, params)defer zeroAndClear(localKEK)- localVerifier, _ := util.EncryptWithAAD(localKEK, kekVerifierMagic, []byte("siyuan:v1:kek-verifier"))+ localVerifier, _ := util.EncryptWithAAD(localKEK, kekVerifierMagic, []byte("siyuan:kek-verifier"))local := &conf.NotebookCrypto{Enabled: true,MasterSalt: localSalt,@@ -467,7 +467,7 @@ func TestDeriveKEKKeepsAuthenticatedLocalCandidateWithDifferentBackup(t *testingbackupSalt, _ := util.GenerateSalt()backupKEK := util.DeriveKey(backupPassword, backupSalt, params)defer zeroAndClear(backupKEK)- backupVerifier, _ := util.EncryptWithAAD(backupKEK, kekVerifierMagic, []byte("siyuan:v1:kek-verifier"))+ backupVerifier, _ := util.EncryptWithAAD(backupKEK, kekVerifierMagic, []byte("siyuan:kek-verifier"))backup := &conf.NotebookCrypto{Enabled: true,MasterSalt: backupSalt,@@ -511,7 +511,7 @@ func TestDeriveKEKAdoptsCompleteSynchronizedCandidate(t *testing.T) {params := util.DefaultArgon2Params()newKEK := util.DeriveKey(newPassword, newSalt, params)defer zeroAndClear(newKEK)- newVerifier, _ := util.EncryptWithAAD(newKEK, kekVerifierMagic, []byte("siyuan:v1:kek-verifier"))+ newVerifier, _ := util.EncryptWithAAD(newKEK, kekVerifierMagic, []byte("siyuan:kek-verifier"))newConfig := &conf.NotebookCrypto{Enabled: true,MasterSalt: newSalt,@@ -539,7 +539,7 @@ func TestDeriveKEKAdoptsCompleteSynchronizedCandidate(t *testing.T) {oldSalt, _ := util.GenerateSalt()oldKEK := util.DeriveKey("old-device-password", oldSalt, params)defer zeroAndClear(oldKEK)- oldVerifier, _ := util.EncryptWithAAD(oldKEK, kekVerifierMagic, []byte("siyuan:v1:kek-verifier"))+ oldVerifier, _ := util.EncryptWithAAD(oldKEK, kekVerifierMagic, []byte("siyuan:kek-verifier"))localConfig := &conf.NotebookCrypto{Enabled: true,MasterSalt: oldSalt,@@ -598,7 +598,7 @@ func TestBackupMACRoundTrip(t *testing.T) {kek := util.DeriveKey(password, salt, params)defer zeroAndClear(kek)- verifierCT, _ := util.EncryptWithAAD(kek, kekVerifierMagic, []byte("siyuan:v1:kek-verifier"))+ verifierCT, _ := util.EncryptWithAAD(kek, kekVerifierMagic, []byte("siyuan:kek-verifier"))nc := &conf.NotebookCrypto{Enabled: true,MasterSalt: salt,@@ -776,7 +776,7 @@ func TestEnabledWithoutBackupReturnsRecoveryError(t *testing.T) {defer zeroAndClear(kek)// 构造本机已启用、本机 verifier 有效的配置(主密码能派生出可用 KEK),但不写备份文件- verifierCT, _ := util.EncryptWithAAD(kek, kekVerifierMagic, []byte("siyuan:v1:kek-verifier"))+ verifierCT, _ := util.EncryptWithAAD(kek, kekVerifierMagic, []byte("siyuan:kek-verifier"))nc := &conf.NotebookCrypto{Enabled: true,MasterSalt: salt,diff --git a/kernel/model/encrypted_export.go b/kernel/model/encrypted_export.goindex a60d003574..59a33b6465 100644--- a/kernel/model/encrypted_export.go+++ b/kernel/model/encrypted_export.go@@ -57,12 +57,16 @@ type MobileExportLease struct {type mobileExportLeaseState struct {boxID stringcleanupDir string+ expiresAt time.Time+ timer *time.Timer}+var mobileExportLeaseTTL = 30 * time.Minute+var mobileExportLeases = struct {sync.Mutex- leases map[string]mobileExportLeaseState-}{leases: map[string]mobileExportLeaseState{}}+ leases map[string]*mobileExportLeaseState+}{leases: map[string]*mobileExportLeaseState{}}func newManagedEncryptedExportID() (string, error) {random := make([]byte, 16)@@ -359,14 +363,30 @@ func registerMobileExportLeaseWithID(leaseID, boxID, artifact, name, cleanupDirif info.IsDir() {return nil, fmt.Errorf("export artifact [%s] is a directory", artifact)}+ state := &mobileExportLeaseState{+ boxID: boxID,+ cleanupDir: cleanupDir,+ expiresAt: time.Now().Add(mobileExportLeaseTTL),+ }mobileExportLeases.Lock()- mobileExportLeases.leases[leaseID] = mobileExportLeaseState{boxID: boxID, cleanupDir: cleanupDir}+ if _, exists := mobileExportLeases.leases[leaseID]; exists {+ mobileExportLeases.Unlock()+ return nil, fmt.Errorf("mobile export lease [%s] already exists", leaseID)+ }+ mobileExportLeases.leases[leaseID] = state+ state.timer = time.AfterFunc(mobileExportLeaseTTL, func() {+ releaseMobileExportLease(leaseID, true)+ })mobileExportLeases.Unlock()return &MobileExportLease{ID: leaseID, Path: artifact, Name: name, Size: info.Size()}, nil}// ReleaseMobileExportLease 释放移动端导出租约;重复调用不会产生副作用。func ReleaseMobileExportLease(leaseID string) {+ releaseMobileExportLease(leaseID, false)+}++func releaseMobileExportLease(leaseID string, expired bool) {mobileExportLeases.Lock()state, ok := mobileExportLeases.leases[leaseID]if ok {@@ -376,6 +396,9 @@ func ReleaseMobileExportLease(leaseID string) {if !ok {return}+ if state.timer != nil {+ state.timer.Stop()+ }if state.cleanupDir != "" {if err := os.RemoveAll(state.cleanupDir); err != nil {logging.LogWarnf("remove mobile export lease [%s] failed: %s", leaseID, err)@@ -384,4 +407,7 @@ func ReleaseMobileExportLease(leaseID string) {if state.boxID != "" {ReleaseBoxReadLock(state.boxID)}+ if expired {+ logging.LogWarnf("mobile export lease [%s] expired at [%s]", leaseID, state.expiresAt.Format(time.RFC3339))+ }}diff --git a/kernel/model/encrypted_export_test.go b/kernel/model/encrypted_export_test.goindex 0b08c1a483..fc56dc3240 100644--- a/kernel/model/encrypted_export_test.go+++ b/kernel/model/encrypted_export_test.go@@ -5,6 +5,7 @@ import ("os""path/filepath""testing"+ "time""github.com/88250/gulu""github.com/siyuan-note/siyuan/kernel/conf"@@ -72,6 +73,50 @@ func TestMobileExportLeaseRejectsTraversal(t *testing.T) {}}+func TestMobileExportLeaseExpiresAndReleasesBoxLock(t *testing.T) {+ originalTTL := mobileExportLeaseTTL+ mobileExportLeaseTTL = 20 * time.Millisecond+ defer func() {+ mobileExportLeaseTTL = originalTTL+ }()++ cleanupDir := t.TempDir()+ artifact := filepath.Join(cleanupDir, "export.zip")+ if err := os.WriteFile(artifact, []byte("plaintext"), 0600); err != nil {+ t.Fatal(err)+ }+ boxID := "20260731170000-lease01"+ HoldBoxReadLock(boxID)+ lease, err := registerMobileExportLeaseWithID("expiring-lease", boxID, artifact, "export.zip", cleanupDir)+ if err != nil {+ ReleaseBoxReadLock(boxID)+ t.Fatal(err)+ }++ writerAcquired := make(chan struct{})+ go func() {+ acquireBoxWriteLock(boxID)+ close(writerAcquired)+ releaseBoxWriteLock(boxID)+ }()+ select {+ case <-writerAcquired:+ case <-time.After(2 * time.Second):+ ReleaseMobileExportLease(lease.ID)+ t.Fatal("expired mobile export lease did not release the box read lock")+ }++ mobileExportLeases.Lock()+ _, exists := mobileExportLeases.leases[lease.ID]+ mobileExportLeases.Unlock()+ if exists {+ t.Fatal("expired mobile export lease remained registered")+ }+ if _, statErr := os.Stat(cleanupDir); !os.IsNotExist(statErr) {+ t.Fatalf("expired mobile export lease did not remove plaintext directory: %v", statErr)+ }+}+func TestMobileExportLeaseStreamsEncryptedAsset(t *testing.T) {originalDataDir := util.DataDiroriginalTempDir := util.TempDirdiff --git a/kernel/model/filesys_init.go b/kernel/model/filesys_init.goindex 991c633ee6..27a5de53e6 100644--- a/kernel/model/filesys_init.go+++ b/kernel/model/filesys_init.go@@ -36,6 +36,7 @@ func init() {av.AVLockRelease = ReleaseBoxReadLockav.AVEncryptedBoxIDs = treenode.GetOpenedEncryptedBoxIDsav.AVIsEncryptedBox = IsEncryptedBox+ av.AVIsBoxUnlocked = IsBoxUnlockedav.AVGetBlockBoxID = func(blockID string) string {bt := treenode.GetBlockTree(blockID)if nil == bt {@@ -44,6 +45,7 @@ func init() {return bt.BoxID}sql.IsEncryptedBoxFn = IsEncryptedBox+ sql.IsBoxUnlockedFn = IsBoxUnlockedtreenode.IsEncryptedBoxFn = IsEncryptedBoxutil.ReloadDocInfoGuard = func(boxID string) bool {// 加密笔记本锁定后丢弃延迟 reloadDocInfo 广播,防止明文元数据泄漏diff --git a/kernel/model/tree.go b/kernel/model/tree.goindex 89a4e348b9..c737c77aa2 100644--- a/kernel/model/tree.go+++ b/kernel/model/tree.go@@ -254,6 +254,18 @@ func LoadTreeByBlockID(id string) (ret *parse.Tree, err error) {return loadTreeByBlockIDInBox(id, "")}+// LoadTreeByBlockIDInExactBox 只在指定笔记本边界内加载块所在文档,boxID 为空时不遍历加密笔记本。+func LoadTreeByBlockIDInExactBox(id, boxID string) (ret *parse.Tree, err error) {+ if !ast.IsNodeIDPattern(id) {+ return nil, ErrTreeNotFound+ }+ bt := treenode.GetBlockTreeInExactBox(id, boxID)+ if bt == nil {+ return nil, ErrTreeNotFound+ }+ return loadTreeByBlockTree(bt)+}+func loadTreeByBlockIDWithoutNotFoundLog(id string) (ret *parse.Tree, err error) {return loadTreeByBlockIDInBox0(id, "", false)}diff --git a/kernel/server/serve.go b/kernel/server/serve.goindex d7ebc3442e..5343ef7b8c 100644--- a/kernel/server/serve.go+++ b/kernel/server/serve.go@@ -931,9 +931,26 @@ func serveAssets(ginServer *gin.Engine) {func serveSVG(context *gin.Context, assetAbsPath string) bool {if strings.HasSuffix(assetAbsPath, ".svg") {- data, err := readAssetBytes(assetAbsPath)+ boxID := model.ExtractBoxIDFromAssetsPath(assetAbsPath)+ var dek []byte+ if boxID != "" && model.IsEncryptedBox(boxID) {+ model.HoldBoxReadLock(boxID)+ var err error+ dek, err = model.GetDEKIfUnlocked(boxID)+ if err != nil {+ model.ReleaseBoxReadLock(boxID)+ context.Status(http.StatusForbidden)+ return true+ }+ defer model.ReleaseBoxReadLock(boxID)+ }+ data, err := readAssetBytesLocked(assetAbsPath, boxID, dek)if err != nil {logging.LogErrorf("read svg file failed: %s", err)+ if boxID != "" && model.IsEncryptedBox(boxID) {+ context.Status(http.StatusInternalServerError)+ return true+ }return false}@@ -956,20 +973,13 @@ func serveSVG(context *gin.Context, assetAbsPath string) bool {return false}-// readAssetBytes 读取 asset 文件字节。加密笔记本的 asset 是密文,自动解密后返回明文。-func readAssetBytes(absPath string) ([]byte, error) {+// readAssetBytesLocked 读取 asset 文件字节;读取加密笔记本资源时调用方必须持有对应的 box 读锁。+func readAssetBytesLocked(absPath, boxID string, dek []byte) ([]byte, error) {data, err := os.ReadFile(absPath)if err != nil {return nil, err}- if boxID := model.ExtractBoxIDFromAssetsPath(absPath); boxID != "" && model.IsEncryptedBox(boxID) {- model.HoldBoxReadLock(boxID)- dek, dekErr := model.GetDEKIfUnlocked(boxID)- if dekErr != nil {- model.ReleaseBoxReadLock(boxID)- return nil, dekErr- }- defer model.ReleaseBoxReadLock(boxID)+ if boxID != "" && model.IsEncryptedBox(boxID) {diskName := filepath.Base(absPath)plain, decErr := model.DecryptAsset(boxID, diskName, dek, data)if decErr != nil {diff --git a/kernel/sql/cache.go b/kernel/sql/cache.goindex 25afcd6d66..d3c79898e6 100644--- a/kernel/sql/cache.go+++ b/kernel/sql/cache.go@@ -59,6 +59,11 @@ type blockCacheEntry struct {block *Block}+func encryptedBoxCacheUnavailable(boxID string) bool {+ return IsEncryptedBoxFn != nil && IsEncryptedBoxFn(boxID) &&+ (IsBoxUnlockedFn == nil || !IsBoxUnlockedFn(boxID))+}+// blockCacheKey 为加密笔记本使用 box 维度缓存键;普通笔记本保持原有全局键,避免影响既有查询路径。func blockCacheKey(id, boxID string) string {if IsEncryptedBoxFn != nil && IsEncryptedBoxFn(boxID) {@@ -76,7 +81,7 @@ func ClearCache() {}func putBlockCache(block *Block) {- if cacheDisabled {+ if cacheDisabled || encryptedBoxCacheUnavailable(block.Box) {return}@@ -99,7 +104,7 @@ func getBlockCache(id string) (ret *Block) {}func getBlockCacheInBox(id, boxID string) (ret *Block) {- if cacheDisabled {+ if cacheDisabled || encryptedBoxCacheUnavailable(boxID) {return}@@ -156,6 +161,9 @@ func GetRefsCacheByDefID(defID string) (ret []*Ref) {}func GetRefsCacheByDefIDInBox(defID, boxID string) (ret []*Ref) {+ if encryptedBoxCacheUnavailable(boxID) {+ return+ }key := refCacheKey(defID, boxID)for k, refs := range defIDRefsCache.Items() {if k == key {@@ -183,6 +191,9 @@ func CacheRef(tree *parse.Tree, refNode *ast.Node) {}func putRefCache(boxID string, ref *Ref) {+ if encryptedBoxCacheUnavailable(boxID) {+ return+ }key := refCacheKey(ref.DefBlockID, boxID)defBlockRefs, ok := defIDRefsCache.Get(key)if !ok {diff --git a/kernel/sql/cache_test.go b/kernel/sql/cache_test.goindex d5e6a64771..82f82956e5 100644--- a/kernel/sql/cache_test.go+++ b/kernel/sql/cache_test.go@@ -22,9 +22,11 @@ import "testing"func TestBlockCacheIsolatedByEncryptedBox(t *testing.T) {originalDisabled := cacheDisabledoriginalIsEncryptedBoxFn := IsEncryptedBoxFn+ originalIsBoxUnlockedFn := IsBoxUnlockedFndefer func() {cacheDisabled = originalDisabledIsEncryptedBoxFn = originalIsEncryptedBoxFn+ IsBoxUnlockedFn = originalIsBoxUnlockedFnClearCache()}()@@ -32,6 +34,9 @@ func TestBlockCacheIsolatedByEncryptedBox(t *testing.T) {IsEncryptedBoxFn = func(boxID string) bool {return boxID == "encrypted-a" || boxID == "encrypted-b"}+ IsBoxUnlockedFn = func(boxID string) bool {+ return boxID == "encrypted-a" || boxID == "encrypted-b"+ }ClearCache()putBlockCache(&Block{ID: "shared-id", Box: "encrypted-a", Content: "secret-a"})@@ -61,3 +66,41 @@ func TestBlockCacheIsolatedByEncryptedBox(t *testing.T) {t.Fatalf("encrypted-b cache entry was not removed: %#v", block)}}++func TestEncryptedBlockCacheUnavailableAfterLock(t *testing.T) {+ originalDisabled := cacheDisabled+ originalIsEncryptedBoxFn := IsEncryptedBoxFn+ originalIsBoxUnlockedFn := IsBoxUnlockedFn+ defer func() {+ cacheDisabled = originalDisabled+ IsEncryptedBoxFn = originalIsEncryptedBoxFn+ IsBoxUnlockedFn = originalIsBoxUnlockedFn+ ClearCache()+ }()++ unlocked := true+ cacheDisabled = false+ IsEncryptedBoxFn = func(boxID string) bool {+ return boxID == "encrypted"+ }+ IsBoxUnlockedFn = func(boxID string) bool {+ return boxID != "encrypted" || unlocked+ }+ ClearCache()++ putBlockCache(&Block{ID: "secret", Box: "encrypted", Content: "plaintext"})+ blockCache.Wait()+ if block := getBlockCacheInBox("secret", "encrypted"); block == nil {+ t.Fatal("expected cache hit while encrypted notebook is unlocked")+ }++ unlocked = false+ if block := getBlockCacheInBox("secret", "encrypted"); block != nil {+ t.Fatalf("locked encrypted notebook returned cached plaintext: %#v", block)+ }+ putBlockCache(&Block{ID: "other", Box: "encrypted", Content: "plaintext"})+ blockCache.Wait()+ if block := getBlockCacheInBox("other", "encrypted"); block != nil {+ t.Fatalf("locked encrypted notebook accepted cached plaintext: %#v", block)+ }+}diff --git a/kernel/sql/database.go b/kernel/sql/database.goindex 542a690429..4969719248 100644--- a/kernel/sql/database.go+++ b/kernel/sql/database.go@@ -65,6 +65,9 @@ var (// sql 包不直接 import model(循环依赖),路由函数据此 fail-closed:// 加密笔记本未解锁时绝不回退全局库,避免加密笔记本索引污染全局明文库。IsEncryptedBoxFn func(boxID string) bool++ // IsBoxUnlockedFn 由 model 层注入,用于在读取明文缓存前确认加密笔记本仍处于解锁状态。+ IsBoxUnlockedFn func(boxID string) bool)func init() {diff --git a/kernel/treenode/blocktree.go b/kernel/treenode/blocktree.goindex 4ebc5744fa..567006761c 100644--- a/kernel/treenode/blocktree.go+++ b/kernel/treenode/blocktree.go@@ -1078,6 +1078,31 @@ func GetBlockTreeInBox(id, boxID string) (ret *BlockTree) {return}+// GetBlockTreeInExactBox 只在指定笔记本边界内查询块树;boxID 为空时只查全局数据库,不遍历加密笔记本。+func GetBlockTreeInExactBox(id, boxID string) (ret *BlockTree) {+ if id == "" {+ return+ }+ if boxID != "" {+ ret = GetBlockTreeInBox(id, boxID)+ if ret != nil && ret.BoxID != boxID {+ return nil+ }+ return+ }++ ret = &BlockTree{}+ sqlStmt := "SELECT * FROM blocktrees WHERE id = ?"+ err := queryRow(sqlStmt, id).Scan(&ret.ID, &ret.RootID, &ret.ParentID, &ret.BoxID, &ret.Path, &ret.HPath, &ret.Updated, &ret.Type)+ if err != nil {+ if !errors.Is(err, sql.ErrNoRows) {+ logging.LogErrorf("sql query [%s] failed: %v\n\t%s", sqlStmt, err, logging.ShortStack())+ }+ return nil+ }+ return+}+// GetBlockTreesInBox 按 ids 在指定 box 的 db 里批量查块树。func GetBlockTreesInBox(ids []string, boxID string) (ret map[string]*BlockTree) {ret = map[string]*BlockTree{}