Skip to content

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

:sparkles: encrypted-notebook box-scoped read: doc/backlink/search + block-ref boundary + AI isolation #18034

Daniel0ce946786554
diff --git a/app/src/editor/util.ts b/app/src/editor/util.ts
index b3c9bc4f3d..3950100e99 100644
--- a/app/src/editor/util.ts
+++ b/app/src/editor/util.ts
@@ -5,7 +5,7 @@ import {getInstanceById, getWndByLayout, pdfIsLoading, setPanelFocus} from "../l
import {getDockByType} from "../layout/tabUtil";
import {getAllModels, getAllTabs} from "../layout/getAll";
import {highlightById, scrollCenter} from "../util/highlightById";
-import {getDisplayName, getDocDisplayName, pathPosix, useShell} from "../util/pathName";
+import {getDisplayName, getDocDisplayName, isEncryptedBox, pathPosix, useShell} from "../util/pathName";
import {Constants} from "../constants";
import {Files} from "../layout/dock/Files";
import {fetchPost, fetchSyncPost} from "../util/fetch";
@@ -375,11 +375,15 @@ const switchEditor = (editor: Editor, options: IOpenFileOptions, allModels: IMod
}
});
if ((!nodeElement || nodeElement?.clientHeight === 0) && options.id !== options.rootID) {
- fetchPost("/api/filetree/getDoc", {
+ const getDocParam: IObject = {
id: options.id,
mode: (options.action && options.action.includes(Constants.CB_GET_CONTEXT)) ? 3 : 0,
size: window.siyuan.config.editor.dynamicLoadBlocks,
- }, getResponse => {
+ };
+ if (isEncryptedBox(editor.editor.protyle.notebookId)) {
+ getDocParam.notebook = editor.editor.protyle.notebookId;
+ }
+ fetchPost("/api/filetree/getDoc", getDocParam, getResponse => {
onGet({
data: getResponse,
protyle: editor.editor.protyle,
@@ -702,13 +706,17 @@ export const updateBacklinkGraph = (models: IModels, protyle: IProtyle) => {
return;
}
item.element.querySelector('.block__icon[data-type="refresh"] svg').classList.add("fn__rotate");
- fetchPost("/api/ref/getBacklink2", {
+ const backlinkParam: IObject = {
sort: item.status[blockId] ? item.status[blockId].sort.toString() : window.siyuan.config.editor.backlinkSort.toString(),
mSort: item.status[blockId] ? item.status[blockId].mSort.toString() : window.siyuan.config.editor.backmentionSort.toString(),
id: blockId || "",
k: item.inputsElement[0].value,
mk: item.inputsElement[1].value,
- }, response => {
+ };
+ if (protyle && isEncryptedBox(protyle.notebookId)) {
+ backlinkParam.notebook = protyle.notebookId;
+ }
+ fetchPost("/api/ref/getBacklink2", backlinkParam, response => {
if (!isCurrentEditor(blockId) || item.blockId === blockId) {
item.element.querySelector('.block__icon[data-type="refresh"] svg').classList.remove("fn__rotate");
return;
diff --git a/app/src/layout/dock/Backlink.ts b/app/src/layout/dock/Backlink.ts
index 1cca321dd0..4a0dc3d68c 100644
--- a/app/src/layout/dock/Backlink.ts
+++ b/app/src/layout/dock/Backlink.ts
@@ -11,7 +11,8 @@ import {Protyle} from "../../protyle";
import {MenuItem} from "../../menus/Menu";
import {App} from "../../index";
import {isSupportCSSHL, searchMarkRender} from "../../protyle/render/searchMarkRender";
-import {getDocDisplayName} from "../../util/pathName";
+import {getDocDisplayName, isEncryptedBox} from "../../util/pathName";
+import {getAllModels} from "../getAll";
export class Backlink extends Model {
public element: HTMLElement;
@@ -518,13 +519,27 @@ export class Backlink extends Model {
return;
}
element.classList.add("fn__rotate");
- fetchPost("/api/ref/getBacklink2", {
+ // 解析当前反链面板所属 box:优先用已记录的 notebookId,首次为空时按 rootId 在已打开的编辑器里查找
+ let notebookId = this.notebookId;
+ if (!notebookId && this.rootId) {
+ getAllModels().editor.some(item => {
+ if (item.editor.protyle.block.rootID === this.rootId) {
+ notebookId = item.editor.protyle.notebookId;
+ return true;
+ }
+ });
+ }
+ const param: IObject = {
sort: parseInt(this.tree.element.previousElementSibling.querySelector('[data-type="sort"]').getAttribute("data-sort")).toString(),
mSort: parseInt(this.mTree.element.previousElementSibling.querySelector('[data-type="mSort"]').getAttribute("data-sort")).toString(),
k: this.inputsElement[0].value,
mk: this.inputsElement[1].value,
id: this.blockId,
- }, response => {
+ };
+ if (isEncryptedBox(notebookId)) {
+ param.notebook = notebookId;
+ }
+ fetchPost("/api/ref/getBacklink2", param, response => {
if (!init) {
this.saveStatus();
}
diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.ts
index a6d4bbdfe1..cb8719c32e 100644
--- a/app/src/layout/dock/agent/AgentChat.ts
+++ b/app/src/layout/dock/agent/AgentChat.ts
@@ -16,6 +16,7 @@ import {setPanelFocus} from "../../util";
import {escapeAriaLabel, escapeHtml} from "../../../util/escape";
import {setPosition} from "../../../util/setPosition";
import {fetchPost, fetchSyncPost} from "../../../util/fetch";
+import {isEncryptedBox} from "../../../util/pathName";
import {Constants} from "../../../constants";
import {confirmDialog} from "../../../dialog/confirmDialog";
import {showMessage} from "../../../dialog/message";
@@ -1478,6 +1479,8 @@ export class AgentChat extends Model {
const focusedBlockID = p.block?.id;
const activeDocTitle = p.title?.editElement?.textContent?.trim() || undefined;
const notebookID = p.notebookId || undefined;
+ // AI/LLM 不得感知加密笔记本:当前文档位于加密 box 时,不下发 notebookID 与文档标题等元数据
+ const encryptedCtx = isEncryptedBox(notebookID);
const selectedBlockIDs: string[] = [];
p.wysiwyg?.element?.querySelectorAll("[data-node-id].protyle-wysiwyg--select")
@@ -1523,10 +1526,10 @@ export class AgentChat extends Model {
if (activeDocID) {
ctx.activeDocID = activeDocID;
}
- if (activeDocTitle) {
+ if (activeDocTitle && !encryptedCtx) {
ctx.activeDocTitle = activeDocTitle;
}
- if (notebookID) {
+ if (notebookID && !encryptedCtx) {
ctx.notebookID = notebookID;
}
if (focusedBlockID && focusedBlockID !== activeDocID) {
diff --git a/app/src/mobile/dock/MobileBacklinks.ts b/app/src/mobile/dock/MobileBacklinks.ts
index 475673cefb..91fb69ba01 100644
--- a/app/src/mobile/dock/MobileBacklinks.ts
+++ b/app/src/mobile/dock/MobileBacklinks.ts
@@ -3,6 +3,7 @@ import {fetchPost} from "../../util/fetch";
import {Constants} from "../../constants";
import {openMobileFileById} from "../editor";
import {App} from "../../index";
+import {isEncryptedBox} from "../../util/pathName";
export class MobileBacklinks {
public element: HTMLElement;
@@ -106,12 +107,16 @@ export class MobileBacklinks {
}
public update() {
- fetchPost("/api/ref/getBacklink", {
+ const param: IObject = {
id: window.siyuan.mobile.editor.protyle.block.id,
beforeLen: this.beforeLen,
k: "",
mk: "",
- }, response => {
+ };
+ if (isEncryptedBox(window.siyuan.mobile.editor.protyle.notebookId)) {
+ param.notebook = window.siyuan.mobile.editor.protyle.notebookId;
+ }
+ fetchPost("/api/ref/getBacklink", param, response => {
this.notebookId = response.data.box;
this.tree.updateData(response.data.backlinks);
this.mTree.updateData(response.data.backmentions);
diff --git a/app/src/mobile/menu/search.ts b/app/src/mobile/menu/search.ts
index 5b8bd71b94..4055f31acb 100644
--- a/app/src/mobile/menu/search.ts
+++ b/app/src/mobile/menu/search.ts
@@ -5,7 +5,7 @@ import {fetchPost} from "../../util/fetch";
import {getIconByType} from "../../editor/getIcon";
import {preventScroll} from "../../protyle/scroll/preventScroll";
import {openModel} from "./model";
-import {getDisplayName, getNotebookIcon, getNotebookName, movePathTo, pathPosix} from "../../util/pathName";
+import {getDisplayName, getNotebookIcon, getNotebookName, isEncryptedBox, movePathTo, pathPosix} from "../../util/pathName";
import {getKeyByLiElement, initCriteriaMenu, moreMenu} from "../../search/menu";
import {setStorageVal} from "../../protyle/util/compatibility";
import {escapeHtml} from "../../util/escape";
@@ -290,7 +290,7 @@ export const updateSearchResult = (config: Config.IUILayoutTabSearchConfig, elem
previousElement.setAttribute("disabled", "disabled");
}
const endpoint = config.method === 4 ? "/api/search/semanticSearchBlock" : "/api/search/fullTextSearchBlock";
- fetchPost(endpoint, {
+ const searchParam: IObject = {
query: config.query,
method: config.method,
types: config.types,
@@ -300,7 +300,16 @@ export const updateSearchResult = (config: Config.IUILayoutTabSearchConfig, elem
orderBy: config.sort,
page: config.page,
pageSize: 32,
- }, (response) => {
+ };
+ // 限定在单个加密 box 内搜索时带 notebook,让内核走加密 db;跨 box 或全局搜索走原函数
+ const idPaths = config.idPath || [];
+ if (idPaths.length > 0) {
+ const box = idPaths[0].split("/")[0];
+ if (isEncryptedBox(box) && idPaths.every(p => p.split("/")[0] === box)) {
+ searchParam.notebook = box;
+ }
+ }
+ fetchPost(endpoint, searchParam, (response) => {
onRecentBlocks(response.data.blocks, config, response, focusId);
loadingElement.classList.add("fn__none");
if (config.page < response.data.pageCount) {
diff --git a/app/src/protyle/hint/extend.ts b/app/src/protyle/hint/extend.ts
index df5e172052..e82128de81 100644
--- a/app/src/protyle/hint/extend.ts
+++ b/app/src/protyle/hint/extend.ts
@@ -11,7 +11,7 @@ import {hasClosestBlock, hasClosestByClassName} from "../util/hasClosest";
import {getContenteditableElement, getTopAloneElement} from "../wysiwyg/getBlock";
import {replaceFileName} from "../../editor/rename";
import {transaction} from "../wysiwyg/transaction";
-import {getAssetName, getDisplayName, pathPosix} from "../../util/pathName";
+import {getAssetName, getDisplayName, isEncryptedBox, pathPosix} from "../../util/pathName";
import {genEmptyElement} from "../../block/util";
import {updateListOrder} from "../wysiwyg/list";
import {escapeHtml} from "../../util/escape";
@@ -458,14 +458,18 @@ export const genHintItemHTML = (item: IBlock) => {
export const hintRef = (key: string, protyle: IProtyle, source: THintSource): IHintData[] => {
const nodeElement = hasClosestBlock(getEditorRange(protyle.wysiwyg.element).startContainer);
protyle.hint.genLoading(protyle);
- fetchPost("/api/search/searchRefBlock", {
+ const refParam: IObject = {
k: key,
id: nodeElement ? nodeElement.getAttribute("data-node-id") : protyle.block.parentID,
beforeLen: Math.floor((Math.max(protyle.element.clientWidth / 2, 320) - 58) / 28.8),
rootID: source === "av" ? "" : protyle.block.rootID,
isDatabase: source === "av",
isSquareBrackets: ["[[", "【【"].includes(protyle.hint.splitChar)
- }, (response) => {
+ };
+ if (isEncryptedBox(protyle.notebookId)) {
+ refParam.notebook = protyle.notebookId;
+ }
+ fetchPost("/api/search/searchRefBlock", refParam, (response) => {
const dataList: IHintData[] = [];
if (response.data.newDoc) {
const newFileName = Lute.UnEscapeHTMLStr(replaceFileName(response.data.k));
@@ -514,13 +518,17 @@ export const hintEmbed = (key: string, protyle: IProtyle): IHintData[] => {
}
protyle.hint.genLoading(protyle);
const nodeElement = hasClosestBlock(getEditorRange(protyle.wysiwyg.element).startContainer);
- fetchPost("/api/search/searchRefBlock", {
+ const embedParam: IObject = {
k: key,
isDatabase: false,
beforeLen: Math.floor((Math.max(protyle.element.clientWidth / 2, 320) - 58) / 28.8),
id: nodeElement ? nodeElement.getAttribute("data-node-id") : protyle.block.parentID,
rootID: protyle.block.rootID,
- }, (response) => {
+ };
+ if (isEncryptedBox(protyle.notebookId)) {
+ embedParam.notebook = protyle.notebookId;
+ }
+ fetchPost("/api/search/searchRefBlock", embedParam, (response) => {
const dataList: IHintData[] = [];
response.data.blocks.forEach((item: IBlock) => {
dataList.push({
diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.ts
index 42e5717466..690b5a1ac6 100644
--- a/app/src/protyle/hint/index.ts
+++ b/app/src/protyle/hint/index.ts
@@ -25,7 +25,7 @@ import {highlightRender} from "../render/highlightRender";
import {assetMenu, imgMenu} from "../../menus/protyle";
import {hideElements} from "../ui/hideElements";
import {fetchPost} from "../../util/fetch";
-import {getDisplayName, pathPosix} from "../../util/pathName";
+import {getDisplayName, isEncryptedBox, pathPosix} from "../../util/pathName";
import {
addEmoji,
filterEmoji,
@@ -360,13 +360,17 @@ ${unicode2Emoji(emoji.unicode)}</button>`;
private genSearchHTML(protyle: IProtyle, searchElement: HTMLInputElement, nodeElement: false | HTMLElement, oldValue: string, source: THintSource) {
this.element.lastElementChild.innerHTML = '<div class="ft__center"><img style="height:32px;width:32px;" src="/stage/loading-pure.svg"></div>';
- fetchPost("/api/search/searchRefBlock", {
+ const searchParam: IObject = {
k: searchElement.value,
id: nodeElement ? nodeElement.getAttribute("data-node-id") : protyle.block.parentID,
beforeLen: Math.floor((Math.max(protyle.element.clientWidth / 2, 320) - 58) / 28.8),
rootID: source === "av" ? "" : protyle.block.rootID,
isDatabase: source === "av",
- }, (response) => {
+ };
+ if (isEncryptedBox(protyle.notebookId)) {
+ searchParam.notebook = protyle.notebookId;
+ }
+ fetchPost("/api/search/searchRefBlock", searchParam, (response) => {
let searchHTML = "";
if (response.data.newDoc) {
const blockRefText = `((newFile "${oldValue}"${Constants.ZWSP}'${response.data.k}${Lute.Caret}'))`;
diff --git a/app/src/search/util.ts b/app/src/search/util.ts
index 79ca026074..58e9aa8802 100644
--- a/app/src/search/util.ts
+++ b/app/src/search/util.ts
@@ -9,7 +9,7 @@ import {openFile, openFileById} from "../editor/util";
import {showMessage} from "../dialog/message";
import {reloadProtyle} from "../protyle/util/reload";
import {MenuItem} from "../menus/Menu";
-import {getDisplayName, getNotebookIcon, getNotebookName, movePathTo, pathPosix, useShell} from "../util/pathName";
+import {getDisplayName, getNotebookIcon, getNotebookName, isEncryptedBox, movePathTo, pathPosix, useShell} from "../util/pathName";
import {Protyle} from "../protyle";
import {onGet} from "../protyle/util/onGet";
import {addLoading} from "../protyle/ui/initUI";
@@ -1349,7 +1349,7 @@ export const inputEvent = (element: Element, config: Config.IUILayoutTabSearchCo
previousElement.setAttribute("disabled", "disabled");
}
const endpoint = config.method === 4 ? "/api/search/semanticSearchBlock" : "/api/search/fullTextSearchBlock";
- fetchPost(endpoint, {
+ const searchParam: IObject = {
query: config.query,
method: config.method,
types: config.types,
@@ -1359,7 +1359,16 @@ export const inputEvent = (element: Element, config: Config.IUILayoutTabSearchCo
orderBy: config.sort,
page: config.page || 1,
pageSize: 32,
- }, (response) => {
+ };
+ // 限定在单个加密 box 内搜索时带 notebook,让内核走加密 db;跨 box 或全局搜索走原函数
+ const idPaths = config.idPath || [];
+ if (idPaths.length > 0) {
+ const box = idPaths[0].split("/")[0];
+ if (isEncryptedBox(box) && idPaths.every(p => p.split("/")[0] === box)) {
+ searchParam.notebook = box;
+ }
+ }
+ fetchPost(endpoint, searchParam, (response) => {
const searchReqId = config.method === 4
? window.siyuan.reqIds["/api/search/semanticSearchBlock"]
: window.siyuan.reqIds["/api/search/fullTextSearchBlock"];
diff --git a/app/src/util/pathName.ts b/app/src/util/pathName.ts
index 19331c3ec8..38fc4b5aec 100644
--- a/app/src/util/pathName.ts
+++ b/app/src/util/pathName.ts
@@ -771,6 +771,18 @@ export const setNoteBook = (cb?: (notebook: INotebook[]) => void, flashcard = fa
});
};
+/**
+ * 返回指定 boxID 是否为加密笔记本。
+ * 用于前端在加密 box 上下文里给 getDoc / 反链 / 搜索请求带上 notebook 参数,
+ * 让内核走 InBox 版(查加密 blocktree + content db)。
+ */
+export const isEncryptedBox = (boxId: string): boolean => {
+ if (!boxId) {
+ return false;
+ }
+ return !!window.siyuan.notebooks?.find((item) => item.id === boxId && item.encrypted);
+};
+
/**
* 规范化并校验相对路径:允许子目录,但禁止通过 ".." 穿越到根外。
* 用于插件存储,确保路径不逃出指定根目录。
diff --git a/kernel/api/filetree.go b/kernel/api/filetree.go
index b3aa4022d0..5061026a63 100644
--- a/kernel/api/filetree.go
+++ b/kernel/api/filetree.go
@@ -1200,8 +1200,21 @@ func getDoc(c *gin.Context) {
highlight = highlightArg.(bool)
}
- blockCount, content, parentID, parent2ID, rootID, typ, eof, scroll, boxID, docPath, isBacklinkExpand, keywords, err :=
- model.GetDoc(startID, endID, id, index, query, queryTypes, querySubTypes, queryMethod, mode, size, isBacklink, originalRefBlockIDs, highlight)
+ var blockCount int
+ var content, parentID, parent2ID, rootID, typ string
+ var eof, scroll bool
+ var boxID, docPath string
+ var isBacklinkExpand bool
+ var keywords []string
+ var err error
+ // 加密笔记本的打开文档走 InBox 版(查加密 blocktree + content db)
+ if notebook, ok := arg["notebook"].(string); ok && notebook != "" && model.IsEncryptedBox(notebook) {
+ blockCount, content, parentID, parent2ID, rootID, typ, eof, scroll, boxID, docPath, isBacklinkExpand, keywords, err =
+ model.GetDocInBox(startID, endID, id, index, query, queryTypes, querySubTypes, queryMethod, mode, size, isBacklink, originalRefBlockIDs, highlight, notebook)
+ } else {
+ blockCount, content, parentID, parent2ID, rootID, typ, eof, scroll, boxID, docPath, isBacklinkExpand, keywords, err =
+ model.GetDoc(startID, endID, id, index, query, queryTypes, querySubTypes, queryMethod, mode, size, isBacklink, originalRefBlockIDs, highlight)
+ }
if errors.Is(err, model.ErrBlockNotFound) {
ret.Code = 3
return
diff --git a/kernel/api/ref.go b/kernel/api/ref.go
index 65bf0f57af..757d6e0cf8 100644
--- a/kernel/api/ref.go
+++ b/kernel/api/ref.go
@@ -124,7 +124,15 @@ func getBacklink2(c *gin.Context) {
if val, ok := arg["containChildren"]; ok {
containChildren = val.(bool)
}
- boxID, backlinks, backmentions, linkRefsCount, mentionsCount := model.GetBacklink2(id, keyword, mentionKeyword, sort, mentionSort, containChildren)
+ var boxID string
+ var backlinks, backmentions []*model.Path
+ var linkRefsCount, mentionsCount int
+ // 加密笔记本的反链面板走 InBox 版(查加密 content db)
+ if notebook, ok := arg["notebook"].(string); ok && notebook != "" && model.IsEncryptedBox(notebook) {
+ boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2InBox(id, keyword, mentionKeyword, sort, mentionSort, containChildren, notebook)
+ } else {
+ boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2(id, keyword, mentionKeyword, sort, mentionSort, containChildren)
+ }
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
backlinks = model.FilterPathsByPublishAccess(c, publishAccess, backlinks)
@@ -165,7 +173,15 @@ func getBacklink(c *gin.Context) {
if val, ok := arg["containChildren"]; ok {
containChildren = val.(bool)
}
- boxID, backlinks, backmentions, linkRefsCount, mentionsCount := model.GetBacklink(id, keyword, mentionKeyword, beforeLen, containChildren)
+ var boxID string
+ var backlinks, backmentions []*model.Path
+ var linkRefsCount, mentionsCount int
+ // 加密笔记本的反链面板走 InBox 版(查加密 content db)
+ if notebook, ok := arg["notebook"].(string); ok && notebook != "" && model.IsEncryptedBox(notebook) {
+ boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklinkInBox(id, keyword, mentionKeyword, beforeLen, containChildren, notebook)
+ } else {
+ boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink(id, keyword, mentionKeyword, beforeLen, containChildren)
+ }
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
backlinks = model.FilterPathsByPublishAccess(c, publishAccess, backlinks)
diff --git a/kernel/api/search.go b/kernel/api/search.go
index 8ac2bc7a2f..6ac393e17d 100644
--- a/kernel/api/search.go
+++ b/kernel/api/search.go
@@ -403,7 +403,14 @@ func searchRefBlock(c *gin.Context) {
id := arg["id"].(string)
keyword := arg["k"].(string)
beforeLen := int(arg["beforeLen"].(float64))
- blocks, newDoc := model.SearchRefBlock(id, rootID, keyword, beforeLen, isSquareBrackets, isDatabase)
+ // 加密笔记本内的块引搜索走 InBox 版(只搜该 box 自己的加密 db,阻止跨加密边界引用)
+ var blocks []*model.Block
+ var newDoc bool
+ if notebook, ok := arg["notebook"].(string); ok && notebook != "" && model.IsEncryptedBox(notebook) {
+ blocks, newDoc = model.SearchRefBlockInBox(id, rootID, keyword, beforeLen, isSquareBrackets, isDatabase, notebook)
+ } else {
+ blocks, newDoc = model.SearchRefBlock(id, rootID, keyword, beforeLen, isSquareBrackets, isDatabase)
+ }
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
blocks = model.FilterBlocksByPublishAccess(c, publishAccess, blocks)
@@ -434,7 +441,15 @@ func fullTextSearchBlock(c *gin.Context) {
return
}
- blocks, matchedBlockCount, matchedRootCount, pageCount, docMode := model.FullTextSearchBlock(query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize)
+ var blocks []*model.Block
+ var matchedBlockCount, matchedRootCount, pageCount int
+ var docMode bool
+ // 加密笔记本的全文搜索走 InBox 版(查加密 content db + blocks_fts)
+ if notebook, ok := arg["notebook"].(string); ok && notebook != "" && model.IsEncryptedBox(notebook) {
+ blocks, matchedBlockCount, matchedRootCount, pageCount, docMode = model.FullTextSearchBlockInBox(query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize, notebook)
+ } else {
+ blocks, matchedBlockCount, matchedRootCount, pageCount, docMode = model.FullTextSearchBlock(query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize)
+ }
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
blocks = model.FilterBlocksByPublishAccess(c, publishAccess, blocks)
diff --git a/kernel/mcp/tools/document.go b/kernel/mcp/tools/document.go
index a92f15e20b..8b768b469d 100644
--- a/kernel/mcp/tools/document.go
+++ b/kernel/mcp/tools/document.go
@@ -151,6 +151,10 @@ func documentList(args map[string]interface{}) (CallToolResult, error) {
if notebook == "" {
return CallToolResult{Content: []ContentItem{{Type: "text", Text: "notebook is required"}}, IsError: true}, nil
}
+ // AI/LLM 不得进入加密笔记本,拒绝列出其文档(防止文档标题等元数据泄漏)
+ if model.IsEncryptedBox(notebook) {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "access denied: encrypted notebook is not accessible to AI"}}, IsError: true}, nil
+ }
hPath, _ := args["path"].(string)
if hPath == "" {
hPath = "/"
diff --git a/kernel/mcp/tools/notebook.go b/kernel/mcp/tools/notebook.go
index 13b48b22c6..23583c8f32 100644
--- a/kernel/mcp/tools/notebook.go
+++ b/kernel/mcp/tools/notebook.go
@@ -78,9 +78,18 @@ func notebookList(args map[string]interface{}) (CallToolResult, error) {
return CallToolResult{Content: []ContentItem{{Type: "text", Text: "list notebooks failed: " + err.Error()}}, IsError: true}, nil
}
- var sb strings.Builder
- sb.WriteString(fmt.Sprintf("Notebooks (%d):\n\n", len(notebooks)))
+ // AI/LLM 不得感知加密笔记本的存在,过滤掉加密 box(含其 ID/名称/图标)
+ var visible []*model.Box
for _, nb := range notebooks {
+ if model.IsEncryptedBox(nb.ID) {
+ continue
+ }
+ visible = append(visible, nb)
+ }
+
+ var sb strings.Builder
+ sb.WriteString(fmt.Sprintf("Notebooks (%d):\n\n", len(visible)))
+ for _, nb := range visible {
sb.WriteString(fmt.Sprintf("- %s (id: %s, icon: %s, closed: %v)\n", nb.Name, nb.ID, nb.Icon, nb.Closed))
}
return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil
diff --git a/kernel/model/backlink.go b/kernel/model/backlink.go
index aa50523247..69bc1210dd 100644
--- a/kernel/model/backlink.go
+++ b/kernel/model/backlink.go
@@ -308,6 +308,11 @@ func getBacklinkRenderNodes(n *ast.Node, originalRefBlockIDs map[string]string)
}
func GetBacklink2(id, keyword, mentionKeyword string, sortMode, mentionSortMode int, containChildren bool) (boxID string, backlinks, backmentions []*Path, linkRefsCount, mentionsCount int) {
+ return GetBacklink2InBox(id, keyword, mentionKeyword, sortMode, mentionSortMode, containChildren, "")
+}
+
+// GetBacklink2InBox 与 GetBacklink2 一致,但按 boxID 路由到加密 db 或全局 db。
+func GetBacklink2InBox(id, keyword, mentionKeyword string, sortMode, mentionSortMode int, containChildren bool, boxID string) (boxIDOut string, backlinks, backmentions []*Path, linkRefsCount, mentionsCount int) {
keyword = strings.TrimSpace(keyword)
var keywords []string
if "" != keyword {
@@ -316,17 +321,17 @@ func GetBacklink2(id, keyword, mentionKeyword string, sortMode, mentionSortMode
mentionKeyword = strings.TrimSpace(mentionKeyword)
backlinks, backmentions = []*Path{}, []*Path{}
- sqlBlock := sql.GetBlock(id)
+ sqlBlock := sql.GetBlockInBox(id, boxID)
if nil == sqlBlock {
return
}
rootID := sqlBlock.RootID
- boxID = sqlBlock.Box
+ boxIDOut = sqlBlock.Box
- refs := sql.QueryRefsByDefID(id, containChildren)
+ refs := sql.QueryRefsByDefIDInBox(id, containChildren, boxID)
refs = removeDuplicatedRefs(refs)
- linkRefs, linkRefsCount, excludeBacklinkIDs, _ := buildLinkRefs(rootID, refs, keywords)
+ linkRefs, linkRefsCount, excludeBacklinkIDs, _ := buildLinkRefsInBox(rootID, refs, keywords, boxID)
tmpBacklinks := toFlatTree(linkRefs, 0, "backlink", nil)
for _, l := range tmpBacklinks {
l.Blocks = nil
@@ -355,7 +360,7 @@ func GetBacklink2(id, keyword, mentionKeyword string, sortMode, mentionSortMode
return backlinks[i].ID > backlinks[j].ID
})
- mentionRefs, _ := buildTreeBackmention(sqlBlock, linkRefs, mentionKeyword, excludeBacklinkIDs, 12)
+ mentionRefs, _ := buildTreeBackmentionInBox(sqlBlock, linkRefs, mentionKeyword, excludeBacklinkIDs, 12, boxID)
tmpBackmentions := toFlatTree(mentionRefs, 0, "backlink", nil)
for _, l := range tmpBackmentions {
l.Blocks = nil
@@ -410,18 +415,23 @@ func GetBacklink2(id, keyword, mentionKeyword string, sortMode, mentionSortMode
}
func GetBacklink(id, keyword, mentionKeyword string, beforeLen int, containChildren bool) (boxID string, linkPaths, mentionPaths []*Path, linkRefsCount, mentionsCount int) {
+ return GetBacklinkInBox(id, keyword, mentionKeyword, beforeLen, containChildren, "")
+}
+
+// GetBacklinkInBox 与 GetBacklink 一致,但按 boxID 路由到加密 db 或全局 db。
+func GetBacklinkInBox(id, keyword, mentionKeyword string, beforeLen int, containChildren bool, boxID string) (boxIDOut string, linkPaths, mentionPaths []*Path, linkRefsCount, mentionsCount int) {
linkPaths = []*Path{}
mentionPaths = []*Path{}
- sqlBlock := sql.GetBlock(id)
+ sqlBlock := sql.GetBlockInBox(id, boxID)
if nil == sqlBlock {
return
}
rootID := sqlBlock.RootID
- boxID = sqlBlock.Box
+ boxIDOut = sqlBlock.Box
var links []*Block
- refs := sql.QueryRefsByDefID(id, containChildren)
+ refs := sql.QueryRefsByDefIDInBox(id, containChildren, boxID)
refs = removeDuplicatedRefs(refs)
// 为了减少查询,组装好 IDs 后一次查出
@@ -433,7 +443,7 @@ func GetBacklink(id, keyword, mentionKeyword string, beforeLen int, containChild
queryBlockIDs = append(queryBlockIDs, ref.DefBlockID)
queryBlockIDs = append(queryBlockIDs, ref.BlockID)
}
- querySQLBlocks := sql.GetBlocks(queryBlockIDs)
+ querySQLBlocks := sql.GetBlocksInBox(queryBlockIDs, boxID)
defSQLBlocksCache := map[string]*sql.Block{}
for _, defSQLBlock := range querySQLBlocks {
if nil != defSQLBlock && defSQLBlockIDs[defSQLBlock.ID] {
@@ -488,7 +498,7 @@ func GetBacklink(id, keyword, mentionKeyword string, beforeLen int, containChild
}
}
}
- paragraphParents := sql.GetBlocks(paragraphParentIDs)
+ paragraphParents := sql.GetBlocksInBox(paragraphParentIDs, boxID)
for _, p := range paragraphParents {
if nil == p {
continue
@@ -518,15 +528,20 @@ func GetBacklink(id, keyword, mentionKeyword string, beforeLen int, containChild
linkRefs = append(linkRefs, ref)
}
}
- linkPaths = toSubTree(linkRefs, keyword)
+ linkPaths = toSubTreeInBox(linkRefs, keyword, boxID)
- mentions, _ := buildTreeBackmention(sqlBlock, linkRefs, mentionKeyword, excludeBacklinkIDs, beforeLen)
+ mentions, _ := buildTreeBackmentionInBox(sqlBlock, linkRefs, mentionKeyword, excludeBacklinkIDs, beforeLen, boxID)
mentionsCount = len(mentions)
mentionPaths = toFlatTree(mentions, 0, "backlink", nil)
return
}
func buildLinkRefs(defRootID string, refs []*sql.Ref, keywords []string) (ret []*Block, refsCount int, excludeBacklinkIDs *hashset.Set, originalRefBlockIDs map[string]string) {
+ return buildLinkRefsInBox(defRootID, refs, keywords, "")
+}
+
+// buildLinkRefsInBox 与 buildLinkRefs 一致,但按 boxID 路由到加密 db 或全局 db。
+func buildLinkRefsInBox(defRootID string, refs []*sql.Ref, keywords []string, boxID string) (ret []*Block, refsCount int, excludeBacklinkIDs *hashset.Set, originalRefBlockIDs map[string]string) {
// 为了减少查询,组装好 IDs 后一次查出
defSQLBlockIDs, refSQLBlockIDs := map[string]bool{}, map[string]bool{}
var queryBlockIDs []string
@@ -537,7 +552,7 @@ func buildLinkRefs(defRootID string, refs []*sql.Ref, keywords []string) (ret []
queryBlockIDs = append(queryBlockIDs, ref.BlockID)
}
queryBlockIDs = gulu.Str.RemoveDuplicatedElem(queryBlockIDs)
- querySQLBlocks := sql.GetBlocks(queryBlockIDs)
+ querySQLBlocks := sql.GetBlocksInBox(queryBlockIDs, boxID)
defSQLBlocksCache := map[string]*sql.Block{}
for _, defSQLBlock := range querySQLBlocks {
if nil != defSQLBlock && defSQLBlockIDs[defSQLBlock.ID] {
@@ -597,7 +612,7 @@ func buildLinkRefs(defRootID string, refs []*sql.Ref, keywords []string) (ret []
paragraphParentIDs = gulu.Str.RemoveDuplicatedElem(paragraphParentIDs)
refsCountDelta -= len(paragraphParentIDs)
refsCount -= refsCountDelta
- sqlParagraphParents := sql.GetBlocks(paragraphParentIDs)
+ sqlParagraphParents := sql.GetBlocksInBox(paragraphParentIDs, boxID)
paragraphParents := fromSQLBlocks(&sqlParagraphParents, "", 12)
luteEngine := util.NewLute()
@@ -678,7 +693,7 @@ func buildLinkRefs(defRootID string, refs []*sql.Ref, keywords []string) (ret []
}
var headingChildren []*Block
for _, headingID := range headingIDs {
- sqlChildren := sql.GetChildBlocks(headingID, "", -1)
+ sqlChildren := sql.GetChildBlocksInBox(headingID, "", -1, boxID)
children := fromSQLBlocks(&sqlChildren, "", 12)
headingChildren = append(headingChildren, children...)
}
@@ -746,16 +761,21 @@ func removeDuplicatedRefs(refs []*sql.Ref) (ret []*sql.Ref) {
}
func buildTreeBackmention(defSQLBlock *sql.Block, refBlocks []*Block, keyword string, excludeBacklinkIDs *hashset.Set, beforeLen int) (ret []*Block, mentionKeywords []string) {
+ return buildTreeBackmentionInBox(defSQLBlock, refBlocks, keyword, excludeBacklinkIDs, beforeLen, "")
+}
+
+// buildTreeBackmentionInBox 与 buildTreeBackmention 一致,但按 boxID 路由到加密 db 或全局 db。
+func buildTreeBackmentionInBox(defSQLBlock *sql.Block, refBlocks []*Block, keyword string, excludeBacklinkIDs *hashset.Set, beforeLen int, boxID string) (ret []*Block, mentionKeywords []string) {
ret = []*Block{}
var names, aliases []string
var fName, rootID string
if "d" == defSQLBlock.Type {
if Conf.Search.BacklinkMentionName {
- names = sql.QueryBlockNamesByRootID(defSQLBlock.ID)
+ names = sql.QueryBlockNamesByRootIDInBox(defSQLBlock.ID, boxID)
}
if Conf.Search.BacklinkMentionAlias {
- aliases = sql.QueryBlockAliases(defSQLBlock.ID)
+ aliases = sql.QueryBlockAliasesInBox(defSQLBlock.ID, boxID)
}
if Conf.Search.BacklinkMentionDoc {
fName = path.Base(defSQLBlock.HPath)
@@ -772,7 +792,7 @@ func buildTreeBackmention(defSQLBlock *sql.Block, refBlocks []*Block, keyword st
aliases = strings.Split(defSQLBlock.Alias, ",")
}
}
- root := treenode.GetBlockTree(defSQLBlock.RootID)
+ root := treenode.GetBlockTreeInBox(defSQLBlock.RootID, boxID)
rootID = root.ID
}
@@ -789,7 +809,7 @@ func buildTreeBackmention(defSQLBlock *sql.Block, refBlocks []*Block, keyword st
if Conf.Search.BacklinkMentionAnchor {
for _, refBlock := range refBlocks {
- refs := sql.QueryRefsByDefIDRefID(refBlock.DefID, refBlock.ID)
+ refs := sql.QueryRefsByDefIDRefIDInBox(refBlock.DefID, refBlock.ID, boxID)
for _, ref := range refs {
set.Add(ref.Content)
}
@@ -800,11 +820,16 @@ func buildTreeBackmention(defSQLBlock *sql.Block, refBlocks []*Block, keyword st
mentionKeywords = append(mentionKeywords, v.(string))
}
mentionKeywords = prepareMarkKeywords(mentionKeywords)
- mentionKeywords, ret = searchBackmention(mentionKeywords, keyword, excludeBacklinkIDs, rootID, beforeLen)
+ mentionKeywords, ret = searchBackmentionInBox(mentionKeywords, keyword, excludeBacklinkIDs, rootID, beforeLen, boxID)
return
}
func searchBackmention(mentionKeywords []string, keyword string, excludeBacklinkIDs *hashset.Set, rootID string, beforeLen int) (retMentionKeywords []string, ret []*Block) {
+ return searchBackmentionInBox(mentionKeywords, keyword, excludeBacklinkIDs, rootID, beforeLen, "")
+}
+
+// searchBackmentionInBox 与 searchBackmention 一致,但按 boxID 路由到加密 db 或全局 db。
+func searchBackmentionInBox(mentionKeywords []string, keyword string, excludeBacklinkIDs *hashset.Set, rootID string, beforeLen int, boxID string) (retMentionKeywords []string, ret []*Block) {
ret = []*Block{}
if 1 > len(mentionKeywords) {
return
@@ -839,7 +864,7 @@ func searchBackmention(mentionKeywords []string, keyword string, excludeBacklink
buf.WriteString(" ORDER BY id DESC LIMIT " + strconv.Itoa(Conf.Search.Limit))
query := buf.String()
- sqlBlocks := sql.SelectBlocksRawStmt(query, 1, Conf.Search.Limit)
+ sqlBlocks := sql.SelectBlocksRawStmtInBox(query, 1, Conf.Search.Limit, boxID)
terms := mentionKeywords
if "" != keyword {
terms = append(terms, keyword)
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index 08a8796e45..9a7be2b5da 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -291,6 +291,26 @@ func IsEncryptedBox(boxID string) bool {
return boxConf != nil && boxConf.Encrypted
}
+// IsBlockRefCrossingBoundary 判断从 srcBoxID 引用 defBlockID 是否跨越加密边界。
+// 加密笔记本禁止跨边界块引(双向):加密 box 的块只能引用同一加密 box 内的块,普通 box 的块不能引用加密 box 的块。
+// 供 transaction 落库时兜底校验,防止手工输入/拖拽/粘贴/API 直调绕过前端搜索分流。
+func IsBlockRefCrossingBoundary(srcBoxID, defBlockID string) bool {
+ if "" == defBlockID {
+ return false
+ }
+ if IsEncryptedBox(srcBoxID) {
+ // 源在加密 box:def 块必须在同一加密 box(查加密 blocktree db)
+ bt := treenode.GetBlockTreeInBox(defBlockID, srcBoxID)
+ return nil == bt || bt.BoxID != srcBoxID
+ }
+ // 源在普通 box:def 块必须在普通 box(查全局 blocktree,且其 box 非加密)
+ bt := treenode.GetBlockTree(defBlockID)
+ if nil == bt {
+ return false // def 块不存在(可能是新建块的临时态),不拦
+ }
+ return IsEncryptedBox(bt.BoxID)
+}
+
// IsEncryptedAssetPath 判断给定 asset 绝对路径是否属于加密笔记本。
// 供 server 层在缩略图等场景判断是否需跳过密文文件的处理。
func IsEncryptedAssetPath(absPath string) bool {
diff --git a/kernel/model/file.go b/kernel/model/file.go
index 083d2266f8..65aece821e 100644
--- a/kernel/model/file.go
+++ b/kernel/model/file.go
@@ -492,6 +492,13 @@ func ListDocTree(boxID, listPath string, sortMode int, flashcard, showHidden boo
func GetDoc(startID, endID, id string, index int, query string, queryTypes, querySubTypes map[string]bool, queryMethod, mode int, size int, isBacklink bool, originalRefBlockIDs map[string]string, highlight bool) (
blockCount int, dom, parentID, parent2ID, rootID, typ string, eof, scroll bool, boxID, docPath string, isBacklinkExpand bool, keywords []string, err error) {
+ return GetDocInBox(startID, endID, id, index, query, queryTypes, querySubTypes, queryMethod, mode, size, isBacklink, originalRefBlockIDs, highlight, "")
+}
+
+// GetDocInBox 与 GetDoc 一致,但按 boxID 路由到加密 db 或全局 db。
+// 加密 box 打开文档时传入 boxID,blocktree/content 查询走加密 db;boxID 为空时 fall-through 全局 db。
+func GetDocInBox(startID, endID, id string, index int, query string, queryTypes, querySubTypes map[string]bool, queryMethod, mode int, size int, isBacklink bool, originalRefBlockIDs map[string]string, highlight bool, boxID string) (
+ blockCount int, dom, parentID, parent2ID, rootID, typ string, eof, scroll bool, boxIDOut, docPath string, isBacklinkExpand bool, keywords []string, err error) {
//os.MkdirAll("pprof", 0755)
//cpuProfile, _ := os.Create("pprof/GetDoc")
//pprof.StartCPUProfile(cpuProfile)
@@ -500,7 +507,7 @@ func GetDoc(startID, endID, id string, index int, query string, queryTypes, quer
FlushTxQueue() // 写入数据时阻塞,避免获取到的数据不一致
inputIndex := index
- tree, err := LoadTreeByBlockID(id)
+ tree, err := loadTreeByBlockIDInBox(id, boxID)
if err != nil {
if errors.Is(err, ErrBlockNotFound) {
if 0 == mode {
@@ -529,7 +536,7 @@ func GetDoc(startID, endID, id string, index int, query string, queryTypes, quer
isDoc := ast.NodeDocument == node.Type
isHeading := ast.NodeHeading == node.Type
- boxID = node.Box
+ boxIDOut = node.Box
docPath = node.Path
if isDoc {
if 4 == mode { // 加载文档末尾
@@ -679,7 +686,7 @@ func GetDoc(startID, endID, id string, index int, query string, queryTypes, quer
}
}
- refCount := sql.QueryRootChildrenRefCount(rootID)
+ refCount := sql.QueryRootChildrenRefCountInBox(rootID, boxID)
virtualBlockRefKeywords := getBlockVirtualRefKeywords(tree.Root)
subTree := &parse.Tree{ID: rootID, Root: &ast.Node{Type: ast.NodeDocument}, Marks: tree.Marks}
@@ -690,11 +697,11 @@ func GetDoc(startID, endID, id string, index int, query string, queryTypes, quer
switch queryMethod {
case 0:
query = stringQuery(query)
- keywords = highlightByFTS(query, typeFilter, rootID)
+ keywords = highlightByFTSInBox(query, typeFilter, rootID, boxID)
case 1:
- keywords = highlightByFTS(query, typeFilter, rootID)
+ keywords = highlightByFTSInBox(query, typeFilter, rootID, boxID)
case 3:
- keywords = highlightByRegexp(query, typeFilter, rootID)
+ keywords = highlightByRegexpInBox(query, typeFilter, rootID, boxID)
}
}
diff --git a/kernel/model/index.go b/kernel/model/index.go
index 3ff3ee35ea..6a05e3d9d1 100644
--- a/kernel/model/index.go
+++ b/kernel/model/index.go
@@ -229,27 +229,42 @@ func IndexRefs() {
util.SetBootDetails(Conf.Language(305))
var defBlockIDs []string
+ defBlockBoxes := map[string]string{} // defBlockID -> boxID,加密 box 下需按 box 路由后续加载
luteEngine := util.NewLute()
boxes := Conf.GetOpenedBoxes()
for _, box := range boxes {
+ encryptedBox := IsEncryptedBox(box.ID)
pages := pagedPaths(filepath.Join(util.DataDir, box.ID), 32)
for _, paths := range pages {
for _, treeAbsPath := range paths {
- data, readErr := filelock.ReadFile(treeAbsPath)
- if nil != readErr {
- logging.LogWarnf("get data [path=%s] failed: %s", treeAbsPath, readErr)
- continue
- }
+ p := filepath.ToSlash(strings.TrimPrefix(treeAbsPath, filepath.Join(util.DataDir, box.ID)))
- if !bytes.Contains(data, []byte("TextMarkBlockRefID")) && !bytes.Contains(data, []byte("TextMarkFileAnnotationRefID")) {
- continue
- }
+ // 加密 box 的 .sy 是密文,必须走 filesys.LoadTree 透明解密;无法用 bytes.Contains 预检
+ var tree *parse.Tree
+ if encryptedBox {
+ loadTree, loadErr := filesys.LoadTree(box.ID, p, luteEngine)
+ if nil != loadErr {
+ logging.LogWarnf("load encrypted box [%s] tree [%s] failed: %s", box.ID, treeAbsPath, loadErr)
+ continue
+ }
+ tree = loadTree
+ } else {
+ data, readErr := filelock.ReadFile(treeAbsPath)
+ if nil != readErr {
+ logging.LogWarnf("get data [path=%s] failed: %s", treeAbsPath, readErr)
+ continue
+ }
- p := filepath.ToSlash(strings.TrimPrefix(treeAbsPath, filepath.Join(util.DataDir, box.ID)))
- tree, parseErr := filesys.LoadTreeByData(data, box.ID, p, luteEngine)
- if nil != parseErr {
- logging.LogWarnf("parse json to tree [%s] failed: %s", treeAbsPath, parseErr)
- continue
+ if !bytes.Contains(data, []byte("TextMarkBlockRefID")) && !bytes.Contains(data, []byte("TextMarkFileAnnotationRefID")) {
+ continue
+ }
+
+ parseTree, parseErr := filesys.LoadTreeByData(data, box.ID, p, luteEngine)
+ if nil != parseErr {
+ logging.LogWarnf("parse json to tree [%s] failed: %s", treeAbsPath, parseErr)
+ continue
+ }
+ tree = parseTree
}
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
@@ -259,6 +274,7 @@ func IndexRefs() {
if treenode.IsBlockRef(n) || treenode.IsFileAnnotationRef(n) {
defBlockIDs = append(defBlockIDs, tree.Root.ID)
+ defBlockBoxes[tree.Root.ID] = box.ID
}
return ast.WalkContinue
})
@@ -274,7 +290,14 @@ func IndexRefs() {
bootProgressPart := int32(10.0 / float64(size))
for _, defBlockID := range defBlockIDs {
- defTree, loadErr := LoadTreeByBlockID(defBlockID)
+ // 加密 box 的 defBlock 在加密 blocktree db,需按 box 路由加载
+ var defTree *parse.Tree
+ var loadErr error
+ if boxID, ok := defBlockBoxes[defBlockID]; ok && IsEncryptedBox(boxID) {
+ defTree, loadErr = loadTreeByBlockIDInBox(defBlockID, boxID)
+ } else {
+ defTree, loadErr = LoadTreeByBlockID(defBlockID)
+ }
if nil != loadErr {
continue
}
diff --git a/kernel/model/path.go b/kernel/model/path.go
index 4ce251c81e..3d75ebbeda 100644
--- a/kernel/model/path.go
+++ b/kernel/model/path.go
@@ -180,6 +180,11 @@ func toFlatTree(blocks []*Block, baseDepth int, typ string, tree *parse.Tree) (r
}
func toSubTree(blocks []*Block, keyword string) (ret []*Path) {
+ return toSubTreeInBox(blocks, keyword, "")
+}
+
+// toSubTreeInBox 与 toSubTree 一致,但按 boxID 路由到加密 db 或全局 db。
+func toSubTreeInBox(blocks []*Block, keyword, boxID string) (ret []*Path) {
keyword = strings.TrimSpace(keyword)
var blockRoots []*Block
for _, block := range blocks {
@@ -206,7 +211,7 @@ func toSubTree(blocks []*Block, keyword string) (ret []*Path) {
}
for _, c := range root.Children {
if "NodeListItem" == c.Type {
- tree, _ := LoadTreeByBlockID(c.RootID)
+ tree, _ := loadTreeByBlockIDInBox(c.RootID, boxID)
li := treenode.GetNodeInTree(tree, c.ID)
if nil == li || nil == li.FirstChild {
// 反链面板拖拽到文档以后可能会出现这种情况 https://github.com/siyuan-note/siyuan/issues/5363
@@ -215,9 +220,9 @@ func toSubTree(blocks []*Block, keyword string) (ret []*Path) {
var first *sql.Block
if 3 != li.ListData.Typ {
- first = sql.GetBlock(li.FirstChild.ID)
+ first = sql.GetBlockInBox(li.FirstChild.ID, boxID)
} else {
- first = sql.GetBlock(li.FirstChild.Next.ID)
+ first = sql.GetBlockInBox(li.FirstChild.Next.ID, boxID)
}
name := first.Content
parentPos := 0
diff --git a/kernel/model/search.go b/kernel/model/search.go
index bf8bdc97cd..7b23122564 100644
--- a/kernel/model/search.go
+++ b/kernel/model/search.go
@@ -312,6 +312,12 @@ func buildEmbedBlock(embedBlockID string, excludeIDs []string, headingMode int,
}
func SearchRefBlock(id, rootID, keyword string, beforeLen int, isSquareBrackets, isDatabase bool) (ret []*Block, newDoc bool) {
+ return SearchRefBlockInBox(id, rootID, keyword, beforeLen, isSquareBrackets, isDatabase, "")
+}
+
+// SearchRefBlockInBox 与 SearchRefBlock 一致,但按 boxID 路由到加密 db 或全局 db。
+// 加密 box 内搜索块引目标时传入 boxID,只搜该 box 自己的加密 db,避免跨加密边界引用。
+func SearchRefBlockInBox(id, rootID, keyword string, beforeLen int, isSquareBrackets, isDatabase bool, boxID string) (ret []*Block, newDoc bool) {
cachedTrees := map[string]*parse.Tree{}
nodeTrees := map[string]*parse.Tree{}
var nodeIDs []string
@@ -327,13 +333,13 @@ func SearchRefBlock(id, rootID, keyword string, beforeLen int, isSquareBrackets,
typeFilter := Conf.Search.TypeFilter()
ignoreLines := getRefSearchIgnoreLines()
- refs := sql.QueryRefsRecent(onlyDoc, typeFilter, ignoreLines)
+ refs := sql.QueryRefsRecentInBox(onlyDoc, typeFilter, ignoreLines, boxID)
var btsID []string
for _, ref := range refs {
btsID = append(btsID, ref.DefBlockRootID)
}
btsID = gulu.Str.RemoveDuplicatedElem(btsID)
- bts := treenode.GetBlockTrees(btsID)
+ bts := treenode.GetBlockTreesInBox(btsID, boxID)
for _, ref := range refs {
tree := cachedTrees[ref.DefBlockRootID]
@@ -355,7 +361,7 @@ func SearchRefBlock(id, rootID, keyword string, beforeLen int, isSquareBrackets,
nodeTrees[node.ID] = tree
}
- refCount := sql.QueryRefCount(nodeIDs)
+ refCount := sql.QueryRefCountInBox(nodeIDs, boxID)
for _, node := range nodes {
tree := nodeTrees[node.ID]
@@ -380,14 +386,14 @@ func SearchRefBlock(id, rootID, keyword string, beforeLen int, isSquareBrackets,
return
}
- ret = fullTextSearchRefBlock(keyword, beforeLen, onlyDoc)
+ ret = fullTextSearchRefBlockInBox(keyword, beforeLen, onlyDoc, boxID)
tmp := ret[:0]
var btsID []string
for _, b := range ret {
btsID = append(btsID, b.RootID)
}
btsID = gulu.Str.RemoveDuplicatedElem(btsID)
- bts := treenode.GetBlockTrees(btsID)
+ bts := treenode.GetBlockTreesInBox(btsID, boxID)
for _, b := range ret {
tree := cachedTrees[b.RootID]
if nil == tree {
@@ -432,14 +438,14 @@ func SearchRefBlock(id, rootID, keyword string, beforeLen int, isSquareBrackets,
}
ret = tmp
- refCount := sql.QueryRefCount(nodeIDs)
+ refCount := sql.QueryRefCountInBox(nodeIDs, boxID)
for _, b := range ret {
b.RefCount = refCount[b.ID]
}
if !isDatabase {
// 如果非数据库中搜索块引,则不允许新建重名文档
- if block := treenode.GetBlockTree(id); nil != block {
+ if block := treenode.GetBlockTreeInBox(id, boxID); nil != block {
p := path.Join(block.HPath, keyword)
newDoc = nil == treenode.GetBlockTreeRootByHPath(block.BoxID, p)
}
@@ -1159,6 +1165,12 @@ func mergeSamePreNext(n *ast.Node) {
// orderBy: 0:按块类型(默认),1:按创建时间升序,2:按创建时间降序,3:按更新时间升序,4:按更新时间降序,5:按内容顺序(仅在按文档分组时),6:按相关度升序,7:按相关度降序
// groupBy:0:不分组,1:按文档分组
func FullTextSearchBlock(query string, boxes, paths []string, types, subTypes map[string]bool, method, orderBy, groupBy, page, pageSize int) (ret []*Block, matchedBlockCount, matchedRootCount, pageCount int, docMode bool) {
+ return FullTextSearchBlockInBox(query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize, "")
+}
+
+// FullTextSearchBlockInBox 与 FullTextSearchBlock 一致,但按 boxID 路由到加密 db 或全局 db。
+// 加密 box 内搜索时传入 boxID,所有 sql/treenode 查询走加密 db;boxID 为空时 fall-through 全局 db。
+func FullTextSearchBlockInBox(query string, boxes, paths []string, types, subTypes map[string]bool, method, orderBy, groupBy, page, pageSize int, boxID string) (ret []*Block, matchedBlockCount, matchedRootCount, pageCount int, docMode bool) {
ret = []*Block{}
if "" == query {
return
@@ -1185,30 +1197,30 @@ func FullTextSearchBlock(query string, boxes, paths []string, types, subTypes ma
boxFilter, boxArgs := buildBoxesFilter(boxes)
pathFilter, pathArgs := buildPathsFilter(paths)
if ast.IsNodeIDPattern(query) {
- blocks, matchedBlockCount, matchedRootCount = searchBySQL("SELECT * FROM `blocks` WHERE `id` = '"+query+"'", beforeLen, page, pageSize)
+ blocks, matchedBlockCount, matchedRootCount = searchBySQLInBox("SELECT * FROM `blocks` WHERE `id` = '"+query+"'", beforeLen, page, pageSize, boxID)
} else {
- blocks, matchedBlockCount, matchedRootCount = fullTextSearchByFTS(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize)
+ blocks, matchedBlockCount, matchedRootCount = fullTextSearchByFTSInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize, boxID)
}
case 2: // SQL
- blocks, matchedBlockCount, matchedRootCount = searchBySQL(query, beforeLen, page, pageSize)
+ blocks, matchedBlockCount, matchedRootCount = searchBySQLInBox(query, beforeLen, page, pageSize, boxID)
case 3: // 正则表达式
typeFilter := buildTypeFilter(types, subTypes)
boxFilter, boxArgs := buildBoxesFilter(boxes)
pathFilter, pathArgs := buildPathsFilter(paths)
- blocks, matchedBlockCount, matchedRootCount = fullTextSearchByRegexp(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize)
+ blocks, matchedBlockCount, matchedRootCount = fullTextSearchByRegexpInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize, boxID)
default: // 关键字
typeFilter := buildTypeFilter(types, subTypes)
boxFilter, boxArgs := buildBoxesFilter(boxes)
pathFilter, pathArgs := buildPathsFilter(paths)
if ast.IsNodeIDPattern(query) {
- blocks, matchedBlockCount, matchedRootCount = searchBySQL("SELECT * FROM `blocks` WHERE `id` = '"+query+"'", beforeLen, page, pageSize)
+ blocks, matchedBlockCount, matchedRootCount = searchBySQLInBox("SELECT * FROM `blocks` WHERE `id` = '"+query+"'", beforeLen, page, pageSize, boxID)
} else {
if 2 > len(strings.Split(strings.TrimSpace(query), " ")) {
query = stringQuery(query)
- blocks, matchedBlockCount, matchedRootCount = fullTextSearchByFTS(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize)
+ blocks, matchedBlockCount, matchedRootCount = fullTextSearchByFTSInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize, boxID)
} else {
docMode = true // 文档全文搜索模式 https://github.com/siyuan-note/siyuan/issues/10584
- blocks, matchedBlockCount, matchedRootCount = fullTextSearchByLikeWithRoot(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize)
+ blocks, matchedBlockCount, matchedRootCount = fullTextSearchByLikeWithRootInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize, boxID)
}
}
}
@@ -1226,7 +1238,7 @@ func FullTextSearchBlock(query string, boxes, paths []string, types, subTypes ma
btsID = append(btsID, b.RootID)
}
btsID = gulu.Str.RemoveDuplicatedElem(btsID)
- bts := treenode.GetBlockTrees(btsID)
+ bts := treenode.GetBlockTreesInBox(btsID, boxID)
for _, b := range blocks {
if _, ok := rootMap[b.RootID]; !ok {
rootMap[b.RootID] = true
@@ -1251,7 +1263,7 @@ func FullTextSearchBlock(query string, boxes, paths []string, types, subTypes ma
}
}
- sqlRoots := sql.GetBlocks(rootIDs)
+ sqlRoots := sql.GetBlocksInBox(rootIDs, boxID)
roots := fromSQLBlocks(&sqlRoots, "", beforeLen)
for _, root := range roots {
for _, b := range blocks {
@@ -1319,7 +1331,7 @@ func FullTextSearchBlock(query string, boxes, paths []string, types, subTypes ma
}
}
- refCount := sql.QueryRefCount(nodeIDs)
+ refCount := sql.QueryRefCountInBox(nodeIDs, boxID)
for _, b := range ret {
if 0 == groupBy {
b.RefCount = refCount[b.ID]
@@ -1580,8 +1592,13 @@ func sqlQuoteJoin(items []string) string {
}
func searchBySQL(stmt string, beforeLen, page, pageSize int) (ret []*Block, matchedBlockCount, matchedRootCount int) {
+ return searchBySQLInBox(stmt, beforeLen, page, pageSize, "")
+}
+
+// searchBySQLInBox 与 searchBySQL 一致,但按 boxID 路由到加密 db 或全局 db。
+func searchBySQLInBox(stmt string, beforeLen, page, pageSize int, boxID string) (ret []*Block, matchedBlockCount, matchedRootCount int) {
stmt = strings.TrimSpace(stmt)
- blocks := sql.SelectBlocksRawStmt(stmt, page, pageSize)
+ blocks := sql.SelectBlocksRawStmtInBox(stmt, page, pageSize, boxID)
ret = fromSQLBlocks(&blocks, "", beforeLen)
if 1 > len(ret) {
ret = []*Block{}
@@ -1598,7 +1615,7 @@ func searchBySQL(stmt string, beforeLen, page, pageSize int) (ret []*Block, matc
}
}
stmt = removeLimitClause(stmt)
- result, _ := sql.QueryNoLimit(stmt)
+ result, _ := sql.QueryNoLimitInBox(stmt, boxID)
if 1 > len(result) {
return
}
@@ -1638,10 +1655,15 @@ func removeLimitClause(stmt string) string {
}
func fullTextSearchRefBlock(keyword string, beforeLen int, onlyDoc bool) (ret []*Block) {
+ return fullTextSearchRefBlockInBox(keyword, beforeLen, onlyDoc, "")
+}
+
+// fullTextSearchRefBlockInBox 与 fullTextSearchRefBlock 一致,但按 boxID 路由到加密 db 或全局 db。
+func fullTextSearchRefBlockInBox(keyword string, beforeLen int, onlyDoc bool, boxID string) (ret []*Block) {
keyword = filterQueryInvisibleChars(keyword)
if id := extractID(keyword); "" != id {
- ret, _, _ = searchBySQL("SELECT * FROM `blocks` WHERE `id` = '"+id+"'", 36, 1, 32)
+ ret, _, _ = searchBySQLInBox("SELECT * FROM `blocks` WHERE `id` = '"+id+"'", 36, 1, 32, boxID)
return
}
@@ -1690,7 +1712,7 @@ func fullTextSearchRefBlock(keyword string, beforeLen int, onlyDoc bool) (ret []
ELSE 65535 END ASC, sort ASC, length ASC`
orderBy = strings.ReplaceAll(orderBy, "${keyword}", strings.ReplaceAll(keyword, "'", "''"))
stmt += orderBy + " LIMIT " + strconv.Itoa(Conf.Search.Limit)
- blocks := sql.SelectBlocksRawStmtNoParse(stmt, Conf.Search.Limit)
+ blocks := sql.SelectBlocksRawStmtNoParseInBox(stmt, Conf.Search.Limit, boxID)
ret = fromSQLBlocks(&blocks, "", beforeLen)
if 1 > len(ret) {
ret = []*Block{}
@@ -1716,6 +1738,10 @@ func extractID(content string) (ret string) {
}
func fullTextSearchByRegexp(exp, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, orderBy string, beforeLen, page, pageSize int) (ret []*Block, matchedBlockCount, matchedRootCount int) {
+ return fullTextSearchByRegexpInBox(exp, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderBy, beforeLen, page, pageSize, "")
+}
+
+func fullTextSearchByRegexpInBox(exp, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, orderBy string, beforeLen, page, pageSize int, boxID string) (ret []*Block, matchedBlockCount, matchedRootCount int) {
fieldFilter := fieldRegexp(exp)
stmt := "SELECT * FROM `blocks` WHERE " + fieldFilter + " AND " + typeFilter
stmt += boxFilter + pathFilter + ignoreFilter + " " + orderBy
@@ -1727,22 +1753,26 @@ func fullTextSearchByRegexp(exp, boxFilter, pathFilter string, boxArgs, pathArgs
// box/path 过滤值通过绑定参数传递,避免 SQL 拼接注入
args := append(append([]any{}, boxArgs...), pathArgs...)
- blocks := sql.SelectBlocksRegexArgs(stmt, regex, Conf.Search.Name, Conf.Search.Alias, Conf.Search.Memo, Conf.Search.IAL, page, pageSize, args...)
+ blocks := sql.SelectBlocksRegexArgsInBox(stmt, regex, Conf.Search.Name, Conf.Search.Alias, Conf.Search.Memo, Conf.Search.IAL, page, pageSize, boxID, args...)
ret = fromSQLBlocks(&blocks, "", beforeLen)
if 1 > len(ret) {
ret = []*Block{}
}
- matchedBlockCount, matchedRootCount = fullTextSearchCountByRegexp(exp, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter)
+ matchedBlockCount, matchedRootCount = fullTextSearchCountByRegexpInBox(exp, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, boxID)
return
}
func fullTextSearchCountByRegexp(exp, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter string) (matchedBlockCount, matchedRootCount int) {
+ return fullTextSearchCountByRegexpInBox(exp, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, "")
+}
+
+func fullTextSearchCountByRegexpInBox(exp, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, boxID string) (matchedBlockCount, matchedRootCount int) {
fieldFilter := fieldRegexp(exp)
stmt := "SELECT COUNT(id) AS `matches`, COUNT(DISTINCT(root_id)) AS `docs` FROM `blocks` WHERE " + fieldFilter + " AND " + typeFilter + ignoreFilter
stmt += boxFilter + pathFilter
args := append(append([]any{}, boxArgs...), pathArgs...)
- result, _ := sql.QueryNoLimitArgs(stmt, args...)
+ result, _ := sql.QueryNoLimitArgsInBox(stmt, boxID, args...)
if 1 > len(result) {
return
}
@@ -1752,6 +1782,10 @@ func fullTextSearchCountByRegexp(exp, boxFilter, pathFilter string, boxArgs, pat
}
func fullTextSearchByFTS(query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, orderBy string, beforeLen, page, pageSize int) (ret []*Block, matchedBlockCount, matchedRootCount int) {
+ return fullTextSearchByFTSInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderBy, beforeLen, page, pageSize, "")
+}
+
+func fullTextSearchByFTSInBox(query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, orderBy string, beforeLen, page, pageSize int, boxID string) (ret []*Block, matchedBlockCount, matchedRootCount int) {
table := "blocks_fts"
projections := "id, parent_id, root_id, hash, box, path, " +
// Search result content snippet returns more text https://github.com/siyuan-note/siyuan/issues/10707
@@ -1768,24 +1802,28 @@ func fullTextSearchByFTS(query, boxFilter, pathFilter string, boxArgs, pathArgs
stmt += " LIMIT " + strconv.Itoa(pageSize) + " OFFSET " + strconv.Itoa((page-1)*pageSize)
// box/path 过滤值通过绑定参数传递,避免 SQL 拼接注入;绕开 sqlparser 以保留 "?" 占位
args := append(append([]any{}, boxArgs...), pathArgs...)
- blocks := sql.SelectBlocksRawStmtArgs(stmt, args, pageSize)
+ blocks := sql.SelectBlocksRawStmtArgsInBox(stmt, args, pageSize, boxID)
ret = fromSQLBlocks(&blocks, "", beforeLen)
if 1 > len(ret) {
ret = []*Block{}
}
- matchedBlockCount, matchedRootCount = fullTextSearchCountByFTS(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter)
+ matchedBlockCount, matchedRootCount = fullTextSearchCountByFTSInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, boxID)
return
}
func fullTextSearchCountByFTS(query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter string) (matchedBlockCount, matchedRootCount int) {
+ return fullTextSearchCountByFTSInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, "")
+}
+
+func fullTextSearchCountByFTSInBox(query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, boxID string) (matchedBlockCount, matchedRootCount int) {
table := "blocks_fts"
stmt := "SELECT COUNT(id) AS `matches`, COUNT(DISTINCT(root_id)) AS `docs` FROM `" + table + "` WHERE (`" + table + "` MATCH '" + columnFilter() + ":(" + query + ")'"
stmt += ") AND " + typeFilter
stmt += boxFilter + pathFilter + ignoreFilter
args := append(append([]any{}, boxArgs...), pathArgs...)
- result, _ := sql.QueryNoLimitArgs(stmt, args...)
+ result, _ := sql.QueryNoLimitArgsInBox(stmt, boxID, args...)
if 1 > len(result) {
return
}
@@ -1795,6 +1833,10 @@ func fullTextSearchCountByFTS(query, boxFilter, pathFilter string, boxArgs, path
}
func fullTextSearchByLikeWithRoot(query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, orderBy string, beforeLen, page, pageSize int) (ret []*Block, matchedBlockCount, matchedRootCount int) {
+ return fullTextSearchByLikeWithRootInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderBy, beforeLen, page, pageSize, "")
+}
+
+func fullTextSearchByLikeWithRootInBox(query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, orderBy string, beforeLen, page, pageSize int, boxID string) (ret []*Block, matchedBlockCount, matchedRootCount int) {
query = strings.ReplaceAll(query, "'", "''") // 不需要转义双引号,因为条件都是通过单引号包裹的,只需要转义单引号即可
keywords := strings.Split(query, " ")
contentField := columnConcat()
@@ -1838,7 +1880,7 @@ func fullTextSearchByLikeWithRoot(query, boxFilter, pathFilter string, boxArgs,
} else {
selectStmt += " " + orderBy
}
- result, _ := sql.QueryNoLimitArgs(selectStmt, args...)
+ result, _ := sql.QueryNoLimitArgsInBox(selectStmt, boxID, args...)
resultBlocks := sql.ToBlocks(result)
if 0 < len(resultBlocks) {
matchedRootCount = int(result[0]["docs"].(int64))
@@ -1856,6 +1898,11 @@ func fullTextSearchByLikeWithRoot(query, boxFilter, pathFilter string, boxArgs,
}
func highlightByFTS(query, typeFilter, id string) (ret []string) {
+ return highlightByFTSInBox(query, typeFilter, id, "")
+}
+
+// highlightByFTSInBox 与 highlightByFTS 一致,但按 boxID 路由到加密 db 或全局 db。
+func highlightByFTSInBox(query, typeFilter, id, boxID string) (ret []string) {
query = strings.ReplaceAll(query, " ", " OR ")
const limit = 256
table := "blocks_fts"
@@ -1873,7 +1920,7 @@ func highlightByFTS(query, typeFilter, id string) (ret []string) {
stmt += ") AND " + typeFilter
stmt += " AND root_id = '" + id + "'"
stmt += " LIMIT " + strconv.Itoa(limit)
- sqlBlocks := sql.SelectBlocksRawStmt(stmt, 1, limit)
+ sqlBlocks := sql.SelectBlocksRawStmtInBox(stmt, 1, limit, boxID)
for _, block := range sqlBlocks {
keyword := gulu.Str.SubstringsBetween(block.HPath, search.SearchMarkLeft, search.SearchMarkRight)
if 0 < len(keyword) {
@@ -1909,6 +1956,11 @@ func highlightByFTS(query, typeFilter, id string) (ret []string) {
}
func highlightByRegexp(query, typeFilter, id string) (ret []string) {
+ return highlightByRegexpInBox(query, typeFilter, id, "")
+}
+
+// highlightByRegexpInBox 与 highlightByRegexp 一致,但按 boxID 路由到加密 db 或全局 db。
+func highlightByRegexpInBox(query, typeFilter, id, boxID string) (ret []string) {
fieldFilter := fieldRegexp(query)
stmt := "SELECT * FROM `blocks` WHERE " + fieldFilter + " AND " + typeFilter
stmt += " AND root_id = '" + id + "'"
@@ -1916,7 +1968,7 @@ func highlightByRegexp(query, typeFilter, id string) (ret []string) {
if nil == regex {
return
}
- sqlBlocks := sql.SelectBlocksRegex(stmt, regex, Conf.Search.Name, Conf.Search.Alias, Conf.Search.Memo, Conf.Search.IAL, 1, 256)
+ sqlBlocks := sql.SelectBlocksRegexInBox(stmt, regex, Conf.Search.Name, Conf.Search.Alias, Conf.Search.Memo, Conf.Search.IAL, 1, 256, boxID)
for _, block := range sqlBlocks {
keyword := gulu.Str.SubstringsBetween(block.HPath, search.SearchMarkLeft, search.SearchMarkRight)
if 0 < len(keyword) {
diff --git a/kernel/model/transaction.go b/kernel/model/transaction.go
index e18ab84c0c..ea5fc7dafc 100644
--- a/kernel/model/transaction.go
+++ b/kernel/model/transaction.go
@@ -1255,6 +1255,8 @@ func (tx *Transaction) doInsert0(operation *Operation, tree *parse.Tree) (ret *T
subTree := tx.luteEngine.BlockDOM2Tree(data)
subTree.Box, subTree.Path = tree.Box, tree.Path
tx.processGlobalAssets(subTree)
+ // 兜底校验:禁止跨加密边界块引(粘贴/拖拽/API 直调可能携带跨边界引用)
+ degradeCrossBoundaryBlockRefs(subTree.Root, subTree.Box)
insertedNode := subTree.Root.FirstChild
if nil == insertedNode {
@@ -1481,6 +1483,9 @@ func (tx *Transaction) doUpdate(operation *Operation) (ret *TxErr) {
oldDefIDs := getRefDefIDs(oldNode)
var newDefIDs []string
+ // 兜底校验:禁止跨加密边界块引(加密 box ↔ 普通 box,或不同加密 box 之间)
+ degradeCrossBoundaryBlockRefs(subTree.Root, subTree.Box)
+
var unlinks []*ast.Node
ast.Walk(subTree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering {
@@ -1494,6 +1499,11 @@ func (tx *Transaction) doUpdate(operation *Operation) (ret *TxErr) {
unlinks = append(unlinks, n)
}
} else if n.IsTextMarkType("block-ref") {
+ if "" == n.TextMarkBlockRefID {
+ // 已被 degradeCrossBoundaryBlockRefs 降级为纯文本,跳过引用处理
+ return ast.WalkContinue
+ }
+
sql.CacheRef(subTree, n)
if "d" == n.TextMarkBlockRefSubtype {
@@ -1682,6 +1692,30 @@ func getRefDefIDs(node *ast.Node) (refDefIDs []string) {
return
}
+// degradeCrossBoundaryBlockRefs 遍历树,把跨越加密边界的块引节点降级为纯文本。
+// 加密笔记本禁止跨边界块引(双向):防止手工输入/拖拽/粘贴/API 直调绕过前端搜索分流。
+// 返回被降级的引用数。
+func degradeCrossBoundaryBlockRefs(root *ast.Node, srcBox string) int {
+ degraded := 0
+ ast.Walk(root, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if !entering {
+ return ast.WalkContinue
+ }
+
+ if ast.NodeTextMark == n.Type && n.IsTextMarkType("block-ref") {
+ if IsBlockRefCrossingBoundary(srcBox, n.TextMarkBlockRefID) {
+ logging.LogWarnf("block ref crosses encrypted boundary, src box [%s] -> def block [%s], degrade to text", srcBox, n.TextMarkBlockRefID)
+ n.TextMarkBlockRefID = ""
+ n.TextMarkBlockRefSubtype = ""
+ n.TextMarkTextContent = strings.TrimSpace(n.TextMarkTextContent)
+ degraded++
+ }
+ }
+ return ast.WalkContinue
+ })
+ return degraded
+}
+
func getRemovedNodes(oldNode, newNode *ast.Node) (ret []*ast.Node) {
oldNodes := map[string]*ast.Node{}
ast.Walk(oldNode, func(n *ast.Node, entering bool) ast.WalkStatus {
diff --git a/kernel/model/tree.go b/kernel/model/tree.go
index b1af7c8344..f1275e33ea 100644
--- a/kernel/model/tree.go
+++ b/kernel/model/tree.go
@@ -265,6 +265,34 @@ func loadTreeByBlockTree(bt *treenode.BlockTree) (ret *parse.Tree, err error) {
return
}
+// loadTreeByBlockIDInBox 与 LoadTreeByBlockID 一致,但按 boxID 路由 blocktree 查询到加密 db 或全局 db。
+func loadTreeByBlockIDInBox(id, boxID string) (ret *parse.Tree, err error) {
+ if !ast.IsNodeIDPattern(id) {
+ stack := logging.ShortStack()
+ logging.LogErrorf("block id is invalid [id=%s], stack: [%s]", id, stack)
+ return nil, ErrTreeNotFound
+ }
+
+ bt := treenode.GetBlockTreeInBox(id, boxID)
+ if nil == bt {
+ if task.ContainIndexTask() {
+ err = ErrIndexing
+ return
+ }
+
+ stack := logging.ShortStack()
+ if !strings.Contains(stack, "BuildBlockBreadcrumb") {
+ if "dev" == util.Mode {
+ logging.LogWarnf("block tree not found [id=%s], stack: [%s]", id, stack)
+ }
+ }
+ return nil, ErrTreeNotFound
+ }
+
+ ret, err = loadTreeByBlockTree(bt)
+ return
+}
+
var searchTreeLimiter = rate.NewLimiter(rate.Every(3*time.Second), 1)
func indexTreeInFilesystem(blockID string) error {
diff --git a/kernel/sql/encrypted_query.go b/kernel/sql/encrypted_query.go
index 285c725d80..380668e791 100644
--- a/kernel/sql/encrypted_query.go
+++ b/kernel/sql/encrypted_query.go
@@ -17,7 +17,10 @@
package sql
import (
+ "bytes"
"database/sql"
+ "math"
+ "regexp"
"strings"
"github.com/siyuan-note/logging"
@@ -187,6 +190,340 @@ func QueryBookmarkBlocksInBox(boxID string) (ret []*Block) {
return
}
+// QueryRefCountInBox 按 defBlockIDs 在指定 box 的 db 里查引用计数。
+func QueryRefCountInBox(defIDs []string, boxID string) (ret map[string]int) {
+ ret = map[string]int{}
+ if 1 > len(defIDs) {
+ return
+ }
+ ids := "('" + strings.Join(defIDs, "','") + "')"
+ rows, err := queryForBox(boxID, "SELECT def_block_id, COUNT(*) AS ref_cnt FROM refs WHERE def_block_id IN "+ids+" GROUP BY def_block_id")
+ if err != nil {
+ logging.LogErrorf("sql query failed: %s", err)
+ return
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var id string
+ var cnt int
+ if err = rows.Scan(&id, &cnt); err != nil {
+ logging.LogErrorf("query scan field failed: %s", err)
+ return
+ }
+ ret[id] = cnt
+ }
+ return
+}
+
+// QueryNoLimitInBox 在指定 box 的 db 里执行无 limit 的原始查询(返回 map 行)。
+func QueryNoLimitInBox(stmt, boxID string) (ret []map[string]any, err error) {
+ return queryRawStmtForBox(boxID, stmt, math.MaxInt)
+}
+
+// QueryNoLimitArgsInBox 与 QueryNoLimitInBox 一致,但支持参数化查询。
+func QueryNoLimitArgsInBox(stmt, boxID string, args ...any) (ret []map[string]any, err error) {
+ return queryRawStmtArgsForBox(boxID, stmt, args, math.MaxInt)
+}
+
+// SelectBlocksRawStmtArgsInBox 在指定 box 的 db 里执行参数化原始 SQL 查询 blocks。
+// 与 SelectBlocksRawStmtArgs 对应,绕开 sqlparser 对 "?" 占位的改写。
+func SelectBlocksRawStmtArgsInBox(stmt string, args []any, limit int, boxID string) (ret []*Block) {
+ rows, err := queryForBox(boxID, stmt, args...)
+ if err != nil {
+ if strings.Contains(err.Error(), "syntax error") {
+ return
+ }
+ logging.LogWarnf("sql query [%s] failed: %s", stmt, err)
+ return
+ }
+ defer rows.Close()
+
+ noLimit := !containsLimitClause(stmt)
+ var count, errCount int
+ for rows.Next() {
+ count++
+ if block := scanBlockRows(rows); nil != block {
+ ret = append(ret, block)
+ } else {
+ logging.LogWarnf("raw sql query [%s] failed", stmt)
+ errCount++
+ }
+
+ if (noLimit && limit < count) || 0 < errCount {
+ break
+ }
+ }
+ return
+}
+
+// SelectBlocksRegexInBox 在指定 box 的 db 里执行正则匹配查询 blocks(无占位参数版)。
+func SelectBlocksRegexInBox(stmt string, exp *regexp.Regexp, name, alias, memo, ial bool, page, pageSize int, boxID string) (ret []*Block) {
+ rows, err := queryForBox(boxID, stmt)
+ if err != nil {
+ logging.LogErrorf("sql query [%s] failed: %s", stmt, err)
+ return
+ }
+ defer rows.Close()
+ count := 0
+ for rows.Next() {
+ count++
+ if count <= (page-1)*pageSize {
+ continue
+ }
+
+ var block Block
+ if err := rows.Scan(&block.ID, &block.ParentID, &block.RootID, &block.Hash, &block.Box, &block.Path, &block.HPath, &block.Name, &block.Alias, &block.Memo, &block.Tag, &block.Content, &block.FContent, &block.Markdown, &block.Length, &block.Type, &block.SubType, &block.IAL, &block.Sort, &block.Created, &block.Updated); err != nil {
+ logging.LogErrorf("query scan field failed: %s\n%s", err, logging.ShortStack())
+ return
+ }
+
+ if matchRegexBlock(&block, exp, name, alias, memo, ial) {
+ ret = append(ret, &block)
+ if len(ret) >= pageSize {
+ break
+ }
+ }
+ }
+ return
+}
+
+// SelectBlocksRegexArgsInBox 与 SelectBlocksRegexInBox 一致,但通过绑定参数执行。
+func SelectBlocksRegexArgsInBox(stmt string, exp *regexp.Regexp, name, alias, memo, ial bool, page, pageSize int, boxID string, args ...any) (ret []*Block) {
+ rows, err := queryForBox(boxID, stmt, args...)
+ if err != nil {
+ logging.LogErrorf("sql query [%s] failed: %s", stmt, err)
+ return
+ }
+ defer rows.Close()
+ count := 0
+ for rows.Next() {
+ count++
+ if count <= (page-1)*pageSize {
+ continue
+ }
+
+ var block Block
+ if err := rows.Scan(&block.ID, &block.ParentID, &block.RootID, &block.Hash, &block.Box, &block.Path, &block.HPath, &block.Name, &block.Alias, &block.Memo, &block.Tag, &block.Content, &block.FContent, &block.Markdown, &block.Length, &block.Type, &block.SubType, &block.IAL, &block.Sort, &block.Created, &block.Updated); err != nil {
+ logging.LogErrorf("query scan field failed: %s\n%s", err, logging.ShortStack())
+ return
+ }
+
+ if matchRegexBlock(&block, exp, name, alias, memo, ial) {
+ ret = append(ret, &block)
+ if len(ret) >= pageSize {
+ break
+ }
+ }
+ }
+ return
+}
+
+// matchRegexBlock 对 block 各字段做正则命中并就地高亮,命中返回 true。
+func matchRegexBlock(block *Block, exp *regexp.Regexp, name, alias, memo, ial bool) bool {
+ hitContent := exp.MatchString(block.Content)
+ hitName := name && exp.MatchString(block.Name)
+ hitAlias := alias && exp.MatchString(block.Alias)
+ hitMemo := memo && exp.MatchString(block.Memo)
+ hitIAL := ial && exp.MatchString(block.IAL)
+ if hitContent || hitName || hitAlias || hitMemo || hitIAL {
+ if hitContent {
+ block.Content = exp.ReplaceAllString(block.Content, "__@mark__${0}__mark@__")
+ }
+ if hitName {
+ block.Name = exp.ReplaceAllString(block.Name, "__@mark__${0}__mark@__")
+ }
+ if hitAlias {
+ block.Alias = exp.ReplaceAllString(block.Alias, "__@mark__${0}__mark@__")
+ }
+ if hitMemo {
+ block.Memo = exp.ReplaceAllString(block.Memo, "__@mark__${0}__mark@__")
+ }
+ if hitIAL {
+ block.IAL = exp.ReplaceAllString(block.IAL, "__@mark__${0}__mark@__")
+ }
+ return true
+ }
+ return false
+}
+
+// QueryBlockNamesByRootIDInBox 按 rootID 在指定 box 的 db 里查块命名。
+func QueryBlockNamesByRootIDInBox(rootID, boxID string) (ret []string) {
+ sqlStmt := "SELECT DISTINCT name FROM blocks WHERE root_id = ? AND name != ''"
+ rows, err := queryForBox(boxID, sqlStmt, rootID)
+ if err != nil {
+ logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
+ return
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var name string
+ rows.Scan(&name)
+ ret = append(ret, name)
+ }
+ return
+}
+
+// QueryBlockAliasesInBox 按 rootID 在指定 box 的 db 里查块别名(按逗号拆分去重)。
+func QueryBlockAliasesInBox(rootID, boxID string) (ret []string) {
+ sqlStmt := "SELECT alias FROM blocks WHERE root_id = ? AND alias != ''"
+ rows, err := queryForBox(boxID, sqlStmt, rootID)
+ if err != nil {
+ logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
+ return
+ }
+ defer rows.Close()
+ var aliasesRows []string
+ for rows.Next() {
+ var name string
+ rows.Scan(&name)
+ aliasesRows = append(aliasesRows, name)
+ }
+
+ for _, aliasStr := range aliasesRows {
+ aliases := strings.Split(aliasStr, ",")
+ for _, alias := range aliases {
+ var exist bool
+ for _, retAlias := range ret {
+ if retAlias == alias {
+ exist = true
+ }
+ }
+ if !exist {
+ ret = append(ret, alias)
+ }
+ }
+ }
+ return
+}
+
+// QueryRefsByDefIDRefIDInBox 按 defBlockID+refBlockID 在指定 box 的 db 里查引用。
+func QueryRefsByDefIDRefIDInBox(defBlockID, refBlockID, boxID string) (ret []*Ref) {
+ stmt := "SELECT * FROM refs WHERE def_block_id = ? AND block_id = ?"
+ rows, err := queryForBox(boxID, stmt, defBlockID, refBlockID)
+ if err != nil {
+ logging.LogErrorf("sql query failed: %s", err)
+ return
+ }
+ defer rows.Close()
+ for rows.Next() {
+ ref := scanRefRows(rows)
+ ret = append(ret, ref)
+ }
+ return
+}
+
+// QueryRefsRecentInBox 按 boxID 路由查最近引用,用于加密 box 内的块引搜索。
+func QueryRefsRecentInBox(onlyDoc bool, typeFilter string, ignoreLines []string, boxID string) (ret []*Ref) {
+ stmt := "SELECT r.* FROM refs AS r, blocks AS b WHERE b.id = r.def_block_id AND b.type IN " + typeFilter
+ if onlyDoc {
+ stmt = "SELECT r.* FROM refs AS r, blocks AS b WHERE b.id = r.def_block_id AND b.type = 'd'"
+ }
+ if 0 < len(ignoreLines) {
+ buf := bytes.Buffer{}
+ for _, line := range ignoreLines {
+ buf.WriteString(" AND ")
+ buf.WriteString(line)
+ }
+ stmt += buf.String()
+ }
+ stmt += " GROUP BY r.def_block_id ORDER BY r.id DESC LIMIT 32"
+ rows, err := queryForBox(boxID, stmt)
+ if err != nil {
+ logging.LogErrorf("sql query failed: %s", err)
+ return
+ }
+ defer rows.Close()
+ for rows.Next() {
+ ref := scanRefRows(rows)
+ ret = append(ret, ref)
+ }
+ return
+}
+
+// SelectBlocksRawStmtNoParseInBox 与 SelectBlocksRawStmtNoParse 一致,但按 boxID 路由。
+func SelectBlocksRawStmtNoParseInBox(stmt string, limit int, boxID string) (ret []*Block) {
+ rows, err := queryForBox(boxID, stmt)
+ if err != nil {
+ if strings.Contains(err.Error(), "syntax error") {
+ return
+ }
+ return
+ }
+ defer rows.Close()
+
+ noLimit := !containsLimitClause(stmt)
+ var count, errCount int
+ for rows.Next() {
+ count++
+ if block := scanBlockRows(rows); nil != block {
+ ret = append(ret, block)
+ } else {
+ logging.LogWarnf("raw sql query [%s] failed", stmt)
+ errCount++
+ }
+
+ if (noLimit && limit < count) || 0 < errCount {
+ break
+ }
+ }
+ return
+}
+
+// GetChildBlocksInBox 按 parentID 在指定 box 的 db 里查所有子块。
+func GetChildBlocksInBox(parentID, condition string, limit int, boxID string) (ret []*Block) {
+ blockIDs := queryBlockChildrenIDsForBox(parentID, boxID)
+ var params []string
+ for _, id := range blockIDs {
+ params = append(params, "\""+id+"\"")
+ }
+
+ ret = []*Block{}
+ sqlStmt := "SELECT * FROM blocks AS ref WHERE ref.id IN (" + strings.Join(params, ",") + ")"
+ if "" != condition {
+ sqlStmt += " AND " + condition
+ }
+ sqlStmt += " LIMIT " + itoa(limit)
+ rows, err := queryForBox(boxID, sqlStmt)
+ if err != nil {
+ logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
+ return
+ }
+ defer rows.Close()
+ for rows.Next() {
+ if block := scanBlockRows(rows); nil != block {
+ ret = append(ret, block)
+ }
+ }
+ return
+}
+
+// queryBlockChildrenIDsForBox 递归收集 parentID 及其全部子块 id,按 boxID 路由。
+func queryBlockChildrenIDsForBox(id, boxID string) (ret []string) {
+ ret = append(ret, id)
+ childIDs := queryBlockIDByParentIDForBox(id, boxID)
+ for _, childID := range childIDs {
+ ret = append(ret, queryBlockChildrenIDsForBox(childID, boxID)...)
+ }
+ return
+}
+
+// queryBlockIDByParentIDForBox 按 parentID 查直接子块 id,按 boxID 路由。
+func queryBlockIDByParentIDForBox(parentID, boxID string) (ret []string) {
+ sqlStmt := "SELECT id FROM blocks WHERE parent_id = ?"
+ rows, err := queryForBox(boxID, sqlStmt, parentID)
+ if err != nil {
+ logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
+ return
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var id string
+ rows.Scan(&id)
+ ret = append(ret, id)
+ }
+ return
+}
+
// itoa 是 strconv.Itoa 的简写别名,避免重复 import。
func itoa(i int) string {
return intToStr(i)
@@ -215,3 +552,88 @@ func intToStr(i int) string {
}
return string(buf[pos:])
}
+
+// queryRawStmtForBox 与 queryRawStmt 一致,但按 boxID 路由到加密 db 或全局 db。
+func queryRawStmtForBox(boxID, stmt string, limit int) (ret []map[string]any, err error) {
+ rows, err := queryForBox(boxID, stmt)
+ if err != nil {
+ if strings.Contains(err.Error(), "syntax error") {
+ return
+ }
+ return
+ }
+ defer rows.Close()
+
+ cols, err := rows.Columns()
+ if err != nil || nil == cols {
+ return
+ }
+
+ noLimit := !containsLimitClause(stmt)
+ var count int
+ for rows.Next() {
+ columns := make([]any, len(cols))
+ columnPointers := make([]any, len(cols))
+ for i := range columns {
+ columnPointers[i] = &columns[i]
+ }
+
+ if err = rows.Scan(columnPointers...); err != nil {
+ return
+ }
+
+ m := make(map[string]any)
+ for i, colName := range cols {
+ val := columnPointers[i].(*any)
+ m[colName] = *val
+ }
+
+ ret = append(ret, m)
+ count++
+ if noLimit && limit < count {
+ break
+ }
+ }
+ return
+}
+
+// queryRawStmtArgsForBox 与 queryRawStmtArgs 一致,但按 boxID 路由到加密 db 或全局 db。
+func queryRawStmtArgsForBox(boxID, stmt string, args []any, limit int) (ret []map[string]any, err error) {
+ rows, err := queryForBox(boxID, stmt, args...)
+ if err != nil {
+ return
+ }
+ defer rows.Close()
+
+ cols, err := rows.Columns()
+ if err != nil || nil == cols {
+ return
+ }
+
+ noLimit := !containsLimitClause(stmt)
+ var count int
+ for rows.Next() {
+ columns := make([]any, len(cols))
+ columnPointers := make([]any, len(cols))
+ for i := range columns {
+ columnPointers[i] = &columns[i]
+ }
+
+ if err = rows.Scan(columnPointers...); err != nil {
+ return
+ }
+
+ m := make(map[string]any)
+ for i, colName := range cols {
+ val := columnPointers[i].(*any)
+ m[colName] = *val
+ }
+
+ ret = append(ret, m)
+ count++
+ if noLimit && limit < count {
+ break
+ }
+ }
+ return
+}