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: Exclude publish-inaccessible documents from search counts https://github.com/siyuan-note/siyuan/security/advisories/GHSA-g45v-hxvm-wccj
Daniela288eab6903e
diff --git a/kernel/api/search.go b/kernel/api/search.goindex 381315ea78..c16e2f254d 100644--- a/kernel/api/search.go+++ b/kernel/api/search.go@@ -53,10 +53,20 @@ func listInvalidBlockRefs(c *gin.Context) {pageSize = 32}- blocks, matchedBlockCount, matchedRootCount, pageCount := model.ListInvalidBlockRefs(page, pageSize)+ var blocks []*model.Block+ var matchedBlockCount, matchedRootCount, pageCount intif model.IsReadOnlyRoleContext(c) {+ denyAll, excludeBoxIDs, excludeDocIDs := model.GetPublishAccessSearchExclusion(c)+ if denyAll {+ blocks = []*model.Block{}+ matchedBlockCount, matchedRootCount, pageCount = 0, 0, 0+ } else {+ blocks, matchedBlockCount, matchedRootCount, pageCount = model.ListInvalidBlockRefs(page, pageSize, excludeBoxIDs, excludeDocIDs)+ }publishAccess := model.GetPublishAccess()blocks = model.FilterBlocksByPublishAccess(c, publishAccess, blocks)+ } else {+ blocks, matchedBlockCount, matchedRootCount, pageCount = model.ListInvalidBlockRefs(page, pageSize, nil, nil)}ret.Data = map[string]any{"blocks": blocks,@@ -564,15 +574,30 @@ func fullTextSearchBlock(c *gin.Context) {searchHPath = value}// 加密笔记本的全文搜索走 InBox 版(查加密 content db + blocks_fts)+ var excludeBoxIDs, excludeDocIDs []string+ if model.IsReadOnlyRoleContext(c) {+ denyAll, deniedBoxIDs, deniedDocIDs := model.GetPublishAccessSearchExclusion(c)+ if denyAll {+ ret.Data = map[string]any{+ "blocks": []*model.Block{},+ "matchedBlockCount": 0,+ "matchedRootCount": 0,+ "pageCount": 0,+ "docMode": false,+ }+ return+ }+ excludeBoxIDs, excludeDocIDs = deniedBoxIDs, deniedDocIDs+ }if notebook != "" && model.IsEncryptedBox(notebook) {if err := holdEncryptedBoxRequest(c, notebook); err != nil {ret.Code = -1ret.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)+ blocks, matchedBlockCount, matchedRootCount, pageCount, docMode = model.FullTextSearchBlockInBoxWithHPathContext(c.Request.Context(), query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize, notebook, searchHPath, excludeBoxIDs, excludeDocIDs)} else {- blocks, matchedBlockCount, matchedRootCount, pageCount, docMode = model.FullTextSearchBlockInBoxWithHPathContext(c.Request.Context(), query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize, "", searchHPath)+ blocks, matchedBlockCount, matchedRootCount, pageCount, docMode = model.FullTextSearchBlockInBoxWithHPathContext(c.Request.Context(), query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize, "", searchHPath, excludeBoxIDs, excludeDocIDs)}if c.Request.Context().Err() != nil {return@@ -725,7 +750,22 @@ func semanticSearchBlock(c *gin.Context) {page, pageSize, query, paths, boxes, types, subTypes, _, _, _ := parseSearchBlockArgs(arg)- blocks, matchedBlockCount, matchedRootCount, pageCount := model.SemanticSearchBlock(query, boxes, paths, types, subTypes, page, pageSize)+ var excludeBoxIDs, excludeDocIDs []string+ if model.IsReadOnlyRoleContext(c) {+ denyAll, deniedBoxIDs, deniedDocIDs := model.GetPublishAccessSearchExclusion(c)+ if denyAll {+ ret.Data = map[string]any{+ "blocks": []*model.Block{},+ "matchedBlockCount": 0,+ "matchedRootCount": 0,+ "pageCount": 0,+ }+ return+ }+ excludeBoxIDs, excludeDocIDs = deniedBoxIDs, deniedDocIDs+ }++ blocks, matchedBlockCount, matchedRootCount, pageCount := model.SemanticSearchBlock(query, boxes, paths, types, subTypes, page, pageSize, excludeBoxIDs, excludeDocIDs)if model.IsReadOnlyRoleContext(c) {publishAccess := model.GetPublishAccess()blocks = model.FilterBlocksByPublishAccess(c, publishAccess, blocks)diff --git a/kernel/api/search_publish_exclusion_test.go b/kernel/api/search_publish_exclusion_test.gonew file mode 100644index 0000000000..3dfad0f7f7--- /dev/null+++ b/kernel/api/search_publish_exclusion_test.go@@ -0,0 +1,177 @@+//go:build fts5++// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package api++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++const publishSearchCountExclusionEnv = "SIYUAN_TEST_PUBLISH_SEARCH_COUNT_EXCLUSION"++// TestPublishSearchCountExclusion 验证发布模式下读者搜索不可见文档时不会通过计数泄露其存在性。+// 覆盖隐藏、禁止发布以及密码保护三种不可见级别,GHSA-g45v-hxvm-wccj。+// 测试在子进程中运行,避免 SQLite 文件句柄影响临时目录回收。+func TestPublishSearchCountExclusion(t *testing.T) {+ if "1" != os.Getenv(publishSearchCountExclusionEnv) {+ cmd := exec.Command(os.Args[0], "-test.run=^TestPublishSearchCountExclusion$", "-test.v")+ cmd.Env = append(os.Environ(), publishSearchCountExclusionEnv+"=1")+ output, err := cmd.CombinedOutput()+ if nil != err {+ t.Fatalf("publish search count exclusion subprocess failed: %v\n%s", err, output)+ }+ return+ }++ gin.SetMode(gin.TestMode)++ oldConf := model.Conf+ oldWorkspaceDir, oldConfDir, oldDataDir := util.WorkspaceDir, util.ConfDir, util.DataDir+ oldHistoryDir, oldTempDir, oldQueueDir := util.HistoryDir, util.TempDir, util.QueueDir+ oldDBPath, oldHistoryDBPath := util.DBPath, util.HistoryDBPath+ oldAssetDBPath, oldBlockTreeDBPath := util.AssetContentDBPath, util.BlockTreeDBPath++ root := t.TempDir()+ t.Cleanup(func() {+ sql.CloseDatabase()+ model.Conf = oldConf+ util.WorkspaceDir, util.ConfDir, util.DataDir = oldWorkspaceDir, oldConfDir, oldDataDir+ util.HistoryDir, util.TempDir, util.QueueDir = oldHistoryDir, oldTempDir, oldQueueDir+ util.DBPath, util.HistoryDBPath = oldDBPath, oldHistoryDBPath+ util.AssetContentDBPath, util.BlockTreeDBPath = oldAssetDBPath, oldBlockTreeDBPath+ })++ util.WorkspaceDir = root+ util.ConfDir = filepath.Join(root, "conf")+ util.DataDir = filepath.Join(root, "data")+ util.HistoryDir = filepath.Join(root, "history")+ util.TempDir = filepath.Join(root, "temp")+ util.QueueDir = filepath.Join(util.TempDir, "queue")+ util.DBPath = filepath.Join(util.TempDir, util.DBName)+ util.HistoryDBPath = filepath.Join(util.TempDir, "history.db")+ util.AssetContentDBPath = filepath.Join(util.TempDir, "asset_content.db")+ util.BlockTreeDBPath = filepath.Join(util.TempDir, "blocktree.db")+ for _, dir := range []string{util.ConfDir, util.DataDir, util.HistoryDir, util.TempDir, util.QueueDir} {+ if err := os.MkdirAll(dir, 0755); err != nil {+ t.Fatal(err)+ }+ }++ model.Conf = model.NewAppConf()+ model.Conf.Lang = "en"+ model.Conf.FileTree = conf.NewFileTree()+ model.Conf.Editor = conf.NewEditor()+ model.Conf.Export = conf.NewExport()+ model.Conf.Search = conf.NewSearch()+ model.Conf.NotebookCrypto = conf.NewNotebookCrypto()+ model.Conf.Sync = conf.NewSync()++ const boxID = "20260823000000-b0xb0x1"+ const publicID = "20260823000001-aabbccd"+ const hiddenID = "20260823000002-aabbccd"+ const disabledID = "20260823000003-aabbccd"+ const passwordID = "20260823000004-aabbccd"+ box := &model.Box{ID: boxID}+ boxConf := conf.NewBoxConf()+ boxConf.Name = "Publish search count exclusion"+ boxConf.Closed = false+ if err := box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }++ sql.InitDatabase(true)+ sql.InitHistoryDatabase(true)+ sql.InitAssetContentDatabase(true)+ treenode.InitBlockTree(true)++ addDoc := func(id, title, term string) {+ tree := treenode.NewTree(boxID, "/"+id+".sy", "/"+title, title)+ tree.Root.FirstChild.Unlink()+ node := &ast.Node{Type: ast.NodeParagraph, ID: id + "-child"}+ node.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(term)})+ tree.Root.AppendChild(node)+ treenode.IndexBlockTree(tree)+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ sql.IndexTreeQueue(tree)+ }+ addDoc(publicID, "Public", "publiccanary")+ addDoc(hiddenID, "Hidden", "hiddencanary")+ addDoc(disabledID, "Disabled", "disabledcanary")+ addDoc(passwordID, "Password", "passwordcanary")+ sql.FlushQueue()++ if err := model.SetPublishAccess(model.PublishAccess{+ {ID: hiddenID, Visible: false},+ {ID: disabledID, Disable: true},+ {ID: passwordID, Password: "secret123"},+ }); err != nil {+ t.Fatal(err)+ }++ search := func(query string) (blocksLen, matchedBlockCount, matchedRootCount, pageCount int, body string) {+ payload := `{"query":"` + query + `","method":0,"types":{"document":true,"paragraph":true},"subTypes":{},"paths":[],"groupBy":0,"orderBy":0,"page":1,"pageSize":32}`+ recorder := httptest.NewRecorder()+ c, _ := gin.CreateTestContext(recorder)+ c.Request = httptest.NewRequest(http.MethodPost, "/api/search/fullTextSearchBlock", strings.NewReader(payload))+ c.Request.Header.Set("Content-Type", "application/json")+ c.Set(model.RoleContextKey, model.RoleReader)+ fullTextSearchBlock(c)++ var response struct {+ Data struct {+ Blocks []json.RawMessage `json:"blocks"`+ MatchedBlockCount int `json:"matchedBlockCount"`+ MatchedRootCount int `json:"matchedRootCount"`+ PageCount int `json:"pageCount"`+ } `json:"data"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {+ t.Fatalf("invalid handler response: %v\n%s", err, recorder.Body.String())+ }+ return len(response.Data.Blocks), response.Data.MatchedBlockCount, response.Data.MatchedRootCount, response.Data.PageCount, recorder.Body.String()+ }++ if blocksLen, matchedBlockCount, matchedRootCount, pageCount, body := search("publiccanary"); 0 >= blocksLen || 0 >= matchedBlockCount || 0 >= matchedRootCount || 0 >= pageCount {+ t.Fatalf("public doc should remain searchable: %s", body)+ }++ for _, term := range []string{"hiddencanary", "disabledcanary", "passwordcanary"} {+ blocksLen, matchedBlockCount, matchedRootCount, pageCount, body := search(term)+ if 0 != blocksLen || 0 != matchedBlockCount || 0 != matchedRootCount || 0 != pageCount {+ t.Fatalf("search [%s] disclosed counts for invisible doc: %s", term, body)+ }+ }+}diff --git a/kernel/cli/cmd/search.go b/kernel/cli/cmd/search.goindex 4dddb7423c..94c4bed70f 100644--- a/kernel/cli/cmd/search.go+++ b/kernel/cli/cmd/search.go@@ -69,7 +69,7 @@ var searchCmd = &cobra.Command{var matchedBlockCount, matchedRootCount, pageCount intif method == 4 {blocks, matchedBlockCount, matchedRootCount, pageCount =- model.SemanticSearchBlock(query, notebooks, paths, types, subTypes, page, pageSize)+ model.SemanticSearchBlock(query, notebooks, paths, types, subTypes, page, pageSize, nil, nil)} else {blocks, matchedBlockCount, matchedRootCount, pageCount, docMode =model.FullTextSearchBlock(query, notebooks, paths, types, subTypes, method, orderBy, groupBy, page, pageSize)diff --git a/kernel/mcp/tools/search.go b/kernel/mcp/tools/search.goindex ee27f7380e..681fdc7892 100644--- a/kernel/mcp/tools/search.go+++ b/kernel/mcp/tools/search.go@@ -191,7 +191,7 @@ func semanticSearch(args map[string]any) (CallToolResult, error) {subtypes := parseStringSet(args["subtype"])blocks, matchedCount, matchedRootCount, pageCount := model.SemanticSearchBlock(- query, notebooks, paths, types, subtypes, page, pageSize,+ query, notebooks, paths, types, subtypes, page, pageSize, nil, nil,)if matchedCount == 0 {diff --git a/kernel/model/embedding.go b/kernel/model/embedding.goindex 0b5f91f346..4a8f55faef 100644--- a/kernel/model/embedding.go+++ b/kernel/model/embedding.go@@ -431,7 +431,7 @@ func (h *scoredHeap) Pop() any {return x}-func SemanticSearchBlock(query string, boxes, paths []string, types, subTypes map[string]bool, page, pageSize int) (blocks []*Block, matchedBlockCount, matchedRootCount, pageCount int) {+func SemanticSearchBlock(query string, boxes, paths []string, types, subTypes map[string]bool, page, pageSize int, excludeBoxIDs, excludeDocIDs []string) (blocks []*Block, matchedBlockCount, matchedRootCount, pageCount int) {blocks = []*Block{}if !embeddingTableOk || !isEmbeddingEnabled() || "" == query {@@ -448,8 +448,9 @@ func SemanticSearchBlock(query string, boxes, paths []string, types, subTypes maboxFilter, boxArgs := buildBoxesFilter(boxes, "be.")pathFilter, pathArgs := buildPathsFilter(paths, "be.")boxDocFilter, boxDocArgs := buildRootIDExclusionFilter(hiddenBoxDocRootIDs(), "b.")+ excludeFilter, excludeArgs := buildPublishAccessExclusionFilter(excludeBoxIDs, excludeDocIDs, "b.")typeFilter := buildTypeFilter(types, subTypes, "b.")- hasFilter := 0 < len(boxes) || 0 < len(paths) || 0 < len(types) || "" != boxDocFilter+ hasFilter := 0 < len(boxes) || 0 < len(paths) || 0 < len(types) || "" != boxDocFilter || "" != excludeFilterhasTypeFilter := 0 < len(types)numWorkers := max(runtime.GOMAXPROCS(0), 1)@@ -473,9 +474,10 @@ func SemanticSearchBlock(query string, boxes, paths []string, types, subTypes maif hasTypeFilter {q += " AND " + typeFilter}- q += boxFilter + pathFilter + boxDocFilter+ q += boxFilter + pathFilter + boxDocFilter + excludeFilter// 过滤值通过绑定参数传递,避免 SQL 拼接注入args = append(append(append([]any{}, boxArgs...), pathArgs...), boxDocArgs...)+ args = append(args, excludeArgs...)q += fmt.Sprintf(" ORDER BY be.rowid LIMIT %d", scanSize)} else {q = fmt.Sprintf("SELECT rowid, id, embedding FROM block_embeddings WHERE embedding IS NOT NULL AND length(embedding) > 0 AND rowid > %d ORDER BY rowid LIMIT %d", cursor, scanSize)diff --git a/kernel/model/publish_access.go b/kernel/model/publish_access.goindex 810c9e89b7..1f49a19174 100644--- a/kernel/model/publish_access.go+++ b/kernel/model/publish_access.go@@ -1387,6 +1387,44 @@ func FilterBlocksByPublishAccess(c *gin.Context, publishAccess PublishAccess, blreturn}+// GetPublishAccessSearchExclusion 返回当前读者在全库搜索中不可见的笔记本 ID 和文档 ID 排除集合。+// 排除来源包括隐藏、禁止发布以及未通过密码验证的发布访问条目,保证搜索计数和分页不泄露这些条目。+// denyAll 为 true 时当前读者不可见任何内容,调用方应直接返回空结果。+func GetPublishAccessSearchExclusion(c *gin.Context) (denyAll bool, boxIDs, docIDs []string) {+ publishAccess := GetPublishAccess()+ denied := PublishAccess{}+ denied = append(denied, GetInvisiblePublishAccess(publishAccess)...)+ denied = append(denied, GetDisablePublishAccess(publishAccess)...)+ for _, item := range publishAccess {+ if "" != item.Password && !CheckPublishAuthCookie(c, item.ID, item.Password) {+ denied = append(denied, item)+ }+ }++ boxIDSet := map[string]bool{}+ docIDSet := map[string]bool{}+ for _, item := range denied {+ if publishAccessDenyAllID == item.ID {+ return true, nil, nil+ }+ if !ast.IsNodeIDPattern(item.ID) {+ continue+ }+ if filelock.IsExist(filepath.Join(util.DataDir, item.ID)) {+ boxIDSet[item.ID] = true+ } else {+ docIDSet[item.ID] = true+ }+ }+ for boxID := range boxIDSet {+ boxIDs = append(boxIDs, boxID)+ }+ for docID := range docIDSet {+ docIDs = append(docIDs, docID)+ }+ return+}+func FilterSearchDocsByPublishAccess(c *gin.Context, publishAccess PublishAccess, docs []map[string]string) (ret []map[string]string) {ret = []map[string]string{}diff --git a/kernel/model/search.go b/kernel/model/search.goindex 2fa3ea3a0c..ec03b9a7cc 100644--- a/kernel/model/search.go+++ b/kernel/model/search.go@@ -27,6 +27,7 @@ import ("path""path/filepath""regexp"+ "slices""sort""strconv""strings"@@ -53,7 +54,7 @@ import ("github.com/xrash/smetrics")-func ListInvalidBlockRefs(page, pageSize int) (ret []*Block, matchedBlockCount, matchedRootCount, pageCount int) {+func ListInvalidBlockRefs(page, pageSize int, excludeBoxIDs, excludeDocIDs []string) (ret []*Block, matchedBlockCount, matchedRootCount, pageCount int) {refBlockMap := map[string][]string{}blockMap := map[string]bool{}var invalidBlockIDs []string@@ -63,6 +64,9 @@ func ListInvalidBlockRefs(page, pageSize int) (ret []*Block, matchedBlockCount,}luteEngine := util.NewLute()for _, notebook := range notebooks {+ if slices.Contains(excludeBoxIDs, notebook.ID) {+ continue+ }pages := pagedPaths(filepath.Join(util.DataDir, notebook.ID), 32)for _, paths := range pages {var trees []*parse.Tree@@ -71,6 +75,9 @@ func ListInvalidBlockRefs(page, pageSize int) (ret []*Block, matchedBlockCount,if nil != loadTreeErr {continue}+ if isTreeExcludedByPublishAccess(tree, excludeDocIDs) {+ continue+ }trees = append(trees, tree)}for _, tree := range trees {@@ -1644,10 +1651,10 @@ func FullTextSearchBlockInBox(query string, boxes, paths []string, types, subTyp// FullTextSearchBlockInBoxWithHPath 与 FullTextSearchBlockInBox 一致,并可控制是否搜索文档层级路径。func FullTextSearchBlockInBoxWithHPath(query string, boxes, paths []string, types, subTypes map[string]bool, method, orderBy, groupBy, page, pageSize int, boxID string, searchHPath bool) (ret []*Block, matchedBlockCount, matchedRootCount, pageCount int, docMode bool) {- return FullTextSearchBlockInBoxWithHPathContext(context.Background(), query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize, boxID, searchHPath)+ return FullTextSearchBlockInBoxWithHPathContext(context.Background(), query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize, boxID, searchHPath, nil, nil)}-func FullTextSearchBlockInBoxWithHPathContext(ctx context.Context, query string, boxes, paths []string, types, subTypes map[string]bool, method, orderBy, groupBy, page, pageSize int, boxID string, searchHPath bool) (ret []*Block, matchedBlockCount, matchedRootCount, pageCount int, docMode bool) {+func FullTextSearchBlockInBoxWithHPathContext(ctx context.Context, query string, boxes, paths []string, types, subTypes map[string]bool, method, orderBy, groupBy, page, pageSize int, boxID string, searchHPath bool, excludeBoxIDs, excludeDocIDs []string) (ret []*Block, matchedBlockCount, matchedRootCount, pageCount int, docMode bool) {ret = []*Block{}if "" == query {return@@ -1657,6 +1664,8 @@ func FullTextSearchBlockInBoxWithHPathContext(ctx context.Context, query string,if 2 != method && 3 != method && ast.IsNodeIDPattern(query) && isHiddenBoxDocBlock(query, boxID) {return}+ excludeFilter, excludeArgs := buildPublishAccessExclusionFilter(excludeBoxIDs, excludeDocIDs)+ excludeInline := buildPublishAccessExclusionInline(excludeBoxIDs, excludeDocIDs)var ignoreFilter stringif ignoreLines := getSearchIgnoreLines(); 0 < len(ignoreLines) {// Support ignore search results https://github.com/siyuan-note/siyuan/issues/10089@@ -1676,11 +1685,12 @@ func FullTextSearchBlockInBoxWithHPathContext(ctx context.Context, query string,typeFilter := buildTypeFilter(types, subTypes)boxFilter, boxArgs := buildBoxesFilter(boxes)boxDocFilter, boxDocArgs := buildRootIDExclusionFilter(hiddenBoxDocRootIDs())- boxFilter += boxDocFilter+ boxFilter += boxDocFilter + excludeFilterboxArgs = append(boxArgs, boxDocArgs...)+ boxArgs = append(boxArgs, excludeArgs...)pathFilter, pathArgs := buildPathsFilter(paths)if ast.IsNodeIDPattern(query) {- blocks, matchedBlockCount, matchedRootCount = searchBySQLInBox("SELECT * FROM `blocks` WHERE `id` = '"+query+"'", beforeLen, page, pageSize, boxID)+ blocks, matchedBlockCount, matchedRootCount = searchBySQLInBox("SELECT * FROM `blocks` WHERE `id` = '"+query+"'"+excludeInline, beforeLen, page, pageSize, boxID)} else {blocks, matchedBlockCount, matchedRootCount = fullTextSearchByFTSInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize, boxID)}@@ -1693,19 +1703,21 @@ func FullTextSearchBlockInBoxWithHPathContext(ctx context.Context, query string,typeFilter := buildTypeFilter(types, subTypes)boxFilter, boxArgs := buildBoxesFilter(boxes)boxDocFilter, boxDocArgs := buildRootIDExclusionFilter(hiddenBoxDocRootIDs())- boxFilter += boxDocFilter+ boxFilter += boxDocFilter + excludeFilterboxArgs = append(boxArgs, boxDocArgs...)+ boxArgs = append(boxArgs, excludeArgs...)pathFilter, pathArgs := buildPathsFilter(paths)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)boxDocFilter, boxDocArgs := buildRootIDExclusionFilter(hiddenBoxDocRootIDs())- boxFilter += boxDocFilter+ boxFilter += boxDocFilter + excludeFilterboxArgs = append(boxArgs, boxDocArgs...)+ boxArgs = append(boxArgs, excludeArgs...)pathFilter, pathArgs := buildPathsFilter(paths)if ast.IsNodeIDPattern(query) {- blocks, matchedBlockCount, matchedRootCount = searchBySQLInBox("SELECT * FROM `blocks` WHERE `id` = '"+query+"'", beforeLen, page, pageSize, boxID)+ blocks, matchedBlockCount, matchedRootCount = searchBySQLInBox("SELECT * FROM `blocks` WHERE `id` = '"+query+"'"+excludeInline, beforeLen, page, pageSize, boxID)} else {if 2 > len(strings.Split(strings.TrimSpace(query), " ")) {ftsQuery, hPathQuery := buildKeywordSearchQueries(query)@@ -1938,6 +1950,45 @@ func buildRootIDExclusionFilter(rootIDs []string, alias ...string) (clause strinreturn}+// buildPublishAccessExclusionFilter 构造发布访问排除子句,排除指定笔记本以及路径中包含指定文档 ID 的块。+// 排除值通过绑定参数传递,避免 SQL 拼接注入;返回的 args 顺序与 clause 中 "?" 的出现顺序一致。+func buildPublishAccessExclusionFilter(boxIDs, docIDs []string, alias ...string) (clause string, args []any) {+ if 0 == len(boxIDs) && 0 == len(docIDs) {+ return+ }+ prefix := ""+ if 0 < len(alias) && "" != alias[0] {+ prefix = alias[0]+ }+ conds := make([]string, 0, len(boxIDs)+len(docIDs))+ for _, boxID := range boxIDs {+ conds = append(conds, fmt.Sprintf("%sbox = ?", prefix))+ args = append(args, boxID)+ }+ for _, docID := range docIDs {+ conds = append(conds, fmt.Sprintf("%spath LIKE ?", prefix))+ args = append(args, "%"+docID+"%")+ }+ clause = " AND NOT (" + strings.Join(conds, " OR ") + ")"+ return+}++// buildPublishAccessExclusionInline 构造内联的发布访问排除子句,用于无绑定参数的原生 SQL 分支。+// 排除 ID 均通过节点 ID 模式校验,可直接内联。+func buildPublishAccessExclusionInline(boxIDs, docIDs []string) string {+ conds := make([]string, 0, len(boxIDs)+len(docIDs))+ for _, boxID := range boxIDs {+ conds = append(conds, "box = '"+boxID+"'")+ }+ for _, docID := range docIDs {+ conds = append(conds, "path LIKE '%"+docID+"%'")+ }+ if 0 == len(conds) {+ return ""+ }+ return " AND NOT (" + strings.Join(conds, " OR ") + ")"+}+func buildOrderBy(query string, method, orderBy int) string {escapedQuery := strings.ReplaceAll(query, "'", "''")switch orderBy {@@ -2156,6 +2207,17 @@ func searchBySQL(stmt string, beforeLen, page, pageSize int) (ret []*Block, matcreturn searchBySQLInBox(stmt, beforeLen, page, pageSize, "")}+// isTreeExcludedByPublishAccess 判断文档树是否命中发布访问排除的文档 ID。+// 文档路径包含排除 ID 即视为不可见,覆盖被排除文档的整个子树。+func isTreeExcludedByPublishAccess(tree *parse.Tree, excludeDocIDs []string) bool {+ for _, docID := range excludeDocIDs {+ if strings.Contains(tree.Path, docID) {+ return true+ }+ }+ return false+}+// searchBySQLInBox 与 searchBySQL 一致,但按 boxID 路由到加密 db 或全局 db。func searchBySQLInBox(stmt string, beforeLen, page, pageSize int, boxID string) (ret []*Block, matchedBlockCount, matchedRootCount int) {return searchBySQLInBoxContext(context.Background(), stmt, beforeLen, page, pageSize, boxID)